@relayflows/sdk 2.0.10 → 2.0.12

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 (172) hide show
  1. package/dist/adapters/base.d.ts +6 -0
  2. package/dist/adapters/base.d.ts.map +1 -1
  3. package/dist/adapters/claude.d.ts.map +1 -1
  4. package/dist/adapters/claude.js +1 -0
  5. package/dist/adapters/claude.js.map +1 -1
  6. package/dist/agent-relay-receipt.d.ts +24 -0
  7. package/dist/agent-relay-receipt.d.ts.map +1 -0
  8. package/dist/agent-relay-receipt.js +66 -0
  9. package/dist/agent-relay-receipt.js.map +1 -0
  10. package/dist/agent-relay-state.d.ts +18 -0
  11. package/dist/agent-relay-state.d.ts.map +1 -0
  12. package/dist/agent-relay-state.js +58 -0
  13. package/dist/agent-relay-state.js.map +1 -0
  14. package/dist/agent-relay-transport.d.ts +17 -70
  15. package/dist/agent-relay-transport.d.ts.map +1 -1
  16. package/dist/agent-relay-transport.js +177 -112
  17. package/dist/agent-relay-transport.js.map +1 -1
  18. package/dist/authored-admission.d.ts +5 -0
  19. package/dist/authored-admission.d.ts.map +1 -0
  20. package/dist/authored-admission.js +14 -0
  21. package/dist/authored-admission.js.map +1 -0
  22. package/dist/authored-budget.d.ts +1 -1
  23. package/dist/authored-budget.d.ts.map +1 -1
  24. package/dist/authored-budget.js +3 -3
  25. package/dist/authored-budget.js.map +1 -1
  26. package/dist/authored-flow-error.d.ts +1 -1
  27. package/dist/authored-flow-error.d.ts.map +1 -1
  28. package/dist/authored-flow-error.js.map +1 -1
  29. package/dist/authored-flow-executor.d.ts +10 -0
  30. package/dist/authored-flow-executor.d.ts.map +1 -1
  31. package/dist/authored-flow-executor.js +10 -7
  32. package/dist/authored-flow-executor.js.map +1 -1
  33. package/dist/authored-flow-loader.d.ts +20 -0
  34. package/dist/authored-flow-loader.d.ts.map +1 -1
  35. package/dist/authored-flow-loader.js +86 -11
  36. package/dist/authored-flow-loader.js.map +1 -1
  37. package/dist/authored-helper-effect.d.ts +1 -1
  38. package/dist/authored-helper-effect.d.ts.map +1 -1
  39. package/dist/authored-helper-effect.js +5 -3
  40. package/dist/authored-helper-effect.js.map +1 -1
  41. package/dist/authored-mcp.d.ts +1 -1
  42. package/dist/authored-mcp.d.ts.map +1 -1
  43. package/dist/authored-mcp.js +7 -4
  44. package/dist/authored-mcp.js.map +1 -1
  45. package/dist/authored-node-entry.d.ts +2 -0
  46. package/dist/authored-node-entry.d.ts.map +1 -0
  47. package/dist/authored-node-entry.js +111 -0
  48. package/dist/authored-node-entry.js.map +1 -0
  49. package/dist/authored-node-runner.d.ts +11 -0
  50. package/dist/authored-node-runner.d.ts.map +1 -0
  51. package/dist/authored-node-runner.js +246 -0
  52. package/dist/authored-node-runner.js.map +1 -0
  53. package/dist/authored-plugin-effect.d.ts +1 -1
  54. package/dist/authored-plugin-effect.d.ts.map +1 -1
  55. package/dist/authored-plugin-effect.js +7 -4
  56. package/dist/authored-plugin-effect.js.map +1 -1
  57. package/dist/authored-root.d.ts +38 -0
  58. package/dist/authored-root.d.ts.map +1 -0
  59. package/dist/authored-root.js +329 -0
  60. package/dist/authored-root.js.map +1 -0
  61. package/dist/authored-runtime-capability.d.ts +6 -0
  62. package/dist/authored-runtime-capability.d.ts.map +1 -0
  63. package/dist/authored-runtime-capability.js +40 -0
  64. package/dist/authored-runtime-capability.js.map +1 -0
  65. package/dist/authored-source-authority.d.ts +4 -0
  66. package/dist/authored-source-authority.d.ts.map +1 -0
  67. package/dist/authored-source-authority.js +61 -0
  68. package/dist/authored-source-authority.js.map +1 -0
  69. package/dist/authored-worker-step.d.ts +2 -2
  70. package/dist/authored-worker-step.d.ts.map +1 -1
  71. package/dist/authored-worker-step.js +11 -6
  72. package/dist/authored-worker-step.js.map +1 -1
  73. package/dist/budget-preflight.d.ts +17 -3
  74. package/dist/budget-preflight.d.ts.map +1 -1
  75. package/dist/budget-preflight.js +31 -24
  76. package/dist/budget-preflight.js.map +1 -1
  77. package/dist/cli/check.js +3 -1
  78. package/dist/cli/check.js.map +1 -1
  79. package/dist/cli/direct-run.d.ts.map +1 -1
  80. package/dist/cli/direct-run.js +18 -14
  81. package/dist/cli/direct-run.js.map +1 -1
  82. package/dist/cli/run.d.ts +2 -0
  83. package/dist/cli/run.d.ts.map +1 -1
  84. package/dist/cli/run.js +56 -1
  85. package/dist/cli/run.js.map +1 -1
  86. package/dist/cli-adapter.d.ts +16 -0
  87. package/dist/cli-adapter.d.ts.map +1 -1
  88. package/dist/cli-adapter.js +17 -0
  89. package/dist/cli-adapter.js.map +1 -1
  90. package/dist/cli.js +4 -4
  91. package/dist/cli.js.map +1 -1
  92. package/dist/cloud-run.d.ts +11 -1
  93. package/dist/cloud-run.d.ts.map +1 -1
  94. package/dist/cloud-run.js +65 -19
  95. package/dist/cloud-run.js.map +1 -1
  96. package/dist/failure-kinds.d.ts +7 -3
  97. package/dist/failure-kinds.d.ts.map +1 -1
  98. package/dist/failure-kinds.js +5 -1
  99. package/dist/failure-kinds.js.map +1 -1
  100. package/dist/journal-client.d.ts +1 -1
  101. package/dist/journal-client.d.ts.map +1 -1
  102. package/dist/journal-client.js +6 -2
  103. package/dist/journal-client.js.map +1 -1
  104. package/dist/llm-worker.d.ts.map +1 -1
  105. package/dist/llm-worker.js +4 -2
  106. package/dist/llm-worker.js.map +1 -1
  107. package/dist/local-agent.d.ts +1 -1
  108. package/dist/local-agent.d.ts.map +1 -1
  109. package/dist/local-agent.js +2 -2
  110. package/dist/local-agent.js.map +1 -1
  111. package/dist/model-pricing.d.ts +3 -4
  112. package/dist/model-pricing.d.ts.map +1 -1
  113. package/dist/model-pricing.js +4 -4
  114. package/dist/model-pricing.js.map +1 -1
  115. package/dist/preflight.d.ts +4 -1
  116. package/dist/preflight.d.ts.map +1 -1
  117. package/dist/preflight.js +36 -18
  118. package/dist/preflight.js.map +1 -1
  119. package/dist/protocol.d.ts +2 -0
  120. package/dist/protocol.d.ts.map +1 -1
  121. package/dist/spec.d.ts +5 -4
  122. package/dist/spec.d.ts.map +1 -1
  123. package/dist/spec.js.map +1 -1
  124. package/dist/worker-cli.d.ts +5 -2
  125. package/dist/worker-cli.d.ts.map +1 -1
  126. package/dist/worker-cli.js +43 -46
  127. package/dist/worker-cli.js.map +1 -1
  128. package/dist/worker-spend.d.ts +4 -3
  129. package/dist/worker-spend.d.ts.map +1 -1
  130. package/dist/worker-spend.js +13 -4
  131. package/dist/worker-spend.js.map +1 -1
  132. package/dist/worker.d.ts.map +1 -1
  133. package/dist/worker.js +12 -4
  134. package/dist/worker.js.map +1 -1
  135. package/package.json +2 -2
  136. package/src/adapters/base.ts +7 -0
  137. package/src/adapters/claude.ts +1 -0
  138. package/src/agent-relay-receipt.ts +120 -0
  139. package/src/agent-relay-state.ts +73 -0
  140. package/src/agent-relay-transport.ts +242 -156
  141. package/src/authored-admission.ts +17 -0
  142. package/src/authored-budget.ts +4 -3
  143. package/src/authored-flow-error.ts +0 -1
  144. package/src/authored-flow-executor.ts +27 -7
  145. package/src/authored-flow-loader.ts +96 -13
  146. package/src/authored-helper-effect.ts +5 -3
  147. package/src/authored-mcp.ts +6 -4
  148. package/src/authored-node-entry.ts +90 -0
  149. package/src/authored-node-runner.ts +219 -0
  150. package/src/authored-plugin-effect.ts +6 -3
  151. package/src/authored-root.ts +396 -0
  152. package/src/authored-runtime-capability.ts +40 -0
  153. package/src/authored-source-authority.ts +62 -0
  154. package/src/authored-worker-step.ts +15 -4
  155. package/src/budget-preflight.ts +41 -25
  156. package/src/cli/check.ts +3 -1
  157. package/src/cli/direct-run.ts +24 -16
  158. package/src/cli/run.ts +58 -1
  159. package/src/cli-adapter.ts +27 -0
  160. package/src/cli.ts +5 -5
  161. package/src/cloud-run.ts +74 -21
  162. package/src/failure-kinds.ts +5 -1
  163. package/src/journal-client.ts +6 -2
  164. package/src/llm-worker.ts +4 -2
  165. package/src/local-agent.ts +7 -2
  166. package/src/model-pricing.ts +4 -4
  167. package/src/preflight.ts +40 -18
  168. package/src/protocol.ts +2 -0
  169. package/src/spec.ts +5 -4
  170. package/src/worker-cli.ts +50 -54
  171. package/src/worker-spend.ts +15 -4
  172. package/src/worker.ts +12 -4
package/src/preflight.ts CHANGED
@@ -8,6 +8,7 @@ import type { TriggerSource } from '@relayflows/surface';
8
8
  import { acceptsAnyOutput, inspectStepGate, type StepGateInspection } from './gate-contract.js';
9
9
  import { compileSpec, CompileError } from './compile.js';
10
10
  import { helperCall } from './yaml-helpers.js';
11
+ import { resolveCliModelSelection, type CliModelSource } from './cli-adapter.js';
11
12
  import { isNamedGate, NAMED_GATE_FAILURE_KINDS, type NamedGateFailureKind } from './named-gates.js';
12
13
  import { compileScopes, type ScopeInput, type MountRegistry } from './scope-compiler.js';
13
14
  import { readMountRegistry } from './mount-registry.js';
@@ -22,8 +23,10 @@ export interface CliResolution {
22
23
  stepId: string;
23
24
  cli: string;
24
25
  source: CliResolutionSource;
25
- /** Model the step or selected named agent declared, probed with the CLI. */
26
+ /** Effective model probed with the CLI. */
26
27
  model?: string;
28
+ /** Exact source selected by step > named agent > adapter default priority. */
29
+ modelSource?: CliModelSource;
27
30
  }
28
31
 
29
32
  export interface CliProbeResult {
@@ -208,18 +211,17 @@ function preflightSync(flow: unknown, options: PreflightOptions): PreflightResul
208
211
  };
209
212
  }
210
213
  const diagnostics: PreflightDiagnostic[] = [];
214
+ const cliResolutionDiagnostics: PreflightDiagnostic[] = [];
211
215
  const resolutions: CliResolution[] = [];
212
216
  const resolutionByStep = new Map<string, CliResolution>();
213
217
  const cliProbeResults = new Map<string, CliProbeOutcome>();
214
218
 
215
- diagnostics.push(...unknownModelDiagnostics(compiled, options));
216
219
  diagnostics.push(...scopeDiagnostics(compiled, options));
217
220
  for (const server of new Set(options.mcpServers ?? [])) {
218
221
  if (options.mcp !== undefined && Object.hasOwn(options.mcp, server)) continue;
219
222
  diagnostics.push({ severity: 'refusal', kind: 'mcp_undeclared_server', server,
220
223
  message: `MCP server "${server}" is not declared in the nearest flows.json mcp map.` });
221
224
  }
222
- diagnostics.push(...budgetDiagnostics(compiled));
223
225
  // Resolve the complete flow before touching any environment fact. A later
224
226
  // statically unresolved CLI makes the whole submission impossible, so no
225
227
  // earlier command, provider/model, or trigger probe may run first.
@@ -228,7 +230,7 @@ function preflightSync(flow: unknown, options: PreflightOptions): PreflightResul
228
230
  if (step.type === 'agent' && helperCall(step) !== undefined) continue;
229
231
  const resolution = resolveCli(step, compiled, options.projectCli);
230
232
  if (resolution === undefined) {
231
- diagnostics.push({
233
+ cliResolutionDiagnostics.push({
232
234
  severity: 'refusal',
233
235
  kind: 'cli_unresolved',
234
236
  stepId: step.id,
@@ -239,7 +241,19 @@ function preflightSync(flow: unknown, options: PreflightOptions): PreflightResul
239
241
  resolutionByStep.set(step.id, resolution);
240
242
  }
241
243
  }
242
- if (diagnostics.length > 0) {
244
+ diagnostics.push(...cliResolutionDiagnostics);
245
+ if (cliResolutionDiagnostics.length > 0) {
246
+ return { ok: false, gates: compiled.steps.map(inspectStepGate), resolutions, diagnostics };
247
+ }
248
+ diagnostics.push(...unknownModelDiagnostics(compiled, options, resolutionByStep));
249
+ diagnostics.push(...budgetDiagnostics(
250
+ compiled,
251
+ new Map(resolutions.map(resolution => [resolution.stepId, {
252
+ cli: resolution.cli,
253
+ ...(resolution.model === undefined ? {} : { model: resolution.model }),
254
+ }])),
255
+ ));
256
+ if (diagnostics.some((diagnostic) => diagnostic.severity === 'refusal')) {
243
257
  return { ok: false, gates: compiled.steps.map(inspectStepGate), resolutions, diagnostics };
244
258
  }
245
259
 
@@ -311,6 +325,7 @@ function scopeDiagnostics(flow: FlowSpec, options: PreflightOptions): PreflightR
311
325
  function unknownModelDiagnostics(
312
326
  flow: FlowSpec,
313
327
  options: PreflightOptions,
328
+ resolutionByStep: ReadonlyMap<string, CliResolution> = new Map(),
314
329
  ): PreflightRefusal[] {
315
330
  const diagnostics: PreflightRefusal[] = [];
316
331
  // model_unknown is a governance check: it exists to enforce a project's
@@ -340,16 +355,21 @@ function unknownModelDiagnostics(
340
355
  }
341
356
 
342
357
  for (const step of flow.steps) {
343
- if (step.type === 'deterministic' || step.model === undefined) continue;
344
- if (isKnownModel(step.model, options.models)) continue;
345
- const resolution = resolveCli(step, flow, options.projectCli);
358
+ if (step.type === 'deterministic') continue;
359
+ const resolution = resolutionByStep.get(step.id);
360
+ // Selected named declarations were checked once above, including unused
361
+ // declarations. Other sources are step declarations or adapter defaults.
362
+ if (resolution?.modelSource === 'named') continue;
363
+ const model = resolution?.model ?? step.model;
364
+ if (model === undefined || isKnownModel(model, options.models)) continue;
365
+ if (!enforceRegistry) continue;
346
366
  diagnostics.push({
347
367
  severity: 'refusal',
348
368
  kind: 'model_unknown',
349
369
  stepId: step.id,
350
370
  ...(resolution === undefined ? {} : { cli: resolution.cli }),
351
- model: step.model,
352
- message: unknownModelMessage(step.id, step.model, resolution?.cli, options.modelRegistryPath),
371
+ model,
372
+ message: unknownModelMessage(step.id, model, resolution?.cli, options.modelRegistryPath),
353
373
  });
354
374
  }
355
375
 
@@ -402,14 +422,16 @@ function resolveCli(
402
422
  const named = step.type === 'agent' && step.agent !== undefined
403
423
  ? flow.agents?.[step.agent]
404
424
  : undefined;
405
- // Model comes only from the step or its explicitly selected declaration.
406
- // There is deliberately no flow/project or host default.
407
- const effectiveModel = step.model ?? named?.model;
408
- const model = effectiveModel !== undefined ? { model: effectiveModel } : {};
409
- if (step.cli !== undefined) return { stepId: step.id, cli: step.cli, source: 'step', ...model };
410
- if (named !== undefined) return { stepId: step.id, cli: named.cli, source: 'named', ...model };
411
- if (flow.cli !== undefined) return { stepId: step.id, cli: flow.cli, source: 'flow', ...model };
412
- if (projectCli !== undefined) return { stepId: step.id, cli: projectCli, source: 'project', ...model };
425
+ const resolved = (cli: string, source: CliResolutionSource): CliResolution => {
426
+ const effectiveModel = resolveCliModelSelection(cli, { step: step.model, named: named?.model });
427
+ return { stepId: step.id, cli, source,
428
+ ...(effectiveModel.model === undefined ? {} : { model: effectiveModel.model }),
429
+ ...(effectiveModel.source === undefined ? {} : { modelSource: effectiveModel.source }) };
430
+ };
431
+ if (step.cli !== undefined) return resolved(step.cli, 'step');
432
+ if (named !== undefined) return resolved(named.cli, 'named');
433
+ if (flow.cli !== undefined) return resolved(flow.cli, 'flow');
434
+ if (projectCli !== undefined) return resolved(projectCli, 'project');
413
435
  return undefined;
414
436
  }
415
437
 
package/src/protocol.ts CHANGED
@@ -77,6 +77,8 @@ export interface StepSpend {
77
77
  }
78
78
 
79
79
  export interface RunStartParams {
80
+ /** Caller-owned retry identity. Reuse with a different spec is refused. */
81
+ admission_key?: string;
80
82
  reuse_from_run_id?: string;
81
83
  /**
82
84
  * The kernel spec dialect — the ONE boundary shape `RunSpec::parse`
package/src/spec.ts CHANGED
@@ -238,10 +238,11 @@ export interface AgentStepSpec extends BaseStepSpec {
238
238
  /** Inert preflight declaration; overrides the flow/project CLI default. */
239
239
  cli?: string;
240
240
  /**
241
- * Model the declared CLI must use. Raw Claude/Codex adapters receive their
242
- * real model flag; an identified Relayflows wrapper receives it in its
243
- * same-process execution request. Declared here so the choice is journaled with the step
244
- * instead of being ambient host state.
241
+ * Model the declared CLI must use. A step declaration wins over its selected
242
+ * named agent and any registered adapter default. Raw Claude/Codex adapters
243
+ * receive the effective model as a real flag; an identified Relayflows
244
+ * wrapper receives an explicitly declared model in its same-process request.
245
+ * The effective choice is journaled instead of being ambient host state.
245
246
  */
246
247
  model?: string;
247
248
  surfaces?: AgentSurfaces;
package/src/worker-cli.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  agentExecution,
7
7
  llmExecution,
8
8
  cliAdapterKind,
9
+ resolveCliModel,
9
10
  type CliInvocation,
10
11
  type CliAdapterKind,
11
12
  } from './cli-adapter.js';
@@ -15,8 +16,7 @@ import {
15
16
  } from './wrapper-session.js';
16
17
  import { wrapperEnvironment } from './wrapper-runtime.js';
17
18
  import {
18
- agentRelaySpawn,
19
- deriveAgentName,
19
+ runAgentRelayTask,
20
20
  AgentRelayTransportError,
21
21
  type AgentTransport,
22
22
  } from './agent-relay-transport.js';
@@ -32,6 +32,7 @@ export const WAKE_CONTEXT_ENV = 'RELAYFLOW_WAKE_CONTEXT';
32
32
  export const MODEL_ENV = 'RELAYFLOW_MODEL';
33
33
 
34
34
  export interface WorkerCliResult {
35
+ relay_task?: import('./agent-relay-receipt.js').RelayTaskReceipt;
35
36
  tokens_input?: number;
36
37
  tokens_output?: number;
37
38
  exit_code: number | null;
@@ -40,12 +41,14 @@ export interface WorkerCliResult {
40
41
  }
41
42
 
42
43
  /**
43
- * Optional identity threaded through so the relay transport can derive a
44
- * stable, DM-addressable agent name (flows#385).
44
+ * Journal identity and durable dispatch storage used by the Relay task transport.
45
45
  */
46
46
  export interface AgentRelayContext {
47
47
  runId: string;
48
48
  stepId: string;
49
+ idempotencyKey: string;
50
+ dataDir?: string;
51
+ resultSchema?: unknown;
49
52
  }
50
53
 
51
54
  export async function runAgentCli(
@@ -66,27 +69,28 @@ export async function runAgentCli(
66
69
  throw new Error('Lease-bound agent execution requires macOS or Linux process-group cancellation; Windows is unsupported.');
67
70
  }
68
71
  const kind = cliAdapterKind(cli);
72
+ const effectiveModel = resolveCliModel(cli, model);
73
+
74
+ if (mode === 'agent' && transport === 'relay') {
75
+ return runViaAgentRelay(kind, instruction, wakeContext, effectiveModel, relayContext, cwd, signal);
76
+ }
69
77
 
70
78
  if (kind === 'relayflows-wrapper-v1') {
71
79
  return requirePricedUsage(decodeWrapperResult(await runWrapperSession(
72
80
  cli,
73
81
  instruction,
74
82
  wakeContext,
75
- model,
83
+ effectiveModel,
76
84
  wrapperEnvironment(process.env),
77
85
  wrapperLimits,
78
86
  signal,
79
- )), model);
80
- }
81
-
82
- if (mode === 'agent' && transport === 'relay') {
83
- return runViaAgentRelay(kind, instruction, model, relayContext, cwd);
87
+ )), effectiveModel);
84
88
  }
85
89
 
86
90
  const env: NodeJS.ProcessEnv = { ...process.env };
87
91
  delete env[WAKE_CONTEXT_ENV];
88
92
  delete env[MODEL_ENV];
89
- const invocation = mode === 'llm' ? llmExecution(kind, instruction, model) : agentExecution(kind, instruction, model);
93
+ const invocation = mode === 'llm' ? llmExecution(kind, instruction, effectiveModel) : agentExecution(kind, instruction, effectiveModel);
90
94
 
91
95
  if (wakeContext !== undefined) {
92
96
  try {
@@ -104,57 +108,49 @@ export async function runAgentCli(
104
108
  // Structured provider output carries the authoritative token counts.
105
109
  const args = [...invocation.args];
106
110
  args.splice(args.length - 1, 0, ...(kind === 'claude' ? ['--output-format', 'json'] : ['--json']));
107
- return requirePricedUsage(decodeProviderResult(await spawnInvocation(cli, { ...invocation, args }, env, signal, sidechannel, cwd), kind), model);
111
+ return requirePricedUsage(decodeProviderResult(await spawnInvocation(cli, { ...invocation, args }, env, signal, sidechannel, cwd), kind), effectiveModel);
108
112
  }
109
113
 
110
- /**
111
- * Relay-transport path (flows#385). Fires an agent-relay spawn HTTP request
112
- * that registers the CLI as a first-class workspace participant DMs can
113
- * steer, then reports the spawn outcome as a WorkerCliResult. Streaming
114
- * completion tracking is a follow-up — this initial slice proves the
115
- * transport wire and returns quickly with the registered name in stdout.
116
- */
114
+ /** Wait under the same worker lease for an authoritative task receipt. */
117
115
  async function runViaAgentRelay(
118
- kind: CliAdapterKind,
119
- instruction: string,
120
- model: string | undefined,
121
- relayContext: AgentRelayContext | undefined,
122
- worker_cwd: string | undefined,
116
+ kind: CliAdapterKind, instruction: string, wakeContext: unknown,
117
+ model: string | undefined, context: AgentRelayContext | undefined,
118
+ worker_cwd: string | undefined, signal: AbortSignal | undefined,
123
119
  ): Promise<WorkerCliResult> {
124
- if (kind === 'relayflows-wrapper-v1') {
125
- return {
126
- exit_code: null,
127
- stdout_tail: '',
128
- stderr_tail: 'agent-relay transport does not support the relayflows-wrapper-v1 same-process session.',
129
- };
130
- }
131
- if (relayContext === undefined) {
132
- return {
133
- exit_code: null,
134
- stdout_tail: '',
135
- stderr_tail: 'agent-relay transport requires a relayContext (runId, stepId); the caller did not thread it through.',
136
- };
137
- }
138
- const name = deriveAgentName(relayContext.runId, relayContext.stepId);
139
120
  try {
140
- const handle = await agentRelaySpawn({
141
- name,
142
- cli: kind,
143
- task: instruction,
144
- ...(model === undefined ? {} : { model }),
145
- ...(worker_cwd === undefined ? {} : { worker_cwd }),
146
- });
147
- return {
148
- exit_code: 0,
149
- stdout_tail: JSON.stringify({ registeredName: handle.registeredName, invocationId: handle.invocationId }),
150
- stderr_tail: '',
121
+ if (kind === 'relayflows-wrapper-v1') throw new Error('Relay task transport does not support same-process wrappers.');
122
+ if (!context?.dataDir) throw new Error('Relay task transport requires a durable data directory and journal dispatch identity.');
123
+ const task = instruction + (wakeContext === undefined ? '' : `\n\nWake context (journaled):\n${JSON.stringify(wakeContext)}`)
124
+ + '\n\nReport the final task output with the injected agent_result tool and final=true. Wait for its successful durable acknowledgment before exiting.';
125
+ const received = await runAgentRelayTask({
126
+ cli: kind, task, model, worker_cwd, result_schema: context.resultSchema,
127
+ runId: context.runId, stepId: context.stepId, idempotencyKey: context.idempotencyKey,
128
+ dataDir: context.dataDir,
129
+ }, { signal });
130
+ const receipt = { ...received, error: received.error === null ? null : redactRelayError(received.error) };
131
+ const accounting = receipt.task_execution.accounting;
132
+ const result: WorkerCliResult = {
133
+ relay_task: receipt, exit_code: receipt.status === 'completed' ? 0 : 1,
134
+ stdout_tail: receipt.status === 'completed' ? JSON.stringify(receipt.output) : '',
135
+ stderr_tail: receipt.status === 'failed' ? `Relay task failed: ${receipt.error}` : '',
136
+ ...(accounting?.tokens_input === undefined ? {} : { tokens_input: accounting.tokens_input }),
137
+ ...(accounting?.tokens_output === undefined ? {} : { tokens_output: accounting.tokens_output }),
151
138
  };
139
+ return requirePricedUsage(result, model);
152
140
  } catch (error) {
153
- const detail = error instanceof AgentRelayTransportError
154
- ? error.message
155
- : `agent-relay spawn failed: ${(error as Error).message ?? String(error)}`;
156
- return { exit_code: null, stdout_tail: '', stderr_tail: detail };
141
+ signal?.throwIfAborted();
142
+ const detail = error instanceof AgentRelayTransportError ? error.message
143
+ : error instanceof Error ? error.message : 'Relay task transport failed';
144
+ return { exit_code: null, stdout_tail: '', stderr_tail: redactRelayError(detail) };
145
+ }
146
+ }
147
+
148
+ function redactRelayError(message: string): string {
149
+ for (const key of ['RELAY_AGENT_TOKEN', 'RELAY_API_KEY']) {
150
+ const secret = process.env[key];
151
+ if (secret) message = message.replaceAll(secret, '[redacted]');
157
152
  }
153
+ return message.replace(/\b(?:at|rk|nt|ot|br|arr)_(?:live_)?[A-Za-z0-9_-]+/g, '[redacted]');
158
154
  }
159
155
 
160
156
  async function spawnInvocation(
@@ -1,17 +1,28 @@
1
1
  import { pricedUsage } from './model-pricing.js';
2
2
  import type { WorkerCliResult } from './worker-cli.js';
3
3
 
4
+ /** Zero-dollar usage for an unpriced step, only when the CLI reported tokens. */
5
+ function unmeteredUsage(input: number | undefined, output: number | undefined) {
6
+ if (input === undefined || output === undefined) return undefined;
7
+ return { tokens_in: input, tokens_out: output, dollars: '0.000000' };
8
+ }
9
+
4
10
  /**
5
11
  * Attach token/dollar usage to a worker's CLI result. Invalid token counts
6
12
  * (non-integer or negative) are the one remaining failure mode — those are
7
13
  * journaled as `worker_error` with the usage projected from clamped counts.
8
14
  *
9
- * Unpriced models are NOT a failure here: `pricedUsage` returns
10
- * `dollars: null` and preflight (see `budgetDiagnostics`) has already refused
11
- * declared dollar budgets against unpriced models before the CLI dispatched.
15
+ * Unpriced models are NOT a failure here: the step journals zero dollars, so it
16
+ * never trips a dollar budget, but its reported tokens still count toward any
17
+ * token budget. Preflight (see `budgetDiagnostics`) warns that such a step is
18
+ * unmetered for dollars.
12
19
  */
13
20
  export function workerSpend(result: WorkerCliResult, model?: string) {
14
- try { return { result, usage: pricedUsage(model, result.tokens_input, result.tokens_output) }; }
21
+ try {
22
+ const usage = pricedUsage(model, result.tokens_input, result.tokens_output)
23
+ ?? unmeteredUsage(result.tokens_input, result.tokens_output);
24
+ return { result, usage };
25
+ }
15
26
  catch (error) {
16
27
  return {
17
28
  result: { ...result, exit_code: null, stderr_tail: error instanceof Error ? error.message : 'Invalid model usage' },
package/src/worker.ts CHANGED
@@ -5,6 +5,7 @@ import type { JournalClient } from './journal-client.js';
5
5
  import type { Pins, StepDispatchEvent } from './protocol.js';
6
6
  import type { KernelAgentStep } from './spec.js';
7
7
  import { runAgentCli } from './worker-cli.js';
8
+ import { resolveCliModel } from './cli-adapter.js';
8
9
  import { withWorkerLease } from './worker-lease.js';
9
10
  import { workerInstruction } from './worker-input.js';
10
11
  import { helperCall } from './yaml-helpers.js';
@@ -105,16 +106,18 @@ export class AgentWorker extends EventEmitter {
105
106
  return;
106
107
  }
107
108
  let humanIntervention = false;
109
+ const effectiveModel = typeof spec.cli === 'string' ? resolveCliModel(spec.cli, spec.model) : spec.model;
108
110
  const completed: WorkerCliResult = await withWorkerLease(this.client, dispatch, signal =>
109
111
  typeof spec.cli === 'string' && typeof spec.instruction === 'string'
110
- ? runAgentCli(spec.cli, workerInstruction(spec.instruction, dispatch), dispatch.wake_context, spec.model, undefined, signal, 'agent', this.options.dataDir === undefined ? undefined : {
112
+ ? runAgentCli(spec.cli, workerInstruction(spec.instruction, dispatch), dispatch.wake_context, effectiveModel, undefined, signal, 'agent', this.options.dataDir === undefined ? undefined : {
111
113
  dataDir: this.options.dataDir, runId: dispatch.run_id, stepId: dispatch.step_id,
112
114
  onReady: this.options.onPtyReady, onDrive: () => { humanIntervention = true; },
113
115
  }, typeof spec.cwd === 'string' ? spec.cwd : undefined,
114
116
  spec.transport === 'relay' ? 'relay' : 'direct',
115
- { runId: dispatch.run_id, stepId: dispatch.step_id })
117
+ { runId: dispatch.run_id, stepId: dispatch.step_id, idempotencyKey: dispatch.idempotency_key,
118
+ dataDir: this.options.dataDir, resultSchema: spec.verification?.json_schema })
116
119
  : Promise.resolve({ exit_code: null, stdout_tail: '', stderr_tail: 'agent step has no declared CLI' }));
117
- const { result, usage } = workerSpend(completed, spec.model);
120
+ const { result, usage } = workerSpend(completed, effectiveModel);
118
121
  const completionReason = result.exit_code === 0 ? 'success' : 'worker_error';
119
122
 
120
123
  // Output shape: if the CLI's stdout parses as JSON, promote THAT
@@ -130,7 +133,8 @@ export class AgentWorker extends EventEmitter {
130
133
  // emitting an error JSON with exit 0. `completionReason` is
131
134
  // derived from exit code, so a CLI that exits 0 while emitting
132
135
  // `{"error":...}` will report success with an error payload.
133
- const output = parseJsonOutput(result.stdout_tail) ?? result;
136
+ const output = result.relay_task?.status === 'completed' && result.exit_code === 0
137
+ ? result.relay_task.output : parseJsonOutput(result.stdout_tail) ?? result;
134
138
 
135
139
  await this.client.stepComplete(
136
140
  dispatch.run_id,
@@ -140,6 +144,10 @@ export class AgentWorker extends EventEmitter {
140
144
  completionReason,
141
145
  {
142
146
  output,
147
+ ...(result.relay_task === undefined ? {} : { trajectory_tail: { relay_task: {
148
+ invocation_id: result.relay_task.invocation_id, status: result.relay_task.status,
149
+ task_execution: result.relay_task.task_execution, error: result.relay_task.error,
150
+ } } }),
143
151
  ...(humanIntervention ? { human_intervention: true } : {}),
144
152
  ...(usage !== undefined ? { usage } : {}),
145
153
  started_pins: dispatch.pins,