@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
|
@@ -0,0 +1,381 @@
|
|
|
1
|
+
/** Optional, local workflow MCP bridge. Native SDK credentials and tools remain owned by the backend. */
|
|
2
|
+
import { randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
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';
|
|
8
|
+
const canonicalTool = /^mcp:[a-z][a-z0-9-]{0,31}\/[A-Za-z0-9_-]{1,64}$/;
|
|
9
|
+
const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
|
|
10
|
+
const copy = (value) => JSON.parse(JSON.stringify(value));
|
|
11
|
+
const freeze = (value) => { if (value && typeof value === 'object') {
|
|
12
|
+
Object.values(value).forEach(freeze);
|
|
13
|
+
Object.freeze(value);
|
|
14
|
+
} return value; };
|
|
15
|
+
const limit = (value, fallback, max, name) => {
|
|
16
|
+
if (value !== undefined && (!Number.isSafeInteger(value) || value < 1 || value > max))
|
|
17
|
+
throw new TypeError(`${name} must be an integer between 1 and ${max}.`);
|
|
18
|
+
return value ?? fallback;
|
|
19
|
+
};
|
|
20
|
+
class Refused extends Error {
|
|
21
|
+
}
|
|
22
|
+
const refuse = (message) => { throw new Refused(message); };
|
|
23
|
+
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
|
+
const toolResult = (text, isError = false) => ({ content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) });
|
|
25
|
+
/** Race work with cancellation without pretending an uncooperative callback can be rolled back. */
|
|
26
|
+
async function cancellable(work, signal) {
|
|
27
|
+
signal.throwIfAborted();
|
|
28
|
+
let stop = () => undefined;
|
|
29
|
+
try {
|
|
30
|
+
return await Promise.race([work, new Promise((_, reject) => {
|
|
31
|
+
stop = () => reject(signal.reason ?? new Error('Workflow cancelled.'));
|
|
32
|
+
signal.addEventListener('abort', stop, { once: true });
|
|
33
|
+
if (signal.aborted)
|
|
34
|
+
stop();
|
|
35
|
+
})]);
|
|
36
|
+
}
|
|
37
|
+
finally {
|
|
38
|
+
signal.removeEventListener('abort', stop);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Start once, explicitly configure this endpoint on the original native SDK, then pass the bridge to its wrapper.
|
|
42
|
+
* The endpoint never executes a workflow supplied by a model: only the server's checked, pinned run snapshot.
|
|
43
|
+
* Nothing is installed into the backend or executed through a new hidden native SDK session. */
|
|
44
|
+
export async function createWorkflowMcpBridge(options) {
|
|
45
|
+
if (!options.engine || typeof options.engine.inspectWorkflow !== 'function' || typeof options.engine.runWorkflow !== 'function' || typeof options.engine.resolveSchemaForWorkflow !== 'function')
|
|
46
|
+
throw new TypeError('Provide an explicit host workflow engine with inspection, execution and schema resolution.');
|
|
47
|
+
if (typeof options.policy !== 'function')
|
|
48
|
+
throw new TypeError('A live backend policy callback is required.');
|
|
49
|
+
if (options.nativeMcpServerName !== undefined && (typeof options.nativeMcpServerName !== 'string' || !/^[A-Za-z0-9_-]{1,64}$/.test(options.nativeMcpServerName)))
|
|
50
|
+
throw new TypeError('nativeMcpServerName must be the exact native MCP server name (1-64 letters, digits, underscores or hyphens).');
|
|
51
|
+
const nativeServer = options.nativeMcpServerName;
|
|
52
|
+
if (!Array.isArray(options.tools) || options.tools.length > 64)
|
|
53
|
+
throw new TypeError('Provide at most 64 explicit backend tools.');
|
|
54
|
+
const maxCalls = limit(options.maxToolCalls, 32, 256, 'maxToolCalls');
|
|
55
|
+
const maxNodes = limit(options.maxNodeSteps, 256, 2048, 'maxNodeSteps');
|
|
56
|
+
const maxDuration = limit(options.maxDurationMs, 60_000, 300_000, 'maxDurationMs');
|
|
57
|
+
const leaseDuration = limit(options.leaseDurationMs, 3_600_000, 86_400_000, 'leaseDurationMs');
|
|
58
|
+
// Capture callbacks and schemas once: later caller mutation cannot silently expand this bridge's authority.
|
|
59
|
+
const { inspectWorkflow, runWorkflow, resolveSchemaForWorkflow } = options.engine;
|
|
60
|
+
const policy = options.policy, runNode = options.runNode, runJudge = options.runJudge, observer = options.onEvent;
|
|
61
|
+
const validator = new AjvJsonSchemaValidator();
|
|
62
|
+
const registered = new Map();
|
|
63
|
+
for (const tool of options.tools) {
|
|
64
|
+
if (!tool || typeof tool !== 'object' || typeof tool.name !== 'string' || !canonicalTool.test(tool.name) || registered.has(tool.name) ||
|
|
65
|
+
typeof tool.description !== 'string' || !tool.description.trim() || tool.description.length > 4000 ||
|
|
66
|
+
!object(tool.input_schema) || (tool.output_schema !== undefined && !object(tool.output_schema)) ||
|
|
67
|
+
!['allow', 'ask', 'deny'].includes(tool.permission) || typeof tool.execute !== 'function' ||
|
|
68
|
+
(tool.readOnly !== undefined && typeof tool.readOnly !== 'boolean') ||
|
|
69
|
+
(tool.price_usd !== undefined && (typeof tool.price_usd !== 'number' || !Number.isFinite(tool.price_usd) || tool.price_usd < 0)))
|
|
70
|
+
throw new TypeError('Invalid or duplicate backend workflow tool.');
|
|
71
|
+
const manifest = freeze(copy({ name: tool.name, description: tool.description, input_schema: tool.input_schema,
|
|
72
|
+
...(tool.output_schema ? { output_schema: tool.output_schema } : {}), permission: tool.permission,
|
|
73
|
+
...(tool.price_usd !== undefined ? { price_usd: tool.price_usd } : {}) }));
|
|
74
|
+
registered.set(tool.name, { manifest, readOnly: tool.readOnly === true, execute: tool.execute, input: validator.getValidator(manifest.input_schema),
|
|
75
|
+
...(manifest.output_schema ? { output: validator.getValidator(manifest.output_schema) } : {}) });
|
|
76
|
+
}
|
|
77
|
+
const catalog = freeze([...registered.values()].map(tool => tool.manifest));
|
|
78
|
+
if (Buffer.byteLength(JSON.stringify(catalog)) > 65_536)
|
|
79
|
+
throw new TypeError('The workflow tool manifest exceeds 64 KiB.');
|
|
80
|
+
const adapters = Object.freeze([...(runNode ? ['runNode'] : []), ...(runJudge ? ['runJudge'] : [])]);
|
|
81
|
+
// A model adapter may perform work outside this callback catalog. Do not label its workflows read-only.
|
|
82
|
+
// Ask/deny callbacks cannot execute; allowing a callback later requires constructing a new bridge.
|
|
83
|
+
const readOnlyHint = !runNode && !runJudge && [...registered.values()].every(tool => tool.manifest.permission !== 'allow' || tool.readOnly);
|
|
84
|
+
const authorization = `Bearer ${randomBytes(32).toString('hex')}`;
|
|
85
|
+
const leases = new Map();
|
|
86
|
+
const connections = new Set();
|
|
87
|
+
let closed = false;
|
|
88
|
+
const emit = (event) => { try {
|
|
89
|
+
observer?.(Object.freeze(event));
|
|
90
|
+
}
|
|
91
|
+
catch { /* Observers cannot change execution. */ } };
|
|
92
|
+
const evidence = async (lease, event) => { await lease.session.event(event).catch(() => undefined); };
|
|
93
|
+
const checked = (text) => {
|
|
94
|
+
if (typeof text !== 'string' || Buffer.byteLength(text) > 262_144)
|
|
95
|
+
refuse('The pinned workflow is too large.');
|
|
96
|
+
let workflow;
|
|
97
|
+
try {
|
|
98
|
+
workflow = JSON.parse(text);
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return refuse('The pinned workflow is invalid JSON.');
|
|
102
|
+
}
|
|
103
|
+
const inspection = inspectWorkflow(workflow);
|
|
104
|
+
if (inspection.requires.executableCode || inspection.requires.sopSections.length || inspection.nodes.length > 128)
|
|
105
|
+
refuse('This bridge refuses code, shell, executor, SOP-dependent or oversized workflows.');
|
|
106
|
+
for (const adapter of inspection.requires.adapters) {
|
|
107
|
+
if (adapter !== 'runEffect' && !adapters.includes(adapter))
|
|
108
|
+
refuse(`The backend has not provided ${adapter}.`);
|
|
109
|
+
}
|
|
110
|
+
for (const name of inspection.requires.tools)
|
|
111
|
+
if (registered.get(name)?.manifest.permission !== 'allow')
|
|
112
|
+
refuse('A required tool is not allowed by this backend.');
|
|
113
|
+
for (const entry of inspection.nodes) {
|
|
114
|
+
const node = pointer(workflow, entry.path);
|
|
115
|
+
if ((Array.isArray(node.tools) && node.tools.length) || node.context === 'fork')
|
|
116
|
+
refuse('Workflow model nodes cannot gain native tools or fork the native conversation.');
|
|
117
|
+
if (node.node === 'call' && (node.via !== 'tool' || object(node.retry) && Number(node.retry.attempts) > 1))
|
|
118
|
+
refuse('Only explicitly delegated tool effects without automatic retries are supported.');
|
|
119
|
+
}
|
|
120
|
+
return workflow;
|
|
121
|
+
};
|
|
122
|
+
const execute = async (args, requestSignal) => {
|
|
123
|
+
const capability = args?.capability;
|
|
124
|
+
const lease = typeof capability === 'string' ? leases.get(capability) : undefined;
|
|
125
|
+
if (!lease || lease.controller.signal.aborted || closed)
|
|
126
|
+
return toolResult('This workflow capability is unavailable or expired. Start a fresh native task.', true);
|
|
127
|
+
if (!args || Object.keys(args).some(key => !['capability', 'name', 'input'].includes(key)) || typeof args.name !== 'string' || !object(args.input))
|
|
128
|
+
return toolResult('Provide capability, workflow name, and an input object.', true);
|
|
129
|
+
if (lease.active || lease.blocked || lease.invocations >= 16)
|
|
130
|
+
return toolResult('This native task cannot admit another workflow invocation. Do not retry an uncertain effect.', true);
|
|
131
|
+
const accepted = lease.workflows.find(workflow => workflow.name === args.name);
|
|
132
|
+
if (!accepted)
|
|
133
|
+
return toolResult('That workflow is not in this native task\'s checked snapshot.', true);
|
|
134
|
+
let workflow;
|
|
135
|
+
try {
|
|
136
|
+
workflow = checked(accepted.workflow);
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
return toolResult(error instanceof Refused ? error.message : 'The pinned workflow failed structural admission.', true);
|
|
140
|
+
}
|
|
141
|
+
lease.active = true;
|
|
142
|
+
lease.invocations++;
|
|
143
|
+
const invocation = randomUUID(), controller = new AbortController();
|
|
144
|
+
const receipt = { input: JSON.stringify(args) };
|
|
145
|
+
lease.receipts.push(receipt);
|
|
146
|
+
const signal = AbortSignal.any([lease.controller.signal, controller.signal, requestSignal, AbortSignal.timeout(maxDuration)]);
|
|
147
|
+
const context = { runId: lease.session.runId, workflow: accepted.name };
|
|
148
|
+
let pending = 0;
|
|
149
|
+
const record = (name, id, status) => evidence(lease, {
|
|
150
|
+
type: 'tool', name, id, status, ...(id !== invocation ? { parent_tool_use_id: invocation } : {}),
|
|
151
|
+
});
|
|
152
|
+
emit({ ...context, type: 'workflow.start' });
|
|
153
|
+
await evidence(lease, { type: 'tool', id: invocation, name: 'learned_workflow', status: 'started', input: { name: accepted.name } });
|
|
154
|
+
try {
|
|
155
|
+
signal.throwIfAborted();
|
|
156
|
+
const result = await cancellable(runWorkflow(workflow, copy(args.input), {
|
|
157
|
+
signal,
|
|
158
|
+
onEvent(event) { if (event.type === 'node.start' && ++lease.nodes > maxNodes)
|
|
159
|
+
controller.abort(new Refused('The workflow node limit was reached.')); },
|
|
160
|
+
runCode: async () => refuse('Code execution is not permitted by this bridge.'),
|
|
161
|
+
...(runNode ? { runNode: async (request) => {
|
|
162
|
+
signal.throwIfAborted();
|
|
163
|
+
if (request.tools?.length || request.context === 'fork')
|
|
164
|
+
refuse('Native tools and transcript forks are not delegated to model nodes.');
|
|
165
|
+
pending++;
|
|
166
|
+
try {
|
|
167
|
+
return await runNode({ ...request, signal: AbortSignal.any([signal, ...(request.signal ? [request.signal] : [])]) });
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
pending--;
|
|
171
|
+
}
|
|
172
|
+
} } : {}),
|
|
173
|
+
...(runJudge ? { runJudge: async (request) => {
|
|
174
|
+
signal.throwIfAborted();
|
|
175
|
+
pending++;
|
|
176
|
+
try {
|
|
177
|
+
return await runJudge({ ...request, signal: AbortSignal.any([signal, ...(request.signal ? [request.signal] : [])]) });
|
|
178
|
+
}
|
|
179
|
+
finally {
|
|
180
|
+
pending--;
|
|
181
|
+
}
|
|
182
|
+
} } : {}),
|
|
183
|
+
runEffect: async (request) => {
|
|
184
|
+
signal.throwIfAborted();
|
|
185
|
+
const name = request.node.via === 'tool' ? request.node.tool : undefined;
|
|
186
|
+
const tool = name ? registered.get(name) : undefined;
|
|
187
|
+
if (!name || !tool || tool.manifest.permission !== 'allow')
|
|
188
|
+
return refuse('This tool was not explicitly delegated.');
|
|
189
|
+
if (++lease.calls > maxCalls)
|
|
190
|
+
return refuse('The native task\'s workflow tool call limit was reached.');
|
|
191
|
+
const input = copy(request.input);
|
|
192
|
+
if (!tool.input(input).valid)
|
|
193
|
+
return refuse('Workflow arguments do not match the original backend tool schema.');
|
|
194
|
+
const ctx = { ...context, signal: AbortSignal.any([signal, request.signal]), idempotencyKey: `${invocation}:${request.idempotencyKey}` };
|
|
195
|
+
ctx.signal.throwIfAborted();
|
|
196
|
+
const id = randomUUID();
|
|
197
|
+
await record(name, id, 'started');
|
|
198
|
+
ctx.signal.throwIfAborted();
|
|
199
|
+
emit({ ...context, type: 'tool.start', tool: name });
|
|
200
|
+
pending++;
|
|
201
|
+
try {
|
|
202
|
+
// Evidence transport can take time. Ask the live policy at dispatch, after that wait.
|
|
203
|
+
if (await cancellable(Promise.resolve(policy(name, copy(input), ctx)), ctx.signal) !== 'allow')
|
|
204
|
+
return refuse('The backend policy did not allow this tool call.');
|
|
205
|
+
ctx.signal.throwIfAborted();
|
|
206
|
+
const output = await tool.execute(input, ctx);
|
|
207
|
+
ctx.signal.throwIfAborted();
|
|
208
|
+
if (tool.output && !tool.output(output).valid)
|
|
209
|
+
refuse('A tool result did not match its backend output schema.');
|
|
210
|
+
await record(name, id, 'completed');
|
|
211
|
+
emit({ ...context, type: 'tool.end', tool: name, status: 'completed' });
|
|
212
|
+
return output;
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
await record(name, id, 'failed');
|
|
216
|
+
emit({ ...context, type: 'tool.end', tool: name, status: ctx.signal.aborted ? 'cancelled' : 'failed' });
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
finally {
|
|
220
|
+
pending--;
|
|
221
|
+
}
|
|
222
|
+
},
|
|
223
|
+
}), signal);
|
|
224
|
+
signal.throwIfAborted();
|
|
225
|
+
if (result.status !== 'complete')
|
|
226
|
+
throw new Refused('The workflow escalated without completing. Inspect its result before another run.');
|
|
227
|
+
// 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);
|
|
230
|
+
if (Buffer.byteLength(output) > 65_536)
|
|
231
|
+
refuse('The workflow output exceeds the bridge response limit. Do not rerun its effects to recover the output.');
|
|
232
|
+
await record('learned_workflow', invocation, 'completed');
|
|
233
|
+
emit({ ...context, type: 'workflow.end', status: 'completed' });
|
|
234
|
+
receipt.status = 'completed';
|
|
235
|
+
receipt.output = output;
|
|
236
|
+
return toolResult(output);
|
|
237
|
+
}
|
|
238
|
+
catch (error) {
|
|
239
|
+
lease.blocked = true;
|
|
240
|
+
if (pending) {
|
|
241
|
+
try {
|
|
242
|
+
lease.session.markEvidenceIncomplete('A workflow callback was still pending at interruption; its effects may be uncertain.');
|
|
243
|
+
}
|
|
244
|
+
catch { /* Completion already closed the run. */ }
|
|
245
|
+
}
|
|
246
|
+
const cancelled = signal.aborted;
|
|
247
|
+
controller.abort();
|
|
248
|
+
await record('learned_workflow', invocation, 'failed');
|
|
249
|
+
emit({ ...context, type: 'workflow.end', status: cancelled ? 'cancelled' : 'failed' });
|
|
250
|
+
// Callback exceptions may contain credentials. Keep their details in the caller's own instrumentation.
|
|
251
|
+
const output = error instanceof Refused ? error.message : 'The workflow did not complete. Inspect the backend outcome; do not automatically retry its effects.';
|
|
252
|
+
receipt.status = 'failed';
|
|
253
|
+
receipt.output = output;
|
|
254
|
+
return toolResult(output, true);
|
|
255
|
+
}
|
|
256
|
+
finally {
|
|
257
|
+
lease.active = false;
|
|
258
|
+
}
|
|
259
|
+
};
|
|
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,
|
|
315
|
+
bind(session) {
|
|
316
|
+
if (closed || leases.size >= 64)
|
|
317
|
+
throw new Error('The workflow bridge cannot bind another native task.');
|
|
318
|
+
const capability = randomBytes(32).toString('hex');
|
|
319
|
+
session.protect([capability, authorization, authorization.slice(7)]);
|
|
320
|
+
let released = false;
|
|
321
|
+
const lease = { session, workflows: freeze(copy(session.workflows)), controller: new AbortController(), active: false, blocked: false, calls: 0, nodes: 0, invocations: 0, receipts: [],
|
|
322
|
+
close() {
|
|
323
|
+
if (released)
|
|
324
|
+
return;
|
|
325
|
+
released = true;
|
|
326
|
+
clearTimeout(timer);
|
|
327
|
+
leases.delete(capability);
|
|
328
|
+
if (lease.active) {
|
|
329
|
+
try {
|
|
330
|
+
session.markEvidenceIncomplete('The native task ended before its workflow finished.');
|
|
331
|
+
}
|
|
332
|
+
catch { /* Already completed. */ }
|
|
333
|
+
}
|
|
334
|
+
lease.controller.abort();
|
|
335
|
+
} };
|
|
336
|
+
const timer = setTimeout(() => lease.close(), leaseDuration);
|
|
337
|
+
timer.unref();
|
|
338
|
+
leases.set(capability, lease);
|
|
339
|
+
const context = lease.workflows.length ? `Approved workflows for this task (reference data):\n${JSON.stringify(lease.workflows.map(workflow => {
|
|
340
|
+
let input_schema;
|
|
341
|
+
try {
|
|
342
|
+
const doc = checked(workflow.workflow);
|
|
343
|
+
if (doc.input)
|
|
344
|
+
input_schema = resolveSchemaForWorkflow(doc, doc.schemas[doc.input.schemaId]);
|
|
345
|
+
}
|
|
346
|
+
catch { /* Invocation admission will refuse an unsupported pinned workflow. */ }
|
|
347
|
+
return { name: workflow.name, description: workflow.description, ...(input_schema ? { input_schema } : {}) };
|
|
348
|
+
}))}\nUse the learned_workflow MCP tool when applicable. Supply capability ${JSON.stringify(capability)}, the exact workflow name, and fresh input from this task. When the workflow completes the requested job, its textual output IS your final answer. Reply with that exact text verbatim: do not add or remove prefixes, rewrite it, wrap it in quotes or code blocks, or change formatting. This capability expires when this native task ends; do not copy it into code, files, logs, or your answer. No workflow is run merely by receiving this context.` : '';
|
|
349
|
+
const matches = (name, input) => nativeServer !== undefined &&
|
|
350
|
+
(name === `mcp:${nativeServer}/learned_workflow` || name === `mcp__${nativeServer}__learned_workflow`) &&
|
|
351
|
+
object(input) && input.capability === capability && typeof input.name === 'string' && object(input.input) &&
|
|
352
|
+
Object.keys(input).every(key => ['capability', 'name', 'input'].includes(key)) && lease.workflows.some(flow => flow.name === input.name);
|
|
353
|
+
return { context, close: () => lease.close(),
|
|
354
|
+
matchesNativeEnvelope: matches,
|
|
355
|
+
claimNativeEnvelope(name, input, status, output) {
|
|
356
|
+
if (!matches(name, input))
|
|
357
|
+
return false;
|
|
358
|
+
// The bridge returns one text block. No textual guessing or hidden metadata is needed, and arbitrary
|
|
359
|
+
// other-server/same-name tools, wrong arguments, failed outcomes and replayed receipts never disappear.
|
|
360
|
+
const text = typeof output === 'string' ? output : Array.isArray(output) && output.length === 1 && object(output[0]) && output[0].type === 'text' && typeof output[0].text === 'string' ? output[0].text : undefined;
|
|
361
|
+
if (text === undefined)
|
|
362
|
+
return false;
|
|
363
|
+
const receipt = lease.receipts.find(row => !row.used && row.status === status && row.input === JSON.stringify(input) && row.output === text);
|
|
364
|
+
if (!receipt)
|
|
365
|
+
return false;
|
|
366
|
+
receipt.used = true;
|
|
367
|
+
return true;
|
|
368
|
+
},
|
|
369
|
+
};
|
|
370
|
+
},
|
|
371
|
+
async close() {
|
|
372
|
+
if (closed)
|
|
373
|
+
return;
|
|
374
|
+
closed = true;
|
|
375
|
+
for (const lease of leases.values())
|
|
376
|
+
lease.close();
|
|
377
|
+
await Promise.allSettled([...connections].map(server => server.close()));
|
|
378
|
+
await new Promise(resolve => { http.close(() => resolve()); http.closeAllConnections(); });
|
|
379
|
+
},
|
|
380
|
+
});
|
|
381
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-client",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.40",
|
|
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",
|
|
@@ -22,7 +22,23 @@
|
|
|
22
22
|
"types": "./dist/index.d.ts",
|
|
23
23
|
"default": "./dist/index.js"
|
|
24
24
|
},
|
|
25
|
-
"./
|
|
25
|
+
"./learning": {
|
|
26
|
+
"types": "./dist/learning.d.ts",
|
|
27
|
+
"default": "./dist/learning.js"
|
|
28
|
+
},
|
|
29
|
+
"./claude": {
|
|
30
|
+
"types": "./dist/claude.d.ts",
|
|
31
|
+
"default": "./dist/claude.js"
|
|
32
|
+
},
|
|
33
|
+
"./codex": {
|
|
34
|
+
"types": "./dist/codex.d.ts",
|
|
35
|
+
"default": "./dist/codex.js"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json",
|
|
38
|
+
"./workflows": {
|
|
39
|
+
"types": "./dist/workflows.d.ts",
|
|
40
|
+
"default": "./dist/workflows.js"
|
|
41
|
+
}
|
|
26
42
|
},
|
|
27
43
|
"files": [
|
|
28
44
|
"dist",
|
|
@@ -49,5 +65,16 @@
|
|
|
49
65
|
"publishConfig": {
|
|
50
66
|
"access": "public",
|
|
51
67
|
"tag": "beta"
|
|
68
|
+
},
|
|
69
|
+
"peerDependencies": {
|
|
70
|
+
"@modelcontextprotocol/sdk": "1.32.2"
|
|
71
|
+
},
|
|
72
|
+
"peerDependenciesMeta": {
|
|
73
|
+
"@modelcontextprotocol/sdk": {
|
|
74
|
+
"optional": true
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
"devDependencies": {
|
|
78
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.40"
|
|
52
79
|
}
|
|
53
80
|
}
|