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