109 lines
7.1 KiB
JavaScript
109 lines
7.1 KiB
JavaScript
// The literal is copied into each owned runtime. Bundling preserves its bytes;
|
|
// no third-party program or currently running release is modified.
|
|
export const CONTROLLED_BRIDGE_PLUGIN = String.raw`import fs from 'node:fs';
|
|
import { createHash } from 'node:crypto';
|
|
export const name = 'agent-workbench-controlled-bridge';
|
|
export const inject = ['tools', 'llm', 'appReady', 'systemPrompt'];
|
|
const canonical = value => Array.isArray(value) ? value.map(canonical) : value && typeof value === 'object'
|
|
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonical(value[key])])) : value;
|
|
const digest = value => createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
|
export async function apply(ctx, config) {
|
|
const { LlmAdapter } = await import(config.llmModule);
|
|
if (config.promptExperiment) {
|
|
const section = config.promptExperiment.section;
|
|
ctx.systemPrompt.section({ name: section.name, order: section.order, interpolate: false, text: () => section.text });
|
|
}
|
|
const controller = new AbortController();
|
|
ctx.effect(() => () => controller.abort(new Error('Owned engine bridge disposed.')));
|
|
const descriptors = config.tools.map(({ name, description, parameters }) => ({ name, description, parameters }));
|
|
const names = new Set(descriptors.map(tool => tool.name));
|
|
const catalogue = () => ctx.tools.schemas().map(({ name, description, parameters }) => ({ name, description, parameters }))
|
|
.sort((left, right) => left.name.localeCompare(right.name));
|
|
const assertCatalogue = () => {
|
|
if (digest(catalogue()) !== config.catalogueSha256) throw new Error('The owned tool catalogue changed.');
|
|
};
|
|
const post = async (route, data, signal) => {
|
|
controller.signal.throwIfAborted(); signal?.throwIfAborted(); assertCatalogue();
|
|
const response = await fetch(config.endpoint + route, { method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + config.nonce },
|
|
signal: signal ? AbortSignal.any([signal, controller.signal]) : controller.signal,
|
|
body: JSON.stringify({ owner: config.owner, sessionId: config.sdkSessionId, pid: process.pid, data }) });
|
|
let size = 0; const chunks = [];
|
|
for await (const chunk of response.body) {
|
|
size += chunk.length;
|
|
if (size > config.maximumFrameBytes) throw new Error('Owned bridge response exceeded its bound.');
|
|
chunks.push(chunk);
|
|
}
|
|
const value = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
if (!response.ok) throw new Error(value.error || 'Owned bridge rejected the request.');
|
|
return value;
|
|
};
|
|
for (const descriptor of descriptors) ctx.tools.register({ ...descriptor,
|
|
output: { schema: {}, render: (_args, value) => [{ type: 'text', text: JSON.stringify(value) }] },
|
|
async execute(args, execution) {
|
|
if (execution.agent?.session?.id !== config.sdkSessionId) throw new Error('Tool caller is not the owned SDK session.');
|
|
return post('/tool', { callId: execution.callId, name: descriptor.name, arguments: args }, execution.signal);
|
|
},
|
|
});
|
|
ctx.on('tools/pre-execute', async (execution, next) => {
|
|
assertCatalogue();
|
|
if (execution.agent?.session?.id !== config.sdkSessionId || !names.has(execution.name)) {
|
|
return { kind: 'deny', reason: 'This tool or caller is outside the owned workbench scope.' };
|
|
}
|
|
return next();
|
|
});
|
|
class WorkbenchAdapter extends LlmAdapter {
|
|
async resolveModel(provider, model) {
|
|
if (provider !== 'agent-workbench' || model !== config.model) throw new Error('Owned model route changed.');
|
|
return { provider, id: model, name: model, contextWindow: config.contextLimit, defaultMaxTokens: config.maxOutputTokens };
|
|
}
|
|
async *stream(options) {
|
|
if (options.provider !== 'agent-workbench' || options.model !== config.model) throw new Error('Unowned model route.');
|
|
const result = await post('/model', { messages: options.messages, system: options.system ?? null,
|
|
tools: options.tools ?? [], toolHistory: options.toolHistory ?? null,
|
|
model: options.model, maxTokens: options.maxTokens ?? config.maxOutputTokens }, options.signal);
|
|
const message = result.message;
|
|
if (result.finishReason === 'length') throw new Error('Owned model output reached its bound; incomplete tools are not executed.');
|
|
if (!message || message.role !== 'assistant' || typeof message.content !== 'string'
|
|
|| message.tool_calls !== undefined && !Array.isArray(message.tool_calls)) throw new Error('Invalid owned model result.');
|
|
let index = 0;
|
|
if (message.content) {
|
|
yield { type: 'block-start', index, blockType: 'text' };
|
|
yield { type: 'text-delta', index, text: message.content };
|
|
yield { type: 'block-end', index, block: { type: 'text', text: message.content } }; index++;
|
|
}
|
|
for (const call of message.tool_calls ?? []) {
|
|
if (typeof call.id !== 'string' || typeof call.function?.name !== 'string'
|
|
|| typeof call.function.arguments !== 'string') throw new Error('Incomplete owned tool call.');
|
|
JSON.parse(call.function.arguments);
|
|
yield { type: 'block-start', index, blockType: 'tool-call' };
|
|
yield { type: 'tool-call-delta', index, id: call.id, name: call.function.name, argumentsDelta: call.function.arguments };
|
|
yield { type: 'block-end', index, block: { type: 'tool-call', id: call.id, name: call.function.name, arguments: call.function.arguments } }; index++;
|
|
}
|
|
const usage = result.usage, valid = value => Number.isSafeInteger(value) && value >= 0;
|
|
if (valid(usage?.prompt_tokens) && valid(usage?.completion_tokens)) {
|
|
yield { type: 'usage', usage: { inputTokens: usage.prompt_tokens, outputTokens: usage.completion_tokens } };
|
|
}
|
|
yield { type: 'finish', reason: { kind: message.tool_calls?.length ? 'tool-calls' : 'stop' } };
|
|
}
|
|
}
|
|
ctx.llm.registerAdapter(['agent-workbench'], new WorkbenchAdapter());
|
|
const off = ctx.appReady.onReady(() => {
|
|
assertCatalogue();
|
|
const providers = ctx.llm.listProviders().map(provider => provider.id).sort();
|
|
if (providers.length !== 1 || providers[0] !== 'agent-workbench') throw new Error('Unexpected native model provider.');
|
|
const marker = { schemaVersion: 1, nonce: config.nonce, pid: process.pid, signal: 'appReady', readyAt: new Date().toISOString(),
|
|
owner: config.owner, sdkSessionId: config.sdkSessionId, catalogue: catalogue(), catalogueSha256: config.catalogueSha256, providers,
|
|
promptExperimentSha256: config.promptExperiment?.sha256 ?? null };
|
|
fs.writeFileSync(config.marker + '.writing', JSON.stringify(marker), { flag: 'wx' });
|
|
fs.renameSync(config.marker + '.writing', config.marker);
|
|
});
|
|
ctx.effect(() => off, 'workbench.controlled-ready');
|
|
}
|
|
`;
|
|
|
|
export const CONTROLLED_DISABLED_PLUGINS = Object.freeze(['tool-fs', 'tool-working-directory', 'persistent-bash', 'persistent-pwsh',
|
|
'terminal-bash', 'terminal-pwsh', 'llm-deepseek', 'llm-retry']);
|
|
export const canonicalEngineValue = value => Array.isArray(value) ? value.map(canonicalEngineValue) : value && typeof value === 'object'
|
|
? Object.fromEntries(Object.keys(value).sort().map(key => [key, canonicalEngineValue(value[key])])) : value;
|