@sayknow-cli/coding-agent 0.7.6 → 0.7.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Automatic, same-model resume of an interrupted model step.
3
+ *
4
+ * A step interrupted by a process restart, or by a transient failure after tools ran
5
+ * or part of the answer was shown (managed fallback chains included), resumes at most once per user turn without a
6
+ * new user message, pinned to the interrupted model. Calls whose outcome was never observed are answered with an error
7
+ * placeholder and never re-run; while such calls exist the resumed turn may only
8
+ * use built-in read-only tools.
9
+ */
10
+ import type { AgentMessage, AgentTool } from "@sayknow-cli/agent-core";
11
+ import type { AssistantMessage, ToolCall } from "@sayknow-cli/ai";
12
+ import { unwrapProxiedTool } from "../extensibility/tool-proxy";
13
+ import { AstGrepTool } from "../tools/ast-grep";
14
+ import { FindTool } from "../tools/find";
15
+ import { LocateTool } from "../tools/locate";
16
+ import { ReadTool } from "../tools/read";
17
+ import { SearchTool } from "../tools/search";
18
+
19
+ export const AUTO_RESUME_MARKER_CUSTOM_TYPE = "auto_resume_marker";
20
+
21
+ /** Requests and time a restart resume may spend; the interrupted step's own budget is unknown. */
22
+ export const RESTART_RESUME_MAX_REQUESTS = 2;
23
+ export const RESTART_RESUME_WINDOW_MS = 120_000;
24
+
25
+ export const INTERRUPTED_TOOL_RESULT_TEXT =
26
+ "Interrupted before its outcome was observed; it was not re-run. Check the current state with read-only tools before assuming it either happened or did not.";
27
+
28
+ export const AUTO_RESUME_RESTRICTED_PROMPT =
29
+ "The previous step was interrupted and some tool calls have unknown outcomes; they were not re-run. Only read-only tools are available now. Verify the current state, then finish your answer or tell the user what still needs to be done. Do not repeat the interrupted actions.";
30
+
31
+ export const AUTO_RESUME_FULL_PROMPT =
32
+ "The previous step was interrupted before it finished. Everything above is preserved exactly as the user saw it. Continue from where it stopped: do not repeat any of it and do not redo completed work.";
33
+
34
+ export type AutoResumeTrigger = "restart" | "interrupted";
35
+ export type AutoResumeMode = "full" | "restricted";
36
+
37
+ export type AutoResumePauseReason =
38
+ | "disabled"
39
+ | "already_resumed"
40
+ | "uncertain_upstream"
41
+ | "unsafe_tail"
42
+ | "budget_exhausted"
43
+ | "user_input_pending"
44
+ | "selector_unavailable"
45
+ | "no_restart_safe_tools"
46
+ | "not_interrupted";
47
+
48
+ export type AutoResumeDecision =
49
+ | { type: "pause"; reason: AutoResumePauseReason }
50
+ | { type: "resume"; mode: AutoResumeMode; interruptedCalls: ToolCall[] };
51
+
52
+ export interface AutoResumeMarker {
53
+ version: 1;
54
+ trigger: AutoResumeTrigger;
55
+ mode: AutoResumeMode;
56
+ selector: string;
57
+ interruptedCallIds: string[];
58
+ }
59
+
60
+ /** Built-in tools whose execution has no side effects and may run again after a restart. */
61
+ const RESTART_SAFE_TOOL_CLASSES = [ReadTool, SearchTool, FindTool, AstGrepTool, LocateTool] as const;
62
+
63
+ function wireName(tool: AgentTool): string {
64
+ return tool.customWireName ?? tool.name;
65
+ }
66
+
67
+ /**
68
+ * Restart-safe means: an instance of a built-in read-only tool class (seen through
69
+ * extension/hook interception wrappers) whose wire name is unique among the selected
70
+ * tools. Name-alikes from MCP, extensions or custom tools never qualify, and a
71
+ * shadowed wire name disqualifies every holder.
72
+ */
73
+ export function isRestartSafeTool(tool: AgentTool, selectedTools: readonly AgentTool[]): boolean {
74
+ const root = unwrapProxiedTool(tool);
75
+ if (!RESTART_SAFE_TOOL_CLASSES.some(toolClass => root instanceof toolClass)) return false;
76
+ const name = wireName(tool);
77
+ let holders = 0;
78
+ for (const candidate of selectedTools) {
79
+ if (candidate.name === name || wireName(candidate) === name) holders++;
80
+ }
81
+ return holders === 1;
82
+ }
83
+
84
+ /** Marks an in-memory pairing result the SDK adds on resume; it observed no outcome. */
85
+ export const SYNTHESIZED_ON_RESUME_DETAIL = "synthesizedOnResume";
86
+
87
+ /** A pairing result synthesized on resume: the call's real outcome is unknown. */
88
+ export function isSynthesizedResumeResult(message: AgentMessage): boolean {
89
+ if (message.role !== "toolResult") return false;
90
+ const details = message.details as Record<string, unknown> | undefined;
91
+ return details?.[SYNTHESIZED_ON_RESUME_DETAIL] === true;
92
+ }
93
+
94
+ /** Tool calls of the current user turn whose outcome no result in the transcript observed. */
95
+ export function findInterruptedToolCalls(messages: readonly AgentMessage[]): ToolCall[] {
96
+ const start = messages.findLastIndex(message => message.role === "user") + 1;
97
+ const answered = new Set<string>();
98
+ for (let i = start; i < messages.length; i++) {
99
+ const message = messages[i];
100
+ if (message.role === "toolResult" && !isSynthesizedResumeResult(message)) answered.add(message.toolCallId);
101
+ }
102
+ const calls: ToolCall[] = [];
103
+ for (let i = start; i < messages.length; i++) {
104
+ const message = messages[i];
105
+ if (message.role !== "assistant") continue;
106
+ for (const block of message.content) {
107
+ if (block.type === "toolCall" && !answered.has(block.id)) calls.push(block);
108
+ }
109
+ }
110
+ return calls;
111
+ }
112
+
113
+ /**
114
+ * Tails that cannot be resumed safely: a failed step holding private signed reasoning
115
+ * or tool calls (possibly cut off mid-arguments), a call without an id, or unanswered
116
+ * calls whose results could no longer be placed directly after their assistant.
117
+ */
118
+ function hasUnsafeAssistantTail(messages: readonly AgentMessage[]): boolean {
119
+ const assistantIndex = messages.findLastIndex(message => message.role === "assistant");
120
+ // Only the current turn matters: an earlier turn's failure was already settled.
121
+ if (assistantIndex === -1 || assistantIndex < messages.findLastIndex(message => message.role === "user"))
122
+ return false;
123
+ const assistant = messages[assistantIndex] as AssistantMessage;
124
+ if (assistant.stopReason === "error" || assistant.stopReason === "aborted") {
125
+ if (
126
+ assistant.content.some(
127
+ block => block.type === "thinking" || block.type === "redactedThinking" || block.type === "toolCall",
128
+ )
129
+ )
130
+ return true;
131
+ }
132
+ const interrupted = findInterruptedToolCalls(messages);
133
+ if (interrupted.length === 0) return false;
134
+ if (interrupted.some(call => call.id.trim().length === 0)) return true;
135
+ const tailCallIds = new Set(assistant.content.flatMap(block => (block.type === "toolCall" ? [block.id] : [])));
136
+ if (interrupted.some(call => !tailCallIds.has(call.id))) return true;
137
+ return messages.slice(assistantIndex + 1).some(message => message.role !== "toolResult");
138
+ }
139
+
140
+ /** The trailing failed assistant shows a text prefix the user already saw. */
141
+ export function hasVisibleFailedPrefix(messages: readonly AgentMessage[]): boolean {
142
+ const assistantIndex = messages.findLastIndex(message => message.role === "assistant");
143
+ if (assistantIndex === -1 || assistantIndex < messages.findLastIndex(message => message.role === "user"))
144
+ return false;
145
+ const assistant = messages[assistantIndex] as AssistantMessage;
146
+ if (assistant.stopReason !== "error" && assistant.stopReason !== "aborted") return false;
147
+ return assistant.content.some(block => block.type === "text" && block.text.length > 0);
148
+ }
149
+
150
+ export interface AutoResumePolicyInput {
151
+ enabled: boolean;
152
+ trigger: AutoResumeTrigger;
153
+ /** Transcript the resume would be sent with. */
154
+ messages: readonly AgentMessage[];
155
+ /** An auto-resume marker exists after the last user message. */
156
+ resumedThisTurn: boolean;
157
+ /** Remote work with an unobservable outcome happened in the interrupted step. */
158
+ uncertainUpstream: boolean;
159
+ /** The provider transport executes work remotely (Cursor, pi-native). */
160
+ opaqueTransport: boolean;
161
+ /** The budget the resume would spend can still admit a request. */
162
+ budgetAdmits: boolean;
163
+ /** A user message, steer or follow-up is queued. */
164
+ userInputPending: boolean;
165
+ /** The interrupted step's selector still resolves to the current model. */
166
+ selectorAvailable: boolean;
167
+ /** The current serializer projects a failed plain-text prefix faithfully. */
168
+ prefixReplayable: boolean;
169
+ /** Currently selected tools. */
170
+ selectedTools: readonly AgentTool[];
171
+ }
172
+
173
+ /** Single decision point for every automatic resume. */
174
+ export function resolveAutoResumePolicy(input: AutoResumePolicyInput): AutoResumeDecision {
175
+ if (!input.enabled) return { type: "pause", reason: "disabled" };
176
+ if (input.resumedThisTurn) return { type: "pause", reason: "already_resumed" };
177
+ if (input.uncertainUpstream || input.opaqueTransport) return { type: "pause", reason: "uncertain_upstream" };
178
+ if (input.userInputPending) return { type: "pause", reason: "user_input_pending" };
179
+ if (!input.selectorAvailable) return { type: "pause", reason: "selector_unavailable" };
180
+ if (!input.budgetAdmits) return { type: "pause", reason: "budget_exhausted" };
181
+ if (hasUnsafeAssistantTail(input.messages)) return { type: "pause", reason: "unsafe_tail" };
182
+ if (hasVisibleFailedPrefix(input.messages) && !input.prefixReplayable)
183
+ return { type: "pause", reason: "unsafe_tail" };
184
+ const tail = input.messages.at(-1);
185
+ if (!tail) return { type: "pause", reason: "not_interrupted" };
186
+ // Only a restart can find a user message whose request never settled.
187
+ if (tail.role === "user") {
188
+ return input.trigger === "restart"
189
+ ? { type: "resume", mode: "full", interruptedCalls: [] }
190
+ : { type: "pause", reason: "not_interrupted" };
191
+ }
192
+ // An answer that already finished (its checkpoint write was simply lost) is not resumed.
193
+ if (tail.role === "assistant" && tail.stopReason !== "error" && tail.stopReason !== "aborted") {
194
+ const settled = !tail.content.some(block => block.type === "toolCall");
195
+ if (settled) return { type: "pause", reason: "not_interrupted" };
196
+ }
197
+ const interruptedCalls = findInterruptedToolCalls(input.messages);
198
+ if (interruptedCalls.length === 0) return { type: "resume", mode: "full", interruptedCalls };
199
+ if (!input.selectedTools.some(tool => isRestartSafeTool(tool, input.selectedTools))) {
200
+ return { type: "pause", reason: "no_restart_safe_tools" };
201
+ }
202
+ return { type: "resume", mode: "restricted", interruptedCalls };
203
+ }
204
+
205
+ /** Whether an auto-resume marker was written after the last user message of `entries`. */
206
+ export function hasAutoResumeMarkerSinceLastUser(
207
+ entries: readonly { type: string; customType?: string; message?: { role: string } }[],
208
+ ): boolean {
209
+ for (let i = entries.length - 1; i >= 0; i--) {
210
+ const entry = entries[i];
211
+ if (entry.type === "message" && entry.message?.role === "user") return false;
212
+ if (entry.type === "custom" && entry.customType === AUTO_RESUME_MARKER_CUSTOM_TYPE) return true;
213
+ }
214
+ return false;
215
+ }
@@ -43,6 +43,13 @@ export class FallbackChainController {
43
43
  #restoredEntryIndices = new Set<number>();
44
44
  skips: Array<{ selector: string; reason: string }> = [];
45
45
  exhaustedForTurn = false;
46
+ /**
47
+ * When true, the session's shared same-model recovery budget (bounded wire
48
+ * count and deadline) owns transient failures instead of the per-entry
49
+ * attempt cap. Set only while `fallback.maxAttempts` is not explicitly
50
+ * configured; quota and auth keep their per-entry chain semantics.
51
+ */
52
+ sessionBudgetOwnsTransient = false;
46
53
 
47
54
  constructor(chain: ConfiguredFallbackChain, maxAttempts: number) {
48
55
  if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
@@ -133,6 +140,14 @@ export class FallbackChainController {
133
140
  }
134
141
  this.#attemptStarted = false;
135
142
  this.tried.push({ selector, triggerClass, reason });
143
+ if (this.sessionBudgetOwnsTransient && (triggerClass === "server" || triggerClass === "rate_limit")) {
144
+ // Transient: the session's shared request budget admits or stops the next
145
+ // same-model request. It must not consume the chain budget reserved for
146
+ // quota/auth advancement, so this attempt is not charged here.
147
+ this.attemptsUsed = Math.max(0, this.attemptsUsed - 1);
148
+ this.#totalAttemptsUsed = Math.max(0, this.#totalAttemptsUsed - 1);
149
+ return "retry";
150
+ }
136
151
  if (this.#totalAttemptsUsed >= this.#maxTotalAttempts()) {
137
152
  this.activeIndex = this.chain.entries.length;
138
153
  this.exhaustedForTurn = true;
@@ -101,6 +101,66 @@ export interface SkillPromptDetails {
101
101
  * (fallback error emission) read it via `isSilentAbort`. */
102
102
  export const SILENT_ABORT_MARKER = "__skc.silent_abort__";
103
103
 
104
+ /** Custom message type of the hidden instruction that resumes an interrupted visible answer. */
105
+ export const VISIBLE_CONTINUATION_CUSTOM_TYPE = "stream-continuation";
106
+ /** Hidden instruction that drives an automatic resume of an interrupted step. */
107
+ export const AUTO_RESUME_CUSTOM_TYPE = "auto-resume";
108
+
109
+ /**
110
+ * The assistant messages that together form one visible answer: a preserved prefix
111
+ * interrupted mid-stream and each same-step continuation that resumed it. Returns
112
+ * `[assistant]` when the message did not resume an interrupted answer.
113
+ */
114
+ export function getVisibleAnswerChain(
115
+ messages: readonly ({ role: string; customType?: string } | AssistantMessage)[],
116
+ assistant: AssistantMessage,
117
+ ): AssistantMessage[] {
118
+ let index = messages.lastIndexOf(assistant);
119
+ if (index < 0) return [assistant];
120
+ const chain = [assistant];
121
+ while (index >= 2) {
122
+ const instruction = messages[index - 1];
123
+ const prefix = messages[index - 2];
124
+ if (instruction.role !== "custom" || !("customType" in instruction)) break;
125
+ if (instruction.customType !== VISIBLE_CONTINUATION_CUSTOM_TYPE) break;
126
+ if (!isAssistantMessage(prefix)) break;
127
+ chain.unshift(prefix);
128
+ index -= 2;
129
+ }
130
+ return chain;
131
+ }
132
+
133
+ /**
134
+ * Text of the last visible answer on a persisted branch, including the preserved
135
+ * prefix of a continued answer. Entries are projected to messages and continuation
136
+ * instructions; everything else breaks a chain.
137
+ */
138
+ export function lastVisibleAnswerText(
139
+ branch: readonly (
140
+ | { type: "message"; message: { role: string } | AssistantMessage }
141
+ | { type: "custom_message"; customType: string }
142
+ | { type: string }
143
+ )[],
144
+ ): string | undefined {
145
+ const messages: Array<{ role: string; customType?: string } | AssistantMessage> = [];
146
+ for (const entry of branch) {
147
+ if ("message" in entry) messages.push(entry.message);
148
+ else if ("customType" in entry) messages.push({ role: "custom", customType: entry.customType });
149
+ else messages.push({ role: entry.type });
150
+ }
151
+ const last = messages.findLast(isAssistantMessage);
152
+ if (!last) return undefined;
153
+ return getVisibleAnswerChain(messages, last)
154
+ .flatMap(message => message.content)
155
+ .filter(block => block.type === "text")
156
+ .map(block => block.text)
157
+ .join("");
158
+ }
159
+
160
+ export function isAssistantMessage(message: { role: string } | AssistantMessage): message is AssistantMessage {
161
+ return message.role === "assistant";
162
+ }
163
+
104
164
  /** Type-guard for `SILENT_ABORT_MARKER`. Renderers MUST branch on this rather
105
165
  * than string-comparing inline so refactors to the marker constant (e.g.,
106
166
  * namespacing changes) propagate through every consumer in lockstep. */
@@ -385,6 +445,36 @@ export function createCustomMessage(
385
445
  };
386
446
  }
387
447
 
448
+ /**
449
+ * A continuation instruction that no assistant answered (its request was never
450
+ * admitted, or a restart/new prompt superseded it). Only the trailing instruction of
451
+ * a live recovery and one followed by its continued answer reach the model.
452
+ */
453
+ function isStaleVisibleContinuation(messages: readonly AgentMessage[], message: AgentMessage, index: number): boolean {
454
+ if (
455
+ message.role !== "custom" ||
456
+ (message.customType !== VISIBLE_CONTINUATION_CUSTOM_TYPE && message.customType !== AUTO_RESUME_CUSTOM_TYPE)
457
+ )
458
+ return false;
459
+ for (let i = index + 1; i < messages.length; i++) {
460
+ const next = messages[i];
461
+ // A failed continuation request with no visible output did not answer the instruction.
462
+ if (
463
+ next.role === "assistant" &&
464
+ next.content.some(
465
+ block =>
466
+ (block.type === "text" && block.text.trim().length > 0) ||
467
+ block.type === "thinking" ||
468
+ block.type === "redactedThinking" ||
469
+ block.type === "toolCall",
470
+ )
471
+ )
472
+ return false;
473
+ if (next.role === "user") return true;
474
+ }
475
+ return false;
476
+ }
477
+
388
478
  /**
389
479
  * Transform AgentMessages (including custom types) to LLM-compatible Messages.
390
480
  *
@@ -395,6 +485,7 @@ export function createCustomMessage(
395
485
  */
396
486
  export function convertToLlm(messages: AgentMessage[]): Message[] {
397
487
  return messages
488
+ .filter((m, index) => !isStaleVisibleContinuation(messages, m, index))
398
489
  .map((m): Message | undefined => {
399
490
  switch (m.role) {
400
491
  case "bashExecution":
@@ -713,7 +713,8 @@ function getUsageTokens(usage: unknown): number {
713
713
  export function createSubagentSettings(baseSettings: Settings, inheritedServiceTier?: ServiceTier): Settings {
714
714
  const snapshot: Partial<Record<SettingPath, unknown>> = {};
715
715
  for (const key of Object.keys(SETTINGS_SCHEMA) as SettingPath[]) {
716
- snapshot[key] = baseSettings.get(key);
716
+ // Materializing schema defaults would turn inherited retry policy into explicit caps.
717
+ if (baseSettings.has(key)) snapshot[key] = baseSettings.get(key);
717
718
  }
718
719
  // Subagent-scoped service-tier override: "inherit" uses the parent session's
719
720
  // LIVE intent (so a runtime `/fast on` reaches subagents and a main-model