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

turnFoldReplies.ts

148 lines5.4 KB

1import type { OrchestrationV2TurnItem } from "@t3tools/contracts";
2import { looksLikeInterimNarration } from "@t3tools/shared/orchestrationV2Timeline";
3​
4type AssistantMessagePhase = Extract<
5 OrchestrationV2TurnItem,
6 { readonly type: "assistant_message" }
7>["phase"];
8​
9/** One settled turn in order, reduced to what decides which replies a fold keeps visible. */
10export type TurnFoldReplyEntry =
11 | {
12 readonly kind: "assistant";
13 readonly id: string;
14 readonly text: string;
15 readonly phase?: AssistantMessagePhase;
16 }
17 | { readonly kind: "steer" }
18 | { readonly kind: "question-answer" }
19 | { readonly kind: "interactive-pause" }
20 | { readonly kind: "reasoning" }
21 | { readonly kind: "work"; readonly toolName?: string | undefined };
22​
23type AssistantReply = Extract<TurnFoldReplyEntry, { readonly kind: "assistant" }>;
24​
25const RICH_STRUCTURE_RE = /(?:^#{1,6}\s+\S|^```|^\|.+\|\s*$)/m;
26const LIST_ITEM_RE = /^\s*(?:[-*+]|\d+\.)\s+\S/gm;
27​
28const QUESTION_TOOL_RE = /(?:^|[._:/-])(?:askuserquestion|ask_question)$/i;
29const INTERACTIVE_PAUSE_TOOL_RE = /(?:^|[._:/-])(?:askuserquestion|ask_question|request_secret)$/i;
30// Tools an agent calls to wait or tidy up after it has already answered.
31const HOUSEKEEPING_TOOL_RE =
32 /(?:^|[._:/-])(?:watch_pull_request|unwatch_pull_request|link_pull_requests?|link_issue|t3_background_wait|taskstop|manage_task|t3_preview_close|preview_close|device_close|t3_thread_organize)$/i;
33const MAX_HOUSEKEEPING_TOOLS = 4;
34const MIN_ANSWER_LENGTH = 180;
35​
36function isShortInterimNarration(text: string): boolean {
37 return (
38 text.length < 320 &&
39 !text.includes("\n\n") &&
40 !RICH_STRUCTURE_RE.test(text) &&
41 !text.match(LIST_ITEM_RE) &&
42 looksLikeInterimNarration(text)
43 );
45​
46/** A short sign-off with no headings, code, tables, or real list. */
47function isThinReply(text: string): boolean {
48 return (
49 text.length <= 260 &&
50 !RICH_STRUCTURE_RE.test(text) &&
51 (text.match(LIST_ITEM_RE)?.length ?? 0) < 2
52 );
54​
55const INTERACTIVE_REQUEST_TYPES: ReadonlySet<OrchestrationV2TurnItem["type"]> = new Set([
56 "user_input_request",
57 "approval_request",
58 "secret_request",
59 "link_request",
60 "feedback_request",
61 "handoff_request",
62]);
63​
64/** How a non-reply turn item counts between two replies. Anything unlisted is work. */
65export function turnItemFoldReplyEntry(
66 item: OrchestrationV2TurnItem | undefined,
67): TurnFoldReplyEntry {
68 if (item?.type === "reasoning") return { kind: "reasoning" };
69 if (item !== undefined && INTERACTIVE_REQUEST_TYPES.has(item.type)) {
70 return { kind: "interactive-pause" };
71 }
72 return {
73 kind: "work",
74 toolName: item?.type === "dynamic_tool" ? (item.toolName ?? undefined) : undefined,
75 };
77​
78function toolMatches(entry: TurnFoldReplyEntry, pattern: RegExp): boolean {
79 return entry.kind === "work" && entry.toolName !== undefined && pattern.test(entry.toolName);
81​
82/** The reply reached by walking back from `index` past reasoning and whatever `skip` accepts. */
83function replyBefore(
84 entries: ReadonlyArray<TurnFoldReplyEntry>,
85 index: number,
86 skip: (entry: TurnFoldReplyEntry) => boolean,
87): AssistantReply | null {
88 for (let cursor = index - 1; cursor >= 0; cursor -= 1) {
89 const entry = entries[cursor]!;
90 if (entry.kind === "reasoning" || skip(entry)) continue;
91 return entry.kind === "assistant" ? entry : null;
92 }
93 return null;
95​
96/**
97 * Replies a collapsed turn keeps visible besides its last one: the reply before
98 * an answered question, the reply a steer responded to, and the answer a short
99 * sign-off followed.
100 */
101export function selectRetainedTurnFoldAssistantIds(
102 entries: ReadonlyArray<TurnFoldReplyEntry>,
103): ReadonlySet<string> {
104 const retained = new Set<string>();
105 for (const [index, entry] of entries.entries()) {
106 if (entry.kind === "question-answer") {
107 const reply = replyBefore(entries, index, (skipped) =>
108 toolMatches(skipped, QUESTION_TOOL_RE),
109 );
110 if (reply !== null && reply.phase !== "commentary") retained.add(reply.id);
111 }
112 if (entry.kind === "steer") {
113 let crossedPause = false;
114 const reply = replyBefore(entries, index, (skipped) => {
115 const pause =
116 skipped.kind === "interactive-pause" ||
117 skipped.kind === "question-answer" ||
118 toolMatches(skipped, INTERACTIVE_PAUSE_TOOL_RE);
119 crossedPause ||= pause;
120 return pause;
121 });
122 if (reply === null || reply.phase === "commentary") continue;
123 const text = reply.text.trim();
124 if (crossedPause || (text.length >= 120 && !isShortInterimNarration(text))) {
125 retained.add(reply.id);
126 }
127 }
128 }
129​
130 const terminalIndex = entries.findLastIndex((entry) => entry.kind === "assistant");
131 const terminal = entries[terminalIndex];
132 if (terminal?.kind !== "assistant") return retained;
133 const terminalText = terminal.text.trim();
134 if (!isThinReply(terminalText)) return retained;
135 let housekeepingTools = 0;
136 const reply = replyBefore(entries, terminalIndex, (skipped) => {
137 if (skipped.kind === "assistant") return skipped.text.trim().length < MIN_ANSWER_LENGTH;
138 if (!toolMatches(skipped, HOUSEKEEPING_TOOL_RE)) return false;
139 housekeepingTools += 1;
140 return housekeepingTools <= MAX_HOUSEKEEPING_TOOLS;
141 });
142 if (reply === null || reply.phase !== undefined) return retained;
143 const text = reply.text.trim();
144 if (text.length >= terminalText.length * 1.5 && !isShortInterimNarration(text)) {
145 retained.add(reply.id);
146 }
147 return retained;