@parcha/agentrun-client 0.1.0-beta.47 → 0.1.0-beta.49

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.
@@ -105,6 +105,8 @@ export const OPERATIONS = {
105
105
  callRunComputer: { "method": "POST", "path": "/runs/{run_id}/computer/call", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
106
106
  releaseRunComputer: { "method": "POST", "path": "/runs/{run_id}/computer/release", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": false, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
107
107
  createInlineRun: { "method": "POST", "path": "/runs", "pathParams": [], "multiSegment": [], "query": [], "headers": ["Idempotency-Key"], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
108
+ createRunComputerViewer: { "method": "POST", "path": "/runs/{run_id}/computer/viewer", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": false, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
109
+ deleteRun: { "method": "DELETE", "path": "/runs/{run_id}", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "none", "secret": false, "publicFields": [], "tagged": false },
108
110
  listRunFiles: { "method": "GET", "path": "/runs/{run_id}/files", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
109
111
  getRun: { "method": "GET", "path": "/runs/{run_id}", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
110
112
  gradeRun: { "method": "PUT", "path": "/runs/{run_id}/grade", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
@@ -125,6 +127,7 @@ export const OPERATIONS = {
125
127
  getTimeline: { "method": "GET", "path": "/runs/{run_id}/timeline", "pathParams": ["run_id"], "multiSegment": [], "query": ["after", "wait_ms", "limit", "calls"], "headers": ["Last-Event-ID"], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
126
128
  getRunTrace: { "method": "GET", "path": "/runs/{run_id}/trace", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
127
129
  unarchiveRun: { "method": "POST", "path": "/runs/{run_id}/unarchive", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
130
+ getRunUsage: { "method": "GET", "path": "/runs/{run_id}/usage", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
128
131
  completeSdkRun: { "method": "POST", "path": "/sdk-runs/{run_id}/complete", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": ["Idempotency-Key"], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
129
132
  sdkRunEvents: { "method": "POST", "path": "/sdk-runs/{run_id}/events", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": ["Idempotency-Key"], "body": { "required": true, "types": ["application/json"] }, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
130
133
  getSdkRun: { "method": "GET", "path": "/sdk-runs/{run_id}", "pathParams": ["run_id"], "multiSegment": [], "query": [], "headers": [], "body": null, "answer": "json", "secret": false, "publicFields": [], "tagged": false },
@@ -177,7 +180,7 @@ export function resources(call) {
177
180
  connectNative: (body, options) => call("connectNative", [], body, undefined, options),
178
181
  /** Create an agent home (POST /agents). */
179
182
  create: (body, params, options) => call("createAgent", [], body, params, options),
180
- /** Delete an agent another system owns (DELETE /agents/{agent_id}). */
183
+ /** Delete an agent another system owns, or purge an archived agent made here (DELETE /agents/{agent_id}). */
181
184
  deleteAgent: (agentId, options) => call("deleteAgent", [agentId], undefined, undefined, options),
182
185
  /** Remove an agent's own Archil disk, and everything on it (DELETE /agents/{agent_id}/archil). */
183
186
  deleteAgentArchil: (agentId, options) => call("deleteAgentArchil", [agentId], undefined, undefined, options),
@@ -391,6 +394,10 @@ export function resources(call) {
391
394
  computerRelease: (runId, body, options) => call("releaseRunComputer", [runId], body, undefined, options),
392
395
  /** Start a run of an agent another system owns, given inline (POST /runs). */
393
396
  createInlineRun: (body, params, options) => call("createInlineRun", [], body, params, options),
397
+ /** Mint a link to the run's live view for the backend's user (POST /runs/{run_id}/computer/viewer). */
398
+ createRunComputerViewer: (runId, body, options) => call("createRunComputerViewer", [runId], body, undefined, options),
399
+ /** Purge a run's content and keep its cost (DELETE /runs/{run_id}). */
400
+ delete: (runId, options) => call("deleteRun", [runId], undefined, undefined, options),
394
401
  /** The files the run wrote (GET /runs/{run_id}/files). */
395
402
  files: (runId, options) => call("listRunFiles", [runId], undefined, undefined, options),
396
403
  /** One run (GET /runs/{run_id}). */
@@ -431,6 +438,8 @@ export function resources(call) {
431
438
  trace: (runId, options) => call("getRunTrace", [runId], undefined, undefined, options),
432
439
  /** Show the archived run in the lists again (POST /runs/{run_id}/unarchive). */
433
440
  unarchive: (runId, options) => call("unarchiveRun", [runId], undefined, undefined, options),
441
+ /** What a run cost, by model, by who charged for its tools, and by browser provider (GET /runs/{run_id}/usage). */
442
+ usage: (runId, options) => call("getRunUsage", [runId], undefined, undefined, options),
434
443
  },
435
444
  sdkRuns: {
436
445
  /** Complete a backend SDK task (POST /sdk-runs/{run_id}/complete). */
@@ -1,4 +1,4 @@
1
- import type { BackendWorkflowSession, BackendWorkflowBinding, BackendWorkflowBridge, BackendWorkflowToolManifest } from './learning.js';
1
+ import type { BackendWorkflowSession, BackendWorkflowBinding, BackendWorkflowBridge, BackendWorkflowToolManifest, BackendWorkflowCheck, BackendNativeEvent } from './learning.js';
2
2
  export interface WorkflowToolContext {
3
3
  signal: AbortSignal;
4
4
  runId: string;
@@ -94,22 +94,44 @@ export interface WorkflowMcpBridgeOptions<Document extends WorkflowEngineDocumen
94
94
  leaseDurationMs?: number;
95
95
  /** Local metadata only; callback inputs/results and capability tokens are never emitted. */
96
96
  onEvent?(event: WorkflowBridgeEvent): void;
97
+ /** Opt in to fresh, explicitly read-only observations when the native recording has no match. Default false. */
98
+ shadowReadFallback?: boolean;
99
+ /** Optional host mapping for a draft's typed input. The default accepts the task's JSON object or one
100
+ * unambiguous recorded tool input matching the schema. It never guesses semantic fields. */
101
+ resolveCheckInput?(check: BackendWorkflowCheck, turn: {
102
+ input: string;
103
+ events: readonly BackendNativeEvent[];
104
+ signal: AbortSignal;
105
+ }): Promise<Record<string, unknown> | null> | Record<string, unknown> | null;
97
106
  }
98
107
  /** Private host handle. Never expose its arguments or capability in model-visible results or logs. */
99
108
  export interface WorkflowMcpBinding extends BackendWorkflowBinding {
109
+ execute(name: string, input: Record<string, unknown>, signal: AbortSignal): Promise<WorkflowToolResult>;
100
110
  mcpArguments(name: string, input: Record<string, unknown>): {
101
111
  capability: string;
102
112
  name: string;
103
113
  input: Record<string, unknown>;
104
114
  };
105
115
  }
106
- export interface WorkflowMcpBridge extends BackendWorkflowBridge {
116
+ export type WorkflowToolResult = {
117
+ content: {
118
+ type: 'text';
119
+ text: string;
120
+ }[];
121
+ isError?: boolean;
122
+ };
123
+ export interface WorkflowBridge extends BackendWorkflowBridge {
124
+ bind(session: BackendWorkflowSession): WorkflowMcpBinding;
125
+ check: NonNullable<BackendWorkflowBridge['check']>;
126
+ close(): Promise<void>;
127
+ }
128
+ export interface WorkflowMcpBridge extends WorkflowBridge {
107
129
  bind(session: BackendWorkflowSession): WorkflowMcpBinding;
108
130
  readonly url: string;
109
131
  readonly headers: Readonly<Record<string, string>>;
110
132
  close(): Promise<void>;
111
133
  }
112
- /** Start once, explicitly configure this endpoint on the original native SDK, then pass the bridge to its wrapper.
113
- * The endpoint never executes a workflow supplied by a model: only the server's checked, pinned run snapshot.
114
- * Nothing is installed into the backend or executed through a new hidden native SDK session. */
134
+ /** In-process host binding; opens no port or MCP connection. */
135
+ export declare function createWorkflowBridge<Document extends WorkflowEngineDocument, NodeRequest extends WorkflowModelRequest, JudgeRequest extends WorkflowJudgeRequest, JudgeResult>(options: WorkflowMcpBridgeOptions<Document, NodeRequest, JudgeRequest, JudgeResult>): WorkflowBridge;
136
+ /** Optional authenticated loopback transport over the same host-owned execution path. */
115
137
  export declare function createWorkflowMcpBridge<Document extends WorkflowEngineDocument, NodeRequest extends WorkflowModelRequest, JudgeRequest extends WorkflowJudgeRequest, JudgeResult>(options: WorkflowMcpBridgeOptions<Document, NodeRequest, JudgeRequest, JudgeResult>): Promise<WorkflowMcpBridge>;
package/dist/workflows.js CHANGED
@@ -1,10 +1,8 @@
1
1
  /** Optional, local workflow MCP bridge. Native SDK credentials and tools remain owned by the backend. */
2
2
  import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
3
3
  import { createServer } from 'node:http';
4
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
5
- import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
6
- import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
7
- import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
4
+ import { Ajv } from 'ajv';
5
+ import formatsModule from 'ajv-formats';
8
6
  const canonicalTool = /^mcp:[a-z][a-z0-9-]{0,31}\/[A-Za-z0-9_-]{1,64}$/;
9
7
  const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
10
8
  const copy = (value) => JSON.parse(JSON.stringify(value));
@@ -19,9 +17,69 @@ const limit = (value, fallback, max, name) => {
19
17
  };
20
18
  class Refused extends Error {
21
19
  }
20
+ /** Schema validation is shared by local and MCP execution; the in-process path imports no MCP runtime. */
21
+ class SchemaValidator {
22
+ #ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true });
23
+ #validators = new Map();
24
+ constructor() { formatsModule(this.#ajv); }
25
+ getValidator(schema) {
26
+ // Tool and workflow snapshots are cloned. Reuse identical definitions, but let Ajv reject a
27
+ // different definition with an already registered $id instead of validating against stale rules.
28
+ const key = canonical(schema), cached = this.#validators.get(key);
29
+ if (cached)
30
+ return cached;
31
+ const validate = this.#ajv.compile(schema);
32
+ // A draft cannot turn this synchronous gate into an unobserved rejecting promise in the host process.
33
+ if ('$async' in validate && validate.$async)
34
+ throw new TypeError('Asynchronous workflow schemas are not supported.');
35
+ const validator = (value) => ({ valid: validate(value) === true });
36
+ this.#validators.set(key, validator);
37
+ return validator;
38
+ }
39
+ }
22
40
  const refuse = (message) => { throw new Refused(message); };
23
41
  const pointer = (value, path) => path.split('/').slice(1).reduce((node, key) => object(node) || Array.isArray(node) ? node[key.replace(/~1/g, '/').replace(/~0/g, '~')] : undefined, value);
24
42
  const toolResult = (text, isError = false) => ({ content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) });
43
+ const canonical = (value) => JSON.stringify(value, (_, item) => object(item)
44
+ ? Object.fromEntries(Object.keys(item).sort().map(key => [key, item[key]])) : item);
45
+ const answerOf = (output) => {
46
+ const values = object(output) ? Object.values(output) : [];
47
+ return typeof output === 'string' ? output : values.length === 1 && typeof values[0] === 'string' ? values[0] : JSON.stringify(output ?? null);
48
+ };
49
+ /** Raw values stay raw. Only an SDK adapter identifies transport; the original tool schema resolves text ambiguity. */
50
+ function recordedOutput(value, format, accepts) {
51
+ if (!format)
52
+ return value;
53
+ if (format === 'mcp') {
54
+ if (!object(value))
55
+ return refuse('The recorded MCP result is not an envelope.');
56
+ if (value.isError === true)
57
+ return refuse('The recorded MCP result reports a tool failure.');
58
+ if (Object.hasOwn(value, 'structuredContent'))
59
+ return value.structuredContent;
60
+ value = value.content;
61
+ }
62
+ else if (format !== 'mcp-content')
63
+ return refuse('The recorded tool output format is unsupported.');
64
+ if (Array.isArray(value) && value.length === 1 && object(value[0]) && value[0].type === 'text')
65
+ value = value[0].text;
66
+ if (typeof value !== 'string')
67
+ return refuse('The recorded MCP result has no unambiguous original output.');
68
+ let parsed;
69
+ try {
70
+ parsed = JSON.parse(value);
71
+ }
72
+ catch {
73
+ return value;
74
+ }
75
+ // Text may be a literal string or JSON. Do not guess or recursively decode business fields.
76
+ if (!accepts)
77
+ return refuse('MCP text needs the original output schema or structured content for a shadow check.');
78
+ const rawValid = accepts(value).valid, parsedValid = accepts(parsed).valid;
79
+ if (rawValid === parsedValid)
80
+ return refuse('The recorded MCP text has ambiguous or invalid output types.');
81
+ return rawValid ? value : parsed;
82
+ }
25
83
  /** Race work with cancellation without pretending an uncooperative callback can be rolled back. */
26
84
  async function cancellable(work, signal) {
27
85
  signal.throwIfAborted();
@@ -41,7 +99,7 @@ async function cancellable(work, signal) {
41
99
  /** Start once, explicitly configure this endpoint on the original native SDK, then pass the bridge to its wrapper.
42
100
  * The endpoint never executes a workflow supplied by a model: only the server's checked, pinned run snapshot.
43
101
  * Nothing is installed into the backend or executed through a new hidden native SDK session. */
44
- export async function createWorkflowMcpBridge(options) {
102
+ function makeWorkflowBridge(options) {
45
103
  if (!options.engine || typeof options.engine.inspectWorkflow !== 'function' || typeof options.engine.runWorkflow !== 'function' || typeof options.engine.resolveSchemaForWorkflow !== 'function')
46
104
  throw new TypeError('Provide an explicit host workflow engine with inspection, execution and schema resolution.');
47
105
  if (typeof options.policy !== 'function')
@@ -58,7 +116,18 @@ export async function createWorkflowMcpBridge(options) {
58
116
  // Capture callbacks and schemas once: later caller mutation cannot silently expand this bridge's authority.
59
117
  const { inspectWorkflow, runWorkflow, resolveSchemaForWorkflow } = options.engine;
60
118
  const policy = options.policy, runNode = options.runNode, runJudge = options.runJudge, observer = options.onEvent;
61
- const validator = new AjvJsonSchemaValidator();
119
+ const resolveCheckInput = options.resolveCheckInput;
120
+ // Where a shadow check differs from the server's own replay (serve learn/replay-calls.ts), and why:
121
+ // - Reads. The server runs a read live when the recording lacks it; here a missing read is refused (the turn is given
122
+ // back, never counted) unless the host opts in. The host's callbacks run under the host's credentials and policy,
123
+ // so running one during a check is the host's call, and every fresh read is reported (fresh_reads).
124
+ // - Writes. Both answer a write only from a recorded call with the same tool and arguments, never sending it. Here a
125
+ // trace with writes must also replay in the recorded order: the host's write callbacks are not idempotent by
126
+ // contract, and order is the only proof the shadow saw the state the native turn saw.
127
+ // - Limits. A server replay is a run bounded by its deadline and the agent's cap; this one runs in the host's process
128
+ // right after the native turn, so maxToolCalls, maxNodeSteps and maxDurationMs bound it there.
129
+ const readFallback = options.shadowReadFallback === true;
130
+ const validator = new SchemaValidator();
62
131
  const registered = new Map();
63
132
  for (const tool of options.tools) {
64
133
  if (!tool || typeof tool !== 'object' || typeof tool.name !== 'string' || !canonicalTool.test(tool.name) || registered.has(tool.name) ||
@@ -83,7 +152,7 @@ export async function createWorkflowMcpBridge(options) {
83
152
  const readOnlyHint = !runNode && !runJudge && [...registered.values()].every(tool => tool.manifest.permission !== 'allow' || tool.readOnly);
84
153
  const authorization = `Bearer ${randomBytes(32).toString('hex')}`;
85
154
  const leases = new Map();
86
- const connections = new Set();
155
+ const shadows = new Set();
87
156
  let closed = false;
88
157
  const emit = (event) => { try {
89
158
  observer?.(Object.freeze(event));
@@ -119,6 +188,204 @@ export async function createWorkflowMcpBridge(options) {
119
188
  }
120
189
  return workflow;
121
190
  };
191
+ const shadowCheck = async (candidate, turn) => {
192
+ // Freeze the exact receipt and native evidence before any caller callback or await. The result reports
193
+ // execution only: agreement and promotion belong to the server's independent comparison.
194
+ const check = freeze(copy(candidate)), events = freeze(copy(turn.events));
195
+ const controller = new AbortController();
196
+ shadows.add(controller);
197
+ const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(maxDuration), ...(turn.signal ? [turn.signal] : [])]);
198
+ let skipped;
199
+ let calls = 0, nodes = 0, fresh = 0;
200
+ // The report names every fresh read it made, so the server's check record says which answers came from live reads.
201
+ const receipt = () => ({ type: 'workflow_check', id: check.id, digest: check.digest, ...(fresh ? { fresh_reads: fresh } : {}) });
202
+ try {
203
+ signal.throwIfAborted();
204
+ if (closed || turn.outcome.status !== 'completed')
205
+ refuse('A shadow needs a completed native turn and an open host bridge.');
206
+ if (Buffer.byteLength(JSON.stringify(events)) > 3_000_000)
207
+ refuse('The native recording exceeds the shadow limit.');
208
+ const workflow = checked(check.workflow.workflow);
209
+ const inspection = inspectWorkflow(workflow), tools = new Set(inspection.requires.tools);
210
+ const byId = new Map();
211
+ // Once a trace writes, reads cannot move across those effects either. Hold any ambiguous
212
+ // lifecycle and replay the entire serial observation/effect sequence, not a bag of receipts.
213
+ const ordered = events.some(event => event.type === 'tool' && registered.has(event.name) && !registered.get(event.name).readOnly);
214
+ if (ordered)
215
+ for (const entry of inspection.nodes) {
216
+ const node = pointer(workflow, entry.path);
217
+ if (node.node === 'parallel' || node.node === 'map' && node.maxConcurrency !== 1)
218
+ refuse('A trace with writes requires a structurally serial candidate; parallel branches and concurrent maps cannot prove effect order.');
219
+ }
220
+ const nativeSequence = [];
221
+ let openCall;
222
+ for (const event of events) {
223
+ if (event.type !== 'tool')
224
+ continue;
225
+ if (event.name === 'learned_workflow' || event.parent_tool_use_id)
226
+ refuse('A shadow needs independent native tool evidence.');
227
+ const tool = registered.get(event.name);
228
+ if (!tool)
229
+ refuse('The native recording includes a tool whose side effects are unknown to this host bridge.');
230
+ // Every native write matters, including a tool the candidate omits. Only wholly read-only
231
+ // traces may ignore/reorder observations. Buffered results cannot establish effect order.
232
+ if (ordered && event.orderUnknown)
233
+ refuse('The native recording does not establish effect order. Use a complete streamed lifecycle.');
234
+ if (!ordered && tool.readOnly && !tools.has(event.name))
235
+ continue;
236
+ if (event.status === 'started') {
237
+ if (byId.has(event.id) || !object(event.input))
238
+ return refuse('The native recording has ambiguous tool inputs.');
239
+ if (ordered) {
240
+ if (openCall !== undefined)
241
+ refuse('Overlapping native calls do not establish a safe effect replay order.');
242
+ openCall = event.id;
243
+ nativeSequence.push(`${event.name}\n${canonical(event.input)}`);
244
+ }
245
+ byId.set(event.id, { name: event.name, input: event.input, status: 'started' });
246
+ }
247
+ else {
248
+ const call = byId.get(event.id);
249
+ if (!call || call.status !== 'started' || call.name !== event.name || !Object.hasOwn(event, 'output'))
250
+ return refuse('The native recording has an unmatched tool result.');
251
+ if (ordered) {
252
+ if (openCall !== event.id || event.status !== 'completed')
253
+ refuse('The native recording has an uncertain effect outcome.');
254
+ openCall = undefined;
255
+ }
256
+ call.status = event.status;
257
+ call.output = recordedOutput(event.output, event.outputFormat, tool.output);
258
+ }
259
+ }
260
+ if ([...byId.values()].some(call => call.status === 'started'))
261
+ refuse('The native recording has an unfinished tool call.');
262
+ const recorded = new Map();
263
+ let nextEffect = 0, activeEffect = false;
264
+ for (const call of byId.values()) {
265
+ const key = `${call.name}\n${canonical(call.input)}`, prior = recorded.get(key);
266
+ if (prior && (prior.status !== call.status || canonical(prior.output) !== canonical(call.output)))
267
+ refuse('Repeated native calls returned different results.');
268
+ recorded.set(key, call);
269
+ }
270
+ const schema = workflow.input ? resolveSchemaForWorkflow(workflow, workflow.schemas[workflow.input.schemaId]) : { type: 'object' };
271
+ const accepts = validator.getValidator(schema);
272
+ let input = null;
273
+ // The server reserves a JSON object task only when the draft takes it (serve's fits); a prose task's input is
274
+ // resolved here, and one that cannot be resolved gives the turn back.
275
+ if (resolveCheckInput)
276
+ input = await cancellable(Promise.resolve(resolveCheckInput(check, { input: turn.input, events, signal })), signal);
277
+ else {
278
+ let parsed;
279
+ try {
280
+ parsed = JSON.parse(turn.input);
281
+ }
282
+ catch { /* A natural-language task is not guessed into fields. */ }
283
+ if (object(parsed) && accepts(parsed).valid)
284
+ input = parsed;
285
+ else {
286
+ const candidates = [...new Map([...recorded.values()].filter(call => call.status === 'completed' && accepts(call.input).valid).map(call => [canonical(call.input), call.input])).values()];
287
+ if (candidates.length === 1)
288
+ input = candidates[0];
289
+ else if (candidates.length === 0 && accepts({}).valid)
290
+ input = {};
291
+ }
292
+ }
293
+ if (!object(input) || !accepts(input).valid)
294
+ return refuse('No unambiguous native input matches the draft schema. Provide resolveCheckInput in the host.');
295
+ const cache = new Map();
296
+ const result = await cancellable(runWorkflow(workflow, copy(input), {
297
+ signal,
298
+ onEvent(event) { if (event.type === 'node.start' && ++nodes > maxNodes)
299
+ controller.abort(new Refused('The shadow node limit was reached.')); },
300
+ runCode: async () => refuse('Code execution is not permitted by this bridge.'),
301
+ ...(runNode ? { runNode: async (request) => {
302
+ signal.throwIfAborted();
303
+ if (request.tools?.length || request.context === 'fork')
304
+ refuse('Native tools and transcript forks are not delegated to model nodes.');
305
+ return runNode({ ...request, signal: AbortSignal.any([signal, ...(request.signal ? [request.signal] : [])]) });
306
+ } } : {}),
307
+ ...(runJudge ? { runJudge: async (request) => {
308
+ signal.throwIfAborted();
309
+ return runJudge({ ...request, signal: AbortSignal.any([signal, ...(request.signal ? [request.signal] : [])]) });
310
+ } } : {}),
311
+ runEffect: async (request) => {
312
+ signal.throwIfAborted();
313
+ const name = request.node.via === 'tool' ? request.node.tool : undefined, tool = name ? registered.get(name) : undefined;
314
+ if (!name || !tool || tool.manifest.permission !== 'allow')
315
+ return refuse('This tool was not explicitly delegated.');
316
+ if (++calls > maxCalls)
317
+ return refuse('The shadow tool call limit was reached.');
318
+ const args = copy(request.input);
319
+ if (!tool.input(args).valid)
320
+ return refuse('Shadow arguments do not match the original tool schema.');
321
+ if (ordered && activeEffect)
322
+ return refuse('Concurrent shadow calls cannot prove the native effect order.');
323
+ if (ordered)
324
+ activeEffect = true;
325
+ try {
326
+ const ctx = { runId: turn.runId, workflow: check.workflow.name, signal: AbortSignal.any([signal, request.signal]), idempotencyKey: `${check.id}:${request.idempotencyKey}` };
327
+ if (await cancellable(Promise.resolve(policy(name, copy(args), ctx)), ctx.signal) !== 'allow')
328
+ return refuse('The backend policy did not allow this shadow call.');
329
+ ctx.signal.throwIfAborted();
330
+ const key = `${name}\n${canonical(args)}`, known = recorded.get(key);
331
+ let output;
332
+ if (known?.status === 'failed')
333
+ return refuse('The recorded native tool failed.');
334
+ if (known && known.status === 'completed' && (!ordered || nativeSequence[nextEffect] === key)) {
335
+ output = copy(known.output);
336
+ if (ordered)
337
+ nextEffect++;
338
+ }
339
+ else if (!tool.readOnly) {
340
+ skipped = { tool: name };
341
+ return refuse('The shadow write does not match the next recorded native write.');
342
+ }
343
+ else {
344
+ if (ordered)
345
+ return refuse('The shadow read does not match the next recorded native call.');
346
+ if (!readFallback)
347
+ return refuse('The native recording has no matching read result; fresh shadow reads are not enabled.');
348
+ // Only explicit read-only callbacks may run, and once per arguments. Failed calls are not retried.
349
+ let read = cache.get(key);
350
+ if (!read) {
351
+ fresh++;
352
+ read = Promise.resolve().then(() => { ctx.signal.throwIfAborted(); return tool.execute(args, ctx); });
353
+ cache.set(key, read);
354
+ }
355
+ output = await cancellable(read, ctx.signal);
356
+ }
357
+ ctx.signal.throwIfAborted();
358
+ if (tool.output && !tool.output(output).valid)
359
+ return refuse('A recorded result does not match the original tool schema.');
360
+ return copy(output);
361
+ }
362
+ finally {
363
+ if (ordered)
364
+ activeEffect = false;
365
+ }
366
+ },
367
+ }), signal);
368
+ signal.throwIfAborted();
369
+ if (skipped)
370
+ return { ...receipt(), outcome: 'skipped_write', skipped };
371
+ if (result.status !== 'complete')
372
+ return { ...receipt(), outcome: 'handed_back', reason: 'The draft did not answer alone.' };
373
+ if (ordered && nextEffect !== nativeSequence.length)
374
+ refuse('The shadow omitted a recorded native call from a trace with writes.');
375
+ const answer = answerOf(result.output);
376
+ if (Buffer.byteLength(answer) > 65_536)
377
+ refuse('The shadow answer exceeds the result limit.');
378
+ return { ...receipt(), outcome: 'answered', answer };
379
+ }
380
+ catch (error) {
381
+ return skipped ? { ...receipt(), outcome: 'skipped_write', skipped }
382
+ : { ...receipt(), outcome: 'failed', reason: error instanceof Refused ? error.message : 'The shadow did not complete; native results are unchanged.' };
383
+ }
384
+ finally {
385
+ controller.abort();
386
+ shadows.delete(controller);
387
+ }
388
+ };
122
389
  const execute = async (args, requestSignal) => {
123
390
  const capability = args?.capability;
124
391
  const lease = typeof capability === 'string' ? leases.get(capability) : undefined;
@@ -225,8 +492,7 @@ export async function createWorkflowMcpBridge(options) {
225
492
  if (result.status !== 'complete')
226
493
  throw new Refused('The workflow escalated without completing. Inspect its result before another run.');
227
494
  // Match the hosted learned_workflow handoff: one textual answer stays text, not an extra JSON wrapper.
228
- const values = object(result.output) ? Object.values(result.output) : [];
229
- const output = typeof result.output === 'string' ? result.output : values.length === 1 && typeof values[0] === 'string' ? values[0] : JSON.stringify(result.output ?? null);
495
+ const output = answerOf(result.output);
230
496
  if (Buffer.byteLength(output) > 65_536)
231
497
  refuse('The workflow output exceeds the bridge response limit. Do not rerun its effects to recover the output.');
232
498
  await record('learned_workflow', invocation, 'completed');
@@ -257,61 +523,9 @@ export async function createWorkflowMcpBridge(options) {
257
523
  lease.active = false;
258
524
  }
259
525
  };
260
- let expectedHost = '';
261
- const http = createServer(async (request, response) => {
262
- const reply = (status) => { response.writeHead(status, { 'content-type': 'text/plain' }); response.end('Request refused.'); };
263
- const bearer = Buffer.from(request.headers.authorization ?? '');
264
- const allowed = Buffer.from(authorization);
265
- if (request.headers.host !== expectedHost || (request.headers.origin !== undefined && request.headers.origin !== `http://${expectedHost}`) ||
266
- request.socket.remoteAddress !== '127.0.0.1' || bearer.length !== allowed.length || !timingSafeEqual(bearer, allowed))
267
- return reply(403);
268
- if (request.url !== '/mcp')
269
- return reply(404);
270
- if (request.method !== 'POST')
271
- return reply(405);
272
- let size = 0;
273
- try {
274
- const chunks = [];
275
- for await (const chunk of request) {
276
- size += chunk.length;
277
- if (size > 131_072)
278
- return reply(413);
279
- chunks.push(chunk);
280
- }
281
- const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
282
- if (connections.size >= 64 || closed)
283
- return reply(503);
284
- const server = new Server({ name: 'agentrun-workflows', version: '1.0.0' }, { capabilities: { tools: {} } });
285
- connections.add(server);
286
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [{ name: 'learned_workflow',
287
- description: 'Run an approved workflow using this backend\'s existing tools, with the current task\'s workflow name, capability and fresh input. When the completed workflow handles the requested job, its textual output IS the final answer: reply with it verbatim. Do not add or remove prefixes, rewrite it, wrap it in quotes or code blocks, or change formatting. Never retry uncertain effects.',
288
- inputSchema: { type: 'object', required: ['capability', 'name', 'input'], additionalProperties: false,
289
- properties: { capability: { type: 'string' }, name: { type: 'string' }, input: { type: 'object' } } },
290
- annotations: { openWorldHint: false, idempotentHint: false, readOnlyHint } }] }));
291
- server.setRequestHandler(CallToolRequestSchema, async (call, extra) => call.params.name === 'learned_workflow' ? execute(call.params.arguments, extra.signal) : toolResult('Unknown tool.', true));
292
- const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
293
- response.once('close', () => { connections.delete(server); void server.close(); });
294
- await server.connect(transport);
295
- await transport.handleRequest(request, response, body);
296
- }
297
- catch {
298
- if (!response.headersSent)
299
- reply(400);
300
- else
301
- response.end();
302
- }
303
- });
304
- http.requestTimeout = 10_000;
305
- http.headersTimeout = 5_000;
306
- await new Promise((resolve, reject) => { http.once('error', reject); http.listen(0, '127.0.0.1', () => { http.off('error', reject); resolve(); }); });
307
- const address = http.address();
308
- if (!address || typeof address === 'string') {
309
- http.close();
310
- throw new Error('Could not bind the workflow MCP server.');
311
- }
312
- expectedHost = `127.0.0.1:${address.port}`;
313
- return Object.freeze({
314
- url: `http://${expectedHost}/mcp`, headers: Object.freeze({ Authorization: authorization }), catalog, adapters,
526
+ const bridge = Object.freeze({
527
+ catalog, adapters,
528
+ check: shadowCheck,
315
529
  bind(session) {
316
530
  if (closed || leases.size >= 64)
317
531
  throw new Error('The workflow bridge cannot bind another native task.');
@@ -336,7 +550,7 @@ export async function createWorkflowMcpBridge(options) {
336
550
  const timer = setTimeout(() => lease.close(), leaseDuration);
337
551
  timer.unref();
338
552
  leases.set(capability, lease);
339
- const context = lease.workflows.length ? `Compiled workflows for this task (not checked):\n${JSON.stringify(lease.workflows.map(workflow => {
553
+ const context = lease.workflows.length ? `Compiled workflows for this task (passed the agent-answer check):\n${JSON.stringify(lease.workflows.map(workflow => {
340
554
  let input_schema;
341
555
  try {
342
556
  const doc = checked(workflow.workflow);
@@ -351,6 +565,7 @@ export async function createWorkflowMcpBridge(options) {
351
565
  object(input) && input.capability === capability && typeof input.name === 'string' && object(input.input) &&
352
566
  Object.keys(input).every(key => ['capability', 'name', 'input'].includes(key)) && lease.workflows.some(flow => flow.name === input.name);
353
567
  return { context, close: () => lease.close(),
568
+ execute: (name, input, signal) => execute({ capability, name, input }, signal),
354
569
  mcpArguments(name, input) {
355
570
  if (released || closed || lease.controller.signal.aborted)
356
571
  throw new Error('The workflow binding has closed.');
@@ -381,6 +596,84 @@ export async function createWorkflowMcpBridge(options) {
381
596
  closed = true;
382
597
  for (const lease of leases.values())
383
598
  lease.close();
599
+ for (const shadow of shadows)
600
+ shadow.abort();
601
+ },
602
+ });
603
+ return { bridge, execute, authorization, readOnlyHint };
604
+ }
605
+ /** In-process host binding; opens no port or MCP connection. */
606
+ export function createWorkflowBridge(options) {
607
+ return makeWorkflowBridge(options).bridge;
608
+ }
609
+ /** Optional authenticated loopback transport over the same host-owned execution path. */
610
+ export async function createWorkflowMcpBridge(options) {
611
+ const { bridge, execute, authorization, readOnlyHint } = makeWorkflowBridge(options);
612
+ const [{ Server }, { StreamableHTTPServerTransport }, { CallToolRequestSchema, ListToolsRequestSchema }] = await Promise.all([
613
+ import('@modelcontextprotocol/sdk/server/index.js'), import('@modelcontextprotocol/sdk/server/streamableHttp.js'), import('@modelcontextprotocol/sdk/types.js'),
614
+ ]);
615
+ const connections = new Set();
616
+ let closed = false;
617
+ let expectedHost = '';
618
+ const http = createServer(async (request, response) => {
619
+ const reply = (status) => { response.writeHead(status, { 'content-type': 'text/plain' }); response.end('Request refused.'); };
620
+ const bearer = Buffer.from(request.headers.authorization ?? '');
621
+ const allowed = Buffer.from(authorization);
622
+ if (request.headers.host !== expectedHost || (request.headers.origin !== undefined && request.headers.origin !== `http://${expectedHost}`) ||
623
+ request.socket.remoteAddress !== '127.0.0.1' || bearer.length !== allowed.length || !timingSafeEqual(bearer, allowed))
624
+ return reply(403);
625
+ if (request.url !== '/mcp')
626
+ return reply(404);
627
+ if (request.method !== 'POST')
628
+ return reply(405);
629
+ let size = 0;
630
+ try {
631
+ const chunks = [];
632
+ for await (const chunk of request) {
633
+ size += chunk.length;
634
+ if (size > 131_072)
635
+ return reply(413);
636
+ chunks.push(chunk);
637
+ }
638
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
639
+ if (connections.size >= 64 || closed)
640
+ return reply(503);
641
+ const server = new Server({ name: 'agentrun-workflows', version: '1.0.0' }, { capabilities: { tools: {} } });
642
+ connections.add(server);
643
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [{ name: 'learned_workflow',
644
+ description: 'Run a compiled workflow that passed the agent-answer check using this backend\'s existing tools, with the current task\'s workflow name, capability and fresh input. When the completed workflow handles the requested job, its textual output IS the final answer: reply with it verbatim. Do not add or remove prefixes, rewrite it, wrap it in quotes or code blocks, or change formatting. Never retry uncertain effects.',
645
+ inputSchema: { type: 'object', required: ['capability', 'name', 'input'], additionalProperties: false,
646
+ properties: { capability: { type: 'string' }, name: { type: 'string' }, input: { type: 'object' } } },
647
+ annotations: { openWorldHint: false, idempotentHint: false, readOnlyHint } }] }));
648
+ server.setRequestHandler(CallToolRequestSchema, async (call, extra) => call.params.name === 'learned_workflow' ? execute(call.params.arguments, extra.signal) : toolResult('Unknown tool.', true));
649
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
650
+ response.once('close', () => { connections.delete(server); void server.close(); });
651
+ await server.connect(transport);
652
+ await transport.handleRequest(request, response, body);
653
+ }
654
+ catch {
655
+ if (!response.headersSent)
656
+ reply(400);
657
+ else
658
+ response.end();
659
+ }
660
+ });
661
+ http.requestTimeout = 10_000;
662
+ http.headersTimeout = 5_000;
663
+ await new Promise((resolve, reject) => { http.once('error', reject); http.listen(0, '127.0.0.1', () => { http.off('error', reject); resolve(); }); });
664
+ const address = http.address();
665
+ if (!address || typeof address === 'string') {
666
+ http.close();
667
+ throw new Error('Could not bind the workflow MCP server.');
668
+ }
669
+ expectedHost = `127.0.0.1:${address.port}`;
670
+ return Object.freeze({
671
+ ...bridge, url: `http://${expectedHost}/mcp`, headers: Object.freeze({ Authorization: authorization }),
672
+ async close() {
673
+ if (closed)
674
+ return;
675
+ closed = true;
676
+ await bridge.close();
384
677
  await Promise.allSettled([...connections].map(server => server.close()));
385
678
  await new Promise(resolve => { http.close(() => resolve()); http.closeAllConnections(); });
386
679
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-client",
3
- "version": "0.1.0-beta.47",
3
+ "version": "0.1.0-beta.49",
4
4
  "description": "A typed TypeScript client for a self-hosted AgentRun server: a method per operation of its API, typed from its OpenAPI document, with waiting for a run and following its timeline. No dependencies; fetch only.",
5
5
  "keywords": [
6
6
  "agentrun",
@@ -67,14 +67,22 @@
67
67
  "tag": "beta"
68
68
  },
69
69
  "peerDependencies": {
70
- "@modelcontextprotocol/sdk": "1.32.2"
70
+ "@modelcontextprotocol/sdk": "1.32.2",
71
+ "ajv": "8.18.0",
72
+ "ajv-formats": "3.0.1"
71
73
  },
72
74
  "peerDependenciesMeta": {
73
75
  "@modelcontextprotocol/sdk": {
74
76
  "optional": true
77
+ },
78
+ "ajv": {
79
+ "optional": true
80
+ },
81
+ "ajv-formats": {
82
+ "optional": true
75
83
  }
76
84
  },
77
85
  "devDependencies": {
78
- "@parcha/agentrun-dsl": "0.1.0-beta.47"
86
+ "@parcha/agentrun-dsl": "0.1.0-beta.49"
79
87
  }
80
88
  }