@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 578 lines 19.4 KB
Raw
1 import type {
2 EventId,
3 MessageId,
4 ModelSelection,
5 NodeId,
6 OrchestrationV2AppThread,
7 OrchestrationV2Actor,
8 OrchestrationV2ConversationMessage,
9 OrchestrationV2CreationSource,
10 OrchestrationV2DomainEvent,
11 OrchestrationV2ProviderRef,
12 OrchestrationV2Run,
13 OrchestrationV2ThreadProjection,
14 OrchestrationV2TurnItem,
15 ProviderInstanceId,
16 ProviderThreadId,
17 ProviderTurnId,
18 ThreadId,
19 TurnItemId,
20 } from "@t3tools/contracts";
21 import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
22 import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
23 import * as DateTime from "effect/DateTime";
24 import * as Effect from "effect/Effect";
25 import { derive } from "./IdAllocator.ts";
26 import { isOrchestrationV2WorkActive, latestProviderTurnForAttempt } from "@t3tools/contracts";
27
28 function trimmed(value: string | null | undefined): string | undefined {
29 const result = value?.trim();
30 return result && result.length > 0 ? result : undefined;
31 }
32
33 export function subagentThreadTitle(input: {
34 readonly parentTitle: string;
35 readonly title?: string | null;
36 readonly prompt: string;
37 readonly ordinal: number;
38 }): string {
39 const detail = trimmed(input.title) ?? trimmed(input.prompt);
40 if (detail === undefined) {
41 return `${input.parentTitle} subagent ${input.ordinal}`;
42 }
43 if (detail.length <= 72) return detail;
44 let end = 69;
45 const previous = detail.charCodeAt(end - 1);
46 const next = detail.charCodeAt(end);
47 if (previous >= 0xd800 && previous <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
48 end -= 1;
49 }
50 return `${detail.slice(0, end)}...`;
51 }
52
53 export function makeSubagentChildThread(input: {
54 readonly parentThread: OrchestrationV2AppThread;
55 readonly childThreadId: ThreadId;
56 readonly parentNodeId: NodeId;
57 readonly activeProviderThreadId: ProviderThreadId | null;
58 readonly providerInstanceId: ProviderInstanceId;
59 readonly modelSelection: ModelSelection;
60 readonly title: string;
61 readonly now: DateTime.Utc;
62 readonly createdBy: OrchestrationV2Actor;
63 readonly creationSource: OrchestrationV2CreationSource;
64 }): OrchestrationV2AppThread {
65 // The remote parent delegated the parent thread, not its subagents.
66 const { delegatedFrom: _delegatedFrom, ...inherited } = input.parentThread;
67 return {
68 ...inherited,
69 createdBy: input.createdBy,
70 creationSource: input.creationSource,
71 id: input.childThreadId,
72 title: input.title,
73 titleRegeneration: null,
74 titleRenamed: false,
75 linkedPullRequest: null,
76 pullRequests: [],
77 historyOrigin: undefined,
78 providerInstanceId: input.providerInstanceId,
79 modelSelection: input.modelSelection,
80 activeProviderThreadId: input.activeProviderThreadId,
81 lineage: {
82 parentThreadId: input.parentThread.id,
83 relationshipToParent: "subagent",
84 rootThreadId: input.parentThread.lineage.rootThreadId,
85 },
86 forkedFrom: {
87 type: "node",
88 nodeId: input.parentNodeId,
89 },
90 createdAt: input.now,
91 updatedAt: input.now,
92 archivedAt: null,
93 settledOverride: null,
94 settledAt: null,
95 snoozedUntil: null,
96 snoozedAt: null,
97 pinnedAt: null,
98 pinOrderKey: null,
99 autoSettleDisabledAt: null,
100 // A guest link belongs to the thread it was made for.
101 guestShare: null,
102 lastVisitedAt: null,
103 deletedAt: null,
104 };
105 }
106
107 export function makeSubagentConversationArtifacts(input: {
108 readonly messageId: MessageId;
109 readonly senderThreadId?: ThreadId;
110 readonly turnItemId: TurnItemId;
111 readonly threadId: ThreadId;
112 readonly rootNodeId: NodeId;
113 readonly providerThreadId: ProviderThreadId | null;
114 readonly providerTurnId: ProviderTurnId | null;
115 readonly nativeItemRef: OrchestrationV2ProviderRef | null;
116 readonly role: "user" | "assistant";
117 readonly text: string;
118 readonly workflowScript?: boolean;
119 readonly ordinal: number;
120 readonly now: DateTime.Utc;
121 }): {
122 readonly message: OrchestrationV2ConversationMessage;
123 readonly turnItem: OrchestrationV2TurnItem;
124 } {
125 const message: OrchestrationV2ConversationMessage = {
126 createdBy: "agent",
127 creationSource: "provider",
128 id: input.messageId,
129 threadId: input.threadId,
130 runId: null,
131 nodeId: input.rootNodeId,
132 role: input.role,
133 ...(input.role === "user" && input.senderThreadId !== undefined
134 ? { senderThreadId: input.senderThreadId }
135 : {}),
136 ...(input.role === "user" && input.workflowScript !== undefined
137 ? { workflowScript: input.workflowScript }
138 : {}),
139 text: input.text,
140 attachments: [],
141 streaming: false,
142 createdAt: input.now,
143 updatedAt: input.now,
144 };
145 const base = {
146 id: input.turnItemId,
147 threadId: input.threadId,
148 runId: null,
149 nodeId: input.rootNodeId,
150 providerThreadId: input.providerThreadId,
151 providerTurnId: input.providerTurnId,
152 nativeItemRef: input.nativeItemRef,
153 parentItemId: null,
154 ordinal: input.ordinal,
155 status: "completed" as const,
156 title: null,
157 startedAt: input.now,
158 completedAt: input.now,
159 updatedAt: input.now,
160 messageId: input.messageId,
161 text: input.text,
162 };
163 const turnItem: OrchestrationV2TurnItem =
164 input.role === "user"
165 ? {
166 ...base,
167 createdBy: "agent",
168 creationSource: "provider",
169 type: "user_message",
170 ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }),
171 ...(input.workflowScript === undefined ? {} : { workflowScript: input.workflowScript }),
172 inputIntent: "turn_start",
173 attachments: [],
174 }
175 : {
176 ...base,
177 type: "assistant_message",
178 streaming: false,
179 };
180 return { message, turnItem };
181 }
182
183 /** A delegated result, led by a note when the provider reported running another model than requested. */
184 export function withExecutedModelNote(
185 result: string,
186 requestedModel: string,
187 executedModel: string | null | undefined,
188 ): string {
189 return executedModel == null || executedModel === requestedModel
190 ? result
191 : `Requested model ${requestedModel}; the provider reported running ${executedModel}.\n\n${result}`;
192 }
193
194 /** Run signal of the notice that carries a provider's stop reason on a completed run. */
195 export const PROVIDER_STOP_REASON_SIGNAL = "provider-stop-reason";
196
197 function stopNotice(
198 projection: Pick<OrchestrationV2ThreadProjection, "turnItems">,
199 run: OrchestrationV2Run,
200 ): string | undefined {
201 const id = derive.runSignalTurnItem({ runId: run.id, signal: PROVIDER_STOP_REASON_SIGNAL });
202 const notice = projection.turnItems.find((item) => item.id === id);
203 return notice?.type === "system_notice" ? notice.message : undefined;
204 }
205
206 type MonitorNotice = Pick<OrchestrationV2ConversationMessage, "runId" | "notification">;
207
208 /** Runs that only acknowledge a monitor update are never a task's work. */
209 export function monitorUpdateRunIds(messages: ReadonlyArray<MonitorNotice>) {
210 return new Set(
211 messages
212 .filter(
213 (message) =>
214 message.notification?.source.kind === "monitor" &&
215 message.notification.outcome === "updated",
216 )
217 .map((message) => message.runId),
218 );
219 }
220
221 /**
222 * The same task's completed runs before `run`, latest first: where its report is when `run`
223 * completed without saying anything. Ends at another task's run or at any other outcome.
224 */
225 export function delegatedTaskReportRuns(
226 projection: {
227 readonly runs: ReadonlyArray<OrchestrationV2Run>;
228 readonly messages: ReadonlyArray<MonitorNotice>;
229 },
230 run: OrchestrationV2Run,
231 ): ReadonlyArray<OrchestrationV2Run> {
232 if (run.status !== "completed") return [];
233 const monitorRuns = monitorUpdateRunIds(projection.messages);
234 const earlier = projection.runs
235 .filter(
236 (candidate) =>
237 candidate.id !== run.id &&
238 candidate.startedAt !== null &&
239 candidate.status !== "rolled_back" &&
240 !monitorRuns.has(candidate.id) &&
241 runRanAfter(run, candidate),
242 )
243 .toSorted((a, b) => (runRanAfter(a, b) ? -1 : 1));
244 const end = earlier.findIndex(
245 (candidate) =>
246 candidate.status !== "completed" || candidate.delegatedTaskId !== run.delegatedTaskId,
247 );
248 return end === -1 ? earlier : earlier.slice(0, end);
249 }
250
251 /**
252 * `runs` scopes where a run that completed without saying anything finds its report, see
253 * `delegatedTaskReportRuns`. The projection must hold the assistant records of every run given.
254 */
255 export function subagentResultForRun(
256 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems" | "providerTurns"> & {
257 readonly runs?: ReadonlyArray<OrchestrationV2Run>;
258 },
259 run: OrchestrationV2Run,
260 ) {
261 const result = resultOfRun(projection, run);
262 if (
263 run.status !== "completed" ||
264 result.messageId !== null ||
265 result.turnItemId !== null ||
266 stopNotice(projection, run) !== undefined
267 )
268 return result;
269 for (const earlier of delegatedTaskReportRuns(
270 { runs: projection.runs ?? [], messages: projection.messages },
271 run,
272 )) {
273 const report = resultOfRun(projection, earlier);
274 if (report.messageId !== null || report.turnItemId !== null) return report;
275 }
276 return result;
277 }
278
279 function resultOfRun(
280 projection: Pick<OrchestrationV2ThreadProjection, "messages" | "turnItems" | "providerTurns">,
281 run: OrchestrationV2Run,
282 ): {
283 readonly text: string;
284 readonly messageId: OrchestrationV2ConversationMessage["id"] | null;
285 readonly turnItemId: OrchestrationV2TurnItem["id"] | null;
286 } {
287 const turnItem =
288 projection.turnItems
289 .filter(
290 (
291 candidate,
292 ): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "assistant_message" }> =>
293 candidate.runId === run.id &&
294 candidate.type === "assistant_message" &&
295 candidate.text.trim().length > 0,
296 )
297 .toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
298 const messages = projection.messages.filter(
299 (candidate) =>
300 candidate.runId === run.id &&
301 candidate.role === "assistant" &&
302 candidate.text.trim().length > 0,
303 );
304 // Prefer turn item order; providers can finalize messages with identical timestamps.
305 const message =
306 messages.find((candidate) => candidate.id === turnItem?.messageId) ??
307 messages.toSorted(
308 (left, right) =>
309 DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt) ||
310 DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
311 )[0] ??
312 null;
313 const failure =
314 run.status === "failed"
315 ? projection.turnItems
316 .filter((item) => item.runId === run.id && item.type === "error")
317 .toSorted((left, right) => right.ordinal - left.ordinal)[0]
318 : undefined;
319 const reportBeforeFailure =
320 failure !== undefined && turnItem !== null && turnItem.ordinal < failure.ordinal
321 ? (message?.text ?? turnItem.text)
322 : undefined;
323 const text =
324 (failure?.type === "error"
325 ? reportBeforeFailure === undefined
326 ? failure.failure.message
327 : `${failure.failure.message}\n\nLast assistant message before the run failed:\n\n${reportBeforeFailure}`
328 : undefined) ??
329 message?.text ??
330 turnItem?.text ??
331 (run.status === "completed"
332 ? ["Child task completed without an assistant result.", stopNotice(projection, run)]
333 .filter((part) => part !== undefined)
334 .join("\n\n")
335 : `Child task ended with status ${run.status}.`);
336 const executedModel = latestProviderTurnForAttempt(
337 projection.providerTurns,
338 run.activeAttemptId,
339 )?.model;
340 return {
341 text:
342 executedModel === undefined
343 ? text
344 : withExecutedModelNote(text, run.modelSelection.model, executedModel),
345 messageId: failure === undefined ? (message?.id ?? turnItem?.messageId ?? null) : null,
346 turnItemId: failure?.id ?? turnItem?.id ?? null,
347 };
348 }
349
350 export function subagentHoldsCompletion(
351 task: Pick<OrchestrationV2ThreadProjection["subagents"][number], "status" | "completionDelivery">,
352 ): boolean {
353 return (
354 isOrchestrationV2WorkActive(task.status) ||
355 // Publishing a child's result precedes scheduling its parent's wake.
356 // The parent still owes that follow-up even between those transactions.
357 (task.status !== "idle" &&
358 (task.completionDelivery?.state === "pending" ||
359 task.completionDelivery?.state === "claimed"))
360 );
361 }
362
363 export function delegatedTaskProgress(projection: {
364 readonly runs: OrchestrationV2ThreadProjection["runs"];
365 readonly messages: ReadonlyArray<
366 Pick<OrchestrationV2ConversationMessage, "runId" | "notification">
367 >;
368 readonly subagents: ReadonlyArray<
369 Pick<OrchestrationV2ThreadProjection["subagents"][number], "status" | "completionDelivery">
370 >;
371 readonly providerThreads: ReadonlyArray<
372 Pick<OrchestrationV2ThreadProjection["providerThreads"][number], "pendingBackgroundTasks">
373 >;
374 }) {
375 const terminal = (status: string) =>
376 ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes(status);
377 const monitorRuns = monitorUpdateRunIds(projection.messages);
378 const workRuns = projection.runs.filter(
379 (run) => !monitorRuns.has(run.id) && run.status !== "rolled_back",
380 );
381 const active = workRuns.some(
382 (run) => !terminal(run.status) && !(run.status === "queued" && run.queueHeld === true),
383 );
384 const children =
385 projection.subagents.some(subagentHoldsCompletion) ||
386 projection.providerThreads.some((thread) =>
387 backgroundWorkHoldsCompletion(thread.pendingBackgroundTasks ?? []),
388 );
389 const resultRun = workRuns
390 .filter((run) => terminal(run.status) && (run.startedAt !== null || run.ordinal === 1))
391 .toSorted((a, b) => (runRanAfter(a, b) ? -1 : runRanAfter(b, a) ? 1 : 0))[0];
392 return {
393 state:
394 active || resultRun === undefined
395 ? ("working" as const)
396 : children
397 ? ("waiting_for_children" as const)
398 : ("result_available" as const),
399 resultRun,
400 };
401 }
402
403 function writtenIds(
404 emitted: ReadonlyArray<OrchestrationV2DomainEvent>,
405 type: "subagent.updated" | "node.updated" | "turn-item.updated" | "provider-turn.updated",
406 ): ReadonlySet<string> {
407 return new Set(emitted.flatMap((event) => (event.type === type ? [event.payload.id] : [])));
408 }
409
410 export const endOrphanedNativeSubagent = Effect.fn("subagentProjection.endOrphanedNativeSubagent")(
411 function* <E>(input: {
412 readonly projection: Pick<OrchestrationV2ThreadProjection, "nodes" | "subagents" | "turnItems">;
413 readonly subagentId: NodeId;
414 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
415 readonly completedAt?: DateTime.Utc;
416 readonly result?: string | null;
417 readonly now: DateTime.Utc;
418 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
419 readonly allocateEventId: () => Effect.Effect<EventId, E>;
420 }) {
421 const { now, status, subagentId, completedAt = now } = input;
422 const subagent = input.projection.subagents.find((entry) => entry.id === subagentId);
423 if (subagent?.origin !== "provider_native") return [];
424 const node = input.projection.nodes.find((entry) => entry.id === subagentId);
425 const item = input.projection.turnItems.find(
426 (entry) => entry.type === "subagent" && entry.subagentId === subagentId,
427 );
428 const scope = {
429 threadId: subagent.threadId,
430 ...(subagent.runId === null ? {} : { runId: subagent.runId }),
431 nodeId: subagentId,
432 providerInstanceId: subagent.providerInstanceId,
433 occurredAt: now,
434 };
435 const events: Array<OrchestrationV2DomainEvent> = [];
436 if (
437 isOrchestrationV2WorkActive(subagent.status) &&
438 !writtenIds(input.emitted, "subagent.updated").has(subagentId)
439 ) {
440 events.push({
441 ...scope,
442 id: yield* input.allocateEventId(),
443 type: "subagent.updated",
444 driver: subagent.driver,
445 payload: {
446 ...subagent,
447 status,
448 completedAt,
449 updatedAt: now,
450 ...(input.result === undefined ? {} : { result: input.result }),
451 },
452 });
453 }
454 if (
455 node !== undefined &&
456 isOrchestrationV2WorkActive(node.status) &&
457 !writtenIds(input.emitted, "node.updated").has(subagentId)
458 ) {
459 events.push({
460 ...scope,
461 id: yield* input.allocateEventId(),
462 type: "node.updated",
463 payload: { ...node, status, completedAt },
464 });
465 }
466 if (
467 item !== undefined &&
468 isOrchestrationV2WorkActive(item.status) &&
469 !writtenIds(input.emitted, "turn-item.updated").has(item.id)
470 ) {
471 events.push({
472 ...scope,
473 id: yield* input.allocateEventId(),
474 type: "turn-item.updated",
475 payload: {
476 ...item,
477 status,
478 completedAt,
479 updatedAt: now,
480 ...(input.result === undefined ? {} : { result: input.result }),
481 },
482 });
483 }
484 return events;
485 },
486 );
487
488 export const endRunlessRootTurns = Effect.fn("subagentProjection.endRunlessRootTurns")(function* <
489 E,
490 >(input: {
491 readonly threadId: ThreadId;
492 readonly providerInstanceId: ProviderInstanceId;
493 readonly projection: Pick<
494 OrchestrationV2ThreadProjection,
495 "nodes" | "providerTurns" | "turnItems"
496 >;
497 readonly status: "completed" | "failed" | "interrupted" | "cancelled";
498 readonly completedAt?: DateTime.Utc;
499 readonly now: DateTime.Utc;
500 readonly emitted: ReadonlyArray<OrchestrationV2DomainEvent>;
501 readonly allocateEventId: () => Effect.Effect<EventId, E>;
502 }) {
503 const { now, status, completedAt = now } = input;
504 const endedNodeIds = writtenIds(input.emitted, "node.updated");
505 const endedItemIds = writtenIds(input.emitted, "turn-item.updated");
506 const endedProviderTurnIds = writtenIds(input.emitted, "provider-turn.updated");
507 const scope = {
508 threadId: input.threadId,
509 providerInstanceId: input.providerInstanceId,
510 occurredAt: now,
511 };
512 const events: Array<OrchestrationV2DomainEvent> = [];
513 for (const node of input.projection.nodes) {
514 if (
515 node.kind !== "root_turn" ||
516 node.runId !== null ||
517 !isOrchestrationV2WorkActive(node.status)
518 ) {
519 continue;
520 }
521 if (!endedNodeIds.has(node.id)) {
522 events.push({
523 ...scope,
524 id: yield* input.allocateEventId(),
525 type: "node.updated",
526 nodeId: node.id,
527 payload: { ...node, status, completedAt },
528 });
529 }
530 for (const item of input.projection.turnItems) {
531 if (
532 item.nodeId !== node.id ||
533 item.runId !== null ||
534 !isOrchestrationV2WorkActive(item.status) ||
535 endedItemIds.has(item.id)
536 ) {
537 continue;
538 }
539 events.push({
540 ...scope,
541 id: yield* input.allocateEventId(),
542 type: "turn-item.updated",
543 nodeId: node.id,
544 payload: {
545 ...item,
546 status:
547 status === "completed" &&
548 (item.type === "command_execution" || item.type === "dynamic_tool")
549 ? "failed"
550 : status,
551 completedAt,
552 updatedAt: now,
553 ...(item.type === "reasoning" || item.type === "assistant_message"
554 ? { streaming: false }
555 : {}),
556 },
557 });
558 }
559 for (const providerTurn of input.projection.providerTurns) {
560 if (
561 providerTurn.nodeId !== node.id ||
562 providerTurn.runAttemptId !== null ||
563 !isOrchestrationV2WorkActive(providerTurn.status) ||
564 endedProviderTurnIds.has(providerTurn.id)
565 ) {
566 continue;
567 }
568 events.push({
569 ...scope,
570 id: yield* input.allocateEventId(),
571 type: "provider-turn.updated",
572 nodeId: node.id,
573 payload: { ...providerTurn, status, completedAt },
574 });
575 }
576 }
577 return events;
578 });