Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

session-logic.ts

679 lines19.5 KB

1import {
2 ApprovalRequestId,
3 isToolLifecycleItemType,
4 type OrchestrationLatestTurn,
5 type OrchestrationThreadActivity,
6 type OrchestrationProposedPlanId,
7 type ProviderKind,
8 type ToolLifecycleItemType,
9 type UserInputQuestion,
10 type TurnId,
11} from "@t3tools/contracts";
12​
13import type {
14 ChatMessage,
15 ProposedPlan,
16 SessionPhase,
17 ThreadSession,
18 TurnDiffSummary,
19} from "./types";
20​
21export type ProviderPickerKind = ProviderKind | "claudeCode" | "cursor";
22​
23export const PROVIDER_OPTIONS: Array<{
24 value: ProviderPickerKind;
25 label: string;
26 available: boolean;
27}> = [
28 { value: "codex", label: "Codex", available: true },
29 { value: "claudeCode", label: "Claude Code", available: false },
30 { value: "cursor", label: "Cursor", available: false },
31];
32​
33export interface WorkLogEntry {
34 id: string;
35 createdAt: string;
36 label: string;
37 detail?: string;
38 command?: string;
39 changedFiles?: ReadonlyArray<string>;
40 tone: "thinking" | "tool" | "info" | "error";
41 toolTitle?: string;
42 itemType?: ToolLifecycleItemType;
43 requestKind?: PendingApproval["requestKind"];
45​
46export interface PendingApproval {
47 requestId: ApprovalRequestId;
48 requestKind: "command" | "file-read" | "file-change";
49 createdAt: string;
50 detail?: string;
52​
53export interface PendingUserInput {
54 requestId: ApprovalRequestId;
55 createdAt: string;
56 questions: ReadonlyArray<UserInputQuestion>;
58​
59export interface ActivePlanState {
60 createdAt: string;
61 turnId: TurnId | null;
62 explanation?: string | null;
63 steps: Array<{
64 step: string;
65 status: "pending" | "inProgress" | "completed";
66 }>;
68​
69export interface LatestProposedPlanState {
70 id: OrchestrationProposedPlanId;
71 createdAt: string;
72 updatedAt: string;
73 turnId: TurnId | null;
74 planMarkdown: string;
76​
77export type TimelineEntry =
78 | {
79 id: string;
80 kind: "message";
81 createdAt: string;
82 message: ChatMessage;
83 }
84 | {
85 id: string;
86 kind: "proposed-plan";
87 createdAt: string;
88 proposedPlan: ProposedPlan;
89 }
90 | {
91 id: string;
92 kind: "work";
93 createdAt: string;
94 entry: WorkLogEntry;
95 };
96​
97export function formatDuration(durationMs: number): string {
98 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
99 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
100 if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
101 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
102 const minutes = Math.floor(durationMs / 60_000);
103 const seconds = Math.round((durationMs % 60_000) / 1_000);
104 if (seconds === 0) return `${minutes}m`;
105 if (seconds === 60) return `${minutes + 1}m`;
106 return `${minutes}m ${seconds}s`;
108​
109export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
110 if (!endIso) return null;
111 const startedAt = Date.parse(startIso);
112 const endedAt = Date.parse(endIso);
113 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
114 return null;
115 }
116 return formatDuration(endedAt - startedAt);
118​
119type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
120type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
121​
122export function isLatestTurnSettled(
123 latestTurn: LatestTurnTiming | null,
124 session: SessionActivityState | null,
125): boolean {
126 if (!latestTurn?.startedAt) return false;
127 if (!latestTurn.completedAt) return false;
128 if (!session) return true;
129 if (session.orchestrationStatus === "running") return false;
130 return true;
132​
133export function deriveActiveWorkStartedAt(
134 latestTurn: LatestTurnTiming | null,
135 session: SessionActivityState | null,
136 sendStartedAt: string | null,
137): string | null {
138 if (!isLatestTurnSettled(latestTurn, session)) {
139 return latestTurn?.startedAt ?? sendStartedAt;
140 }
141 return sendStartedAt;
143​
144function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
145 switch (requestType) {
146 case "command_execution_approval":
147 case "exec_command_approval":
148 return "command";
149 case "file_read_approval":
150 return "file-read";
151 case "file_change_approval":
152 case "apply_patch_approval":
153 return "file-change";
154 default:
155 return null;
156 }
158​
159export function derivePendingApprovals(
160 activities: ReadonlyArray<OrchestrationThreadActivity>,
161): PendingApproval[] {
162 const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
163 const ordered = [...activities].toSorted(compareActivitiesByOrder);
164​
165 for (const activity of ordered) {
166 const payload =
167 activity.payload && typeof activity.payload === "object"
168 ? (activity.payload as Record<string, unknown>)
169 : null;
170 const requestId =
171 payload && typeof payload.requestId === "string"
172 ? ApprovalRequestId.makeUnsafe(payload.requestId)
173 : null;
174 const requestKind =
175 payload &&
176 (payload.requestKind === "command" ||
177 payload.requestKind === "file-read" ||
178 payload.requestKind === "file-change")
179 ? payload.requestKind
180 : payload
181 ? requestKindFromRequestType(payload.requestType)
182 : null;
183 const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
184​
185 if (activity.kind === "approval.requested" && requestId && requestKind) {
186 openByRequestId.set(requestId, {
187 requestId,
188 requestKind,
189 createdAt: activity.createdAt,
190 ...(detail ? { detail } : {}),
191 });
192 continue;
193 }
194​
195 if (activity.kind === "approval.resolved" && requestId) {
196 openByRequestId.delete(requestId);
197 continue;
198 }
199​
200 if (
201 activity.kind === "provider.approval.respond.failed" &&
202 requestId &&
203 detail?.includes("Unknown pending permission request")
204 ) {
205 openByRequestId.delete(requestId);
206 continue;
207 }
208 }
209​
210 return [...openByRequestId.values()].toSorted((left, right) =>
211 left.createdAt.localeCompare(right.createdAt),
212 );
214​
215function parseUserInputQuestions(
216 payload: Record<string, unknown> | null,
217): ReadonlyArray<UserInputQuestion> | null {
218 const questions = payload?.questions;
219 if (!Array.isArray(questions)) {
220 return null;
221 }
222 const parsed = questions
223 .map<UserInputQuestion | null>((entry) => {
224 if (!entry || typeof entry !== "object") return null;
225 const question = entry as Record<string, unknown>;
226 if (
227 typeof question.id !== "string" ||
228 typeof question.header !== "string" ||
229 typeof question.question !== "string" ||
230 !Array.isArray(question.options)
231 ) {
232 return null;
233 }
234 const options = question.options
235 .map<UserInputQuestion["options"][number] | null>((option) => {
236 if (!option || typeof option !== "object") return null;
237 const optionRecord = option as Record<string, unknown>;
238 if (
239 typeof optionRecord.label !== "string" ||
240 typeof optionRecord.description !== "string"
241 ) {
242 return null;
243 }
244 return {
245 label: optionRecord.label,
246 description: optionRecord.description,
247 };
248 })
249 .filter((option): option is UserInputQuestion["options"][number] => option !== null);
250 if (options.length === 0) {
251 return null;
252 }
253 return {
254 id: question.id,
255 header: question.header,
256 question: question.question,
257 options,
258 };
259 })
260 .filter((question): question is UserInputQuestion => question !== null);
261 return parsed.length > 0 ? parsed : null;
263​
264export function derivePendingUserInputs(
265 activities: ReadonlyArray<OrchestrationThreadActivity>,
266): PendingUserInput[] {
267 const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
268 const ordered = [...activities].toSorted(compareActivitiesByOrder);
269​
270 for (const activity of ordered) {
271 const payload =
272 activity.payload && typeof activity.payload === "object"
273 ? (activity.payload as Record<string, unknown>)
274 : null;
275 const requestId =
276 payload && typeof payload.requestId === "string"
277 ? ApprovalRequestId.makeUnsafe(payload.requestId)
278 : null;
279​
280 if (activity.kind === "user-input.requested" && requestId) {
281 const questions = parseUserInputQuestions(payload);
282 if (!questions) {
283 continue;
284 }
285 openByRequestId.set(requestId, {
286 requestId,
287 createdAt: activity.createdAt,
288 questions,
289 });
290 continue;
291 }
292​
293 if (activity.kind === "user-input.resolved" && requestId) {
294 openByRequestId.delete(requestId);
295 }
296 }
297​
298 return [...openByRequestId.values()].toSorted((left, right) =>
299 left.createdAt.localeCompare(right.createdAt),
300 );
302​
303export function deriveActivePlanState(
304 activities: ReadonlyArray<OrchestrationThreadActivity>,
305 latestTurnId: TurnId | undefined,
306): ActivePlanState | null {
307 const ordered = [...activities].toSorted(compareActivitiesByOrder);
308 const candidates = ordered.filter((activity) => {
309 if (activity.kind !== "turn.plan.updated") {
310 return false;
311 }
312 if (!latestTurnId) {
313 return true;
314 }
315 return activity.turnId === latestTurnId;
316 });
317 const latest = candidates.at(-1);
318 if (!latest) {
319 return null;
320 }
321 const payload =
322 latest.payload && typeof latest.payload === "object"
323 ? (latest.payload as Record<string, unknown>)
324 : null;
325 const rawPlan = payload?.plan;
326 if (!Array.isArray(rawPlan)) {
327 return null;
328 }
329 const steps = rawPlan
330 .map((entry) => {
331 if (!entry || typeof entry !== "object") return null;
332 const record = entry as Record<string, unknown>;
333 if (typeof record.step !== "string") {
334 return null;
335 }
336 const status =
337 record.status === "completed" || record.status === "inProgress" ? record.status : "pending";
338 return {
339 step: record.step,
340 status,
341 };
342 })
343 .filter(
344 (
345 step,
346 ): step is {
347 step: string;
348 status: "pending" | "inProgress" | "completed";
349 } => step !== null,
350 );
351 if (steps.length === 0) {
352 return null;
353 }
354 return {
355 createdAt: latest.createdAt,
356 turnId: latest.turnId,
357 ...(payload && "explanation" in payload
358 ? { explanation: payload.explanation as string | null }
359 : {}),
360 steps,
361 };
363​
364export function findLatestProposedPlan(
365 proposedPlans: ReadonlyArray<ProposedPlan>,
366 latestTurnId: TurnId | string | null | undefined,
367): LatestProposedPlanState | null {
368 if (latestTurnId) {
369 const matchingTurnPlan = [...proposedPlans]
370 .filter((proposedPlan) => proposedPlan.turnId === latestTurnId)
371 .toSorted(
372 (left, right) =>
373 left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id),
374 )
375 .at(-1);
376 if (matchingTurnPlan) {
377 return {
378 id: matchingTurnPlan.id,
379 createdAt: matchingTurnPlan.createdAt,
380 updatedAt: matchingTurnPlan.updatedAt,
381 turnId: matchingTurnPlan.turnId,
382 planMarkdown: matchingTurnPlan.planMarkdown,
383 };
384 }
385 }
386​
387 const latestPlan = [...proposedPlans]
388 .toSorted(
389 (left, right) =>
390 left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id),
391 )
392 .at(-1);
393 if (!latestPlan) {
394 return null;
395 }
396​
397 return {
398 id: latestPlan.id,
399 createdAt: latestPlan.createdAt,
400 updatedAt: latestPlan.updatedAt,
401 turnId: latestPlan.turnId,
402 planMarkdown: latestPlan.planMarkdown,
403 };
405​
406export function deriveWorkLogEntries(
407 activities: ReadonlyArray<OrchestrationThreadActivity>,
408 latestTurnId: TurnId | undefined,
409): WorkLogEntry[] {
410 const ordered = [...activities].toSorted(compareActivitiesByOrder);
411 return ordered
412 .filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
413 .filter((activity) => activity.kind !== "tool.started")
414 .filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
415 .filter((activity) => activity.summary !== "Checkpoint captured")
416 .map((activity) => {
417 const payload =
418 activity.payload && typeof activity.payload === "object"
419 ? (activity.payload as Record<string, unknown>)
420 : null;
421 const command = extractToolCommand(payload);
422 const changedFiles = extractChangedFiles(payload);
423 const title = extractToolTitle(payload);
424 const entry: WorkLogEntry = {
425 id: activity.id,
426 createdAt: activity.createdAt,
427 label: activity.summary,
428 tone: activity.tone === "approval" ? "info" : activity.tone,
429 };
430 const itemType = extractWorkLogItemType(payload);
431 const requestKind = extractWorkLogRequestKind(payload);
432 if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
433 const detail = stripTrailingExitCode(payload.detail).output;
434 if (detail) {
435 entry.detail = detail;
436 }
437 }
438 if (command) {
439 entry.command = command;
440 }
441 if (changedFiles.length > 0) {
442 entry.changedFiles = changedFiles;
443 }
444 if (title) {
445 entry.toolTitle = title;
446 }
447 if (itemType) {
448 entry.itemType = itemType;
449 }
450 if (requestKind) {
451 entry.requestKind = requestKind;
452 }
453 return entry;
454 });
456​
457function asRecord(value: unknown): Record<string, unknown> | null {
458 return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
460​
461function asTrimmedString(value: unknown): string | null {
462 if (typeof value !== "string") {
463 return null;
464 }
465 const trimmed = value.trim();
466 return trimmed.length > 0 ? trimmed : null;
468​
469function normalizeCommandValue(value: unknown): string | null {
470 const direct = asTrimmedString(value);
471 if (direct) {
472 return direct;
473 }
474 if (!Array.isArray(value)) {
475 return null;
476 }
477 const parts = value
478 .map((entry) => asTrimmedString(entry))
479 .filter((entry): entry is string => entry !== null);
480 return parts.length > 0 ? parts.join(" ") : null;
482​
483function extractToolCommand(payload: Record<string, unknown> | null): string | null {
484 const data = asRecord(payload?.data);
485 const item = asRecord(data?.item);
486 const itemResult = asRecord(item?.result);
487 const itemInput = asRecord(item?.input);
488 const candidates = [
489 normalizeCommandValue(item?.command),
490 normalizeCommandValue(itemInput?.command),
491 normalizeCommandValue(itemResult?.command),
492 normalizeCommandValue(data?.command),
493 ];
494 return candidates.find((candidate) => candidate !== null) ?? null;
496​
497function extractToolTitle(payload: Record<string, unknown> | null): string | null {
498 return asTrimmedString(payload?.title);
500​
501function stripTrailingExitCode(value: string): {
502 output: string | null;
503 exitCode?: number | undefined;
504} {
505 const trimmed = value.trim();
506 const match = /^(?<output>[\s\S]*?)(?:\s*<exited with exit code (?<code>\d+)>)\s*$/i.exec(
507 trimmed,
508 );
509 if (!match?.groups) {
510 return {
511 output: trimmed.length > 0 ? trimmed : null,
512 };
513 }
514 const exitCode = Number.parseInt(match.groups.code ?? "", 10);
515 const normalizedOutput = match.groups.output?.trim() ?? "";
516 return {
517 output: normalizedOutput.length > 0 ? normalizedOutput : null,
518 ...(Number.isInteger(exitCode) ? { exitCode } : {}),
519 };
521​
522function extractWorkLogItemType(
523 payload: Record<string, unknown> | null,
524): WorkLogEntry["itemType"] | undefined {
525 if (typeof payload?.itemType === "string" && isToolLifecycleItemType(payload.itemType)) {
526 return payload.itemType;
527 }
528 return undefined;
530​
531function extractWorkLogRequestKind(
532 payload: Record<string, unknown> | null,
533): WorkLogEntry["requestKind"] | undefined {
534 if (
535 payload?.requestKind === "command" ||
536 payload?.requestKind === "file-read" ||
537 payload?.requestKind === "file-change"
538 ) {
539 return payload.requestKind;
540 }
541 return requestKindFromRequestType(payload?.requestType) ?? undefined;
543​
544function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
545 const normalized = asTrimmedString(value);
546 if (!normalized || seen.has(normalized)) {
547 return;
548 }
549 seen.add(normalized);
550 target.push(normalized);
552​
553function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
554 if (depth > 4 || target.length >= 12) {
555 return;
556 }
557 if (Array.isArray(value)) {
558 for (const entry of value) {
559 collectChangedFiles(entry, target, seen, depth + 1);
560 if (target.length >= 12) {
561 return;
562 }
563 }
564 return;
565 }
566​
567 const record = asRecord(value);
568 if (!record) {
569 return;
570 }
571​
572 pushChangedFile(target, seen, record.path);
573 pushChangedFile(target, seen, record.filePath);
574 pushChangedFile(target, seen, record.relativePath);
575 pushChangedFile(target, seen, record.filename);
576 pushChangedFile(target, seen, record.newPath);
577 pushChangedFile(target, seen, record.oldPath);
578​
579 for (const nestedKey of [
580 "item",
581 "result",
582 "input",
583 "data",
584 "changes",
585 "files",
586 "edits",
587 "patch",
588 "patches",
589 "operations",
590 ]) {
591 if (!(nestedKey in record)) {
592 continue;
593 }
594 collectChangedFiles(record[nestedKey], target, seen, depth + 1);
595 if (target.length >= 12) {
596 return;
597 }
598 }
600​
601function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
602 const changedFiles: string[] = [];
603 const seen = new Set<string>();
604 collectChangedFiles(asRecord(payload?.data), changedFiles, seen, 0);
605 return changedFiles;
607​
608function compareActivitiesByOrder(
609 left: OrchestrationThreadActivity,
610 right: OrchestrationThreadActivity,
611): number {
612 if (left.sequence !== undefined && right.sequence !== undefined) {
613 if (left.sequence !== right.sequence) {
614 return left.sequence - right.sequence;
615 }
616 } else if (left.sequence !== undefined) {
617 return 1;
618 } else if (right.sequence !== undefined) {
619 return -1;
620 }
621​
622 return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
624​
625export function hasToolActivityForTurn(
626 activities: ReadonlyArray<OrchestrationThreadActivity>,
627 turnId: TurnId | null | undefined,
628): boolean {
629 if (!turnId) return false;
630 return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
632​
633export function deriveTimelineEntries(
634 messages: ChatMessage[],
635 proposedPlans: ProposedPlan[],
636 workEntries: WorkLogEntry[],
637): TimelineEntry[] {
638 const messageRows: TimelineEntry[] = messages.map((message) => ({
639 id: message.id,
640 kind: "message",
641 createdAt: message.createdAt,
642 message,
643 }));
644 const proposedPlanRows: TimelineEntry[] = proposedPlans.map((proposedPlan) => ({
645 id: proposedPlan.id,
646 kind: "proposed-plan",
647 createdAt: proposedPlan.createdAt,
648 proposedPlan,
649 }));
650 const workRows: TimelineEntry[] = workEntries.map((entry) => ({
651 id: entry.id,
652 kind: "work",
653 createdAt: entry.createdAt,
654 entry,
655 }));
656 return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) =>
657 a.createdAt.localeCompare(b.createdAt),
658 );
660​
661export function inferCheckpointTurnCountByTurnId(
662 summaries: TurnDiffSummary[],
663): Record<TurnId, number> {
664 const sorted = [...summaries].toSorted((a, b) => a.completedAt.localeCompare(b.completedAt));
665 const result: Record<TurnId, number> = {};
666 for (let index = 0; index < sorted.length; index += 1) {
667 const summary = sorted[index];
668 if (!summary) continue;
669 result[summary.turnId] = index + 1;
670 }
671 return result;
673​
674export function derivePhase(session: ThreadSession | null): SessionPhase {
675 if (!session || session.status === "closed") return "disconnected";
676 if (session.status === "connecting") return "connecting";
677 if (session.status === "running") return "running";
678 return "ready";