@kingsoftcloud/agentkit-harness-node 0.0.16 → 0.0.18
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/dist/engine-view.html +566 -0
- package/dist/index.mjs +22 -14
- package/dist/rpc-entry.mjs +22 -14
- package/package.json +16 -2
- package/src/native/child-owner.mjs +8 -4
- package/src/native/children.mjs +12 -7
- package/src/native/command-shell.mjs +28 -3
- package/src/native/engine-client.mjs +83 -0
- package/src/native/engine-context.mjs +47 -0
- package/src/native/engine-hooks.mjs +53 -0
- package/src/native/engine-host-effects.mjs +98 -0
- package/src/native/engine-managed-delivery.mjs +65 -0
- package/src/native/engine-managed-host.mjs +75 -0
- package/src/native/engine-managed-service.mjs +249 -0
- package/src/native/engine-runtime.mjs +480 -0
- package/src/native/engine-server.mjs +454 -0
- package/src/native/engine-service.mjs +281 -0
- package/src/native/engine-tool-policy.mjs +29 -0
- package/src/native/engine-verification.mjs +111 -0
- package/src/native/engine-view-store.mjs +63 -0
- package/src/native/instruction-assembly.mjs +67 -3
- package/src/native/local-background-supervisor.mjs +1 -1
- package/src/native/local-background.mjs +4 -3
- package/src/native/local-command-tools.mjs +10 -7
- package/src/native/model-provider-compat.mjs +12 -7
- package/src/native/native-kernel-events.mjs +103 -0
- package/src/native/native-kernel-permit.mjs +95 -0
- package/src/native/native-managed-execution-grants.mjs +232 -0
- package/src/native/native-managed-injection.mjs +53 -0
- package/src/native/native-managed-interaction.mjs +192 -0
- package/src/native/native-managed-kernel-http.mjs +122 -0
- package/src/native/native-managed-kernel.mjs +922 -0
- package/src/native/native-managed-scoped-control.mjs +116 -0
- package/src/native/native-managed-session-frames.mjs +43 -0
- package/src/native/native-managed-teams-context.mjs +126 -0
- package/src/native/native-teams-callback-authority.mjs +73 -0
- package/src/native/native-teams-context-contract.mjs +272 -0
- package/src/native/native-teams-json.mjs +38 -0
- package/src/native/native-terminal-failure.mjs +53 -0
- package/src/native/sqlite-store.mjs +1 -0
- package/src/native/workspace-tools.mjs +2 -0
|
@@ -0,0 +1,480 @@
|
|
|
1
|
+
// A complete Native engine composed only from this package and Core.
|
|
2
|
+
//
|
|
3
|
+
// A host that runs the engine out of process does not assemble tools, policy
|
|
4
|
+
// versions or prompts. It gives the engine a workspace, a model binding, its
|
|
5
|
+
// own instructions and an approval callback; everything else is engine-owned
|
|
6
|
+
// and can change with an engine release alone.
|
|
7
|
+
import { createHash } from 'node:crypto';
|
|
8
|
+
import { mkdirSync, realpathSync } from 'node:fs';
|
|
9
|
+
import { join, resolve } from 'node:path';
|
|
10
|
+
import { NativeKernel, configure, initialSnapshot, canonical, terminal, invariant, todoToolDefinitions, toolDiscoveryDefinitions,
|
|
11
|
+
resolveEnginePreset, enginePresetToolDefinitions, presetRequestOutputTokens, FINAL_SUBMISSION_TOOL, REVIEW_SUBMISSION_TOOL } from '@kingsoftcloud/agentkit-harness-core';
|
|
12
|
+
|
|
13
|
+
/** Control tools the kernel adds while a Run executes, beyond those listed in its configuration. */
|
|
14
|
+
const KERNEL_TOOL_NAMES = [FINAL_SUBMISSION_TOOL, REVIEW_SUBMISSION_TOOL];
|
|
15
|
+
import { SqliteRunStore } from './sqlite-store.mjs';
|
|
16
|
+
import { createNativeModelPort, nativeModelRecoveryPolicy } from './model-port.mjs';
|
|
17
|
+
import { admitChatUsagePolicy } from './model-chat-usage.mjs';
|
|
18
|
+
import { validateMediaBlock } from './model-media.mjs';
|
|
19
|
+
import { admitProviderCompatibilityPolicy } from './model-provider-compat.mjs';
|
|
20
|
+
import { bindNativeContext, nativeContextDefaults } from './context-profile.mjs';
|
|
21
|
+
import { createNativeWorkspaceTools } from './workspace-tools.mjs';
|
|
22
|
+
import { createNativeLocalCommandTools } from './local-command-tools.mjs';
|
|
23
|
+
import { createOwnedCommandResolver } from './owned-command.mjs';
|
|
24
|
+
import { createBackgroundCommandPort } from './background-command-port.mjs';
|
|
25
|
+
import { createNativeArtifactStore } from './artifact-store.mjs';
|
|
26
|
+
import { nativeLocalExecutionMethods } from './local-execution-profile.mjs';
|
|
27
|
+
import { bindNativeModelSurface } from './model-surface-host.mjs';
|
|
28
|
+
import { nativeToolModelGuidance } from './tool-guidance.mjs';
|
|
29
|
+
import { createNativeWebTools } from './web-tools.mjs';
|
|
30
|
+
import { createNativeChildren, nativeChildRoles } from './children.mjs';
|
|
31
|
+
import { nativeChildToolDefinitions } from './child-tools.mjs';
|
|
32
|
+
import { nativeChildReaderDefinitions } from './child-readers.mjs';
|
|
33
|
+
import { nativeChildMergeDefinition } from './child-merge.mjs';
|
|
34
|
+
import { childCommandResource } from './child-command-resource.mjs';
|
|
35
|
+
import { createStudioNativeChildWorkspaces } from './child-workspace-binding.mjs';
|
|
36
|
+
import { NATIVE_ENGINE_INSTRUCTION_ASSEMBLY, engineBaseInstructions, renderEngineInstructions } from './instruction-assembly.mjs';
|
|
37
|
+
import { redactDiagnosticText } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
|
|
38
|
+
import { admitEngineToolPolicy, restrictEngineTools } from './engine-tool-policy.mjs';
|
|
39
|
+
import { admitEngineContextSources, engineContextPort } from './engine-context.mjs';
|
|
40
|
+
import { admitEngineHooks, engineHookPort } from './engine-hooks.mjs';
|
|
41
|
+
import { ENGINE_HOST_EFFECT, completedHostObservations, engineUserObservations } from './engine-host-effects.mjs';
|
|
42
|
+
import { admitEngineVerification, engineVerificationPort } from './engine-verification.mjs';
|
|
43
|
+
|
|
44
|
+
export const ENGINE_RUNTIME_CONTRACT = 'agentkit.engine-runtime/v1';
|
|
45
|
+
export const ENGINE_EXECUTION_POLICY = 'agentkit.engine-execution-policy/v1';
|
|
46
|
+
const digest = value => createHash('sha256').update(canonical(value)).digest('hex');
|
|
47
|
+
const text = value => typeof value === 'string' && value.trim().length > 0;
|
|
48
|
+
const DURABLE_APPROVAL = 'durable-preflight/v1';
|
|
49
|
+
export const ENGINE_APPROVAL_CONTRACT = 'agentkit.engine-approval/v1';
|
|
50
|
+
export const engineApprovalSubject = ({ arguments: args = {} }) => {
|
|
51
|
+
const subject = [args.command, args.path, args.url, args.task_id].find(text);
|
|
52
|
+
return subject ? redactDiagnosticText(subject, 500) : null;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
function durableDecision(record, request) {
|
|
56
|
+
const { call, operationKey } = request;
|
|
57
|
+
const interactionId = `engine-permission-${digest({ runId: request.runId, call, definition: request.definition })}`;
|
|
58
|
+
// Walk backward only within the lifetime of this call. A reused provider
|
|
59
|
+
// call ID cannot inherit a grant after its previous invocation completed.
|
|
60
|
+
for (let index = record.events.length - 1; index >= 0; index--) {
|
|
61
|
+
const { kind, payload } = record.events[index];
|
|
62
|
+
if (payload.callId !== call.callId) continue;
|
|
63
|
+
if (kind === 'tool.completed') break;
|
|
64
|
+
if (kind !== 'approval.resolved') continue;
|
|
65
|
+
const intentKey = payload.interactionId?.slice(0, -':approval'.length);
|
|
66
|
+
if (!intentKey || intentKey === operationKey) continue;
|
|
67
|
+
const receipt = record.receipts.find(row => row.operationKey === intentKey && row.status === 'committed');
|
|
68
|
+
if (receipt?.result.results?.some(result => result.status === 'approval_required' && result.interactionId === interactionId))
|
|
69
|
+
return payload.decision === 'allow' ? 'allow' : 'deny';
|
|
70
|
+
}
|
|
71
|
+
return { status: 'approval_required', approvalPolicy: DURABLE_APPROVAL, interactionId,
|
|
72
|
+
content: { contract: ENGINE_APPROVAL_CONTRACT, code: 'approval_required', argumentDigest: digest(call.arguments),
|
|
73
|
+
subject: engineApprovalSubject(call) } };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function admitExecutionPolicy(policy, legacyMaxModelCalls) {
|
|
77
|
+
if (policy === undefined) return { maxWallMs: null, maxModelCalls: legacyMaxModelCalls, maxToolCalls: null };
|
|
78
|
+
const limit = (value, minimum) => value === null || Number.isSafeInteger(value) && value >= minimum;
|
|
79
|
+
invariant(policy && typeof policy === 'object' && legacyMaxModelCalls === null
|
|
80
|
+
&& Object.keys(policy).every(key => ['contract', 'strategy', 'maxWallMs', 'maxModelCalls', 'maxToolCalls'].includes(key))
|
|
81
|
+
&& policy.contract === ENGINE_EXECUTION_POLICY && ['direct', 'plan-act-observe'].includes(policy.strategy)
|
|
82
|
+
&& limit(policy.maxWallMs, 1) && limit(policy.maxModelCalls, 1) && limit(policy.maxToolCalls, 0),
|
|
83
|
+
'engine_execution_policy_invalid');
|
|
84
|
+
return { maxWallMs: policy.maxWallMs, maxModelCalls: policy.maxModelCalls, maxToolCalls: policy.maxToolCalls };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** Validate the model binding a host supplies. The API key never enters a Run. */
|
|
88
|
+
export function admitEngineModel(model) {
|
|
89
|
+
invariant(model && typeof model === 'object' && text(model.name) && text(model.baseUrl)
|
|
90
|
+
&& ['openai-chat', 'anthropic-messages', 'openai-responses'].includes(model.protocol ?? 'openai-chat')
|
|
91
|
+
&& (model.contextWindow === undefined || Number.isSafeInteger(model.contextWindow) && model.contextWindow >= 2048)
|
|
92
|
+
&& (model.maxOutputTokens == null || Number.isSafeInteger(model.maxOutputTokens) && model.maxOutputTokens > 0)
|
|
93
|
+
&& (model.requestOutputTokens == null || Number.isSafeInteger(model.requestOutputTokens) && model.requestOutputTokens > 0)
|
|
94
|
+
&& (model.images === undefined || typeof model.images === 'boolean')
|
|
95
|
+
&& typeof model.apiKey === 'function', 'engine_model_invalid');
|
|
96
|
+
const contextWindow = model.contextWindow ?? 128000;
|
|
97
|
+
return { protocol: model.protocol ?? 'openai-chat', modelName: model.name, baseUrl: model.baseUrl, parameters: {},
|
|
98
|
+
input: model.images ? ['text', 'image'] : ['text'], contextWindow,
|
|
99
|
+
maxOutputTokens: presetRequestOutputTokens({ configured: model.requestOutputTokens ?? null,
|
|
100
|
+
modelMaxOutputTokens: model.maxOutputTokens ?? null, contextWindow }),
|
|
101
|
+
requestTimeoutMs: model.requestTimeoutMs ?? 180000 };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const CONVERSATION_TURNS = 64, CONVERSATION_CHARS = 60000;
|
|
105
|
+
export const ENGINE_INPUT_IMAGES = Object.freeze({ maxCount: 8, maxEncodedBytes: 6 * 1024 * 1024 });
|
|
106
|
+
|
|
107
|
+
function engineInputMedia(inputImages, supportsImages) {
|
|
108
|
+
if (inputImages === undefined) return [];
|
|
109
|
+
invariant(Array.isArray(inputImages) && inputImages.length <= ENGINE_INPUT_IMAGES.maxCount, 'engine_input_images_invalid');
|
|
110
|
+
if (!inputImages.length) return [];
|
|
111
|
+
invariant(supportsImages, 'engine_input_images_unsupported');
|
|
112
|
+
let encodedBytes = 0;
|
|
113
|
+
return inputImages.map(block => {
|
|
114
|
+
const url = block?.image_url?.url;
|
|
115
|
+
invariant(typeof url === 'string' && url.startsWith('data:image/'), 'engine_input_image_must_be_inline');
|
|
116
|
+
encodedBytes += Buffer.byteLength(url, 'utf8');
|
|
117
|
+
invariant(encodedBytes <= ENGINE_INPUT_IMAGES.maxEncodedBytes, 'engine_input_images_too_large');
|
|
118
|
+
try { return validateMediaBlock(block, ENGINE_INPUT_IMAGES.maxEncodedBytes); }
|
|
119
|
+
catch { invariant(false, 'engine_input_images_invalid'); }
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Earlier turns of the conversation a new Run continues. The engine decides how
|
|
124
|
+
* they reach the model; the host only supplies role and text. Newest turns win
|
|
125
|
+
* when the history exceeds the budget. */
|
|
126
|
+
function engineConversation(conversation) {
|
|
127
|
+
invariant(conversation === undefined || Array.isArray(conversation) && conversation.every(turn => turn && typeof turn === 'object'
|
|
128
|
+
&& ['user', 'assistant'].includes(turn.role) && typeof turn.text === 'string'), 'engine_conversation_invalid');
|
|
129
|
+
const turns = [];
|
|
130
|
+
let used = 0;
|
|
131
|
+
for (const turn of [...(conversation ?? [])].reverse()) {
|
|
132
|
+
const body = turn.text.trim();
|
|
133
|
+
if (!body) continue;
|
|
134
|
+
if (turns.length >= CONVERSATION_TURNS || used + body.length > CONVERSATION_CHARS) break;
|
|
135
|
+
turns.unshift(`${turn.role === 'user' ? 'User' : 'Assistant'}: ${body}`); used += body.length;
|
|
136
|
+
}
|
|
137
|
+
return turns;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export function renderEngineObjective(objective, conversation) {
|
|
141
|
+
const turns = engineConversation(conversation);
|
|
142
|
+
if (!turns.length) return objective;
|
|
143
|
+
return ['This Run continues an existing conversation. Earlier turns, oldest first:', '', ...turns, '',
|
|
144
|
+
'The current request, which is your task:', objective].join('\n');
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const HOST_TOOL_LIMIT = 128;
|
|
148
|
+
const HOST_TOOL_NAME = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
|
|
149
|
+
|
|
150
|
+
/** Admit tools the host implements (MCP servers, knowledge bases, Skills).
|
|
151
|
+
* The engine only advertises them and forwards calls; the host executes and
|
|
152
|
+
* authorizes. A read-only tool may be re-run after a crash; any other tool is
|
|
153
|
+
* never replayed by the engine. */
|
|
154
|
+
export function admitHostTools(tools, reserved, durableApprovals = false, hostReceipts = false) {
|
|
155
|
+
invariant(tools === undefined || Array.isArray(tools) && tools.length <= HOST_TOOL_LIMIT, 'engine_host_tools_invalid');
|
|
156
|
+
const seen = new Set();
|
|
157
|
+
return (tools ?? []).map(tool => {
|
|
158
|
+
invariant(tool && typeof tool === 'object' && !Array.isArray(tool)
|
|
159
|
+
&& Object.keys(tool).every(key => ['name', 'description', 'parameters', 'readOnly', 'timeoutMs', 'deferred', 'effectProtocol', 'receiptObservation'].includes(key))
|
|
160
|
+
&& typeof tool.name === 'string' && HOST_TOOL_NAME.test(tool.name) && !reserved.has(tool.name) && !seen.has(tool.name)
|
|
161
|
+
&& typeof tool.description === 'string' && tool.description.length <= 4000
|
|
162
|
+
&& tool.parameters && typeof tool.parameters === 'object' && !Array.isArray(tool.parameters) && tool.parameters.type === 'object'
|
|
163
|
+
&& (tool.readOnly === undefined || typeof tool.readOnly === 'boolean')
|
|
164
|
+
&& (tool.deferred === undefined || typeof tool.deferred === 'boolean')
|
|
165
|
+
&& (tool.effectProtocol === undefined || tool.effectProtocol === ENGINE_HOST_EFFECT && tool.readOnly !== true)
|
|
166
|
+
&& (tool.receiptObservation === undefined || hostReceipts && tool.receiptObservation === true && tool.effectProtocol === ENGINE_HOST_EFFECT)
|
|
167
|
+
&& (tool.timeoutMs === undefined || Number.isSafeInteger(tool.timeoutMs) && tool.timeoutMs >= 1000 && tool.timeoutMs <= 600000),
|
|
168
|
+
'engine_host_tools_invalid');
|
|
169
|
+
seen.add(tool.name);
|
|
170
|
+
const readOnly = tool.readOnly === true;
|
|
171
|
+
return { name: tool.name, description: tool.description || `Host tool ${tool.name}`, parameters: structuredClone(tool.parameters),
|
|
172
|
+
readOnly, concurrentSafe: readOnly, permissions: [], timeoutMs: tool.timeoutMs ?? 120000,
|
|
173
|
+
contextRole: 'none', observationRole: 'none', progressObservation: false, contextRetention: 'normal',
|
|
174
|
+
recoveryPolicy: readOnly ? 'safe-read/v1' : tool.receiptObservation ? 'receipt-observation/v1' : 'manual',
|
|
175
|
+
...(tool.effectProtocol ? { hostEffectProtocol: tool.effectProtocol,
|
|
176
|
+
...(durableApprovals ? { approvalPolicy: DURABLE_APPROVAL } : {}) } : {}),
|
|
177
|
+
...(tool.deferred ? { discovery: { deferred: true } } : {}) };
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Build one engine bound to a workspace and a session. `authorize(request)`
|
|
182
|
+
* resolves to 'allow' or 'deny' for every mutating or command tool call.
|
|
183
|
+
* `callHostTool({ runId, callId, name, arguments, signal })` executes a host
|
|
184
|
+
* tool and resolves to `{ status: 'ok' | 'error', content }`. */
|
|
185
|
+
export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId, scope, model, authorize, callHostTool,
|
|
186
|
+
callHostContext, callHostHook, callHostVerification, callHostReceipt, owner = `engine-${process.pid}`,
|
|
187
|
+
fetchImpl = fetch, sourceEnv = process.env, commandSandbox, subAgents, runStore } = {}) {
|
|
188
|
+
invariant(text(workspaceRoot) && text(stateDir) && text(sessionId) && typeof authorize === 'function'
|
|
189
|
+
&& scope && ['tenantId', 'workspaceId', 'userId', 'agentId'].every(key => text(scope[key])), 'engine_runtime_invalid');
|
|
190
|
+
const root = realpathSync(resolve(workspaceRoot));
|
|
191
|
+
mkdirSync(stateDir, { recursive: true });
|
|
192
|
+
const description = admitEngineModel(model);
|
|
193
|
+
const roles = nativeChildRoles({ subAgents });
|
|
194
|
+
const supportsImages = description.input.includes('image');
|
|
195
|
+
const store = runStore ?? new SqliteRunStore(join(stateDir, 'runs.sqlite'));
|
|
196
|
+
const decide = async request => {
|
|
197
|
+
if (request.definition?.approvalPolicy === DURABLE_APPROVAL) return durableDecision(store.load(request.scope, request.runId), request);
|
|
198
|
+
return await authorize(request) === 'allow' ? 'allow' : 'deny';
|
|
199
|
+
};
|
|
200
|
+
const artifacts = await createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope });
|
|
201
|
+
const execution = nativeLocalExecutionMethods({ enabled: true, settings: {}, sourceEnv, workspaceRoot: root, commandBackend: 'local_process' });
|
|
202
|
+
const executionOptions = { modern: true, resourceProfile: 'local-development/v2' };
|
|
203
|
+
const local = execution.localExecution(executionOptions);
|
|
204
|
+
const workspace = createNativeWorkspaceTools({ workspaceRoot: root, stateDir: join(stateDir, 'workspace'), sessionId, authorize: decide });
|
|
205
|
+
const commands = createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
|
|
206
|
+
settings: local.settings, sourceEnv: local.environment, outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy,
|
|
207
|
+
shellPolicy: commandSandbox,
|
|
208
|
+
artifacts, authorize: decide, captureWorkspace: request => workspace.capture(request),
|
|
209
|
+
resolveOwnedCommand: createOwnedCommandResolver({ scope, store }) });
|
|
210
|
+
const web = createNativeWebTools({ fetch: fetchImpl, providerConfig: { provider: '' }, authorize: decide, sessionId, inlineMaxChars: 6000 });
|
|
211
|
+
const owners = [workspace, commands, web];
|
|
212
|
+
const route = new Map(owners.flatMap(port => port.definitions.map(definition => [definition.name, port])));
|
|
213
|
+
// Anything a Run advertises that the engine does not own was admitted as a host tool.
|
|
214
|
+
const hostPort = {
|
|
215
|
+
async execute(request) {
|
|
216
|
+
if (typeof callHostTool !== 'function') return { status: 'error', content: { code: 'host_tools_unavailable', message: 'The host did not provide tool execution.' } };
|
|
217
|
+
try {
|
|
218
|
+
const effectBound = request.definition?.hostEffectProtocol === ENGINE_HOST_EFFECT;
|
|
219
|
+
const record = effectBound ? store.load(request.scope, request.runId) : null;
|
|
220
|
+
const decision = record && request.definition.approvalPolicy === DURABLE_APPROVAL
|
|
221
|
+
? durableDecision(record, request) : null;
|
|
222
|
+
if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
|
|
223
|
+
const effect = record ? {
|
|
224
|
+
contract: ENGINE_HOST_EFFECT, operationKey: request.operationKey,
|
|
225
|
+
sourceEventId: record.events.at(-1)?.eventId ?? null,
|
|
226
|
+
goal: record.snapshot.goal, goalRevision: record.snapshot.goalRevision,
|
|
227
|
+
observations: engineUserObservations(store, request.scope, record.snapshot),
|
|
228
|
+
approved: decision === 'allow', canRequestApproval: !!decision && typeof decision === 'object',
|
|
229
|
+
} : undefined;
|
|
230
|
+
const reply = await callHostTool({ runId: request.runId, callId: request.call.callId, name: request.call.name,
|
|
231
|
+
arguments: request.call.arguments ?? {}, signal: request.signal, timeoutMs: request.definition?.timeoutMs ?? 120000, effect });
|
|
232
|
+
if (effectBound && reply?.status === 'approval_required') {
|
|
233
|
+
return decision && typeof decision === 'object' ? decision
|
|
234
|
+
: { status: 'error', content: { code: 'host_tool_approval_unavailable', executed: false } };
|
|
235
|
+
}
|
|
236
|
+
if (effectBound && reply?.status === 'uncertain')
|
|
237
|
+
return { status: 'uncertain', content: { code: 'host_tool_outcome_unknown' } };
|
|
238
|
+
if (effectBound && !['ok', 'error'].includes(reply?.status))
|
|
239
|
+
return { status: 'uncertain', content: { code: 'host_tool_outcome_unknown' } };
|
|
240
|
+
const status = reply?.status === 'ok' ? 'ok' : 'error';
|
|
241
|
+
return { status, content: reply?.content === undefined ? null : JSON.parse(JSON.stringify(reply.content)) };
|
|
242
|
+
} catch (error) {
|
|
243
|
+
if (request.definition?.hostEffectProtocol === ENGINE_HOST_EFFECT) {
|
|
244
|
+
request.signal.throwIfAborted();
|
|
245
|
+
return { status: 'uncertain', content: { code: 'host_tool_outcome_unknown' } };
|
|
246
|
+
}
|
|
247
|
+
return { status: 'error', content: { code: 'host_tool_failed', message: String(error?.message ?? error).slice(0, 2000) } };
|
|
248
|
+
}
|
|
249
|
+
},
|
|
250
|
+
};
|
|
251
|
+
const ownerOf = request => route.get(request?.call?.name ?? request?.name) ?? hostPort;
|
|
252
|
+
const bound = owners.flatMap(port => port.definitions).map(definition => {
|
|
253
|
+
const media = definition.name === 'read_workspace_file' && supportsImages ? { ...definition, workspaceMediaPolicy: 'bounded-image-read/v1' } : definition;
|
|
254
|
+
const guidance = nativeToolModelGuidance(media, { commandBackend: 'local_process' });
|
|
255
|
+
return guidance.length ? { ...media, modelGuidance: guidance } : media;
|
|
256
|
+
});
|
|
257
|
+
// Some owners do their own preflight, including validating the workspace
|
|
258
|
+
// before requesting approval. Gate read-only workspace calls and externally
|
|
259
|
+
// owned callbacks here when the Run's policy explicitly requires it.
|
|
260
|
+
const preflight = async (request, dispatch) => {
|
|
261
|
+
if (request.definition.approvalPolicy === DURABLE_APPROVAL
|
|
262
|
+
&& (!request.definition.hostEffectProtocol || request.definition.hostApprovalRequired)) {
|
|
263
|
+
const decision = await decide(request);
|
|
264
|
+
if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
|
|
265
|
+
if (decision !== 'allow') return decision;
|
|
266
|
+
}
|
|
267
|
+
return dispatch();
|
|
268
|
+
};
|
|
269
|
+
const tools = {
|
|
270
|
+
approvalPolicy: DURABLE_APPROVAL,
|
|
271
|
+
execute(request, lifecycle) {
|
|
272
|
+
const owner = ownerOf(request);
|
|
273
|
+
const dispatch = () => owner.execute(request, lifecycle);
|
|
274
|
+
return owner === hostPort || owner === children || owner === workspace && request.definition.readOnly
|
|
275
|
+
? preflight(request, dispatch) : dispatch();
|
|
276
|
+
},
|
|
277
|
+
checkPlanMode: async request => (ownerOf(request).checkPlanMode ?? (async () => true))(request),
|
|
278
|
+
observeReceipt(request) {
|
|
279
|
+
if (ownerOf(request) === hostPort && request.definition?.hostEffectProtocol === ENGINE_HOST_EFFECT
|
|
280
|
+
&& request.definition.recoveryPolicy === 'receipt-observation/v1') return callHostReceipt?.(request);
|
|
281
|
+
return (route.get(request?.call?.name) ?? workspace).observeReceipt?.(request);
|
|
282
|
+
},
|
|
283
|
+
repairWorkspace: request => workspace.repairWorkspace(request),
|
|
284
|
+
};
|
|
285
|
+
const context = bindNativeContext({ description, context: {}, ...nativeContextDefaults(undefined) });
|
|
286
|
+
const chatUsage = admitChatUsagePolicy(description.protocol);
|
|
287
|
+
const profile = { profileId: 'engine', profileVersion: digest(description), providerFamily: description.protocol,
|
|
288
|
+
compatibilityDigest: digest(description), supportsImages, discoveredToolExposure: 'direct-after-search/v1', streamTimeoutPolicy: 'idle/v1',
|
|
289
|
+
...(chatUsage ? { chatUsagePolicy: chatUsage } : {}), maxRetries: 2, maxProviderRetries: 10, ...context.profile,
|
|
290
|
+
maxOutputTokens: description.maxOutputTokens, contextWindow: description.contextWindow,
|
|
291
|
+
requestTimeoutMs: description.requestTimeoutMs, providerReplayMode: 'reasoning_content',
|
|
292
|
+
providerCompatibilityPolicy: admitProviderCompatibilityPolicy() };
|
|
293
|
+
const modelSurface = bindNativeModelSurface({ environment: execution.executionEnvironment(executionOptions), description });
|
|
294
|
+
const modelPort = createNativeModelPort({ fetchImpl, resolveProfile: async () => ({ protocol: description.protocol, baseUrl: description.baseUrl,
|
|
295
|
+
apiKey: await model.apiKey(), model: description.modelName, parameters: description.parameters }) });
|
|
296
|
+
const background = createBackgroundCommandPort({ scope, store, readers: { local_process: commands.reader } });
|
|
297
|
+
const lifetime = new AbortController();
|
|
298
|
+
const childDefinitions = [];
|
|
299
|
+
let children;
|
|
300
|
+
if (roles.length) {
|
|
301
|
+
try {
|
|
302
|
+
const childTools = [...workspace.definitions, ...commands.definitions].map(tool => tool.readOnly
|
|
303
|
+
? tool : { ...tool, approvalPolicy: DURABLE_APPROVAL });
|
|
304
|
+
const fileWorkspaces = createStudioNativeChildWorkspaces({ workspaceRoot: root, stateDir });
|
|
305
|
+
const commandResource = childCommandResource({ ...local.binding,
|
|
306
|
+
controls: { ...local.binding.controls, shellPolicy: commandSandbox ?? local.binding.controls.shellPolicy } });
|
|
307
|
+
children = await createNativeChildren({ roles, scope, sessionId, store, tools: childTools, fileWorkspaces,
|
|
308
|
+
commandResource, isClosed: () => lifetime.signal.aborted, detachSignal: lifetime.signal,
|
|
309
|
+
restrictTools: (tools, parent) => tools.flatMap(tool => {
|
|
310
|
+
if (!childTools.some(definition => definition.name === tool.name)) return [tool];
|
|
311
|
+
const parentTool = parent.tools.find(definition => definition.name === tool.name);
|
|
312
|
+
return parentTool ? [parentTool.hostApprovalRequired
|
|
313
|
+
? { ...tool, approvalPolicy: DURABLE_APPROVAL, hostApprovalRequired: true } : tool] : [];
|
|
314
|
+
}),
|
|
315
|
+
artifactPolicy: 'runtime-artifacts/v1', artifactFactory: childScope =>
|
|
316
|
+
createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope: childScope }),
|
|
317
|
+
resolveModel: async id => {
|
|
318
|
+
invariant(id === null || id === 'engine', 'engine_child_model_unbound');
|
|
319
|
+
return { profile, supportsImages, model: modelPort, context: context.port, contextPolicy: context.policy,
|
|
320
|
+
modelRecoveryPolicy: nativeModelRecoveryPolicy(description) };
|
|
321
|
+
},
|
|
322
|
+
bindTools({ scope: childScope, sessionId: childSession, workspaceRoot: childRoot = root, executionResource }) {
|
|
323
|
+
const childState = join(stateDir, 'children', digest({ childScope, childSession }));
|
|
324
|
+
const files = createNativeWorkspaceTools({ workspaceRoot: childRoot, stateDir: join(childState, 'workspace'),
|
|
325
|
+
sessionId: childSession, authorize: decide });
|
|
326
|
+
const command = executionResource ? createNativeLocalCommandTools({ workspaceRoot: childRoot,
|
|
327
|
+
stateRoot: join(childState, 'commands'), sessionId: childSession, settings: local.settings, sourceEnv: local.environment,
|
|
328
|
+
outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy, shellPolicy: commandSandbox,
|
|
329
|
+
authorize: decide, captureWorkspace: request => files.capture(request),
|
|
330
|
+
resolveOwnedCommand: createOwnedCommandResolver({ scope: childScope, store }) }) : null;
|
|
331
|
+
const names = new Set(command?.definitions.map(tool => tool.name));
|
|
332
|
+
return { workspace: files, tools: { approvalPolicy: DURABLE_APPROVAL,
|
|
333
|
+
execute(request, observations) {
|
|
334
|
+
if (names.has(request.call.name)) return command.execute(request, observations);
|
|
335
|
+
const dispatch = () => files.execute(request, observations);
|
|
336
|
+
return request.definition.readOnly ? preflight(request, dispatch) : dispatch();
|
|
337
|
+
},
|
|
338
|
+
observeReceipt: request => files.observeReceipt(request) },
|
|
339
|
+
...(command ? { background: createBackgroundCommandPort({ scope: childScope, store, readers: { local_process: command.reader } }) } : {}) };
|
|
340
|
+
},
|
|
341
|
+
verificationFactory: async () => undefined });
|
|
342
|
+
const timeout = Math.max(120000, ...roles.map(role => role.timeoutSeconds * 1000 + 5000));
|
|
343
|
+
childDefinitions.push(...nativeChildToolDefinitions(roles.map(role => role.name), timeout), ...nativeChildReaderDefinitions());
|
|
344
|
+
if (roles.some(role => role.tools.some(name => childTools.some(tool => tool.name === name && !tool.readOnly)))) {
|
|
345
|
+
const definition = { ...nativeChildMergeDefinition(), approvalPolicy: DURABLE_APPROVAL };
|
|
346
|
+
childDefinitions.push(definition);
|
|
347
|
+
route.set(definition.name, { async execute(request) {
|
|
348
|
+
const decision = await decide(request);
|
|
349
|
+
return decision === 'allow' ? children.execute(request) : decision === 'deny'
|
|
350
|
+
? { status: 'error', content: { code: 'policy_denied', executed: false } } : decision;
|
|
351
|
+
} });
|
|
352
|
+
}
|
|
353
|
+
for (const definition of childDefinitions) if (!route.has(definition.name)) route.set(definition.name, children);
|
|
354
|
+
} catch (error) { if (!runStore) store.close(); throw error; }
|
|
355
|
+
}
|
|
356
|
+
const ports = { model: modelPort, tools, workspace,
|
|
357
|
+
context: engineContextPort(context.port, callHostContext),
|
|
358
|
+
verification: engineVerificationPort(store, callHostVerification, digest),
|
|
359
|
+
hooks: engineHookPort(callHostHook, request => {
|
|
360
|
+
const { snapshot } = store.authority(request.scope, request.runId);
|
|
361
|
+
const indexes = new Set(request.input.compaction.messageRefs.map(ref => Number(ref.split(':', 3)[1])));
|
|
362
|
+
return engineUserObservations(store, request.scope, snapshot, { indexes });
|
|
363
|
+
}),
|
|
364
|
+
artifacts, background, ...(children ? { children: children.owner } : {}) };
|
|
365
|
+
const kernel = new NativeKernel({ store, owner, digest, ports });
|
|
366
|
+
|
|
367
|
+
function prepareRun({ runId, objective, conversation, inputImages, hostInstructions = '', hostTools, toolPolicy,
|
|
368
|
+
hostContext, hostHooks, hostVerification, executionPolicy, preset: presetName, maxModelCalls = null,
|
|
369
|
+
durableApprovals = false, originalInput = false }) {
|
|
370
|
+
invariant(text(runId) && text(objective) && typeof hostInstructions === 'string', 'engine_run_invalid');
|
|
371
|
+
const limits = admitExecutionPolicy(executionPolicy, maxModelCalls);
|
|
372
|
+
const preset = resolveEnginePreset({ ...(presetName === undefined ? {} : { preset: presetName }), maxModelCalls: limits.maxModelCalls });
|
|
373
|
+
const presetTools = enginePresetToolDefinitions(preset);
|
|
374
|
+
const kernelTools = [...presetTools, ...toolDiscoveryDefinitions(), ...todoToolDefinitions(true)].map(tool => tool.name);
|
|
375
|
+
const internal = [...kernelTools, ...KERNEL_TOOL_NAMES];
|
|
376
|
+
const reserved = new Set([...bound.map(tool => tool.name), ...childDefinitions.map(tool => tool.name), ...internal]);
|
|
377
|
+
const policy = admitEngineToolPolicy(toolPolicy, durableApprovals);
|
|
378
|
+
invariant(!policy || internal.every(name => !policy.rules.has(name) || policy.rules.get(name) === 'inherit'),
|
|
379
|
+
'engine_tool_policy_internal_control_unsupported');
|
|
380
|
+
const hosted = restrictEngineTools(admitHostTools(hostTools, reserved, durableApprovals, typeof callHostReceipt === 'function'), policy, DURABLE_APPROVAL);
|
|
381
|
+
const builtins = restrictEngineTools(durableApprovals ? bound.map(tool => route.get(tool.name) === workspace && tool.readOnly
|
|
382
|
+
? tool : { ...tool, approvalPolicy: DURABLE_APPROVAL }) : bound, policy, DURABLE_APPROVAL);
|
|
383
|
+
const childControls = durableApprovals ? restrictEngineTools(childDefinitions, policy, DURABLE_APPROVAL) : [];
|
|
384
|
+
const searchable = builtins.some(tool => tool.discovery) || hosted.some(tool => tool.discovery);
|
|
385
|
+
const runtimeTools = [...builtins, ...hosted, ...(searchable ? toolDiscoveryDefinitions() : []), ...todoToolDefinitions(searchable),
|
|
386
|
+
...presetTools, ...childControls];
|
|
387
|
+
const instructions = renderEngineInstructions({ hostInstructions });
|
|
388
|
+
// The engine already inherits its own journal for subsequent Runs.
|
|
389
|
+
const importedConversation = store.sessionHead(scope, sessionId) ? undefined : conversation;
|
|
390
|
+
const task = renderEngineObjective(objective, importedConversation);
|
|
391
|
+
const media = engineInputMedia(inputImages, supportsImages);
|
|
392
|
+
const contextSources = admitEngineContextSources(hostContext);
|
|
393
|
+
const hooks = admitEngineHooks(hostHooks);
|
|
394
|
+
const verification = admitEngineVerification(hostVerification);
|
|
395
|
+
const effectBound = hosted.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT);
|
|
396
|
+
const scopedCallbacks = contextSources.length || hooks.definitions.length || effectBound || !!verification;
|
|
397
|
+
const inputMessages = effectBound || originalInput ? [
|
|
398
|
+
...(task !== objective ? [{ role: 'user', kind: 'host_imported_history',
|
|
399
|
+
content: canonical({ trust: 'untrusted', earlierTurns: engineConversation(importedConversation) }) }] : []),
|
|
400
|
+
{ role: 'user', kind: 'user_input', content: objective, ...(media.length ? { media } : {}) },
|
|
401
|
+
] : [{ role: 'user', content: task, ...(media.length ? { media } : {}) }];
|
|
402
|
+
const configuration = configure({ profile, tools: runtimeTools, contextSources, hooks: hooks.definitions,
|
|
403
|
+
...hooks.configuration,
|
|
404
|
+
...(verification ? { hostVerification: verification } : {}),
|
|
405
|
+
...(executionPolicy?.strategy === 'plan-act-observe' ? { initialPlanPolicy: 'plan-act-observe/v1' } : {}),
|
|
406
|
+
contract: { objective: scopedCallbacks ? objective : task,
|
|
407
|
+
...(verification ? { acceptance: [{ id: 'host_goal', required: true, verifierRef: verification.verifierRef,
|
|
408
|
+
verifierVersion: verification.verifierVersion, verificationMethod: 'deterministic',
|
|
409
|
+
description: 'Verify the requested result using the bound host owner.' }] } : {}) },
|
|
410
|
+
...(media.length || scopedCallbacks || originalInput ? { inputMessages } : {}), ...preset.policies,
|
|
411
|
+
hostBindingDigest: digest({ contract: ENGINE_RUNTIME_CONTRACT, workspaceRoot: root, description, tools: runtimeTools, instructions,
|
|
412
|
+
...(commandSandbox ? { commandSandbox } : {}), ...(durableApprovals && roles.length ? { roles } : {}),
|
|
413
|
+
...(contextSources.length ? { contextSources } : {}),
|
|
414
|
+
...(hooks.definitions.length ? { hooks: hooks.definitions, ...hooks.configuration } : {}),
|
|
415
|
+
...(verification ? { verification } : {}),
|
|
416
|
+
...(executionPolicy === undefined ? {} : { executionPolicy }),
|
|
417
|
+
preset: { preset: preset.preset, revision: preset.revision } }),
|
|
418
|
+
limits: { ...preset.limits, ...limits,
|
|
419
|
+
effectTimeoutMs: Math.max(120000, description.requestTimeoutMs + 10000, hooks.timeoutMs + 1000,
|
|
420
|
+
...runtimeTools.map(tool => (tool.timeoutMs ?? 0) + 10000)) },
|
|
421
|
+
modelRecoveryPolicy: nativeModelRecoveryPolicy(description), contextPolicy: context.policy, modelSurface,
|
|
422
|
+
backgroundNotificationPolicy: 'completed-before-model/v1', todoPolicy: 'session-todos/v1',
|
|
423
|
+
...(durableApprovals && children ? { childLifecyclePolicy: 'owned-background/v2', childApprovalPolicy: 'owned-child-approval/v1' } : {}),
|
|
424
|
+
...(searchable ? { toolDiscoveryPolicy: 'local-tool-search/v1' } : {}), instructions });
|
|
425
|
+
const identity = { scope, runId, sessionId, turnId: scopedCallbacks ? runId : 'turn-1',
|
|
426
|
+
buildId: `engine-preset-${preset.preset}-${preset.revision}`,
|
|
427
|
+
parentRunId: null, taskChainId: runId };
|
|
428
|
+
return { identity, configuration, preset: { preset: preset.preset, revision: preset.revision },
|
|
429
|
+
hostTools: hosted.map(tool => tool.name) };
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Admit a new Run. The Run freezes the preset and instructions it starts with. */
|
|
433
|
+
function start(input) {
|
|
434
|
+
const { identity, configuration, preset, hostTools } = prepareRun(input);
|
|
435
|
+
kernel.start(initialSnapshot(identity, configuration, digest(configuration)), configuration);
|
|
436
|
+
return { runId: input.runId, preset, hostTools };
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
return {
|
|
440
|
+
scope, workspaceRoot: root,
|
|
441
|
+
info: () => ({ contract: ENGINE_RUNTIME_CONTRACT, preset: (({ preset, revision }) => ({ preset, revision }))(resolveEnginePreset()),
|
|
442
|
+
instructions: { policy: NATIVE_ENGINE_INSTRUCTION_ASSEMBLY, baseRevision: engineBaseInstructions().revision },
|
|
443
|
+
model: { name: description.modelName, protocol: description.protocol, contextWindow: description.contextWindow,
|
|
444
|
+
requestOutputTokens: description.maxOutputTokens, images: supportsImages },
|
|
445
|
+
tools: bound.map(tool => tool.name),
|
|
446
|
+
// Every name a host tool may not use: engine tools plus the control tools the preset or discovery can add.
|
|
447
|
+
reservedToolNames: [...new Set([...[...bound, ...childDefinitions, ...enginePresetToolDefinitions(resolveEnginePreset()), ...toolDiscoveryDefinitions(),
|
|
448
|
+
...todoToolDefinitions(true), ...todoToolDefinitions(false)].map(tool => tool.name), ...KERNEL_TOOL_NAMES])].sort(),
|
|
449
|
+
hostToolNamePattern: HOST_TOOL_NAME.source }),
|
|
450
|
+
start, prepareRun, ports,
|
|
451
|
+
async run(runId, options) {
|
|
452
|
+
const snapshot = await kernel.runUntilIdle(scope, runId, options);
|
|
453
|
+
if (children && terminal(snapshot.phase)) await children.owner.releaseRun({ scope, runId });
|
|
454
|
+
return snapshot;
|
|
455
|
+
},
|
|
456
|
+
submit: (runId, command) => kernel.submit(scope, runId, command),
|
|
457
|
+
pendingApproval(snapshot, configuration) {
|
|
458
|
+
const pending = snapshot.pendingInteraction;
|
|
459
|
+
if (!pending || pending.approvalPolicy !== DURABLE_APPROVAL && !snapshot.childApproval) return null;
|
|
460
|
+
const call = snapshot.childApproval?.toolCall ?? snapshot.pendingTools.find(tool => tool.callId === pending.callId);
|
|
461
|
+
if (!call) return null;
|
|
462
|
+
const subject = engineApprovalSubject(call);
|
|
463
|
+
const tools = snapshot.childApproval
|
|
464
|
+
? store.authority(snapshot.childApproval.childScope, snapshot.childApproval.childRunId).configuration.tools
|
|
465
|
+
: configuration.tools;
|
|
466
|
+
return { interactionId: pending.interactionId, callId: pending.callId, tool: call.name,
|
|
467
|
+
...(tools.some(tool => tool.name === call.name && (tool.hostApprovalRequired
|
|
468
|
+
|| tool.hostEffectProtocol === ENGINE_HOST_EFFECT)) ? { requiresUserApproval: true } : {}),
|
|
469
|
+
...(snapshot.childApproval ? { childRunId: snapshot.childApproval.childRunId } : {}),
|
|
470
|
+
...(subject ? { subject } : {}) };
|
|
471
|
+
},
|
|
472
|
+
load: runId => store.load(scope, runId),
|
|
473
|
+
completedHostObservations: record => completedHostObservations(store, scope, record),
|
|
474
|
+
authority: runId => store.authority(scope, runId),
|
|
475
|
+
pendingCommands: runId => store.pendingCommands(scope, runId),
|
|
476
|
+
events: (runId, cursor) => store.events(scope, runId, cursor),
|
|
477
|
+
terminal: snapshot => terminal(snapshot.phase),
|
|
478
|
+
async close() { lifetime.abort(); await children?.owner.drain(); if (!runStore) store.close(); },
|
|
479
|
+
};
|
|
480
|
+
}
|