@stigmer/runner 3.0.8-dev.20260613085218 → 3.0.8

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.
Files changed (94) hide show
  1. package/dist/.build-fingerprint +1 -1
  2. package/dist/activities/execute-cursor/hook-script.d.ts +23 -12
  3. package/dist/activities/execute-cursor/hook-script.js +85 -51
  4. package/dist/activities/execute-cursor/hook-script.js.map +1 -1
  5. package/dist/activities/execute-cursor/index.js +210 -79
  6. package/dist/activities/execute-cursor/index.js.map +1 -1
  7. package/dist/activities/execute-cursor/message-translator.d.ts +35 -0
  8. package/dist/activities/execute-cursor/message-translator.js +114 -6
  9. package/dist/activities/execute-cursor/message-translator.js.map +1 -1
  10. package/dist/activities/execute-cursor/prompt-builder.d.ts +25 -0
  11. package/dist/activities/execute-cursor/prompt-builder.js +54 -0
  12. package/dist/activities/execute-cursor/prompt-builder.js.map +1 -1
  13. package/dist/activities/execute-cursor/workspace-setup.d.ts +8 -2
  14. package/dist/activities/execute-cursor/workspace-setup.js +62 -30
  15. package/dist/activities/execute-cursor/workspace-setup.js.map +1 -1
  16. package/dist/activities/execute-deep-agent/index.js +14 -4
  17. package/dist/activities/execute-deep-agent/index.js.map +1 -1
  18. package/dist/activities/execute-deep-agent/status-builder-shared.d.ts +0 -1
  19. package/dist/activities/execute-deep-agent/status-builder-shared.js +32 -8
  20. package/dist/activities/execute-deep-agent/status-builder-shared.js.map +1 -1
  21. package/dist/activities/execute-deep-agent/status-builder.js +4 -5
  22. package/dist/activities/execute-deep-agent/status-builder.js.map +1 -1
  23. package/dist/activities/execute-deep-agent/streaming-v3.js +3 -4
  24. package/dist/activities/execute-deep-agent/streaming-v3.js.map +1 -1
  25. package/dist/activities/execute-deep-agent/streaming.d.ts +8 -0
  26. package/dist/activities/execute-deep-agent/streaming.js +3 -4
  27. package/dist/activities/execute-deep-agent/streaming.js.map +1 -1
  28. package/dist/activities/execute-deep-agent/subagent-tracker.js +4 -5
  29. package/dist/activities/execute-deep-agent/subagent-tracker.js.map +1 -1
  30. package/dist/activities/execute-deep-agent/v3-status-builder.js +6 -5
  31. package/dist/activities/execute-deep-agent/v3-status-builder.js.map +1 -1
  32. package/dist/config.d.ts +21 -0
  33. package/dist/config.js +12 -0
  34. package/dist/config.js.map +1 -1
  35. package/dist/in-flight.d.ts +35 -0
  36. package/dist/in-flight.js +61 -0
  37. package/dist/in-flight.js.map +1 -0
  38. package/dist/runner-manager.d.ts +2 -0
  39. package/dist/runner-manager.js +90 -29
  40. package/dist/runner-manager.js.map +1 -1
  41. package/dist/runner.d.ts +2 -0
  42. package/dist/runner.js +2 -0
  43. package/dist/runner.js.map +1 -1
  44. package/dist/shared/grpc-retry.d.ts +9 -20
  45. package/dist/shared/grpc-retry.js +9 -52
  46. package/dist/shared/grpc-retry.js.map +1 -1
  47. package/dist/shared/stall-watchdog.d.ts +68 -0
  48. package/dist/shared/stall-watchdog.js +102 -0
  49. package/dist/shared/stall-watchdog.js.map +1 -0
  50. package/dist/shared/status-offload.d.ts +84 -0
  51. package/dist/shared/status-offload.js +292 -0
  52. package/dist/shared/status-offload.js.map +1 -0
  53. package/dist/shared/status.d.ts +34 -3
  54. package/dist/shared/status.js +102 -9
  55. package/dist/shared/status.js.map +1 -1
  56. package/package.json +2 -2
  57. package/src/__tests__/config.test.ts +8 -0
  58. package/src/__tests__/in-flight.test.ts +84 -0
  59. package/src/activities/__tests__/classify-tool-approvals.test.ts +1 -0
  60. package/src/activities/__tests__/discover-mcp-server.test.ts +1 -0
  61. package/src/activities/execute-cursor/__tests__/build-prompt.test.ts +74 -0
  62. package/src/activities/execute-cursor/__tests__/hook-script.test.ts +90 -15
  63. package/src/activities/execute-cursor/__tests__/tool-result-image.test.ts +244 -0
  64. package/src/activities/execute-cursor/__tests__/workspace-setup.test.ts +53 -4
  65. package/src/activities/execute-cursor/hook-script.ts +85 -51
  66. package/src/activities/execute-cursor/index.ts +170 -35
  67. package/src/activities/execute-cursor/message-translator.ts +113 -6
  68. package/src/activities/execute-cursor/prompt-builder.ts +59 -0
  69. package/src/activities/execute-cursor/workspace-setup.ts +76 -44
  70. package/src/activities/execute-deep-agent/__tests__/index.test.ts +1 -0
  71. package/src/activities/execute-deep-agent/__tests__/status-builder-shared.test.ts +66 -0
  72. package/src/activities/execute-deep-agent/__tests__/status-builder.test.ts +6 -3
  73. package/src/activities/execute-deep-agent/__tests__/streaming-v3.test.ts +70 -0
  74. package/src/activities/execute-deep-agent/index.ts +16 -4
  75. package/src/activities/execute-deep-agent/status-builder-shared.ts +27 -5
  76. package/src/activities/execute-deep-agent/status-builder.ts +3 -5
  77. package/src/activities/execute-deep-agent/streaming-v3.ts +4 -4
  78. package/src/activities/execute-deep-agent/streaming.ts +13 -4
  79. package/src/activities/execute-deep-agent/subagent-tracker.ts +4 -5
  80. package/src/activities/execute-deep-agent/v3-status-builder.ts +5 -5
  81. package/src/config.ts +27 -0
  82. package/src/in-flight.ts +71 -0
  83. package/src/runner-manager.ts +127 -33
  84. package/src/runner.ts +6 -0
  85. package/src/shared/__tests__/artifact-storage.test.ts +1 -0
  86. package/src/shared/__tests__/grpc-retry-extended.test.ts +6 -144
  87. package/src/shared/__tests__/grpc-retry.test.ts +5 -134
  88. package/src/shared/__tests__/stall-watchdog.test.ts +193 -0
  89. package/src/shared/__tests__/status-offload.test.ts +256 -0
  90. package/src/shared/__tests__/status.test.ts +199 -0
  91. package/src/shared/grpc-retry.ts +9 -72
  92. package/src/shared/stall-watchdog.ts +122 -0
  93. package/src/shared/status-offload.ts +342 -0
  94. package/src/shared/status.ts +142 -8
@@ -0,0 +1,342 @@
1
+ /**
2
+ * Size-bounding guard for the persisted AgentExecutionStatus payload.
3
+ *
4
+ * Tool outputs (an MCP screenshot's base64 image, a giant accessibility-tree
5
+ * dump, a multi-MB shell log, a huge file write) are stored inline in
6
+ * `ToolCall.result`/`args_preview`, which live in `status.messages` and are
7
+ * re-serialized whole on every `persistStatus` -> `updateStatus` gRPC call.
8
+ * Left unchecked, a single large result pushes the message past the server's
9
+ * 4 MiB gRPC receive cap; the call fails with `resource_exhausted`, progress
10
+ * stops persisting, and the live UI freezes mid-execution.
11
+ *
12
+ * This module enforces, at the single persist boundary, that the payload stays
13
+ * under the limit:
14
+ *
15
+ * 1. offloadOversizedToolOutputs — per-tool-call, SIZE-DRIVEN (not keyed on
16
+ * tool type): any result over the byte threshold is spilled to artifact
17
+ * storage and replaced with a short head plus a typed ToolCallOutputRef.
18
+ * Images are uploaded as their decoded bytes (so the UI can render an
19
+ * <img>); other large output is uploaded as text with a preview head.
20
+ * Idempotent and content-hash-deduped so the throttled, repeated persists
21
+ * (and result re-inflation by mergeToolCallEvent) upload each blob once.
22
+ *
23
+ * 2. enforceStatusSizeLimit — an aggregate, type-agnostic backstop that runs
24
+ * even when no artifact storage is available: if the encoded status still
25
+ * exceeds a soft cap (comfortably under 4 MiB), it elides the largest
26
+ * remaining inline fields in place until the payload fits.
27
+ *
28
+ * Both operate ONLY on what is persisted/streamed; the agent's working context
29
+ * is managed by the harness/SDK separately, so reasoning is unaffected.
30
+ */
31
+
32
+ import { createHash } from "node:crypto";
33
+ import { create, toBinary } from "@bufbuild/protobuf";
34
+ import {
35
+ AgentExecutionStatusSchema,
36
+ } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/api_pb";
37
+ import type { AgentExecutionStatus } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/api_pb";
38
+ import { ToolCallOutputRefSchema } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/message_pb";
39
+ import type { ToolCall } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/message_pb";
40
+ import type { ArtifactStorage } from "./artifact-storage.js";
41
+
42
+ /**
43
+ * A single tool output (result or args_preview) larger than this many bytes is
44
+ * offloaded to artifact storage instead of inlined into the persisted status.
45
+ * 256 KiB is generous for ordinary tool output yet far below the 4 MiB cap, so
46
+ * even a handful of large-but-sub-threshold results cannot aggregate past it.
47
+ */
48
+ export const INLINE_TOOL_OUTPUT_MAX_BYTES = 256 * 1024;
49
+
50
+ /** Head of an offloaded text result kept inline for an at-a-glance preview. */
51
+ export const TEXT_PREVIEW_HEAD_CHARS = 4_000;
52
+
53
+ /**
54
+ * Soft cap for the whole encoded status. Kept comfortably under the 4 MiB gRPC
55
+ * receive limit so the aggregate backstop trims before the server ever rejects.
56
+ */
57
+ export const STATUS_PAYLOAD_SOFT_LIMIT_BYTES = 3 * 1024 * 1024;
58
+
59
+ /**
60
+ * Tighter cap used only after the server has already rejected a payload as too
61
+ * large, to maximize the chance the retry succeeds.
62
+ */
63
+ export const STATUS_PAYLOAD_HARD_LIMIT_BYTES = 2 * 1024 * 1024;
64
+
65
+ /** Marker left in place of an aggregate-elided inline field. */
66
+ const ELISION_MARKER = "[output elided to keep status under the size limit]";
67
+
68
+ /** Below this size an inline field is not worth eliding (the marker is ~50B). */
69
+ const ELISION_MIN_BYTES = 1_024;
70
+
71
+ export interface ToolOutputOffloadContext {
72
+ readonly artifactStorage: ArtifactStorage;
73
+ readonly executionId: string;
74
+ /** Override the per-result byte threshold (tests use a small value). */
75
+ readonly maxInlineBytes?: number;
76
+ }
77
+
78
+ interface ImagePayload {
79
+ readonly base64: string;
80
+ readonly mimeType: string;
81
+ }
82
+
83
+ function byteLen(s: string | undefined): number {
84
+ return s ? Buffer.byteLength(s, "utf8") : 0;
85
+ }
86
+
87
+ function sha256(s: string): string {
88
+ return createHash("sha256").update(s, "utf8").digest("hex");
89
+ }
90
+
91
+ function headChars(s: string, n: number): string {
92
+ return s.length <= n ? s : s.slice(0, n);
93
+ }
94
+
95
+ function formatBytes(n: number): string {
96
+ if (n >= 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`;
97
+ if (n >= 1024) return `${(n / 1024).toFixed(1)} KB`;
98
+ return `${n} B`;
99
+ }
100
+
101
+ function extFromMime(mimeType: string): string {
102
+ switch (mimeType) {
103
+ case "image/png": return "png";
104
+ case "image/jpeg": return "jpg";
105
+ case "image/gif": return "gif";
106
+ case "image/webp": return "webp";
107
+ case "image/svg+xml": return "svg";
108
+ default: return "bin";
109
+ }
110
+ }
111
+
112
+ function matchDataUrl(s: string): ImagePayload | null {
113
+ const m = s.match(/^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]+)$/);
114
+ if (!m) return null;
115
+ return { mimeType: m[1], base64: m[2].replace(/\s+/g, "") };
116
+ }
117
+
118
+ function contentBlocks(parsed: unknown): unknown[] {
119
+ if (Array.isArray(parsed)) return parsed;
120
+ if (parsed && typeof parsed === "object") {
121
+ const obj = parsed as Record<string, unknown>;
122
+ if (Array.isArray(obj.content)) return obj.content;
123
+ // Defensive: a serialized LangChain ToolMessage envelope nests its blocks
124
+ // under kwargs.content. The deep-agent extractor already normalizes image
125
+ // results to a top-level array (status-builder-shared.ts), so this branch is
126
+ // insurance against future shape drift — not the primary path.
127
+ const kwargs = obj.kwargs;
128
+ if (kwargs && typeof kwargs === "object" && Array.isArray((kwargs as Record<string, unknown>).content)) {
129
+ return (kwargs as Record<string, unknown>).content as unknown[];
130
+ }
131
+ }
132
+ return [];
133
+ }
134
+
135
+ /**
136
+ * Best-effort extraction of an inline base64 image from a tool result string.
137
+ * Handles a raw data URL, MCP image content blocks ({type:"image", data,
138
+ * mimeType}) and OpenAI-style image_url blocks. Returns null for non-image or
139
+ * unparseable results so the caller falls back to text offload.
140
+ */
141
+ export function detectImagePayload(result: string): ImagePayload | null {
142
+ const direct = matchDataUrl(result.trim());
143
+ if (direct) return direct;
144
+
145
+ let parsed: unknown;
146
+ try {
147
+ parsed = JSON.parse(result);
148
+ } catch {
149
+ return null;
150
+ }
151
+
152
+ for (const block of contentBlocks(parsed)) {
153
+ if (!block || typeof block !== "object") continue;
154
+ const obj = block as Record<string, unknown>;
155
+ const type = typeof obj.type === "string" ? obj.type : "";
156
+ if (type !== "image" && type !== "image_url") continue;
157
+
158
+ const raw =
159
+ typeof obj.data === "string" ? obj.data :
160
+ typeof obj.image === "string" ? obj.image :
161
+ undefined;
162
+ if (raw) {
163
+ const asUrl = matchDataUrl(raw);
164
+ if (asUrl) return asUrl;
165
+ const mimeType =
166
+ typeof obj.mimeType === "string" ? obj.mimeType :
167
+ typeof obj.mime_type === "string" ? obj.mime_type :
168
+ "image/png";
169
+ return { mimeType, base64: raw.replace(/\s+/g, "") };
170
+ }
171
+
172
+ const imageUrl = obj.image_url;
173
+ if (imageUrl && typeof imageUrl === "object") {
174
+ const url = (imageUrl as Record<string, unknown>).url;
175
+ if (typeof url === "string") {
176
+ const asUrl = matchDataUrl(url);
177
+ if (asUrl) return asUrl;
178
+ }
179
+ }
180
+ }
181
+ return null;
182
+ }
183
+
184
+ function collapsedResultFor(ref: { isImage: boolean; sizeBytes: bigint; truncatedPreview: string }): string {
185
+ if (ref.isImage) {
186
+ return `[image output — ${formatBytes(Number(ref.sizeBytes))}, view inline]`;
187
+ }
188
+ const tail = `\n\n[output truncated — ${formatBytes(Number(ref.sizeBytes))} total; view full output]`;
189
+ return ref.truncatedPreview + tail;
190
+ }
191
+
192
+ async function maybeOffloadToolCall(
193
+ tc: ToolCall,
194
+ ctx: ToolOutputOffloadContext,
195
+ maxBytes: number,
196
+ ): Promise<void> {
197
+ const result = tc.result;
198
+ if (!result) return;
199
+
200
+ const hash = sha256(result);
201
+
202
+ // Idempotent: the same content was already offloaded on a prior persist (or
203
+ // mergeToolCallEvent re-inflated `result` with identical bytes). Re-collapse
204
+ // the inline copy without re-uploading.
205
+ if (tc.outputRef && tc.outputRef.contentHash === hash) {
206
+ tc.result = collapsedResultFor(tc.outputRef);
207
+ return;
208
+ }
209
+
210
+ // Images are offloaded regardless of size, BEFORE the size gate below: a
211
+ // `ToolCallOutputRef` is the only path the UI has to render an image inline,
212
+ // so even a sub-threshold screenshot must be lifted out of `result` into a
213
+ // renderable ref. Non-image text only offloads when it exceeds maxBytes.
214
+ const image = detectImagePayload(result);
215
+ if (image) {
216
+ const bytes = Buffer.from(image.base64, "base64");
217
+ const key = `artifacts/${ctx.executionId}/toolcalls/${tc.id}.${extFromMime(image.mimeType)}`;
218
+ await ctx.artifactStorage.upload(key, bytes, image.mimeType);
219
+ const downloadUrl = await ctx.artifactStorage.getDownloadUrl(key);
220
+ tc.outputRef = create(ToolCallOutputRefSchema, {
221
+ storageKey: key,
222
+ downloadUrl,
223
+ sizeBytes: BigInt(bytes.length),
224
+ contentHash: hash,
225
+ mimeType: image.mimeType,
226
+ isImage: true,
227
+ truncatedPreview: "",
228
+ });
229
+ tc.result = collapsedResultFor(tc.outputRef);
230
+ return;
231
+ }
232
+
233
+ // Non-image text below the inline budget stays inline; only oversized text is
234
+ // spilled (with a head preview) to keep the persisted payload bounded.
235
+ if (byteLen(result) <= maxBytes) return;
236
+
237
+ const content = Buffer.from(result, "utf8");
238
+ const key = `artifacts/${ctx.executionId}/toolcalls/${tc.id}.txt`;
239
+ await ctx.artifactStorage.upload(key, content, "text/plain");
240
+ const downloadUrl = await ctx.artifactStorage.getDownloadUrl(key);
241
+ tc.outputRef = create(ToolCallOutputRefSchema, {
242
+ storageKey: key,
243
+ downloadUrl,
244
+ sizeBytes: BigInt(content.length),
245
+ contentHash: hash,
246
+ mimeType: "text/plain",
247
+ isImage: false,
248
+ truncatedPreview: headChars(result, TEXT_PREVIEW_HEAD_CHARS),
249
+ });
250
+ tc.result = collapsedResultFor(tc.outputRef);
251
+ }
252
+
253
+ /**
254
+ * Offload every oversized tool result in the status to artifact storage,
255
+ * replacing the inline value with a short head + ToolCallOutputRef. Per-tool
256
+ * failures fall back to an inline truncation (a bounded result beats a failed
257
+ * persist) and never throw, so a storage hiccup cannot fail the execution.
258
+ */
259
+ export async function offloadOversizedToolOutputs(
260
+ status: AgentExecutionStatus,
261
+ ctx: ToolOutputOffloadContext,
262
+ ): Promise<void> {
263
+ const maxBytes = ctx.maxInlineBytes ?? INLINE_TOOL_OUTPUT_MAX_BYTES;
264
+ for (const msg of status.messages) {
265
+ for (const tc of msg.toolCalls) {
266
+ try {
267
+ await maybeOffloadToolCall(tc, ctx, maxBytes);
268
+ } catch (err) {
269
+ const original = tc.result ?? "";
270
+ tc.result =
271
+ headChars(original, TEXT_PREVIEW_HEAD_CHARS) +
272
+ `\n\n[output truncated — offload failed: ${err instanceof Error ? err.message : String(err)}]`;
273
+ console.warn(
274
+ `[status-offload] execution=${ctx.executionId} tool=${tc.name} ` +
275
+ `offload failed (non-fatal); truncated inline`,
276
+ );
277
+ }
278
+ }
279
+ }
280
+ }
281
+
282
+ function encodedSize(status: AgentExecutionStatus): number {
283
+ return toBinary(AgentExecutionStatusSchema, status).length;
284
+ }
285
+
286
+ /**
287
+ * Aggregate, type-agnostic backstop. If the encoded status exceeds
288
+ * `softLimitBytes`, elide the largest inline tool fields (and, as a last
289
+ * resort, message content) in place until it fits. Returns true if anything
290
+ * was elided. This guarantees a bounded payload even without artifact storage
291
+ * (e.g. offload disabled) or when many medium results sum past the limit.
292
+ */
293
+ export function enforceStatusSizeLimit(
294
+ status: AgentExecutionStatus,
295
+ softLimitBytes: number = STATUS_PAYLOAD_SOFT_LIMIT_BYTES,
296
+ ): boolean {
297
+ if (encodedSize(status) <= softLimitBytes) return false;
298
+
299
+ const toolCalls: ToolCall[] = [];
300
+ for (const msg of status.messages) {
301
+ for (const tc of msg.toolCalls) toolCalls.push(tc);
302
+ }
303
+ // Largest inline footprint first so we shed the most bytes per elision.
304
+ toolCalls.sort(
305
+ (a, b) =>
306
+ byteLen(b.result) + byteLen(b.argsPreview) -
307
+ (byteLen(a.result) + byteLen(a.argsPreview)),
308
+ );
309
+
310
+ let elidedAny = false;
311
+ for (const tc of toolCalls) {
312
+ if (encodedSize(status) <= softLimitBytes) return elidedAny;
313
+ if (byteLen(tc.result) > ELISION_MIN_BYTES) {
314
+ tc.result = ELISION_MARKER;
315
+ elidedAny = true;
316
+ }
317
+ if (byteLen(tc.argsPreview) > ELISION_MIN_BYTES) {
318
+ tc.argsPreview = ELISION_MARKER;
319
+ elidedAny = true;
320
+ }
321
+ if (tc.args !== undefined) {
322
+ tc.args = undefined;
323
+ elidedAny = true;
324
+ }
325
+ }
326
+
327
+ // Last resort: oversized message content (e.g. a huge AI response).
328
+ if (encodedSize(status) > softLimitBytes) {
329
+ const byContent = [...status.messages].sort(
330
+ (a, b) => byteLen(b.content) - byteLen(a.content),
331
+ );
332
+ for (const msg of byContent) {
333
+ if (encodedSize(status) <= softLimitBytes) break;
334
+ if (byteLen(msg.content) > ELISION_MIN_BYTES) {
335
+ msg.content = headChars(msg.content, TEXT_PREVIEW_HEAD_CHARS) + `\n\n${ELISION_MARKER}`;
336
+ elidedAny = true;
337
+ }
338
+ }
339
+ }
340
+
341
+ return elidedAny;
342
+ }
@@ -19,28 +19,162 @@ import {
19
19
  ExecutionPhase,
20
20
  } from "@stigmer/protos/ai/stigmer/agentic/agentexecution/v1/enum_pb";
21
21
  import type { StigmerClient } from "../client/stigmer-client.js";
22
+ import {
23
+ offloadOversizedToolOutputs,
24
+ enforceStatusSizeLimit,
25
+ STATUS_PAYLOAD_HARD_LIMIT_BYTES,
26
+ type ToolOutputOffloadContext,
27
+ } from "./status-offload.js";
28
+ import {
29
+ isRetryableError,
30
+ isTerminalError,
31
+ type RetryOptions,
32
+ } from "./grpc-retry.js";
22
33
 
23
34
  export function utcTimestamp(): string {
24
35
  return new Date().toISOString().replace("+00:00", "Z");
25
36
  }
26
37
 
38
+ /**
39
+ * A connect-rpc `resource_exhausted` (gRPC code 8) — the payload exceeded the
40
+ * server's receive cap. Matched by code and, defensively, by the message buf's
41
+ * size check emits ("exceeds maximum size").
42
+ */
43
+ function isPayloadTooLarge(err: unknown): boolean {
44
+ if (typeof err === "object" && err !== null && "code" in err) {
45
+ if ((err as { code?: unknown }).code === 8) return true;
46
+ }
47
+ const msg = err instanceof Error ? err.message : String(err);
48
+ return /resource_exhausted|exceeds maximum size/i.test(msg);
49
+ }
50
+
51
+ /** Options controlling how a status payload is bounded and persisted. */
52
+ export interface PersistStatusOptions {
53
+ /**
54
+ * When supplied, oversized tool outputs (a screenshot's base64, a multi-MB
55
+ * dump) are spilled to artifact storage before persisting — the only path
56
+ * that populates a renderable `ToolCallOutputRef`. When omitted, the
57
+ * aggregate size backstop still runs, so the payload is bounded regardless.
58
+ */
59
+ readonly offload?: ToolOutputOffloadContext;
60
+ /**
61
+ * Transient-error backoff policy. Omitted fields fall back to
62
+ * {@link DEFAULT_PERSIST_RETRY}; an omitted `retry` uses it entirely.
63
+ */
64
+ readonly retry?: RetryOptions;
65
+ }
66
+
67
+ /**
68
+ * Default transient-retry policy: three attempts with exponential backoff.
69
+ * Applied to every persist so a transient drop (server restart, brief
70
+ * unavailability) recovers silently instead of dropping a status update.
71
+ */
72
+ const DEFAULT_PERSIST_RETRY = {
73
+ baseDelayMs: 100,
74
+ backoffFactor: 2,
75
+ maxRetries: 3,
76
+ } as const;
77
+
78
+ function defaultDelay(ms: number): Promise<void> {
79
+ return new Promise((resolve) => setTimeout(resolve, ms));
80
+ }
81
+
27
82
  /**
28
83
  * Persist execution status via gRPC. Returns the control signal from the
29
- * backend (e.g. STOP to abort the execution). Errors are logged and
30
- * swallowed — a failed status update should not crash the activity.
84
+ * backend (e.g. STOP to abort the execution).
85
+ *
86
+ * This is the single, unforgeable chokepoint for status persistence across
87
+ * every harness (streaming and terminal, native and Cursor). Routing all
88
+ * persistence through here guarantees three invariants that must never be
89
+ * skipped by an individual call site:
90
+ *
91
+ * 1. Size bounding — when `offload` is supplied, oversized tool outputs are
92
+ * spilled to artifact storage first (the path that makes screenshots
93
+ * render); an aggregate backstop then runs unconditionally so callers
94
+ * without storage are still protected from the 4 MiB gRPC cap.
95
+ * 2. Transient resilience — `Unavailable`/`DeadlineExceeded` back off and
96
+ * retry (default three attempts); terminal errors never retry.
97
+ * 3. Oversize recovery — a `resource_exhausted` rejection is never silently
98
+ * swallowed: we hard-elide and retry once, so an oversized payload can
99
+ * never freeze persistence invisibly (the bug that stalled the UI).
31
100
  */
32
101
  export async function persistStatus(
33
102
  client: StigmerClient,
34
103
  executionId: string,
35
104
  status: AgentExecutionStatus,
105
+ options: PersistStatusOptions = {},
36
106
  ): Promise<ExecutionControlSignal> {
37
- try {
38
- const response = await client.updateStatus(executionId, status);
39
- return response.signal;
40
- } catch (err) {
41
- console.error(`Failed to persist status for ${executionId}:`, err);
42
- return ExecutionControlSignal.UNSPECIFIED;
107
+ const { offload, retry } = options;
108
+
109
+ if (offload) {
110
+ try {
111
+ await offloadOversizedToolOutputs(status, offload);
112
+ } catch (err) {
113
+ console.warn(`[persistStatus] ${executionId}: tool-output offload failed (non-fatal): ${err}`);
114
+ }
43
115
  }
116
+ if (enforceStatusSizeLimit(status)) {
117
+ console.warn(
118
+ `[persistStatus] ${executionId}: status exceeded the soft size limit; ` +
119
+ `elided oversized inline fields to fit under the gRPC cap`,
120
+ );
121
+ }
122
+
123
+ const baseDelayMs = retry?.baseDelayMs ?? DEFAULT_PERSIST_RETRY.baseDelayMs;
124
+ const backoffFactor = retry?.backoffFactor ?? DEFAULT_PERSIST_RETRY.backoffFactor;
125
+ const maxRetries = retry?.maxRetries ?? DEFAULT_PERSIST_RETRY.maxRetries;
126
+ const delay = retry?.delayFn ?? defaultDelay;
127
+
128
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
129
+ try {
130
+ const response = await client.updateStatus(executionId, status);
131
+ return response.signal;
132
+ } catch (err) {
133
+ // Oversize rejection is recoverable exactly once and out-of-band from the
134
+ // transient budget: hard-elide the largest inline fields and retry now.
135
+ if (isPayloadTooLarge(err)) {
136
+ console.error(
137
+ `[persistStatus] ${executionId}: payload rejected as too large despite ` +
138
+ `the size guard; hard-eliding and retrying once`,
139
+ );
140
+ enforceStatusSizeLimit(status, STATUS_PAYLOAD_HARD_LIMIT_BYTES);
141
+ try {
142
+ const response = await client.updateStatus(executionId, status);
143
+ return response.signal;
144
+ } catch (retryErr) {
145
+ console.error(`[persistStatus] ${executionId}: still failing after hard elide:`, retryErr);
146
+ return ExecutionControlSignal.UNSPECIFIED;
147
+ }
148
+ }
149
+
150
+ // Terminal errors (invalid argument, not found, permission denied) are
151
+ // deterministic — retrying cannot help.
152
+ if (isTerminalError(err)) {
153
+ console.error(
154
+ `[persistStatus] ${executionId}: terminal error persisting status ` +
155
+ `(attempt ${attempt + 1}/${maxRetries + 1}): ${err}`,
156
+ );
157
+ return ExecutionControlSignal.UNSPECIFIED;
158
+ }
159
+
160
+ // Transient errors back off and retry until the budget is exhausted.
161
+ if (isRetryableError(err) && attempt < maxRetries) {
162
+ const delayMs = baseDelayMs * Math.pow(backoffFactor, attempt);
163
+ console.warn(
164
+ `[persistStatus] ${executionId}: retryable error ` +
165
+ `(attempt ${attempt + 1}/${maxRetries + 1}, retry in ${delayMs}ms): ${err}`,
166
+ );
167
+ await delay(delayMs);
168
+ continue;
169
+ }
170
+
171
+ // Non-retryable, non-terminal (e.g. a bare Error), or retries exhausted.
172
+ console.error(`Failed to persist status for ${executionId}:`, err);
173
+ return ExecutionControlSignal.UNSPECIFIED;
174
+ }
175
+ }
176
+
177
+ return ExecutionControlSignal.UNSPECIFIED;
44
178
  }
45
179
 
46
180
  /**