@runtypelabs/sdk 9.2.1 → 9.3.1

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.
package/dist/index.cjs CHANGED
@@ -39,6 +39,7 @@ __export(index_exports, {
39
39
  CollectionsEndpoint: () => CollectionsEndpoint,
40
40
  ContextTemplatesEndpoint: () => ContextTemplatesEndpoint,
41
41
  ConversationsEndpoint: () => ConversationsEndpoint,
42
+ DEFAULT_MAX_DETACHED_RECONNECTS: () => DEFAULT_MAX_DETACHED_RECONNECTS,
42
43
  DEFAULT_RECOVERY_AFTER_EMPTY_SESSIONS: () => DEFAULT_RECOVERY_AFTER_EMPTY_SESSIONS,
43
44
  DEFAULT_STALL_STOP_AFTER: () => DEFAULT_STALL_STOP_AFTER,
44
45
  DispatchEndpoint: () => DispatchEndpoint,
@@ -97,6 +98,7 @@ __export(index_exports, {
97
98
  UsersEndpoint: () => UsersEndpoint,
98
99
  applyGeneratedRuntimeToolProposalToDispatchRequest: () => applyGeneratedRuntimeToolProposalToDispatchRequest,
99
100
  attachRuntimeToolsToDispatchRequest: () => attachRuntimeToolsToDispatchRequest,
101
+ buildAgentAdmissionHeaders: () => buildAgentAdmissionHeaders,
100
102
  buildEmptySessionNudge: () => buildEmptySessionNudge,
101
103
  buildGeneratedRuntimeToolGateOutput: () => buildGeneratedRuntimeToolGateOutput,
102
104
  buildLedgerOffloadReference: () => buildLedgerOffloadReference,
@@ -186,6 +188,7 @@ __export(index_exports, {
186
188
  unregisterWorkflowHook: () => unregisterWorkflowHook,
187
189
  usedNoTools: () => usedNoTools,
188
190
  validJson: () => validJson,
191
+ withDetachedReconnect: () => withDetachedReconnect,
189
192
  withUnifiedEvents: () => withUnifiedEvents
190
193
  });
191
194
  module.exports = __toCommonJS(index_exports);
@@ -372,10 +375,7 @@ function createFlowEventTranslator() {
372
375
  pageOrigin: data.pageOrigin
373
376
  })
374
377
  ];
375
- // Channels/markers/tool-family/approval/skip/source/state/custom/ping the
376
- // flow consumer never read → no callback event. (A non-terminal `error` is
377
- // only produced on agent streams; dropping it here avoids a false
378
- // flow_error.)
378
+ // WHY(docs/why/packages/client/src.md#default-case-drops-events-the-flow-consumer-neve): Default case drops events the flow consumer never reads; a non-terminal error is agent-only, dropped here.
379
379
  default:
380
380
  return [];
381
381
  }
@@ -547,9 +547,7 @@ function createAgentEventTranslator() {
547
547
  toolName: data.toolName,
548
548
  success: data.success,
549
549
  result: data.result,
550
- // A failure's reason travels on the frame's `error` field the
551
- // only carrier for complete-only failures like the MCP discovery
552
- // connection pseudo-tool, which no longer emits an `error` frame.
550
+ // WHY(docs/why/packages/client/src.md#a-failures-reason-travels-on-error-the-only-carr): A failure's reason travels on `error`, the only carrier for complete-only MCP discovery failures.
553
551
  error: str(data.error),
554
552
  executionTime: data.executionTime
555
553
  })
@@ -686,10 +684,7 @@ function createAgentEventTranslator() {
686
684
  ];
687
685
  case "ping":
688
686
  return [compact({ type: "agent_ping", executionId, seq, timestamp: data.timestamp })];
689
- // turn/text/reasoning open+close markers, step_*, artifact_*, source,
690
- // state_snapshot/state_delta (agent-state channel with no stable SDK
691
- // callback), custom (fallback beat / routing), and the skill-fold result
692
- // envelope the SDK never consumed → no callback event.
687
+ // WHY(docs/why/packages/client/src.md#default-case-lists-every-channel-type-the-sdk-ca): Default case lists every channel type the SDK callback surface never consumed, so it maps to nothing.
693
688
  default:
694
689
  return [];
695
690
  }
@@ -1244,9 +1239,6 @@ var FlowBuilder = class {
1244
1239
  );
1245
1240
  return this;
1246
1241
  }
1247
- // ============================================================================
1248
- // Step Methods
1249
- // ============================================================================
1250
1242
  /**
1251
1243
  * Add a prompt step
1252
1244
  */
@@ -1745,9 +1737,6 @@ var FlowBuilder = class {
1745
1737
  memorySummary(config) {
1746
1738
  return this.addRawStep("memory-summary", config);
1747
1739
  }
1748
- // ============================================================================
1749
- // Subagent Helpers
1750
- // ============================================================================
1751
1740
  /**
1752
1741
  * Attach a subagent runtime tool to the most recent prompt step.
1753
1742
  *
@@ -1842,9 +1831,6 @@ var FlowBuilder = class {
1842
1831
  lastStep.config.tools = { ...existingTools, subagentConfig: opts };
1843
1832
  return this;
1844
1833
  }
1845
- // ============================================================================
1846
- // Build Method
1847
- // ============================================================================
1848
1834
  /**
1849
1835
  * Build the final dispatch request configuration
1850
1836
  */
@@ -1935,9 +1921,6 @@ var FlowBuilder = class {
1935
1921
  if (lastStep) lastStep.when = expression;
1936
1922
  return this;
1937
1923
  }
1938
- // ============================================================================
1939
- // Private Helpers
1940
- // ============================================================================
1941
1924
  addRawStep(type, config) {
1942
1925
  const { name, enabled, when, ...stepConfig } = config;
1943
1926
  this.addStep(type, name, stepConfig, enabled, when);
@@ -2141,7 +2124,6 @@ var CHECK_GRADER_KINDS = /* @__PURE__ */ new Set([
2141
2124
  "length",
2142
2125
  "latency",
2143
2126
  "no_error",
2144
- // Trace checks.
2145
2127
  "called_tool",
2146
2128
  "not_called_tool",
2147
2129
  "used_no_tools",
@@ -2425,7 +2407,8 @@ function normalizeCaseInput(input, where) {
2425
2407
  const mock = { toolName: m.toolName, output: m.output };
2426
2408
  if (m.input !== void 0) mock.input = m.input;
2427
2409
  if (typeof m.isError === "boolean") mock.isError = m.isError;
2428
- if (typeof m.sourceToolExecutionId === "string") mock.sourceToolExecutionId = m.sourceToolExecutionId;
2410
+ if (typeof m.sourceToolExecutionId === "string")
2411
+ mock.sourceToolExecutionId = m.sourceToolExecutionId;
2429
2412
  if (typeof m.truncated === "boolean") mock.truncated = m.truncated;
2430
2413
  return mock;
2431
2414
  });
@@ -2530,7 +2513,7 @@ async function computeEvalContentHash(definition) {
2530
2513
  name: c.name,
2531
2514
  input: normalizeForHash(c.input),
2532
2515
  ...c.expected !== void 0 ? { expected: normalizeForHash(c.expected) } : {},
2533
- // Grader order preserved on purpose (it maps to the result index).
2516
+ // INVARIANT: Grader order is preserved on purpose; it maps to the result index.
2534
2517
  expect: c.expect.map((g) => normalizeForHash(g))
2535
2518
  }))
2536
2519
  };
@@ -2736,8 +2719,7 @@ function defineFlow(input) {
2736
2719
  return {
2737
2720
  type: step.type,
2738
2721
  name: step.name,
2739
- // Explicit 1-based order (the flow builder's convention) so the local
2740
- // probe hash agrees with the server's persisted step order.
2722
+ // WHY(docs/why/packages/client/src.md#explicit-1-based-order-matches-the-flow-builders): Explicit 1-based order matches the flow builder's convention so the local hash agrees with the server
2741
2723
  order: typeof step.order === "number" ? step.order : index + 1,
2742
2724
  ...step.enabled !== void 0 ? { enabled: step.enabled } : {},
2743
2725
  ...typeof step.when === "string" ? { when: step.when } : {},
@@ -3039,9 +3021,6 @@ var RuntypeFlowBuilder = class {
3039
3021
  this.flowConfig = { name: "Untitled Flow" };
3040
3022
  }
3041
3023
  }
3042
- // ============================================================================
3043
- // Configuration Methods
3044
- // ============================================================================
3045
3024
  /**
3046
3025
  * Set the record configuration
3047
3026
  */
@@ -3085,9 +3064,6 @@ var RuntypeFlowBuilder = class {
3085
3064
  );
3086
3065
  return this;
3087
3066
  }
3088
- // ============================================================================
3089
- // Step Methods
3090
- // ============================================================================
3091
3067
  /**
3092
3068
  * Add a prompt step
3093
3069
  */
@@ -3871,9 +3847,6 @@ var RuntypeFlowBuilder = class {
3871
3847
  "Use Runtype.flows.virtual(...) or Runtype.flows.upsert(...) with inline steps to validate a flow before saving."
3872
3848
  );
3873
3849
  }
3874
- // ============================================================================
3875
- // Private Helpers
3876
- // ============================================================================
3877
3850
  /**
3878
3851
  * Persisted flow protocol (APQ-style): send hash-only first, retry with
3879
3852
  * full definition on FLOW_DEFINITION_REQUIRED. For non-upsert modes,
@@ -4949,7 +4922,8 @@ var AGENT_CONFIG_KEYS = [
4949
4922
  "temporal",
4950
4923
  "memory",
4951
4924
  "sandbox",
4952
- "tenancyStrategy"
4925
+ "tenancyStrategy",
4926
+ "durability"
4953
4927
  ];
4954
4928
  var AGENT_CONFIG_KEY_LIST = [...AGENT_CONFIG_KEYS].sort();
4955
4929
  function isPlainObject2(value) {
@@ -6235,9 +6209,6 @@ var RuntypeClient = class {
6235
6209
  }
6236
6210
  };
6237
6211
  var Runtype = class {
6238
- // ============================================================================
6239
- // Global Configuration
6240
- // ============================================================================
6241
6212
  /**
6242
6213
  * Configure the global Runtype client
6243
6214
  *
@@ -6275,9 +6246,6 @@ var Runtype = class {
6275
6246
  static createClient(config) {
6276
6247
  return new RuntypeClient({ ...globalConfig, ...config });
6277
6248
  }
6278
- // ============================================================================
6279
- // Static Namespaces
6280
- // ============================================================================
6281
6249
  /**
6282
6250
  * Flows namespace - Build and execute flows
6283
6251
  *
@@ -6519,10 +6487,150 @@ var Runtype = class {
6519
6487
 
6520
6488
  // src/version.ts
6521
6489
  var FALLBACK_VERSION = "0.0.0";
6522
- var SDK_VERSION = "9.2.1".length > 0 ? "9.2.1" : FALLBACK_VERSION;
6490
+ var SDK_VERSION = "9.3.1".length > 0 ? "9.3.1" : FALLBACK_VERSION;
6523
6491
  var RUNTYPE_CLIENT_KIND = "sdk";
6524
6492
  var SDK_USER_AGENT = `runtype-sdk/${SDK_VERSION} (typescript)`;
6525
6493
 
6494
+ // src/detached-reconnect.ts
6495
+ var TERMINAL_EVENTS = /* @__PURE__ */ new Set(["execution_complete", "execution_error"]);
6496
+ var DEFAULT_MAX_DETACHED_RECONNECTS = 12;
6497
+ function observeBlock(block, into) {
6498
+ let eventName = null;
6499
+ for (const line of block.split("\n")) {
6500
+ if (line.startsWith("id:")) {
6501
+ into.lastId = line.slice(3).trim();
6502
+ continue;
6503
+ }
6504
+ if (line.startsWith("event:")) {
6505
+ eventName = line.slice(6).trim();
6506
+ continue;
6507
+ }
6508
+ if (!line.startsWith("data:")) continue;
6509
+ const raw = line.slice(5).trim();
6510
+ if (!raw || raw === "[DONE]") continue;
6511
+ let payload;
6512
+ try {
6513
+ const parsed = JSON.parse(raw);
6514
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) continue;
6515
+ payload = parsed;
6516
+ } catch {
6517
+ continue;
6518
+ }
6519
+ if (typeof payload.executionId === "string") into.executionId = payload.executionId;
6520
+ const type = typeof payload.type === "string" ? payload.type : eventName;
6521
+ if (type && TERMINAL_EVENTS.has(type)) into.sawTerminal = true;
6522
+ if (type === "await" && payload.awaitReason === "detached") into.sawDetach = true;
6523
+ }
6524
+ }
6525
+ function withDetachedReconnect(response, reattach, options = {}) {
6526
+ if (options.autoReconnect === false) return response;
6527
+ if (!response.ok || !response.body) return response;
6528
+ const contentType = response.headers.get("content-type") ?? "";
6529
+ if (!contentType.includes("text/event-stream")) return response;
6530
+ const maxReconnects = options.maxReconnects ?? DEFAULT_MAX_DETACHED_RECONNECTS;
6531
+ const reconnectDelayMs = options.reconnectDelayMs ?? 0;
6532
+ const encoder = new TextEncoder();
6533
+ const decoder = new TextDecoder();
6534
+ const abort = new AbortController();
6535
+ let cancelled = false;
6536
+ let activeReader = null;
6537
+ const stream = new ReadableStream({
6538
+ async start(controller) {
6539
+ const observed = {
6540
+ lastId: null,
6541
+ executionId: null,
6542
+ sawTerminal: false,
6543
+ sawDetach: false
6544
+ };
6545
+ let current = response;
6546
+ let legs = 0;
6547
+ const enqueue = (chunk) => {
6548
+ if (cancelled) return;
6549
+ controller.enqueue(chunk);
6550
+ };
6551
+ try {
6552
+ while (!cancelled && current?.body) {
6553
+ const reader = current.body.getReader();
6554
+ activeReader = reader;
6555
+ let buffer = "";
6556
+ observed.sawDetach = false;
6557
+ for (; ; ) {
6558
+ const { value, done } = await reader.read();
6559
+ if (cancelled) break;
6560
+ if (value) {
6561
+ enqueue(value);
6562
+ buffer += decoder.decode(value, { stream: !done });
6563
+ let boundary = buffer.indexOf("\n\n");
6564
+ while (boundary >= 0) {
6565
+ observeBlock(buffer.slice(0, boundary), observed);
6566
+ buffer = buffer.slice(boundary + 2);
6567
+ boundary = buffer.indexOf("\n\n");
6568
+ }
6569
+ }
6570
+ if (done) break;
6571
+ }
6572
+ activeReader = null;
6573
+ if (cancelled) break;
6574
+ if (buffer.trim()) observeBlock(buffer, observed);
6575
+ if (observed.sawTerminal || !observed.sawDetach) break;
6576
+ if (!observed.executionId || legs >= maxReconnects) break;
6577
+ legs += 1;
6578
+ if (reconnectDelayMs > 0) {
6579
+ await new Promise((resolve) => setTimeout(resolve, reconnectDelayMs));
6580
+ }
6581
+ if (cancelled) break;
6582
+ current = await reattach({
6583
+ executionId: observed.executionId,
6584
+ // WHY(docs/why/packages/client/src.md#0-replays-the-whole-turn-the-fail-open-answer-fo): '0' replays the whole turn, the fail-open answer for a leg that produced no cursor.
6585
+ after: observed.lastId ?? "0",
6586
+ signal: abort.signal
6587
+ });
6588
+ if (cancelled) {
6589
+ await current?.body?.cancel().catch(() => {
6590
+ });
6591
+ break;
6592
+ }
6593
+ if (!current || !current.ok || !current.body) {
6594
+ enqueue(
6595
+ encoder.encode(
6596
+ `event: error
6597
+ data: ${JSON.stringify({
6598
+ type: "error",
6599
+ executionId: observed.executionId,
6600
+ error: {
6601
+ code: "detached_reconnect_failed",
6602
+ message: "The agent detached and this client could not rejoin its stream. The execution is still running; reattach with the events route."
6603
+ },
6604
+ recoverable: false
6605
+ })}
6606
+
6607
+ `
6608
+ )
6609
+ );
6610
+ break;
6611
+ }
6612
+ }
6613
+ } finally {
6614
+ activeReader = null;
6615
+ if (!cancelled) controller.close();
6616
+ }
6617
+ },
6618
+ async cancel(reason) {
6619
+ cancelled = true;
6620
+ abort.abort(reason);
6621
+ const reader = activeReader;
6622
+ activeReader = null;
6623
+ if (reader) await reader.cancel(reason).catch(() => {
6624
+ });
6625
+ }
6626
+ });
6627
+ return new Response(stream, {
6628
+ status: response.status,
6629
+ statusText: response.statusText,
6630
+ headers: response.headers
6631
+ });
6632
+ }
6633
+
6526
6634
  // src/generated-tool-gate.ts
6527
6635
  var TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]{1,63}$/;
6528
6636
  var DEFAULT_MAX_CODE_LENGTH = 12e3;
@@ -6794,11 +6902,7 @@ function attachRuntimeToolsToDispatchRequest(request6, runtimeTools, options = {
6794
6902
  ...request6,
6795
6903
  flow: {
6796
6904
  ...flow,
6797
- // `clonedSteps` is a structural clone of `request.flow.steps` (already
6798
- // `FlowStepDefinition[]`); only the prompt step's `config.tools` was
6799
- // merged, so every step's `type` discriminant is preserved. The clone is
6800
- // intentionally built as loose records to merge tool config opaquely, so
6801
- // re-narrow to the typed step shape at this boundary.
6905
+ // WHY(docs/why/packages/client/src.md#clonedsteps-preserves-each-steps-type-discrimina): clonedSteps preserves each step's type discriminant; re-narrow from loose records here
6802
6906
  steps: clonedSteps
6803
6907
  }
6804
6908
  };
@@ -8062,13 +8166,7 @@ function ensureDefaultWorkflowHooks() {
8062
8166
  }
8063
8167
  var defaultWorkflowConfig = {
8064
8168
  name: "default",
8065
- // Empty-session escalation. The counter only counts tool actions, so
8066
- // narration-only sessions ("I'll create the files now" with no tool calls)
8067
- // escalate here even though the phase recovery conditions keyed on
8068
- // hadTextOutput skip them: nudge after the first actionless session, signal
8069
- // model escalation after the second (a no-op unless the caller configured a
8070
- // fallback model), and stop as 'stalled' after the third — the same total
8071
- // session budget as before stallPolicy existed.
8169
+ // WHY(docs/why/packages/client/src/workflows.md#empty-session-escalation-preserves-legacy-behavi): empty-session escalation preserves legacy behavior: nudge, then escalate, then stall after three
8072
8170
  stallPolicy: { nudgeAfter: 1, escalateModelAfter: 2, stopAfter: 3 },
8073
8171
  classifyVariant: "builtin:classify-task-variant",
8074
8172
  bootstrap: "builtin:repo-bootstrap-discovery",
@@ -8096,16 +8194,14 @@ var defaultWorkflowConfig = {
8096
8194
  transitionSummary: "builtin:planning-transition-summary",
8097
8195
  recovery: "builtin:planning-recovery",
8098
8196
  forceEndTurn: "builtin:planning-force-end-turn"
8099
- // canAcceptCompletion intentionally absent: the hand-written planning
8100
- // phase never defined it, and the SDK accepts completion when the slot
8101
- // is undefined. Keep parity.
8197
+ // WHY(docs/why/packages/client/src/workflows.md#canacceptcompletion-is-intentionally-absent-for): canAcceptCompletion is intentionally absent for planning to keep parity with the hand-written phase
8102
8198
  },
8103
8199
  {
8104
8200
  name: "execution",
8105
8201
  description: "Execute the plan by editing target files",
8106
8202
  instructions: "builtin:execution-instructions",
8107
8203
  toolGuidance: "builtin:execution-tool-guidance",
8108
- // Execution never auto-advances; completion is agent-driven via TASK_COMPLETE
8204
+ // WHY(needs-review): execution never auto-advances; completion is agent-driven via TASK_COMPLETE
8109
8205
  completionCriteria: { type: "never" },
8110
8206
  intercept: "builtin:execution-guard",
8111
8207
  recovery: "builtin:execution-recovery",
@@ -8275,11 +8371,11 @@ var deployWorkflow = {
8275
8371
  name: "deploy",
8276
8372
  phases: [scaffoldPhase, deployPhase],
8277
8373
  classifyVariant: classifyVariant2,
8278
- // No bootstrap context needed we're not searching the repo
8374
+ // WHY(needs-review): no bootstrap context needed; this workflow doesn't search the repo
8279
8375
  async generateBootstrapContext() {
8280
8376
  return void 0;
8281
8377
  },
8282
- // No candidate block we're not editing repo files
8378
+ // WHY(needs-review): no candidate block; this workflow doesn't edit repo files
8283
8379
  buildCandidateBlock() {
8284
8380
  return "";
8285
8381
  }
@@ -9650,9 +9746,7 @@ var ClientTokensEndpoint = class {
9650
9746
  if (params?.limit !== void 0) {
9651
9747
  return {
9652
9748
  clientTokens: response.clientTokens,
9653
- // The API always includes pagination when limit is supplied; the
9654
- // fallback mirrors the server's own envelope math so the paged
9655
- // overload stays total against older API deployments.
9749
+ // WHY(docs/why/packages/client/src.md#the-fallback-mirrors-the-servers-own-envelope-ma): The fallback mirrors the server's own envelope math so paging stays correct against older API deployments.
9656
9750
  pagination: response.pagination ?? {
9657
9751
  limit: params.limit,
9658
9752
  offset: params.offset ?? 0,
@@ -9903,6 +9997,14 @@ function appendRuntimeToolsToAgentRequest(request6, runtimeTools) {
9903
9997
  }
9904
9998
  };
9905
9999
  }
10000
+ function buildAgentAdmissionHeaders(options) {
10001
+ if (!options) return {};
10002
+ const headers = {};
10003
+ if (options.concurrency) headers["x-runtype-concurrency"] = options.concurrency;
10004
+ if (options.coalesce) headers["x-runtype-coalesce"] = "true";
10005
+ if (options.idempotencyKey) headers["idempotency-key"] = options.idempotencyKey;
10006
+ return headers;
10007
+ }
9906
10008
  var _AgentsEndpoint = class _AgentsEndpoint {
9907
10009
  constructor(client) {
9908
10010
  this.client = client;
@@ -9994,18 +10096,22 @@ var _AgentsEndpoint = class _AgentsEndpoint {
9994
10096
  /**
9995
10097
  * Execute an agent (non-streaming)
9996
10098
  */
9997
- async execute(id, data) {
9998
- return this.client.post(`/agents/${id}/execute`, {
9999
- ...data,
10000
- streamResponse: false
10001
- });
10099
+ async execute(id, data, options) {
10100
+ return this.client.post(
10101
+ `/agents/${id}/execute`,
10102
+ {
10103
+ ...data,
10104
+ streamResponse: false
10105
+ },
10106
+ buildAgentAdmissionHeaders(options)
10107
+ );
10002
10108
  }
10003
10109
  /** Start an agent execution and return its durable handle immediately. */
10004
- async executeAsync(id, data) {
10110
+ async executeAsync(id, data, options) {
10005
10111
  return this.client.post(
10006
10112
  `/agents/${id}/execute`,
10007
10113
  { ...data, streamResponse: false },
10008
- { Prefer: "respond-async" }
10114
+ { Prefer: "respond-async", ...buildAgentAdmissionHeaders(options) }
10009
10115
  );
10010
10116
  }
10011
10117
  /**
@@ -10027,14 +10133,42 @@ var _AgentsEndpoint = class _AgentsEndpoint {
10027
10133
  * ```
10028
10134
  */
10029
10135
  async executeStream(id, data, init) {
10030
- return this.client.requestStream(`/agents/${id}/execute`, {
10136
+ const admissionHeaders = buildAgentAdmissionHeaders(init);
10137
+ const response = await this.client.requestStream(`/agents/${id}/execute`, {
10031
10138
  method: "POST",
10032
10139
  body: JSON.stringify({
10033
10140
  ...data,
10034
10141
  streamResponse: true
10035
10142
  }),
10143
+ ...Object.keys(admissionHeaders).length > 0 ? { headers: admissionHeaders } : {},
10036
10144
  ...init?.signal ? { signal: init.signal } : {}
10037
10145
  });
10146
+ return withDetachedReconnect(
10147
+ response,
10148
+ this.buildDetachedReattach(id, data, init?.signal),
10149
+ init ?? {}
10150
+ );
10151
+ }
10152
+ /**
10153
+ * The `?after=` reattach leg every durable agent stream is followed with.
10154
+ *
10155
+ * Shared by `executeStream` and by the local-tool loop's RESUME leg: a
10156
+ * durable resume answers on the same watch-lease contract as the original
10157
+ * execute, so its socket can close on `awaitReason: 'detached'` too. Building
10158
+ * it once is what keeps the two from drifting into different cursor or
10159
+ * conversation-key behavior.
10160
+ */
10161
+ buildDetachedReattach(id, data, signal) {
10162
+ return async ({ executionId, after }) => {
10163
+ const named = data?.conversationId;
10164
+ const conversationId = typeof named === "string" ? named : "";
10165
+ const query = new URLSearchParams({ after });
10166
+ if (conversationId) query.set("conversationId", conversationId);
10167
+ return this.client.requestStream(`/agents/${id}/executions/${executionId}/events?${query.toString()}`, {
10168
+ method: "GET",
10169
+ ...signal ? { signal } : {}
10170
+ }).catch(() => null);
10171
+ };
10038
10172
  }
10039
10173
  /**
10040
10174
  * Execute an agent with streaming and callbacks
@@ -10198,7 +10332,7 @@ var _AgentsEndpoint = class _AgentsEndpoint {
10198
10332
  callbacks?.onTurnComplete?.(event);
10199
10333
  },
10200
10334
  onAgentPaused: (event) => {
10201
- pausedEvent = event;
10335
+ if (event.awaitReason !== "detached") pausedEvent = event;
10202
10336
  callbacks?.onAgentPaused?.(event);
10203
10337
  },
10204
10338
  onAgentComplete: (event) => {
@@ -10364,8 +10498,7 @@ var _AgentsEndpoint = class _AgentsEndpoint {
10364
10498
  iterations: 1,
10365
10499
  stopReason: "end_turn",
10366
10500
  completedAt: (/* @__PURE__ */ new Date()).toISOString(),
10367
- // Carry the spend observed so far so the interrupted session's
10368
- // cost still lands in marathon totals and budget accounting
10501
+ // WHY(docs/why/packages/client/src.md#carries-accumulated-spend-so-an-interrupted-sess): Carries accumulated spend so an interrupted session's cost still lands in totals
10369
10502
  totalCost: lastKnownCost,
10370
10503
  ...lastKnownTokens ? { totalTokens: lastKnownTokens } : {},
10371
10504
  finalOutput: [
@@ -10379,7 +10512,7 @@ var _AgentsEndpoint = class _AgentsEndpoint {
10379
10512
  }
10380
10513
  let resumeResponse;
10381
10514
  try {
10382
- resumeResponse = await this.client.requestStream(`/agents/${id}/resume`, {
10515
+ const rawResumeResponse = await this.client.requestStream(`/agents/${id}/resume`, {
10383
10516
  method: "POST",
10384
10517
  body: JSON.stringify({
10385
10518
  executionId,
@@ -10389,6 +10522,11 @@ var _AgentsEndpoint = class _AgentsEndpoint {
10389
10522
  }),
10390
10523
  ...abortSignal ? { signal: abortSignal } : {}
10391
10524
  });
10525
+ resumeResponse = withDetachedReconnect(
10526
+ rawResumeResponse,
10527
+ this.buildDetachedReattach(id, data, abortSignal),
10528
+ {}
10529
+ );
10392
10530
  } catch (error) {
10393
10531
  if (abortSignal?.aborted) return finishAborted(executionId);
10394
10532
  throw error;
@@ -10414,7 +10552,6 @@ var _AgentsEndpoint = class _AgentsEndpoint {
10414
10552
  return null;
10415
10553
  }
10416
10554
  }
10417
- // ─── Long-Task Agent Execution ───────────────────────────────────────
10418
10555
  createEmptyToolTrace() {
10419
10556
  return {
10420
10557
  entries: [],
@@ -13189,12 +13326,7 @@ var RuntypeClient2 = class {
13189
13326
  this.timeout = config.timeout === void 0 ? 3e4 : config.timeout;
13190
13327
  this.headers = {
13191
13328
  "Content-Type": "application/json",
13192
- // Advertise client identity + version so the API can attribute SDK traffic
13193
- // (see detectActorSource in apps/api/src/lib/audit-log.ts). Defaults come
13194
- // first so callers that wrap this client with their own attribution — the
13195
- // CLI sends `X-Runtype-Client: cli` + `runtype-cli/<v>` — override them.
13196
- // `User-Agent` is a forbidden header in browsers and is silently dropped
13197
- // there; `X-Runtype-Client` is the reliable cross-environment signal.
13329
+ // WHY(docs/why/packages/client/src.md#user-agent-is-a-forbidden-header-in-browsers-and): User-Agent is a forbidden header in browsers and is silently dropped; X-Runtype-Client is the reliable
13198
13330
  "X-Runtype-Client": RUNTYPE_CLIENT_KIND,
13199
13331
  "User-Agent": SDK_USER_AGENT,
13200
13332
  ...config.headers || {}
@@ -13255,8 +13387,7 @@ var RuntypeClient2 = class {
13255
13387
  {
13256
13388
  dispatch: (config) => this.dispatch.executeStream(config),
13257
13389
  runWithLocalTools: (config, tools, callbacks, opts) => this.runWithLocalTools(config, tools, callbacks, opts),
13258
- // Validation capability for ClientFlowBuilder.validate() reuses the
13259
- // client's JSON POST transport (zero new HTTP plumbing).
13390
+ // WHY(docs/why/packages/client/src.md#clientflowbuilder-validate-reuses-the-clients-js): ClientFlowBuilder.validate() reuses the client's JSON POST transport instead of new HTTP plumbing.
13260
13391
  post: (path, data) => this.post(path, data)
13261
13392
  },
13262
13393
  name
@@ -13510,8 +13641,7 @@ var RuntypeClient2 = class {
13510
13641
  const response = await this.makeRequest(url, {
13511
13642
  method: "POST",
13512
13643
  headers,
13513
- // TS 5.7 types Uint8Array over ArrayBufferLike, which no longer
13514
- // overlaps DOM BodyInit; the runtime value is a valid fetch body.
13644
+ // WORKAROUND(docs/why/packages/client/src.md#ts-5-7-types-uint8array-over-arraybufferlike-whi): TS 5.7 types Uint8Array over ArrayBufferLike, which no longer overlaps DOM BodyInit, though the
13515
13645
  body
13516
13646
  });
13517
13647
  return transformResponse(response);
@@ -14451,6 +14581,7 @@ var STEP_TYPE_TO_METHOD = {
14451
14581
  CollectionsEndpoint,
14452
14582
  ContextTemplatesEndpoint,
14453
14583
  ConversationsEndpoint,
14584
+ DEFAULT_MAX_DETACHED_RECONNECTS,
14454
14585
  DEFAULT_RECOVERY_AFTER_EMPTY_SESSIONS,
14455
14586
  DEFAULT_STALL_STOP_AFTER,
14456
14587
  DispatchEndpoint,
@@ -14509,6 +14640,7 @@ var STEP_TYPE_TO_METHOD = {
14509
14640
  UsersEndpoint,
14510
14641
  applyGeneratedRuntimeToolProposalToDispatchRequest,
14511
14642
  attachRuntimeToolsToDispatchRequest,
14643
+ buildAgentAdmissionHeaders,
14512
14644
  buildEmptySessionNudge,
14513
14645
  buildGeneratedRuntimeToolGateOutput,
14514
14646
  buildLedgerOffloadReference,
@@ -14598,5 +14730,6 @@ var STEP_TYPE_TO_METHOD = {
14598
14730
  unregisterWorkflowHook,
14599
14731
  usedNoTools,
14600
14732
  validJson,
14733
+ withDetachedReconnect,
14601
14734
  withUnifiedEvents
14602
14735
  });