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

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/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # @parcha/agentrun-client
2
2
 
3
3
  A typed TypeScript client for an AgentRun server you host yourself, the open platform's server: one method per operation of
4
- its API, typed from the OpenAPI document it serves, plus waiting for a run and following its timeline. No dependencies: it
5
- uses `fetch`, on Node.js 24.22.3 or newer.
4
+ its API, typed from the OpenAPI document it serves, plus waiting for a run and following its timeline. The base API client has no dependencies: it
5
+ uses `fetch`, on Node.js 24.22.3 or newer. Optional workflow helpers use the peers documented below.
6
6
 
7
7
  ## Install
8
8
 
@@ -10,6 +10,35 @@ uses `fetch`, on Node.js 24.22.3 or newer.
10
10
  npm install @parcha/agentrun-client
11
11
  ```
12
12
 
13
+ ## Check the installation without credentials
14
+
15
+ Save this as `check-agentrun.mjs`, then run `node check-agentrun.mjs`. It exercises the installed client's
16
+ request and response handling using an injected local response and a fake key. It contacts no server and
17
+ does not test a live connection or model.
18
+
19
+ ```js
20
+ import assert from "node:assert/strict";
21
+ import { AgentRun } from "@parcha/agentrun-client";
22
+
23
+ const client = new AgentRun({
24
+ baseUrl: "https://agentrun.example.com/v2",
25
+ apiKey: "not-a-secret",
26
+ fetch: async (url, request) => {
27
+ assert.equal(String(url), "https://agentrun.example.com/v2/agents");
28
+ assert.equal(request.method, "GET");
29
+ return Response.json({ agents: [], next_cursor: null });
30
+ },
31
+ });
32
+ assert.deepEqual(await client.agents.list(), { agents: [], next_cursor: null });
33
+ console.log("AgentRun client loaded; offline request passed. No server was contacted.");
34
+ ```
35
+
36
+ Expected output:
37
+
38
+ ```text
39
+ AgentRun client loaded; offline request passed. No server was contacted.
40
+ ```
41
+
13
42
  ## Construct
14
43
 
15
44
  ```ts
@@ -80,11 +109,13 @@ checkout; these new exports are not a guarantee about the current npm release.
80
109
  | Codex SDK client, project and tools | [Preserve native threads, add checked learning](../../docs/tutorials/codex-sdk-learning.md) |
81
110
 
82
111
  Your backend still starts and cancels tasks. The wrapper records original source policy/input, assistant text,
83
- tool names/status and usage; raw tool arguments/results and SDK credentials are not sent. AgentRun supplies the
112
+ tool names/status and usage. With an explicit workflow bridge, bounded arguments/results for its registered tools also supply compilation evidence; other raw tool payloads and SDK credentials are not sent. AgentRun supplies the
84
113
  owner's corrections (`corrections.md`, whole) to the next fresh task, and compiles a workflow once the agent has
85
- enough completed runs.
114
+ enough completed runs. A compiled draft is checked on a separate native task before the server promotes it: the client checks it against that task's recorded tool evidence (missing reads are refused unless the host enables `shadowReadFallback` for explicitly read-only callbacks), and the server compares its result with the native answer. Drafts are not offered as executable workflows to the native model.
86
115
  `learning: true` opts in on first registration only; existing agents keep their console setting.
87
116
 
117
+ Checks involving writes require complete serial native tool recordings and a serial workflow that preserves every original call in order. Buffered Codex results cannot prove write order, so those drafts remain unpromoted. Read-only turns may reuse and reorder recorded reads. See the workflow cookbook for the full evidence requirements.
118
+
88
119
  Both wrappers expose `flushLearning()`. Await it before shutdown or before testing a fresh run's use of newly
89
120
  accepted learning. Errors in persistence or learning surface there without replacing the original SDK result/error.
90
121
  The first integration supports fresh, single-task sessions/threads only. See the cookbooks for cancellation,
@@ -94,13 +125,38 @@ For executable workflow learning, explicitly configure `createWorkflowMcpBridge`
94
125
  `@parcha/agentrun-client/workflows` with your existing backend tool callbacks, live permission policy and an explicit `engine` object containing
95
126
  `inspectWorkflow`, `runWorkflow` and `resolveSchemaForWorkflow`. Your backend imports and supplies its interpreter
96
127
  (for example, `import * as engine from "@parcha/agentrun-dsl"`); the client imports no workflow engine.
97
- The optional MCP entry point requires `@modelcontextprotocol/sdk`.
128
+ The workflow entry point requires `ajv` and `ajv-formats`; the MCP bridge additionally requires `@modelcontextprotocol/sdk`. Install these optional peers explicitly when using the bridge:
129
+
130
+ ```sh
131
+ npm install @modelcontextprotocol/sdk@1.32.2 ajv@8.18.0 ajv-formats@3.0.1
132
+ ```
133
+
134
+ The in-process executor uses the same validators without loading the MCP SDK.
98
135
  Set the bridge's optional `nativeMcpServerName` to the exact name you configure for its endpoint in the native SDK.
99
136
  Only a native envelope matching one actual bridge completion's capability, arguments, status and result is correlated;
100
137
  without that binding, native tool evidence is retained and the cost path can read `handed_back`.
101
138
  The [workflow cookbook](../../docs/tutorials/sdk-workflow-learning.md) covers native MCP setup, checked promotion,
102
139
  run-scoped access, cancellation, and tests proving the next task reuses a workflow with fresh inputs.
103
140
 
141
+ ## Durable host integrations
142
+
143
+ The `BackendLearningClient` export from `@parcha/agentrun-client/learning` is the shared lifecycle beneath the wrappers and Eve extension. A durable host can admit a turn with `client.begin(source, signal, { idempotencyKey })`, keep `session.checkpoint()`, then restore it with `client.resume(checkpoint)` after a restart. Resume validates the server, agent and runtime and reuses the original admission. The checkpoint includes a scoped credential: persist it as private host state, never in a model prompt, tool result or log.
144
+
145
+ For a finite recorded turn, call:
146
+
147
+ ```ts
148
+ await session.submit(events, outcome, {
149
+ evidenceComplete: true,
150
+ nativeEvents, // Original tool arguments/results, retained locally for the shadow check.
151
+ waitForLearning: false,
152
+ onCheckpoint: async checkpoint => {
153
+ await savePrivateCheckpoint(checkpoint);
154
+ },
155
+ });
156
+ ```
157
+
158
+ `events` is the bounded transcript sent to the server; `nativeEvents` is separate local evidence and is not uploaded by this argument. `onCheckpoint` must durably save each shadow `started` or `complete` marker before returning. A restored completed check reuses its result without calling tools again. A restored started check with no result records an unknown failure rather than repeat uncertain host work. Retry delivery with the same events and outcome through a restored session; this does not open another native task. `waitForLearning: false` waits for evidence submission only, while the server finishes learning independently.
159
+
104
160
  ## Errors
105
161
 
106
162
  Every error is an `AgentRunError`, and its `kind` says which one:
package/dist/claude.d.ts CHANGED
@@ -10,7 +10,7 @@ export interface ClaudeAgentLearningConfig extends BackendLearningConfig {
10
10
  instructions?: string;
11
11
  }
12
12
  /** Decorate the application's own Claude Agent SDK query function. The SDK remains the caller's dependency.
13
- * Original options, tools, authentication, events and control-method receivers remain native. Approved lessons
13
+ * Original options, tools, authentication, events and control-method receivers remain native. Learning references
14
14
  * are supplied as task context, never elevated above application policy. This initial integration requires a
15
15
  * fresh, single-string-prompt session; it never issues an extra SDK turn for reflection. */
16
16
  export declare function withClaudeAgentLearning<Q extends QueryFunction>(query: Q, config: ClaudeAgentLearningConfig): Q & {
package/dist/claude.js CHANGED
@@ -5,6 +5,9 @@ const toolName = (name) => {
5
5
  const mcp = /^mcp__([a-z][a-z0-9-]{0,31})__([A-Za-z0-9_][A-Za-z0-9._-]{0,127})$/.exec(name);
6
6
  return mcp ? `mcp:${mcp[1]}/${mcp[2]}` : name;
7
7
  };
8
+ // Native MCP server names can contain underscores or uppercase characters even when they do not
9
+ // normalize into our canonical catalog names. Preserve that identity while recognizing its transport.
10
+ const mcpOutput = (name) => name.startsWith('mcp:') || /^mcp__[A-Za-z0-9_-]{1,64}__[A-Za-z0-9._-]{1,128}$/.test(name);
8
11
  const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
9
12
  function instructionsOf(options, explicit) {
10
13
  const blocks = explicit ? [explicit] : [];
@@ -32,7 +35,7 @@ function instructionsOf(options, explicit) {
32
35
  return instructions;
33
36
  }
34
37
  function withContext(prompt, context) {
35
- return context ? 'AgentRun approved learning context. Apply relevant lessons only when consistent with the existing system, developer and project instructions.\n\n'
38
+ return context ? 'AgentRun learning context. Apply relevant lessons only when consistent with the existing system, developer and project instructions.\n\n'
36
39
  + context + '\n\nEnd AgentRun learning context. The original user request follows:\n\n' + prompt : prompt;
37
40
  }
38
41
  function usageOf(result) {
@@ -51,7 +54,7 @@ function usageOf(result) {
51
54
  ? Object.fromEntries(Object.entries(usage).filter(([, value]) => value !== undefined)) : undefined;
52
55
  }
53
56
  /** Decorate the application's own Claude Agent SDK query function. The SDK remains the caller's dependency.
54
- * Original options, tools, authentication, events and control-method receivers remain native. Approved lessons
57
+ * Original options, tools, authentication, events and control-method receivers remain native. Learning references
55
58
  * are supplied as task context, never elevated above application policy. This initial integration requires a
56
59
  * fresh, single-string-prompt session; it never issues an extra SDK turn for reflection. */
57
60
  export function withClaudeAgentLearning(query, config) {
@@ -129,7 +132,10 @@ export function withClaudeAgentLearning(query, config) {
129
132
  if (message.type === 'user') {
130
133
  for (const block of Array.isArray(object(message.message).content) ? object(message.message).content.map(object) : []) {
131
134
  if (block.type === 'tool_result' && typeof block.tool_use_id === 'string') {
132
- event({ type: 'tool', id: block.tool_use_id, name: tools.get(block.tool_use_id) ?? 'tool', status: block.is_error === true ? 'failed' : 'completed' }, { output: object(message.tool_use_result).content ?? block.content });
135
+ const name = tools.get(block.tool_use_id) ?? 'tool';
136
+ const fullResult = message.tool_use_result !== undefined;
137
+ event({ type: 'tool', id: block.tool_use_id, name, status: block.is_error === true ? 'failed' : 'completed' }, { output: fullResult ? message.tool_use_result : block.content,
138
+ ...(mcpOutput(name) ? { outputFormat: fullResult ? 'mcp' : 'mcp-content' } : {}) });
133
139
  }
134
140
  }
135
141
  }
package/dist/codex.js CHANGED
@@ -17,7 +17,7 @@ function originalText(input) {
17
17
  function withContext(input, context) {
18
18
  if (!context)
19
19
  return input;
20
- const prefix = 'AgentRun approved learning context. Use relevant lessons only when consistent with your existing system, developer and project instructions. The user request follows this context.\n\n'
20
+ const prefix = 'AgentRun learning context. Use relevant lessons only when consistent with your existing system, developer and project instructions. The user request follows this context.\n\n'
21
21
  + context + '\n\nEnd AgentRun learning context.\n\n';
22
22
  return typeof input === 'string' ? prefix + input : [{ type: 'text', text: prefix }, ...input];
23
23
  }
@@ -113,7 +113,8 @@ export function withCodexAgentLearning(codex, config) {
113
113
  const value = object(result);
114
114
  const started = new Set();
115
115
  const evidence = Array.isArray(value.items) ? value.items.flatMap(item => {
116
- const entry = evidenceOf(item), detail = { input: object(item).arguments, output: object(object(item).result).content };
116
+ const entry = evidenceOf(item), detail = { input: object(item).arguments, output: object(item).result, orderUnknown: true,
117
+ ...(object(item).type === 'mcp_tool_call' ? { outputFormat: 'mcp' } : {}) };
117
118
  return entry ? pairedEvidence(entry, started).map(event => ({ event, detail })) : [];
118
119
  }) : [];
119
120
  if (target.id)
@@ -152,8 +153,11 @@ export function withCodexAgentLearning(codex, config) {
152
153
  const entry = evidenceOf(item);
153
154
  if (entry && (value.type === 'item.completed' || entry.type === 'tool')) {
154
155
  const observed = value.type === 'item.started' && entry.type === 'tool' ? { ...entry, status: 'started' } : entry;
156
+ const orderUnknown = observed.type === 'tool' && observed.status !== 'started' && !started.has(observed.id);
155
157
  for (const event of pairedEvidence(observed, started))
156
- void record(session, event, { input: item.arguments, output: object(item.result).content });
158
+ void record(session, event, { input: item.arguments, output: item.result,
159
+ ...(item.type === 'mcp_tool_call' ? { outputFormat: 'mcp' } : {}),
160
+ ...(orderUnknown ? { orderUnknown: true } : {}) });
157
161
  }
158
162
  }
159
163
  if (value.type === 'turn.completed') {
@@ -30,12 +30,23 @@ export interface BackendWorkflowBridge {
30
30
  readonly catalog: readonly BackendWorkflowToolManifest[];
31
31
  readonly adapters: readonly ('runNode' | 'runJudge')[];
32
32
  bind(session: BackendWorkflowSession): BackendWorkflowBinding;
33
+ /** Shadow execution uses only this native turn's recorded results, never new side effects. */
34
+ check?(check: BackendWorkflowCheck, turn: {
35
+ runId: string;
36
+ input: string;
37
+ events: readonly BackendNativeEvent[];
38
+ outcome: SdkLearningOutcome;
39
+ signal?: AbortSignal;
40
+ }): Promise<Extract<SdkLearningEvent, {
41
+ type: 'workflow_check';
42
+ }>>;
33
43
  }
34
44
  /** The learning loop's numbers an agent definition may set (`learning: {...}`); each one left out is the server's default. */
35
45
  export interface BackendLearningLoop {
36
46
  compile_after?: number;
37
47
  agree_min?: number;
38
48
  alone_min?: number;
49
+ agree_on?: readonly string[];
39
50
  }
40
51
  export interface BackendLearningConfig extends ClientOptions {
41
52
  /** A stable agent id, shared by fresh runs of the same backend agent. */
@@ -47,13 +58,56 @@ export interface BackendLearningConfig extends ClientOptions {
47
58
  * is on, with the learning loop's numbers set on the agent: `compile_after` (completed runs before its job compiles
48
59
  * into a workflow, default 20), `agree_min` and `alone_min` (the draft's one check, default 0.8 and 0.7). */
49
60
  learning?: boolean | BackendLearningLoop;
50
- /** Explicit local MCP bridge over the backend's existing approved tool callbacks. */
61
+ /** Explicit host workflow binding over the backend's existing allowed callbacks; MCP is optional. */
51
62
  workflows?: BackendWorkflowBridge;
52
63
  /** Poll interval while waiting for checked learning (default 250 ms). */
53
64
  pollIntervalMs?: number;
54
65
  /** Maximum wait after completion for checked learning (default 120000 ms). The server continues after a timeout. */
55
66
  learningTimeoutMs?: number;
56
67
  }
68
+ export interface BackendWorkflowCheck {
69
+ id: string;
70
+ revision: string;
71
+ digest: string;
72
+ workflow: {
73
+ name: string;
74
+ workflow: string;
75
+ description: string;
76
+ };
77
+ }
78
+ type SdkReceipt = Awaited<ReturnType<AgentRun['sdkRuns']['start']>>;
79
+ /** Private durable host state, including a scoped credential. Never put this in a model prompt, result or log. */
80
+ export interface BackendLearningCheckpoint {
81
+ baseUrl: string;
82
+ agentId: string;
83
+ source: BackendLearningStart;
84
+ receipt: SdkReceipt;
85
+ /** A completed shadow result is replayed verbatim after transport ambiguity; it never reruns a host callback. */
86
+ shadow?: {
87
+ fingerprint: string;
88
+ redacted?: true;
89
+ state: 'started';
90
+ } | {
91
+ fingerprint: string;
92
+ redacted?: true;
93
+ state: 'complete';
94
+ event: Extract<SdkLearningEvent, {
95
+ type: 'workflow_check';
96
+ }>;
97
+ };
98
+ }
99
+ export interface BackendLearningBeginOptions {
100
+ idempotencyKey?: string;
101
+ }
102
+ export interface BackendLearningSubmitOptions {
103
+ evidenceComplete?: boolean;
104
+ /** Native arguments and results stay local; only the separate events argument is uploaded. */
105
+ nativeEvents?: readonly BackendNativeEvent[];
106
+ /** Durable hooks can return after persistence; the server continues checking independently. */
107
+ waitForLearning?: boolean;
108
+ /** Persist the private updated receipt before the first shadow-result upload. */
109
+ onCheckpoint?(checkpoint: BackendLearningCheckpoint): void | Promise<void>;
110
+ }
57
111
  export interface BackendLearningStart {
58
112
  runtime: BackendSdkRuntime;
59
113
  input: string;
@@ -66,6 +120,19 @@ export type SdkLearningEvent = {
66
120
  } | {
67
121
  type: 'session';
68
122
  session_id: string;
123
+ } | {
124
+ type: 'workflow_check';
125
+ id: string;
126
+ digest: string;
127
+ outcome: 'answered' | 'handed_back' | 'failed' | 'skipped_write';
128
+ answer?: string;
129
+ reason?: string;
130
+ skipped?: {
131
+ tool: string;
132
+ unmarked?: true;
133
+ };
134
+ /** Fresh read-only calls the shadow made where the native recording had no result (shadowReadFallback). Absent: none. */
135
+ fresh_reads?: number;
69
136
  } | {
70
137
  type: 'tool';
71
138
  id: string;
@@ -75,6 +142,18 @@ export type SdkLearningEvent = {
75
142
  output?: unknown;
76
143
  parent_tool_use_id?: string;
77
144
  };
145
+ /** Local shadow evidence only. A buffered result cannot prove effect order. SDK adapters explicitly identify
146
+ * MCP transport results; original callback values have no outputFormat and are never decoded as transport. */
147
+ export type BackendNativeEvent = SdkLearningEvent & {
148
+ orderUnknown?: true;
149
+ outputFormat?: 'mcp' | 'mcp-content';
150
+ };
151
+ type NativeDetail = {
152
+ input?: unknown;
153
+ output?: unknown;
154
+ orderUnknown?: true;
155
+ outputFormat?: BackendNativeEvent['outputFormat'];
156
+ };
78
157
  export interface SdkLearningUsage {
79
158
  /** Uncached input only. Cache reads and writes have their own counters; unknown splits remain null. */
80
159
  input_tokens?: number | null;
@@ -101,6 +180,8 @@ export interface BackendLearningSnapshot {
101
180
  description: string;
102
181
  }>;
103
182
  workflowContext?: string;
183
+ /** A private check candidate; never included in reusable workflows or model context. */
184
+ check?: BackendWorkflowCheck;
104
185
  }
105
186
  export interface BackendLearningStatus {
106
187
  run_id: string;
@@ -121,13 +202,15 @@ export declare class BackendLearningError extends Error {
121
202
  export declare class BackendLearningClient {
122
203
  #private;
123
204
  constructor(config: BackendLearningConfig);
124
- begin(source: BackendLearningStart, signal?: AbortSignal): Promise<BackendLearningSession>;
205
+ begin(source: BackendLearningStart, signal?: AbortSignal, options?: BackendLearningBeginOptions): Promise<BackendLearningSession>;
206
+ /** Restore a persisted receipt without registering or admitting a second native turn. */
207
+ resume(checkpoint: BackendLearningCheckpoint): BackendLearningSession;
125
208
  /** Observe completion immediately; the original SDK call can return without waiting for the run's learning. */
126
209
  track(promise: Promise<unknown>): void;
127
210
  /** Wait for tracked writes and checked learning. Does not retry or re-run the caller's SDK task. */
128
211
  flushLearning(): Promise<void>;
129
212
  }
130
- /** One immutable source/seed snapshot and its ordered evidence. The scoped token is never exposed to the wrapper. */
213
+ /** One immutable source snapshot and ordered evidence. Only checkpoint() exposes private durable receipt state. */
131
214
  export declare class BackendLearningSession implements BackendLearningSnapshot {
132
215
  #private;
133
216
  readonly runId: string;
@@ -140,7 +223,11 @@ export declare class BackendLearningSession implements BackendLearningSnapshot {
140
223
  constructor(scoped: AgentRun, snapshot: BackendLearningSnapshot & {
141
224
  runId: string;
142
225
  consoleUrl: string;
143
- }, config: Pick<BackendLearningConfig, 'pollIntervalMs' | 'learningTimeoutMs' | 'workflows'>);
226
+ input?: string;
227
+ }, config: Pick<BackendLearningConfig, 'pollIntervalMs' | 'learningTimeoutMs' | 'workflows'>, checkpoint?: BackendLearningCheckpoint);
228
+ checkpoint(): BackendLearningCheckpoint;
229
+ /** Deliver one finite recorded turn. Retry through a restored checkpoint; identical batches retain their keys. */
230
+ submit(events: readonly SdkLearningEvent[], outcome: SdkLearningOutcome, options?: BackendLearningSubmitOptions): Promise<void>;
144
231
  /** Keep ephemeral bridge capabilities out of stored evidence without changing native SDK results. */
145
232
  protect(values: readonly string[]): void;
146
233
  /** Stop admitting work immediately; evidence can still drain before durable completion. */
@@ -153,10 +240,7 @@ export declare class BackendLearningSession implements BackendLearningSnapshot {
153
240
  /** Observe native SDK tools without counting a positively correlated bridge envelope twice. Candidate starts wait
154
241
  * for their result; every unmatched or unfinished candidate is still ordinary top-level evidence. Raw arguments
155
242
  * and results stay local, and at most sixteen bounded candidates (the bridge's invocation bound) are retained. */
156
- nativeEvent(event: SdkLearningEvent, detail?: {
157
- input?: unknown;
158
- output?: unknown;
159
- }): Promise<void>;
243
+ nativeEvent(event: SdkLearningEvent, detail?: NativeDetail): Promise<void>;
160
244
  /** Await to apply backpressure. A failed/oversized batch prevents learning from an incomplete transcript. */
161
245
  event(event: SdkLearningEvent): Promise<void>;
162
246
  /** Persist the caller's outcome, then wait for the server's independent checked-learning verdict. */
@@ -164,3 +248,4 @@ export declare class BackendLearningSession implements BackendLearningSnapshot {
164
248
  }
165
249
  /** The owner's corrections and the bound workflows, as reference text for the application's own agent. */
166
250
  export declare function renderLearningContext(snapshot: BackendLearningSnapshot): string;
251
+ export {};