@parcha/agentrun-client 0.1.0-beta.38 → 0.1.0-beta.40
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 +32 -0
- package/dist/claude.d.ts +19 -0
- package/dist/claude.js +210 -0
- package/dist/codex.d.ts +23 -0
- package/dist/codex.js +198 -0
- package/dist/learning.d.ts +154 -0
- package/dist/learning.js +407 -0
- package/dist/operations.generated.d.ts +1525 -128
- package/dist/operations.generated.js +109 -4
- package/dist/workflows.d.ts +106 -0
- package/dist/workflows.js +381 -0
- package/package.json +29 -2
package/README.md
CHANGED
|
@@ -68,6 +68,38 @@ ends, or the body is cut before its length) rejects with `AgentRunUnreachable` a
|
|
|
68
68
|
Only the server's silence counts as a dropped connection (`idleMs`, default 45000), never the time your loop spends on a
|
|
69
69
|
page.
|
|
70
70
|
|
|
71
|
+
## Learning for existing backend SDK agents
|
|
72
|
+
|
|
73
|
+
The development build includes `withClaudeAgentLearning` from `@parcha/agentrun-client/claude` and
|
|
74
|
+
`withCodexAgentLearning` from `@parcha/agentrun-client/codex`. Use the client and server from the same reviewed
|
|
75
|
+
checkout; these new exports are not a guarantee about the current npm release.
|
|
76
|
+
|
|
77
|
+
| Existing backend | Cookbook |
|
|
78
|
+
| --- | --- |
|
|
79
|
+
| Claude Agent SDK `query` and custom tools | [Preserve the native query, add checked learning](../../docs/tutorials/claude-sdk-learning.md) |
|
|
80
|
+
| Codex SDK client, project and tools | [Preserve native threads, add checked learning](../../docs/tutorials/codex-sdk-learning.md) |
|
|
81
|
+
|
|
82
|
+
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 reflects
|
|
84
|
+
without tools, independently grades proposals, and supplies accepted context to the next fresh task.
|
|
85
|
+
`learning: true` opts in on first registration only; existing agents keep their console setting.
|
|
86
|
+
|
|
87
|
+
Both wrappers expose `flushLearning()`. Await it before shutdown or before testing a fresh run's use of newly
|
|
88
|
+
accepted learning. Errors in persistence or grading surface there without replacing the original SDK result/error.
|
|
89
|
+
The first integration supports fresh, single-task sessions/threads only. See the cookbooks for cancellation,
|
|
90
|
+
policy snapshots and multimodal limits, or run the [opt-in live examples](../../examples/sdk-learning/README.md).
|
|
91
|
+
|
|
92
|
+
For executable workflow learning, explicitly configure `createWorkflowMcpBridge` from
|
|
93
|
+
`@parcha/agentrun-client/workflows` with your existing backend tool callbacks, live permission policy and an explicit `engine` object containing
|
|
94
|
+
`inspectWorkflow`, `runWorkflow` and `resolveSchemaForWorkflow`. Your backend imports and supplies its interpreter
|
|
95
|
+
(for example, `import * as engine from "@parcha/agentrun-dsl"`); the client imports no workflow engine.
|
|
96
|
+
The optional MCP entry point requires `@modelcontextprotocol/sdk`.
|
|
97
|
+
Set the bridge's optional `nativeMcpServerName` to the exact name you configure for its endpoint in the native SDK.
|
|
98
|
+
Only a native envelope matching one actual bridge completion's capability, arguments, status and result is correlated;
|
|
99
|
+
without that binding, native tool evidence is retained and the cost path can read `handed_back`.
|
|
100
|
+
The [workflow cookbook](../../docs/tutorials/sdk-workflow-learning.md) covers native MCP setup, checked promotion,
|
|
101
|
+
run-scoped access, cancellation, and tests proving the next task reuses a workflow with fresh inputs.
|
|
102
|
+
|
|
71
103
|
## Errors
|
|
72
104
|
|
|
73
105
|
Every error is an `AgentRunError`, and its `kind` says which one:
|
package/dist/claude.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { type BackendLearningConfig } from './learning.js';
|
|
2
|
+
type NativeQuery = AsyncGenerator<unknown, unknown, unknown> & {
|
|
3
|
+
close?: () => void;
|
|
4
|
+
};
|
|
5
|
+
type QueryFunction = (args: any) => NativeQuery;
|
|
6
|
+
export interface ClaudeAgentLearningConfig extends BackendLearningConfig {
|
|
7
|
+
/** Additional standing policy for the checker, including relevant project-file instructions that the SDK does
|
|
8
|
+
* not expose. Programmatic systemPrompt and the selected named agent's prompt are captured automatically.
|
|
9
|
+
* This evidence does not replace the existing SDK options. */
|
|
10
|
+
instructions?: string;
|
|
11
|
+
}
|
|
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
|
|
14
|
+
* are supplied as task context, never elevated above application policy. This initial integration requires a
|
|
15
|
+
* fresh, single-string-prompt session; it never issues an extra SDK turn for reflection. */
|
|
16
|
+
export declare function withClaudeAgentLearning<Q extends QueryFunction>(query: Q, config: ClaudeAgentLearningConfig): Q & {
|
|
17
|
+
flushLearning(): Promise<void>;
|
|
18
|
+
};
|
|
19
|
+
export {};
|
package/dist/claude.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { BackendLearningClient, renderLearningContext } from './learning.js';
|
|
2
|
+
const object = (value) => value !== null && typeof value === 'object' ? value : {};
|
|
3
|
+
const string = (value) => typeof value === 'string' ? value : undefined;
|
|
4
|
+
const toolName = (name) => {
|
|
5
|
+
const mcp = /^mcp__([a-z][a-z0-9-]{0,31})__([A-Za-z0-9_][A-Za-z0-9._-]{0,127})$/.exec(name);
|
|
6
|
+
return mcp ? `mcp:${mcp[1]}/${mcp[2]}` : name;
|
|
7
|
+
};
|
|
8
|
+
const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
9
|
+
function instructionsOf(options, explicit) {
|
|
10
|
+
const blocks = explicit ? [explicit] : [];
|
|
11
|
+
const append = (value) => {
|
|
12
|
+
if (typeof value === 'string')
|
|
13
|
+
blocks.push(value);
|
|
14
|
+
else if (Array.isArray(value) && value.every(part => typeof part === 'string'))
|
|
15
|
+
blocks.push(...value);
|
|
16
|
+
};
|
|
17
|
+
const system = options.systemPrompt;
|
|
18
|
+
if (typeof system === 'string' || Array.isArray(system))
|
|
19
|
+
append(system);
|
|
20
|
+
else {
|
|
21
|
+
const configured = object(system);
|
|
22
|
+
if (configured.type === 'custom')
|
|
23
|
+
append(configured.prompt);
|
|
24
|
+
else if (configured.type === 'preset')
|
|
25
|
+
append(configured.append);
|
|
26
|
+
}
|
|
27
|
+
if (typeof options.agent === 'string')
|
|
28
|
+
append(object(object(options.agents)[options.agent]).prompt);
|
|
29
|
+
const instructions = blocks.join('\n\n').trim();
|
|
30
|
+
if (!instructions)
|
|
31
|
+
throw new TypeError('Claude learning needs a programmatic systemPrompt or an explicit instructions snapshot of the existing agent policy.');
|
|
32
|
+
return instructions;
|
|
33
|
+
}
|
|
34
|
+
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'
|
|
36
|
+
+ context + '\n\nEnd AgentRun learning context. The original user request follows:\n\n' + prompt : prompt;
|
|
37
|
+
}
|
|
38
|
+
function usageOf(result) {
|
|
39
|
+
const models = Object.values(object(result.modelUsage)).map(object);
|
|
40
|
+
const raw = object(result.usage);
|
|
41
|
+
const sum = (key) => models.length && models.every(model => count(model[key]) !== undefined)
|
|
42
|
+
? models.reduce((total, model) => total + model[key], 0) : undefined;
|
|
43
|
+
const usage = {
|
|
44
|
+
input_tokens: sum('inputTokens') ?? count(raw.input_tokens),
|
|
45
|
+
output_tokens: sum('outputTokens') ?? count(raw.output_tokens),
|
|
46
|
+
cache_read_tokens: sum('cacheReadInputTokens') ?? count(raw.cache_read_input_tokens),
|
|
47
|
+
cache_write_tokens: sum('cacheCreationInputTokens') ?? count(raw.cache_creation_input_tokens),
|
|
48
|
+
cost_usd: count(result.total_cost_usd),
|
|
49
|
+
};
|
|
50
|
+
return Object.values(usage).some(value => value !== undefined)
|
|
51
|
+
? Object.fromEntries(Object.entries(usage).filter(([, value]) => value !== undefined)) : undefined;
|
|
52
|
+
}
|
|
53
|
+
/** 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
|
|
55
|
+
* are supplied as task context, never elevated above application policy. This initial integration requires a
|
|
56
|
+
* fresh, single-string-prompt session; it never issues an extra SDK turn for reflection. */
|
|
57
|
+
export function withClaudeAgentLearning(query, config) {
|
|
58
|
+
const client = new BackendLearningClient(config);
|
|
59
|
+
const wrapped = (params) => {
|
|
60
|
+
if (typeof params.prompt !== 'string')
|
|
61
|
+
throw new TypeError('Claude learning currently supports one string prompt in a fresh session.');
|
|
62
|
+
const options = params.options ?? {};
|
|
63
|
+
if (options.resume || options.continue || options.forkSession || options.resumeSessionAt || options.resumeDropsTurn) {
|
|
64
|
+
throw new TypeError('Claude learning requires a fresh session; resume and continue are not supported by this wrapper.');
|
|
65
|
+
}
|
|
66
|
+
const instructions = instructionsOf(options, config.instructions);
|
|
67
|
+
const nativeAbort = options.abortController instanceof AbortController ? options.abortController : undefined;
|
|
68
|
+
const closedBeforeDispatch = new AbortController();
|
|
69
|
+
const admissionSignal = nativeAbort ? AbortSignal.any([nativeAbort.signal, closedBeforeDispatch.signal]) : closedBeforeDispatch.signal;
|
|
70
|
+
let session, native;
|
|
71
|
+
let closed = false, finalized = false, terminal = false, sessionId, model = string(options.model);
|
|
72
|
+
const tools = new Map();
|
|
73
|
+
const finish = (status, answer = '', result) => {
|
|
74
|
+
if (!session || finalized)
|
|
75
|
+
return;
|
|
76
|
+
finalized = true;
|
|
77
|
+
client.track(session.complete({ status, answer,
|
|
78
|
+
...(status === 'completed' ? {} : { error: 'The original Claude SDK session did not complete. Inspect its error or cancellation in the backend.' }),
|
|
79
|
+
...(sessionId ? { session_id: sessionId } : {}), ...(model ? { model } : {}),
|
|
80
|
+
...(result && usageOf(result) ? { usage: usageOf(result) } : {}),
|
|
81
|
+
}));
|
|
82
|
+
};
|
|
83
|
+
const ready = client.begin({ runtime: 'claude-agent-sdk', input: params.prompt, instructions, ...(model ? { model } : {}) }, admissionSignal).then(value => {
|
|
84
|
+
session = value;
|
|
85
|
+
session.followAbort(nativeAbort?.signal);
|
|
86
|
+
if (closed || nativeAbort?.signal.aborted) {
|
|
87
|
+
closed = true;
|
|
88
|
+
finish('cancelled');
|
|
89
|
+
throw nativeAbort?.signal.reason ?? new DOMException('The Claude SDK query was closed before dispatch.', 'AbortError');
|
|
90
|
+
}
|
|
91
|
+
const context = renderLearningContext(value);
|
|
92
|
+
try {
|
|
93
|
+
native = query(context ? { ...params, prompt: withContext(params.prompt, context) } : params);
|
|
94
|
+
return native;
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
finish('failed');
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
// Registration is asynchronous, while query() keeps its native synchronous shape. Observe the rejection even
|
|
102
|
+
// when the caller closes without iterating; next/control methods still receive the original error.
|
|
103
|
+
ready.catch(() => undefined);
|
|
104
|
+
const event = (value, detail) => {
|
|
105
|
+
if (session)
|
|
106
|
+
client.track(session.nativeEvent(value, detail));
|
|
107
|
+
};
|
|
108
|
+
const capture = (value) => {
|
|
109
|
+
const message = object(value);
|
|
110
|
+
if (typeof message.session_id === 'string' && message.session_id !== sessionId) {
|
|
111
|
+
sessionId = message.session_id;
|
|
112
|
+
event({ type: 'session', session_id: sessionId });
|
|
113
|
+
}
|
|
114
|
+
if (message.type === 'system' && typeof message.model === 'string')
|
|
115
|
+
model = message.model;
|
|
116
|
+
if (message.type === 'assistant') {
|
|
117
|
+
const content = object(message.message);
|
|
118
|
+
if (!model && typeof content.model === 'string')
|
|
119
|
+
model = content.model;
|
|
120
|
+
for (const block of Array.isArray(content.content) ? content.content.map(object) : []) {
|
|
121
|
+
if (block.type === 'text' && typeof block.text === 'string')
|
|
122
|
+
event({ type: 'text', text: block.text });
|
|
123
|
+
if (block.type === 'tool_use' && typeof block.id === 'string' && typeof block.name === 'string') {
|
|
124
|
+
tools.set(block.id, toolName(block.name));
|
|
125
|
+
event({ type: 'tool', id: block.id, name: toolName(block.name), status: 'started' }, { input: block.input });
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
if (message.type === 'user') {
|
|
130
|
+
for (const block of Array.isArray(object(message.message).content) ? object(message.message).content.map(object) : []) {
|
|
131
|
+
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 });
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (message.type === 'result') {
|
|
137
|
+
terminal = true;
|
|
138
|
+
finish(message.subtype === 'success' && message.is_error !== true ? 'completed' : 'failed', string(message.result) ?? '', message);
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
const close = () => {
|
|
142
|
+
closed = true;
|
|
143
|
+
closedBeforeDispatch.abort(new DOMException('The Claude SDK query was closed before dispatch.', 'AbortError'));
|
|
144
|
+
try {
|
|
145
|
+
native?.close?.();
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
if (!terminal)
|
|
149
|
+
finish('cancelled');
|
|
150
|
+
// begin() owns any late receipt cleanup; intentional closure is not a persistence error.
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
const iterator = {
|
|
154
|
+
async next(value) {
|
|
155
|
+
try {
|
|
156
|
+
const sdk = await ready;
|
|
157
|
+
if (closed)
|
|
158
|
+
return { done: true, value: undefined };
|
|
159
|
+
const result = await sdk.next(value);
|
|
160
|
+
if (!result.done)
|
|
161
|
+
capture(result.value);
|
|
162
|
+
else if (!terminal)
|
|
163
|
+
finish(nativeAbort?.signal.aborted ? 'cancelled' : 'failed');
|
|
164
|
+
return result;
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
finish(nativeAbort?.signal.aborted || closed ? 'cancelled' : 'failed');
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
},
|
|
171
|
+
async return(value) {
|
|
172
|
+
close();
|
|
173
|
+
if (native?.return)
|
|
174
|
+
return native.return(value);
|
|
175
|
+
await ready.catch(() => undefined);
|
|
176
|
+
return { done: true, value };
|
|
177
|
+
},
|
|
178
|
+
async throw(error) {
|
|
179
|
+
close();
|
|
180
|
+
if (native?.throw)
|
|
181
|
+
return native.throw(error);
|
|
182
|
+
throw error;
|
|
183
|
+
},
|
|
184
|
+
close,
|
|
185
|
+
[Symbol.asyncIterator]() { return proxy; },
|
|
186
|
+
async [Symbol.asyncDispose]() { await iterator.return(); },
|
|
187
|
+
};
|
|
188
|
+
const proxy = new Proxy(iterator, {
|
|
189
|
+
get(target, key, receiver) {
|
|
190
|
+
if (key in target)
|
|
191
|
+
return Reflect.get(target, key, receiver);
|
|
192
|
+
if (key === 'then')
|
|
193
|
+
return undefined;
|
|
194
|
+
if (key === 'streamInput')
|
|
195
|
+
return async () => {
|
|
196
|
+
throw new TypeError('Claude learning supports one task per fresh query; start another wrapped query for additional input.');
|
|
197
|
+
};
|
|
198
|
+
return async (...args) => {
|
|
199
|
+
const sdk = await ready;
|
|
200
|
+
const method = Reflect.get(sdk, key);
|
|
201
|
+
if (typeof method !== 'function')
|
|
202
|
+
throw new TypeError(`The existing Claude SDK query has no ${String(key)} method.`);
|
|
203
|
+
return Reflect.apply(method, sdk, args);
|
|
204
|
+
};
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
return proxy;
|
|
208
|
+
};
|
|
209
|
+
return Object.assign(wrapped, { flushLearning: () => client.flushLearning() });
|
|
210
|
+
}
|
package/dist/codex.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type BackendLearningConfig } from './learning.js';
|
|
2
|
+
/** The native SDK remains the caller's dependency. These method shapes preserve its inferred public types. */
|
|
3
|
+
type CodexLike = {
|
|
4
|
+
startThread: (...args: any[]) => {
|
|
5
|
+
readonly id: string | null;
|
|
6
|
+
run: (...args: any[]) => Promise<any>;
|
|
7
|
+
runStreamed: (...args: any[]) => Promise<{
|
|
8
|
+
events: AsyncGenerator<any>;
|
|
9
|
+
}>;
|
|
10
|
+
};
|
|
11
|
+
};
|
|
12
|
+
export interface CodexAgentLearningConfig extends BackendLearningConfig {
|
|
13
|
+
/** The standing policy for this backend agent, including relevant project instructions. It is evidence for the
|
|
14
|
+
* independent grader, not a replacement for Codex's own instructions or configuration. */
|
|
15
|
+
instructions: string;
|
|
16
|
+
}
|
|
17
|
+
/** Add AgentRun learning to fresh Codex SDK threads without replacing their tools, credentials or execution.
|
|
18
|
+
* Each wrapped thread admits one task; use startThread() again for the next task and its current learning revision.
|
|
19
|
+
* Reflection and grading run on the AgentRun server, never as a hidden turn in the caller's Codex conversation. */
|
|
20
|
+
export declare function withCodexAgentLearning<T extends CodexLike>(codex: T, config: CodexAgentLearningConfig): T & {
|
|
21
|
+
flushLearning(): Promise<void>;
|
|
22
|
+
};
|
|
23
|
+
export {};
|
package/dist/codex.js
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { BackendLearningClient, renderLearningContext } from './learning.js';
|
|
2
|
+
const object = (value) => value !== null && typeof value === 'object' ? value : {};
|
|
3
|
+
const text = (value) => typeof value === 'string' ? value : undefined;
|
|
4
|
+
const count = (value) => typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : undefined;
|
|
5
|
+
const aborted = (options) => object(options).signal instanceof AbortSignal && object(options).signal.aborted;
|
|
6
|
+
const signalOf = (options) => object(options).signal instanceof AbortSignal ? object(options).signal : undefined;
|
|
7
|
+
function originalText(input) {
|
|
8
|
+
if (typeof input === 'string')
|
|
9
|
+
return input;
|
|
10
|
+
if (!Array.isArray(input) || input.some(part => !part || (part.type !== 'text' && part.type !== 'local_image') ||
|
|
11
|
+
(part.type === 'text' && typeof part.text !== 'string') || (part.type === 'local_image' && typeof part.path !== 'string'))) {
|
|
12
|
+
throw new TypeError('Codex learning supports the SDK text and local_image input forms.');
|
|
13
|
+
}
|
|
14
|
+
// Image paths and bytes remain with the native SDK. They are not user instructions or uploaded evidence.
|
|
15
|
+
return input.filter((part) => part.type === 'text').map(part => part.text).join('\n\n');
|
|
16
|
+
}
|
|
17
|
+
function withContext(input, context) {
|
|
18
|
+
if (!context)
|
|
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'
|
|
21
|
+
+ context + '\n\nEnd AgentRun learning context.\n\n';
|
|
22
|
+
return typeof input === 'string' ? prefix + input : [{ type: 'text', text: prefix }, ...input];
|
|
23
|
+
}
|
|
24
|
+
function usageOf(value) {
|
|
25
|
+
const usage = object(value);
|
|
26
|
+
const input = count(usage.input_tokens), output = count(usage.output_tokens);
|
|
27
|
+
const reads = count(usage.cached_input_tokens), writes = count(usage.cache_write_input_tokens);
|
|
28
|
+
if (input === undefined && output === undefined)
|
|
29
|
+
return undefined;
|
|
30
|
+
return {
|
|
31
|
+
// Codex input includes cache reads/writes; AgentRun's input counter is exclusive of both. If the SDK
|
|
32
|
+
// does not report a component, keep uncached input unknown rather than double counting or inventing zero.
|
|
33
|
+
input_tokens: input !== undefined && reads !== undefined && writes !== undefined ? Math.max(0, input - reads - writes) : null,
|
|
34
|
+
...(output === undefined ? {} : { output_tokens: output }),
|
|
35
|
+
...(reads === undefined ? {} : { cache_read_tokens: reads }),
|
|
36
|
+
...(writes === undefined ? {} : { cache_write_tokens: writes }),
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
/** Capture results and tool identity/status, never Codex reasoning, configuration, command output or tool arguments. */
|
|
40
|
+
function evidenceOf(itemValue) {
|
|
41
|
+
const item = object(itemValue);
|
|
42
|
+
if (item.type === 'agent_message' && typeof item.text === 'string')
|
|
43
|
+
return { type: 'text', text: item.text };
|
|
44
|
+
if (['command_execution', 'file_change', 'mcp_tool_call', 'web_search'].includes(String(item.type))) {
|
|
45
|
+
return { type: 'tool', id: text(item.id) ?? 'sdk-tool',
|
|
46
|
+
name: item.type === 'mcp_tool_call' ? `mcp:${text(item.server) ?? 'mcp'}/${text(item.tool) ?? 'tool'}` : String(item.type),
|
|
47
|
+
status: item.status === 'failed' ? 'failed' : item.status === 'in_progress' ? 'started' : 'completed' };
|
|
48
|
+
}
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
function pairedEvidence(event, started) {
|
|
52
|
+
if (event.type !== 'tool')
|
|
53
|
+
return [event];
|
|
54
|
+
const known = started.has(event.id);
|
|
55
|
+
started.add(event.id);
|
|
56
|
+
if (event.status === 'started')
|
|
57
|
+
return known ? [] : [event];
|
|
58
|
+
// Buffered SDK results only arrive when the native turn has ended. Record the observed call identity before
|
|
59
|
+
// its outcome so the timeline can pair them; no original start time or live execution time is fabricated.
|
|
60
|
+
return known ? [event] : [{ ...event, status: 'started' }, event];
|
|
61
|
+
}
|
|
62
|
+
/** Add AgentRun learning to fresh Codex SDK threads without replacing their tools, credentials or execution.
|
|
63
|
+
* Each wrapped thread admits one task; use startThread() again for the next task and its current learning revision.
|
|
64
|
+
* Reflection and grading run on the AgentRun server, never as a hidden turn in the caller's Codex conversation. */
|
|
65
|
+
export function withCodexAgentLearning(codex, config) {
|
|
66
|
+
if (typeof config.instructions !== 'string')
|
|
67
|
+
throw new TypeError('Codex learning requires an explicit instructions snapshot.');
|
|
68
|
+
const client = new BackendLearningClient(config);
|
|
69
|
+
const wrap = (thread, options) => {
|
|
70
|
+
if (thread.id !== null && thread.id !== undefined)
|
|
71
|
+
throw new Error('Codex learning requires a fresh thread.');
|
|
72
|
+
let used = false;
|
|
73
|
+
const model = text(object(options).model);
|
|
74
|
+
const begin = async (input, turnOptions) => {
|
|
75
|
+
if (used)
|
|
76
|
+
throw new Error('A learning-wrapped Codex thread supports one task. Start a fresh thread for the next task.');
|
|
77
|
+
used = true;
|
|
78
|
+
const signal = signalOf(turnOptions);
|
|
79
|
+
const session = await client.begin({ runtime: 'codex-sdk', input: originalText(input), instructions: config.instructions, ...(model ? { model } : {}) }, signal);
|
|
80
|
+
session.followAbort(signal);
|
|
81
|
+
if (session.learningEnabled && Array.isArray(input) && input.some(part => part.type === 'local_image')) {
|
|
82
|
+
session.markEvidenceIncomplete('Image inputs remain in the native Codex SDK and are not available to the learning grader. This run will not produce new learning.');
|
|
83
|
+
}
|
|
84
|
+
return session;
|
|
85
|
+
};
|
|
86
|
+
const record = async (session, event, detail) => {
|
|
87
|
+
// The shared client marks incomplete evidence and reports persistence errors from flushLearning(). It must
|
|
88
|
+
// not replace the caller's result or original SDK failure with an observability transport error.
|
|
89
|
+
await session.nativeEvent(event, detail).catch(() => undefined);
|
|
90
|
+
};
|
|
91
|
+
const finish = (session, outcome, evidence = []) => {
|
|
92
|
+
session.closeWorkflows();
|
|
93
|
+
client.track((async () => {
|
|
94
|
+
for (const { event, detail } of evidence)
|
|
95
|
+
await record(session, event, detail);
|
|
96
|
+
await session.complete(outcome);
|
|
97
|
+
})());
|
|
98
|
+
};
|
|
99
|
+
const failure = (session, options) => finish(session, {
|
|
100
|
+
status: aborted(options) ? 'cancelled' : 'failed',
|
|
101
|
+
error: 'The existing Codex SDK call did not complete. Inspect the original SDK error in the backend.',
|
|
102
|
+
answer: '',
|
|
103
|
+
...(thread.id ? { session_id: thread.id } : {}),
|
|
104
|
+
});
|
|
105
|
+
return new Proxy(thread, {
|
|
106
|
+
get(target, key) {
|
|
107
|
+
if (key === 'run')
|
|
108
|
+
return async (input, turnOptions) => {
|
|
109
|
+
const session = await begin(input, turnOptions);
|
|
110
|
+
try {
|
|
111
|
+
signalOf(turnOptions)?.throwIfAborted();
|
|
112
|
+
const result = await target.run(withContext(input, renderLearningContext(session)), turnOptions);
|
|
113
|
+
const value = object(result);
|
|
114
|
+
const started = new Set();
|
|
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 };
|
|
117
|
+
return entry ? pairedEvidence(entry, started).map(event => ({ event, detail })) : [];
|
|
118
|
+
}) : [];
|
|
119
|
+
if (target.id)
|
|
120
|
+
evidence.unshift({ event: { type: 'session', session_id: target.id } });
|
|
121
|
+
finish(session, { status: 'completed', answer: text(value.finalResponse) ?? '', ...(target.id ? { session_id: target.id } : {}),
|
|
122
|
+
...(model ? { model } : {}), ...(usageOf(value.usage) ? { usage: usageOf(value.usage) } : {}) }, evidence);
|
|
123
|
+
return result;
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
failure(session, turnOptions);
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
if (key === 'runStreamed')
|
|
131
|
+
return async (input, turnOptions) => {
|
|
132
|
+
// Native Codex does no work before its iterator is consumed. Defer registration too, so an unused stream
|
|
133
|
+
// creates neither an orphan AgentRun job nor a model request.
|
|
134
|
+
const events = (async function* () {
|
|
135
|
+
const session = await begin(input, turnOptions);
|
|
136
|
+
let completed = false, failed = false, answer = '', usage;
|
|
137
|
+
const started = new Set();
|
|
138
|
+
try {
|
|
139
|
+
signalOf(turnOptions)?.throwIfAborted();
|
|
140
|
+
const streamed = await target.runStreamed(withContext(input, renderLearningContext(session)), turnOptions);
|
|
141
|
+
for await (const event of streamed.events) {
|
|
142
|
+
const value = object(event);
|
|
143
|
+
// event() synchronously admits evidence to the session's bounded, ordered upload queue. Native
|
|
144
|
+
// delivery and cancellation must not wait for that transport; complete() drains it for flushLearning().
|
|
145
|
+
if (value.type === 'thread.started' && typeof value.thread_id === 'string') {
|
|
146
|
+
void record(session, { type: 'session', session_id: value.thread_id });
|
|
147
|
+
}
|
|
148
|
+
if (value.type === 'item.started' || value.type === 'item.completed') {
|
|
149
|
+
const item = object(value.item);
|
|
150
|
+
if (value.type === 'item.completed' && item.type === 'agent_message')
|
|
151
|
+
answer = text(item.text) ?? answer;
|
|
152
|
+
const entry = evidenceOf(item);
|
|
153
|
+
if (entry && (value.type === 'item.completed' || entry.type === 'tool')) {
|
|
154
|
+
const observed = value.type === 'item.started' && entry.type === 'tool' ? { ...entry, status: 'started' } : entry;
|
|
155
|
+
for (const event of pairedEvidence(observed, started))
|
|
156
|
+
void record(session, event, { input: item.arguments, output: object(item.result).content });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (value.type === 'turn.completed') {
|
|
160
|
+
completed = true;
|
|
161
|
+
usage = usageOf(value.usage);
|
|
162
|
+
}
|
|
163
|
+
if (value.type === 'turn.failed' || value.type === 'error')
|
|
164
|
+
failed = true;
|
|
165
|
+
yield event;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
failed = true;
|
|
170
|
+
throw error;
|
|
171
|
+
}
|
|
172
|
+
finally {
|
|
173
|
+
finish(session, { status: aborted(turnOptions) ? 'cancelled' : failed ? 'failed' : completed ? 'completed' : 'cancelled',
|
|
174
|
+
answer: completed && !failed ? answer : '',
|
|
175
|
+
...(!completed || failed ? { error: 'The Codex SDK stream ended without a successful completed turn.' } : {}),
|
|
176
|
+
...(target.id ? { session_id: target.id } : {}), ...(model ? { model } : {}), ...(usage ? { usage } : {}) });
|
|
177
|
+
}
|
|
178
|
+
})();
|
|
179
|
+
return { events };
|
|
180
|
+
};
|
|
181
|
+
const value = Reflect.get(target, key, target);
|
|
182
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
return new Proxy(codex, {
|
|
187
|
+
get(target, key) {
|
|
188
|
+
if (key === 'flushLearning')
|
|
189
|
+
return () => client.flushLearning();
|
|
190
|
+
if (key === 'startThread')
|
|
191
|
+
return (...args) => wrap(target.startThread(...args), args[0]);
|
|
192
|
+
if (key === 'resumeThread')
|
|
193
|
+
return () => { throw new Error('Codex learning currently supports fresh threads. Use the original Codex client to resume an existing conversation.'); };
|
|
194
|
+
const value = Reflect.get(target, key, target);
|
|
195
|
+
return typeof value === 'function' ? value.bind(target) : value;
|
|
196
|
+
},
|
|
197
|
+
});
|
|
198
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { AgentRun, type ClientOptions } from './client.js';
|
|
2
|
+
export type BackendSdkRuntime = 'claude-agent-sdk' | 'codex-sdk';
|
|
3
|
+
export interface BackendWorkflowToolManifest {
|
|
4
|
+
name: string;
|
|
5
|
+
description: string;
|
|
6
|
+
input_schema: Record<string, unknown>;
|
|
7
|
+
output_schema?: Record<string, unknown>;
|
|
8
|
+
permission: 'allow' | 'ask' | 'deny';
|
|
9
|
+
price_usd?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface BackendWorkflowBinding {
|
|
12
|
+
context: string;
|
|
13
|
+
close(): void;
|
|
14
|
+
/** Optional explicit host binding: only this native MCP envelope can be a duplicate of bridge evidence. */
|
|
15
|
+
matchesNativeEnvelope?(name: string, input: unknown): boolean;
|
|
16
|
+
/** Consume one actual bridge completion with identical arguments, status and result. No match keeps native evidence. */
|
|
17
|
+
claimNativeEnvelope?(name: string, input: unknown, status: 'completed' | 'failed', output: unknown): boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Structural seam: importing the base client does not load the optional workflow interpreter or MCP server. */
|
|
20
|
+
export interface BackendWorkflowBridge {
|
|
21
|
+
readonly catalog: readonly BackendWorkflowToolManifest[];
|
|
22
|
+
readonly adapters: readonly ('runNode' | 'runJudge')[];
|
|
23
|
+
bind(session: BackendLearningSession): BackendWorkflowBinding;
|
|
24
|
+
}
|
|
25
|
+
export interface BackendLearningConfig extends ClientOptions {
|
|
26
|
+
/** A stable agent id, shared by fresh runs of the same backend agent. */
|
|
27
|
+
agentId: string;
|
|
28
|
+
name?: string;
|
|
29
|
+
/** The backend's standing policy. Wrappers add their explicit SDK system instructions to the source snapshot. */
|
|
30
|
+
instructions?: string;
|
|
31
|
+
/** Opt in when this wrapper first registers a missing agent (default false). Never changes an existing agent. */
|
|
32
|
+
learning?: boolean;
|
|
33
|
+
/** Explicit local MCP bridge over the backend's existing approved tool callbacks. */
|
|
34
|
+
workflows?: BackendWorkflowBridge;
|
|
35
|
+
/** Poll interval while waiting for checked learning (default 250 ms). */
|
|
36
|
+
pollIntervalMs?: number;
|
|
37
|
+
/** Maximum wait after completion for checked learning (default 120000 ms). The server continues after a timeout. */
|
|
38
|
+
learningTimeoutMs?: number;
|
|
39
|
+
}
|
|
40
|
+
export interface BackendLearningStart {
|
|
41
|
+
runtime: BackendSdkRuntime;
|
|
42
|
+
input: string;
|
|
43
|
+
instructions: string;
|
|
44
|
+
model?: string;
|
|
45
|
+
}
|
|
46
|
+
export type SdkLearningEvent = {
|
|
47
|
+
type: 'text';
|
|
48
|
+
text: string;
|
|
49
|
+
} | {
|
|
50
|
+
type: 'session';
|
|
51
|
+
session_id: string;
|
|
52
|
+
} | {
|
|
53
|
+
type: 'tool';
|
|
54
|
+
id: string;
|
|
55
|
+
name: string;
|
|
56
|
+
status: 'started' | 'completed' | 'failed';
|
|
57
|
+
input?: unknown;
|
|
58
|
+
output?: unknown;
|
|
59
|
+
parent_tool_use_id?: string;
|
|
60
|
+
};
|
|
61
|
+
export interface SdkLearningUsage {
|
|
62
|
+
/** Uncached input only. Cache reads and writes have their own counters; unknown splits remain null. */
|
|
63
|
+
input_tokens?: number | null;
|
|
64
|
+
output_tokens?: number | null;
|
|
65
|
+
cache_read_tokens?: number | null;
|
|
66
|
+
cache_write_tokens?: number | null;
|
|
67
|
+
cost_usd?: number | null;
|
|
68
|
+
}
|
|
69
|
+
export interface SdkLearningOutcome {
|
|
70
|
+
status: 'completed' | 'failed' | 'cancelled';
|
|
71
|
+
answer: string;
|
|
72
|
+
error?: string;
|
|
73
|
+
model?: string;
|
|
74
|
+
session_id?: string;
|
|
75
|
+
usage?: SdkLearningUsage;
|
|
76
|
+
}
|
|
77
|
+
export interface BackendLearningSnapshot {
|
|
78
|
+
learningEnabled: boolean;
|
|
79
|
+
revision: string | null;
|
|
80
|
+
context: string;
|
|
81
|
+
skills: ReadonlyArray<{
|
|
82
|
+
name: string;
|
|
83
|
+
files: Readonly<Record<string, string>>;
|
|
84
|
+
}>;
|
|
85
|
+
workflows?: ReadonlyArray<{
|
|
86
|
+
name: string;
|
|
87
|
+
workflow: string;
|
|
88
|
+
description: string;
|
|
89
|
+
}>;
|
|
90
|
+
workflowContext?: string;
|
|
91
|
+
}
|
|
92
|
+
export interface BackendLearningStatus {
|
|
93
|
+
run_id: string;
|
|
94
|
+
state: 'running' | 'processing' | 'completed' | 'failed' | 'cancelled';
|
|
95
|
+
learning_run_id?: string;
|
|
96
|
+
learning?: {
|
|
97
|
+
state: string;
|
|
98
|
+
reason?: string | null;
|
|
99
|
+
} | null;
|
|
100
|
+
}
|
|
101
|
+
/** A persistence or grading failure, separate from the application's original SDK result or error. */
|
|
102
|
+
export declare class BackendLearningError extends Error {
|
|
103
|
+
readonly runId: string;
|
|
104
|
+
readonly reason: string;
|
|
105
|
+
constructor(runId: string, reason: string);
|
|
106
|
+
}
|
|
107
|
+
/** Coordinates registration and background persistence without changing the SDK's own result/error contract. */
|
|
108
|
+
export declare class BackendLearningClient {
|
|
109
|
+
#private;
|
|
110
|
+
constructor(config: BackendLearningConfig);
|
|
111
|
+
begin(source: BackendLearningStart, signal?: AbortSignal): Promise<BackendLearningSession>;
|
|
112
|
+
/** Observe completion immediately; the original SDK call can return without waiting for reflection/grading. */
|
|
113
|
+
track(promise: Promise<unknown>): void;
|
|
114
|
+
/** Wait for tracked writes and checked learning. Does not retry or re-run the caller's SDK task. */
|
|
115
|
+
flushLearning(): Promise<void>;
|
|
116
|
+
}
|
|
117
|
+
/** One immutable source/seed snapshot and its ordered evidence. The scoped token is never exposed to the wrapper. */
|
|
118
|
+
export declare class BackendLearningSession implements BackendLearningSnapshot {
|
|
119
|
+
#private;
|
|
120
|
+
readonly runId: string;
|
|
121
|
+
readonly consoleUrl: string;
|
|
122
|
+
readonly learningEnabled: boolean;
|
|
123
|
+
readonly revision: string | null;
|
|
124
|
+
readonly context: string;
|
|
125
|
+
readonly skills: BackendLearningSnapshot['skills'];
|
|
126
|
+
readonly workflows: NonNullable<BackendLearningSnapshot['workflows']>;
|
|
127
|
+
readonly workflowContext: string;
|
|
128
|
+
constructor(scoped: AgentRun, snapshot: BackendLearningSnapshot & {
|
|
129
|
+
runId: string;
|
|
130
|
+
consoleUrl: string;
|
|
131
|
+
}, config: Pick<BackendLearningConfig, 'pollIntervalMs' | 'learningTimeoutMs' | 'workflows'>);
|
|
132
|
+
/** Keep ephemeral bridge capabilities out of stored evidence without changing native SDK results. */
|
|
133
|
+
protect(values: readonly string[]): void;
|
|
134
|
+
/** Stop admitting work immediately; evidence can still drain before durable completion. */
|
|
135
|
+
closeWorkflows(): void;
|
|
136
|
+
/** Revoke workflow capabilities as soon as the native SDK cancels, including an idle stream. */
|
|
137
|
+
followAbort(signal?: AbortSignal): void;
|
|
138
|
+
get status(): BackendLearningStatus | undefined;
|
|
139
|
+
/** Keep the native task outcome, but refuse to learn from evidence the wrapper cannot faithfully capture. */
|
|
140
|
+
markEvidenceIncomplete(reason: string): void;
|
|
141
|
+
/** Observe native SDK tools without counting a positively correlated bridge envelope twice. Candidate starts wait
|
|
142
|
+
* for their result; every unmatched or unfinished candidate is still ordinary top-level evidence. Raw arguments
|
|
143
|
+
* and results stay local, and at most sixteen bounded candidates (the bridge's invocation bound) are retained. */
|
|
144
|
+
nativeEvent(event: SdkLearningEvent, detail?: {
|
|
145
|
+
input?: unknown;
|
|
146
|
+
output?: unknown;
|
|
147
|
+
}): Promise<void>;
|
|
148
|
+
/** Await to apply backpressure. A failed/oversized batch prevents learning from an incomplete transcript. */
|
|
149
|
+
event(event: SdkLearningEvent): Promise<void>;
|
|
150
|
+
/** Persist the caller's outcome, then wait for the server's independent checked-learning verdict. */
|
|
151
|
+
complete(outcome: SdkLearningOutcome): Promise<void>;
|
|
152
|
+
}
|
|
153
|
+
/** Skills are supplied as quoted reference text, never installed/executed on the application's filesystem. */
|
|
154
|
+
export declare function renderLearningContext(snapshot: BackendLearningSnapshot): string;
|