@kingsoftcloud/agentkit-harness-node 0.0.17 → 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.
Files changed (40) hide show
  1. package/dist/engine-view.html +566 -0
  2. package/dist/index.mjs +4 -0
  3. package/dist/rpc-entry.mjs +4 -0
  4. package/package.json +16 -2
  5. package/src/native/child-owner.mjs +8 -4
  6. package/src/native/children.mjs +12 -7
  7. package/src/native/command-shell.mjs +28 -3
  8. package/src/native/engine-client.mjs +83 -0
  9. package/src/native/engine-context.mjs +47 -0
  10. package/src/native/engine-hooks.mjs +53 -0
  11. package/src/native/engine-host-effects.mjs +98 -0
  12. package/src/native/engine-managed-delivery.mjs +65 -0
  13. package/src/native/engine-managed-host.mjs +75 -0
  14. package/src/native/engine-managed-service.mjs +249 -0
  15. package/src/native/engine-runtime.mjs +480 -0
  16. package/src/native/engine-server.mjs +454 -0
  17. package/src/native/engine-service.mjs +281 -0
  18. package/src/native/engine-tool-policy.mjs +29 -0
  19. package/src/native/engine-verification.mjs +111 -0
  20. package/src/native/engine-view-store.mjs +63 -0
  21. package/src/native/instruction-assembly.mjs +67 -3
  22. package/src/native/local-background-supervisor.mjs +1 -1
  23. package/src/native/local-background.mjs +4 -3
  24. package/src/native/local-command-tools.mjs +10 -7
  25. package/src/native/native-kernel-events.mjs +103 -0
  26. package/src/native/native-kernel-permit.mjs +95 -0
  27. package/src/native/native-managed-execution-grants.mjs +232 -0
  28. package/src/native/native-managed-injection.mjs +53 -0
  29. package/src/native/native-managed-interaction.mjs +192 -0
  30. package/src/native/native-managed-kernel-http.mjs +122 -0
  31. package/src/native/native-managed-kernel.mjs +922 -0
  32. package/src/native/native-managed-scoped-control.mjs +116 -0
  33. package/src/native/native-managed-session-frames.mjs +43 -0
  34. package/src/native/native-managed-teams-context.mjs +126 -0
  35. package/src/native/native-teams-callback-authority.mjs +73 -0
  36. package/src/native/native-teams-context-contract.mjs +272 -0
  37. package/src/native/native-teams-json.mjs +38 -0
  38. package/src/native/native-terminal-failure.mjs +53 -0
  39. package/src/native/sqlite-store.mjs +1 -0
  40. package/src/native/workspace-tools.mjs +2 -0
@@ -0,0 +1,454 @@
1
+ #!/usr/bin/env node
2
+ // agentkit.engine/v1 — the Native engine as its own process.
3
+ //
4
+ // JSON-RPC 2.0 over NDJSON on stdio. One process serves one workspace and one
5
+ // session; the host starts it, speaks the protocol and never imports engine
6
+ // code. Upgrading the engine is replacing this executable.
7
+ //
8
+ // Host -> engine: initialize, run/start, run/status, run/events (cursor
9
+ // long-poll), run/resume, run/approve (durable service approval), run/cancel, shutdown.
10
+ // Engine -> host: host/approveTool, only when the host declared the
11
+ // `approvals` service during initialize (otherwise the startup `--approval`
12
+ // policy decides), and host/callTool for tools the host passed in
13
+ // run/start `hostTools`, only when the host declared the `tools` service.
14
+ //
15
+ // The protocol is additive: new methods, fields and event kinds may appear in
16
+ // any release. A host must ignore what it does not understand and decide by
17
+ // the capabilities returned from initialize, never by the engine version.
18
+ //
19
+ // Trusted startup configuration (arguments and environment) fixes the
20
+ // workspace, the state directory and the model binding. The protocol cannot
21
+ // widen them. The model API key is read from the environment per request and
22
+ // never enters stdout, events or the Run store. stdout carries protocol frames
23
+ // only; diagnostics go to stderr.
24
+ import { parseArgs } from 'node:util';
25
+ import { createHash, randomUUID } from 'node:crypto';
26
+ import { readFileSync, realpathSync } from 'node:fs';
27
+ import * as readline from 'node:readline';
28
+ import { setTimeout as wait } from 'node:timers/promises';
29
+ import { fileURLToPath } from 'node:url';
30
+ import { isNativeError, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
31
+ import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
32
+ import { createEngineRuntime, engineApprovalSubject, ENGINE_APPROVAL_CONTRACT, ENGINE_EXECUTION_POLICY,
33
+ ENGINE_INPUT_IMAGES } from './engine-runtime.mjs';
34
+ import { ENGINE_VIEW_CONTRACT } from './engine-view-store.mjs';
35
+ import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
36
+ import { ENGINE_CONTEXT } from './engine-context.mjs';
37
+ import { ENGINE_HOOKS } from './engine-hooks.mjs';
38
+ import { ENGINE_HOST_EFFECT, hostReceiptReply, hostReceiptSource, waitForHostReceipt } from './engine-host-effects.mjs';
39
+ import { ENGINE_VERIFICATION } from './engine-verification.mjs';
40
+ export { ENGINE_VIEW_CONTRACT };
41
+
42
+ export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
43
+ export const ENGINE_EVENT_SCHEMA = 'agentkit.engine-event/v1';
44
+ const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/cancel', 'ui/view', 'shutdown'];
45
+ const DURABLE_APPROVAL_METHOD = 'run/approve';
46
+ const HOST_OBSERVATIONS_METHOD = 'run/host-observations';
47
+ const ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602, internalError: -32603,
48
+ notInitialized: -32010, runNotFound: -32011, runBusy: -32012 };
49
+ const text = value => typeof value === 'string' && value.trim().length > 0;
50
+ const sleep = ms => new Promise(done => setTimeout(done, ms));
51
+
52
+ /** The engine's own task view, built by agentkit-harness-ui into this package's dist. */
53
+ let viewCache;
54
+ export function engineView() {
55
+ if (viewCache !== undefined) return viewCache;
56
+ try {
57
+ const html = readFileSync(new URL('../../dist/engine-view.html', import.meta.url), 'utf8');
58
+ viewCache = { contract: ENGINE_VIEW_CONTRACT, version: packageVersion(), contentType: 'text/html; charset=utf-8',
59
+ sha256: createHash('sha256').update(html).digest('hex'), html };
60
+ } catch { viewCache = null; }
61
+ return viewCache;
62
+ }
63
+
64
+ function packageVersion() {
65
+ try { return JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version; } catch { return 'unknown'; }
66
+ }
67
+
68
+ /** Stable, host-renderable projection. Engine-internal payloads stay in the Run
69
+ * store; a host renders `kind`, `title` and `detail` without knowing each kind. */
70
+ export function projectEngineEvent(event, requiredVerification = false) {
71
+ const payload = event.payload ?? {}, base = { schema: ENGINE_EVENT_SCHEMA, seq: event.seq, kind: event.kind };
72
+ switch (event.kind) {
73
+ case 'model.completed': return { ...base, category: 'model', title: payload.kind ?? 'model',
74
+ ...(text(payload.text) && !(requiredVerification && payload.kind === 'final_candidate') ? { detail: payload.text } : {}),
75
+ ...(Array.isArray(payload.toolCalls) && payload.toolCalls.length ? { tools: payload.toolCalls.map(call => call.name),
76
+ calls: payload.toolCalls.map(call => ({ callId: call.callId, name: call.name, arguments: bounded(call.arguments) })) } : {}),
77
+ ...(payload.usage ? { usage: { inputTokens: payload.usage.inputTokens, outputTokens: payload.usage.outputTokens } } : {}) };
78
+ case 'tool.completed': return { ...base, category: 'tool', title: payload.name, status: payload.status,
79
+ ...(text(payload.callId) ? { callId: payload.callId } : {}), ...(payload.content === undefined ? {} : { result: bounded(payload.content) }) };
80
+ case 'approval.requested': return { ...base, category: 'approval', title: payload.name, status: 'pending',
81
+ callId: payload.callId, interactionId: payload.interactionId,
82
+ ...(payload.source === 'child_tool' ? { approvalContract: ENGINE_APPROVAL_CONTRACT,
83
+ childRunId: payload.childRunId, detail: engineApprovalSubject(payload) } : {}),
84
+ ...(payload.content?.contract === ENGINE_APPROVAL_CONTRACT ? { approvalContract: ENGINE_APPROVAL_CONTRACT,
85
+ ...(text(payload.content.subject) ? { detail: payload.content.subject } : {}) } : {}) };
86
+ case 'approval.resolved': return { ...base, category: 'approval', status: payload.decision,
87
+ callId: payload.callId, interactionId: payload.interactionId };
88
+ case 'model.failure_observed': return { ...base, category: 'model', title: 'model_failure', status: 'retrying', detail: payload.code };
89
+ case 'run.started': return { ...base, category: 'run', title: 'started' };
90
+ case 'run.terminal': return { ...base, category: 'run', title: payload.phase, status: payload.outcome,
91
+ ...(requiredVerification ? { requiredVerification: true } : {}),
92
+ ...(payload.reason ? { reason: payload.reason } : {}),
93
+ ...(text(payload.finalText) && (!requiredVerification || payload.outcome === 'verified') ? { detail: payload.finalText } : {}) };
94
+ default: return { ...base, category: event.kind.split('.')[0] };
95
+ }
96
+ }
97
+
98
+ /** Bound a value carried in a projected event: views show previews, never whole files. */
99
+ const PREVIEW_CHARS = 4000;
100
+ function bounded(value) {
101
+ if (value === undefined || value === null) return value ?? null;
102
+ const encoded = typeof value === 'string' ? value : JSON.stringify(value);
103
+ if (encoded.length <= PREVIEW_CHARS) return typeof value === 'string' ? value : JSON.parse(encoded);
104
+ return { truncated: true, preview: encoded.slice(0, PREVIEW_CHARS), chars: encoded.length };
105
+ }
106
+
107
+ export async function serveEngine({ input, output, log = () => {}, startup, env = process.env, fetchImpl = fetch, detachOnShutdown = false, viewStore }) {
108
+ const frames = readline.createInterface({ input, crlfDelay: Infinity });
109
+ const send = frame => output.write(`${JSON.stringify(frame)}\n`);
110
+ const pending = new Map(), active = new Map(), driven = new Set(), receiptWaits = new Map();
111
+ let host = null, runtime = null, runtimePromise, closing = false;
112
+ const viewRef = viewStore ? viewStore.archive(engineView()) : null;
113
+
114
+ const callHost = (method, params, timeoutMs, signal) => new Promise((resolve, reject) => {
115
+ signal?.throwIfAborted();
116
+ const id = `engine-${randomUUID()}`;
117
+ const finish = () => { pending.delete(id); clearTimeout(timer); signal?.removeEventListener('abort', abort); };
118
+ const fail = error => { finish(); reject(error); };
119
+ const abort = () => fail(signal.reason);
120
+ const timer = setTimeout(() => fail(new Error('host request timed out')), timeoutMs);
121
+ pending.set(id, { resolve: value => { finish(); resolve(value); }, reject: fail });
122
+ signal?.addEventListener('abort', abort, { once: true });
123
+ send({ jsonrpc: '2.0', id, method, params, expiresAt: Date.now() + timeoutMs });
124
+ });
125
+ const authorize = async request => {
126
+ if (!host?.services?.approvals) return startup.approval === 'allow' ? 'allow' : 'deny';
127
+ try {
128
+ const reply = await callHost('host/approveTool', { tool: request.call?.name ?? null, arguments: request.call?.arguments ?? {},
129
+ runId: request.runId ?? null }, startup.approvalTimeoutMs);
130
+ return reply?.decision === 'allow' ? 'allow' : 'deny';
131
+ } catch (error) { log(`approval unavailable: ${publicErrorMessage(error)}`); return 'deny'; }
132
+ };
133
+ const callHostTool = async ({ runId, callId, name, arguments: args, timeoutMs, signal, effect }) => {
134
+ if (!host?.services?.tools) return { status: 'error', content: { code: 'host_tools_unavailable', message: 'The host did not declare tool execution.' } };
135
+ return callHost('host/callTool', { runId, callId, name, arguments: args, ...(effect ? { effect } : {}) },
136
+ timeoutMs + 5000, effect ? signal : undefined);
137
+ };
138
+ async function readHostReceipt(runId, call, originalOperationKey, signal, observationId) {
139
+ if (!host?.services?.toolReceipts) throw new Error('host receipt service unavailable');
140
+ const reply = await callHost('host/readToolReceipt', { runId, callId: call.callId, name: call.name, arguments: call.arguments,
141
+ originalOperationKey, ...(observationId ? { observationId } : {}) }, observationId ? 12000 : 3000, signal);
142
+ return hostReceiptReply(reply, observationId);
143
+ }
144
+ const callHostReceipt = async request => ({
145
+ contract: request.contract, originalOperationKey: request.originalOperationKey, callId: request.call.callId,
146
+ result: await readHostReceipt(request.runId, request.call, request.originalOperationKey, request.signal, request.operationKey),
147
+ });
148
+ const callHostContext = async (params, timeoutMs, signal) => {
149
+ if (!host?.services?.context) throw new Error('host context service unavailable');
150
+ return callHost('host/readContext', params, timeoutMs, signal);
151
+ };
152
+ const callHostHook = async (params, timeoutMs, signal) => {
153
+ if (!host?.services?.hooks) throw new Error('host Hook service unavailable');
154
+ return callHost('host/invokeHook', params, timeoutMs, signal);
155
+ };
156
+ const callHostVerification = async (params, timeoutMs, signal) => {
157
+ if (!host?.services?.verification) throw new Error('host verification unavailable');
158
+ return callHost('host/verifyGoal', params, timeoutMs, signal);
159
+ };
160
+
161
+ // Highest event seq seen per Run, so status never rescans the whole journal.
162
+ const seen = new Map();
163
+ const tail = runId => {
164
+ const events = runtime.events(runId, seen.get(runId) ?? 0);
165
+ if (events.length) seen.set(runId, events.at(-1).seq);
166
+ return seen.get(runId) ?? 0;
167
+ };
168
+ const status = runId => {
169
+ const { snapshot, configuration } = runtime.authority(runId);
170
+ const pendingApproval = runtime.pendingApproval(snapshot, configuration);
171
+ return { runId, phase: snapshot.phase, outcome: snapshot.outcome ?? null, reason: snapshot.reason ?? null,
172
+ terminal: runtime.terminal(snapshot), running: active.has(runId), usage: snapshot.usage,
173
+ finalText: configuration.hostVerification && snapshot.outcome !== 'verified' ? null
174
+ : snapshot.finalText ?? snapshot.candidate?.text ?? null, cursor: tail(runId),
175
+ ...(pendingApproval ? { pendingApproval } : {}),
176
+ ...(viewStore ? { view: viewStore.reference(startup.stateDir, runId) } : {}) };
177
+ };
178
+ const drive = runId => {
179
+ if (closing || active.has(runId)) return;
180
+ driven.add(runId);
181
+ const controller = new AbortController();
182
+ const runOptions = detachOnShutdown ? { detachSignal: controller.signal } : { signal: controller.signal };
183
+ const execute = async () => {
184
+ let deadline;
185
+ for (;;) {
186
+ try {
187
+ const snapshot = await runtime.run(runId, runOptions);
188
+ if (snapshot.phase !== 'awaiting_reconciliation' || !snapshot.toolReconciliation || !host?.services?.toolReceipts) return snapshot;
189
+ const record = runtime.load(runId);
190
+ if (!hostReceiptSource(record)) return snapshot;
191
+ if (runtime.pendingCommands(runId).length) continue;
192
+ const idle = new AbortController();
193
+ receiptWaits.set(runId, idle);
194
+ const signal = AbortSignal.any([idle.signal, controller.signal]);
195
+ try {
196
+ const command = await waitForHostReceipt(record, {
197
+ read: (call, operationKey, receiptSignal) => readHostReceipt(runId, call, operationKey, receiptSignal),
198
+ signal, assertCurrent: () => signal.throwIfAborted(),
199
+ });
200
+ if (command) runtime.submit(runId, command);
201
+ } catch (error) {
202
+ if (controller.signal.aborted || !idle.signal.aborted) throw error;
203
+ } finally { receiptWaits.delete(runId); }
204
+ }
205
+ catch (error) {
206
+ if (!detachOnShutdown || !isNativeError(error) || error.code !== 'lease_busy') throw error;
207
+ // After an unclean shutdown, let the previous lease expire. A
208
+ // healthy owner that renews its lease still wins.
209
+ deadline ??= Date.now() + runtime.authority(runId).configuration.limits.leaseMs + 500;
210
+ if (Date.now() >= deadline) throw error;
211
+ await wait(250, undefined, { signal: controller.signal });
212
+ }
213
+ }
214
+ };
215
+ const done = execute()
216
+ .catch(error => {
217
+ if (!detachOnShutdown || !controller.signal.aborted)
218
+ log(`run ${runId} stopped: ${isNativeError(error) ? error.code : publicErrorMessage(error)}`);
219
+ })
220
+ .finally(() => active.delete(runId));
221
+ active.set(runId, { controller, done });
222
+ };
223
+ const lookup = runId => {
224
+ try { return runtime.authority(runId); }
225
+ catch (error) {
226
+ if (isNativeError(error) && error.code === 'run_not_found') return null;
227
+ throw error;
228
+ }
229
+ };
230
+ const hasScopedCallbacks = record => record.configuration.hooks.length > 0
231
+ || !!record.configuration.hostVerification
232
+ || record.configuration.contextSources.some(source => source.hostProjection)
233
+ || record.configuration.tools.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT);
234
+ const continueOnSubscription = (runId, record) => {
235
+ if (hasScopedCallbacks(record)) driven.delete(runId);
236
+ else drive(runId);
237
+ };
238
+
239
+ const handlers = {
240
+ async initialize(params) {
241
+ const offered = Array.isArray(params?.protocolVersions) ? params.protocolVersions : [];
242
+ if (!offered.includes(ENGINE_PROTOCOL)) throw rpcError(ERRORS.params, 'no common protocol version', { supported: [ENGINE_PROTOCOL] });
243
+ host = { name: text(params.host?.name) ? params.host.name : 'unknown',
244
+ services: { approvals: params.services?.approvals === true, tools: params.services?.tools === true,
245
+ context: detachOnShutdown && params.services?.context === ENGINE_CONTEXT,
246
+ hooks: detachOnShutdown && params.services?.hooks === ENGINE_HOOKS,
247
+ verification: detachOnShutdown && params.services?.verification === ENGINE_VERIFICATION,
248
+ toolEffects: detachOnShutdown && params.services?.toolEffects === ENGINE_HOST_EFFECT,
249
+ toolReceipts: detachOnShutdown && params.services?.toolEffects === ENGINE_HOST_EFFECT
250
+ && params.services?.toolReceipts === TOOL_RECEIPT_OBSERVATION_CONTRACT,
251
+ durableApprovals: detachOnShutdown && params.services?.durableApprovals === true } };
252
+ runtimePromise ??= createEngineRuntime({ workspaceRoot: startup.workspace, stateDir: startup.stateDir, sessionId: startup.sessionId,
253
+ scope: startup.scope, authorize, callHostTool, callHostContext, callHostHook, callHostVerification, callHostReceipt, fetchImpl, sourceEnv: env,
254
+ commandSandbox: startup.commandSandbox,
255
+ subAgents: detachOnShutdown ? startup.subAgents : undefined,
256
+ model: { ...startup.model, apiKey: async () => env[startup.model.apiKeyEnv] ?? '' } })
257
+ .catch(error => { runtimePromise = null; throw error; });
258
+ runtime = await runtimePromise;
259
+ return { protocolVersion: ENGINE_PROTOCOL, engine: { name: '@kingsoftcloud/agentkit-harness-node', version: packageVersion(), ...runtime.info() },
260
+ capabilities: { methods: detachOnShutdown ? [...METHODS, DURABLE_APPROVAL_METHOD,
261
+ ...(host.services.toolEffects ? [HOST_OBSERVATIONS_METHOD] : [])] : METHODS,
262
+ eventSchema: ENGINE_EVENT_SCHEMA, hostServices: ['approvals', 'tools'],
263
+ approvals: host.services.durableApprovals ? 'durable' : host.services.approvals ? 'host' : startup.approval,
264
+ hostTools: host.services.tools, toolPolicy: ENGINE_TOOL_POLICY, executionPolicy: ENGINE_EXECUTION_POLICY,
265
+ ...(detachOnShutdown ? { scopedHostRequests: true } : {}),
266
+ ...(host.services.context ? { hostContext: ENGINE_CONTEXT } : {}),
267
+ ...(host.services.hooks ? { hostHooks: ENGINE_HOOKS } : {}),
268
+ ...(host.services.verification ? { hostVerification: ENGINE_VERIFICATION } : {}),
269
+ ...(host.services.toolEffects ? { hostToolEffects: ENGINE_HOST_EFFECT } : {}),
270
+ ...(host.services.toolReceipts ? { hostToolReceipts: TOOL_RECEIPT_OBSERVATION_CONTRACT } : {}),
271
+ ...(runtime.info().model.images ? { inputImages: ENGINE_INPUT_IMAGES } : {}),
272
+ ...(engineView() ? { ui: { contract: ENGINE_VIEW_CONTRACT, sha256: engineView().sha256 } } : {}) } };
273
+ },
274
+ async 'run/start'(params) {
275
+ if (!text(params?.objective)) throw rpcError(ERRORS.params, 'objective is required');
276
+ if (params.hostTools?.length && !host.services.tools) throw rpcError(ERRORS.params, 'hostTools require the tools host service');
277
+ if (params.hostContext !== undefined && !host.services.context)
278
+ throw rpcError(ERRORS.params, 'hostContext requires a negotiated context host service');
279
+ if (params.hostHooks !== undefined && !host.services.hooks)
280
+ throw rpcError(ERRORS.params, 'hostHooks requires a negotiated Hook host service');
281
+ if (params.hostVerification !== undefined && !host.services.verification)
282
+ throw rpcError(ERRORS.params, 'hostVerification requires a negotiated verification service');
283
+ const hostEffects = Array.isArray(params.hostTools) && params.hostTools.some(tool => tool?.effectProtocol !== undefined);
284
+ if (hostEffects && !host.services.toolEffects)
285
+ throw rpcError(ERRORS.params, 'host tool effects require a negotiated host service');
286
+ if (Array.isArray(params.hostTools) && params.hostTools.some(tool => tool?.receiptObservation !== undefined) && !host.services.toolReceipts)
287
+ throw rpcError(ERRORS.params, 'host receipt observation requires a negotiated host service');
288
+ const runId = text(params.runId) ? params.runId : `run-${createHash('sha256').update(randomUUID()).digest('hex').slice(0, 24)}`;
289
+ const existing = lookup(runId);
290
+ if (existing) {
291
+ if (!hasScopedCallbacks(existing)) drive(runId);
292
+ return { ...status(runId), existing: true };
293
+ }
294
+ viewStore?.pin(startup.stateDir, runId, viewRef);
295
+ const started = runtime.start({ runId, objective: params.objective, conversation: params.conversation, inputImages: params.inputImages, hostInstructions: params.hostInstructions ?? '', hostTools: params.hostTools, toolPolicy: params.toolPolicy,
296
+ durableApprovals: host.services.durableApprovals, hostContext: params.hostContext, hostHooks: params.hostHooks,
297
+ hostVerification: params.hostVerification,
298
+ executionPolicy: params.executionPolicy,
299
+ ...(params.preset === undefined ? {} : { preset: params.preset }), maxModelCalls: params.maxModelCalls ?? null });
300
+ // A subscribed host is required to service budgeted context and Hook callbacks.
301
+ if (!params.hostContext?.sources?.length && !params.hostHooks?.hooks?.length && !hostEffects && !params.hostVerification) drive(runId);
302
+ return { ...status(runId), preset: started.preset, hostTools: started.hostTools, existing: false };
303
+ },
304
+ async 'run/status'(params) { requireRun(params); return status(params.runId); },
305
+ async [HOST_OBSERVATIONS_METHOD](params) {
306
+ if (!host.services.toolEffects) throw rpcError(ERRORS.method, 'host observations unavailable');
307
+ requireRun(params);
308
+ const result = runtime.completedHostObservations(runtime.load(params.runId));
309
+ if (!result) throw rpcError(ERRORS.params, 'host observations unavailable for this Run');
310
+ return result;
311
+ },
312
+ async 'run/events'(params) {
313
+ const { runId } = params;
314
+ const { snapshot, configuration } = requireRun(params);
315
+ if (detachOnShutdown && params.follow === true && !driven.has(runId) && !runtime.terminal(snapshot)) {
316
+ const idle = ['paused', 'awaiting_interaction', 'awaiting_reconciliation'].includes(snapshot.phase);
317
+ const hasReceipt = snapshot.phase === 'awaiting_reconciliation' && snapshot.toolReconciliation
318
+ && host.services.toolReceipts && hostReceiptSource(runtime.load(runId));
319
+ if (!idle || hasReceipt || runtime.pendingCommands(runId).length) drive(runId);
320
+ }
321
+ const cursor = Number.isSafeInteger(params.cursor) && params.cursor >= 0 ? params.cursor : 0;
322
+ const deadline = Date.now() + Math.min(Math.max(Number(params.waitMs) || 0, 0), 30000);
323
+ // The wait reads only the journal suffix; the Run record is loaded once, on return.
324
+ for (;;) {
325
+ const running = active.has(params.runId), events = runtime.events(params.runId, cursor);
326
+ if (events.length || !running || Date.now() >= deadline) {
327
+ const next = events.length ? events.at(-1).seq : cursor;
328
+ if (next > (seen.get(params.runId) ?? 0)) seen.set(params.runId, next);
329
+ return { events: events.map(event => projectEngineEvent(event, !!configuration.hostVerification)), cursor: next,
330
+ terminal: runtime.terminal(runtime.authority(runId).snapshot), running: active.has(runId) };
331
+ }
332
+ await sleep(250);
333
+ }
334
+ },
335
+ async 'run/resume'(params) {
336
+ const record = requireRun(params);
337
+ if (active.has(params.runId)) throw rpcError(ERRORS.runBusy, 'run is already running');
338
+ const before = status(params.runId);
339
+ if (before.phase === 'paused') runtime.submit(params.runId, { commandId: `resume-${randomUUID()}`, kind: 'resume', payload: {} });
340
+ if (!before.terminal) continueOnSubscription(params.runId, record);
341
+ return status(params.runId);
342
+ },
343
+ async [DURABLE_APPROVAL_METHOD](params) {
344
+ requireRun(params);
345
+ if (!detachOnShutdown || !text(params.interactionId) || !['allow', 'deny'].includes(params.decision))
346
+ throw rpcError(ERRORS.params, 'interactionId and approval decision are required');
347
+ const { runId, interactionId, decision } = params;
348
+ const commandId = `approval-${createHash('sha256').update(interactionId).digest('hex')}`;
349
+ const record = runtime.load(runId);
350
+ if (!record.commands.some(row => row.command.commandId === commandId)
351
+ && runtime.pendingApproval(record.snapshot, record.configuration)?.interactionId !== interactionId)
352
+ throw rpcError(ERRORS.params, 'interaction_mismatch');
353
+ const receipt = runtime.submit(runId, { commandId, kind: 'submit_interaction', payload: { interactionId, decision } });
354
+ if (receipt.status !== 'rejected') {
355
+ const continueRun = () => { if (!closing && !status(runId).terminal) continueOnSubscription(runId, record); };
356
+ const running = active.get(runId);
357
+ if (running) {
358
+ if (receipt.status === 'accepted') void running.done.then(continueRun);
359
+ } else continueRun();
360
+ }
361
+ return receipt;
362
+ },
363
+ async 'run/cancel'(params) {
364
+ requireRun(params);
365
+ runtime.submit(params.runId, { commandId: `cancel-${randomUUID()}`, kind: 'cancel', payload: {} });
366
+ receiptWaits.get(params.runId)?.abort();
367
+ if (!active.has(params.runId) && !status(params.runId).terminal) drive(params.runId);
368
+ return status(params.runId);
369
+ },
370
+ async 'ui/view'(params) {
371
+ const view = params.sha256 === undefined ? engineView() : viewStore?.get(params.sha256);
372
+ if (!view) throw rpcError(ERRORS.method, 'this engine build ships no task view');
373
+ return view;
374
+ },
375
+ async shutdown() { closing = true; return { ok: true }; },
376
+ };
377
+ function requireRun(params) {
378
+ if (!text(params?.runId)) throw rpcError(ERRORS.params, 'runId is required');
379
+ const record = lookup(params.runId);
380
+ if (!record) throw rpcError(ERRORS.runNotFound, 'run not found');
381
+ return record;
382
+ }
383
+
384
+ for await (const line of frames) {
385
+ if (!line.trim()) continue;
386
+ let frame;
387
+ try { frame = JSON.parse(line); } catch { send({ jsonrpc: '2.0', id: null, error: { code: ERRORS.parse, message: 'Parse error' } }); continue; }
388
+ if (frame && frame.method === undefined && pending.has(frame.id)) {
389
+ const waiter = pending.get(frame.id); pending.delete(frame.id);
390
+ if (frame.error) waiter.reject(new Error(String(frame.error.message ?? 'host error'))); else waiter.resolve(frame.result);
391
+ continue;
392
+ }
393
+ if (!frame || frame.jsonrpc !== '2.0' || !text(frame.method)) {
394
+ send({ jsonrpc: '2.0', id: frame?.id ?? null, error: { code: ERRORS.request, message: 'Invalid Request' } }); continue;
395
+ }
396
+ // Requests run concurrently so a long poll never blocks a cancel or an approval reply.
397
+ void (async () => {
398
+ const reply = body => { if (frame.id !== undefined) send({ jsonrpc: '2.0', id: frame.id, ...body }); };
399
+ try {
400
+ if (!Object.hasOwn(handlers, frame.method)) throw rpcError(ERRORS.method, 'Method not found');
401
+ if (frame.method !== 'initialize' && !runtime) throw rpcError(ERRORS.notInitialized, 'initialize first');
402
+ reply({ result: await handlers[frame.method](frame.params ?? {}) });
403
+ } catch (error) {
404
+ reply({ error: error.rpc ?? { code: isNativeError(error) ? ERRORS.params : ERRORS.internalError,
405
+ message: isNativeError(error) ? error.code : publicErrorMessage(error) } });
406
+ }
407
+ if (closing) frames.close();
408
+ })();
409
+ }
410
+ closing = true;
411
+ for (const { controller } of active.values()) controller.abort();
412
+ for (const waiter of pending.values()) waiter.reject(new Error('engine closing'));
413
+ await Promise.allSettled([...active.values()].map(item => item.done));
414
+ await (await runtimePromise?.catch(() => null))?.close();
415
+ }
416
+ function rpcError(code, message, data) { return Object.assign(new Error(message), { rpc: { code, message, ...(data ? { data } : {}) } }); }
417
+
418
+ export function engineStartupFromArgs(argv, env) {
419
+ const { values } = parseArgs({ args: argv, options: { workspace: { type: 'string' }, 'state-dir': { type: 'string' },
420
+ session: { type: 'string' }, approval: { type: 'string' }, tenant: { type: 'string' }, user: { type: 'string' }, agent: { type: 'string' } } });
421
+ const need = (value, name) => { if (!text(value)) throw new Error(`${name} is required`); return value; };
422
+ const number = name => env[name] === undefined ? undefined : Number(env[name]);
423
+ const approval = values.approval ?? 'deny';
424
+ if (!['allow', 'deny'].includes(approval)) throw new Error('--approval must be allow or deny');
425
+ let subAgents;
426
+ if (env.AGENTKIT_ENGINE_CHILD_ROLES !== undefined) {
427
+ try { subAgents = JSON.parse(env.AGENTKIT_ENGINE_CHILD_ROLES); }
428
+ catch { throw new Error('AGENTKIT_ENGINE_CHILD_ROLES must be a JSON array'); }
429
+ if (!Array.isArray(subAgents)) throw new Error('AGENTKIT_ENGINE_CHILD_ROLES must be a JSON array');
430
+ }
431
+ return { workspace: need(values.workspace, '--workspace'), stateDir: need(values['state-dir'], '--state-dir'),
432
+ subAgents,
433
+ sessionId: values.session ?? 'engine-session', approval, approvalTimeoutMs: number('AGENTKIT_ENGINE_APPROVAL_TIMEOUT_MS') ?? 600000,
434
+ scope: { tenantId: values.tenant ?? 'local', workspaceId: 'local', userId: values.user ?? 'local-user', agentId: values.agent ?? 'engine' },
435
+ model: { protocol: env.AGENTKIT_ENGINE_MODEL_PROTOCOL ?? 'openai-chat', name: need(env.AGENTKIT_ENGINE_MODEL_NAME, 'AGENTKIT_ENGINE_MODEL_NAME'),
436
+ baseUrl: need(env.AGENTKIT_ENGINE_MODEL_BASE_URL, 'AGENTKIT_ENGINE_MODEL_BASE_URL'),
437
+ apiKeyEnv: env.AGENTKIT_ENGINE_MODEL_API_KEY_ENV ?? 'AGENTKIT_ENGINE_MODEL_API_KEY',
438
+ contextWindow: number('AGENTKIT_ENGINE_MODEL_CONTEXT_WINDOW'), maxOutputTokens: number('AGENTKIT_ENGINE_MODEL_MAX_OUTPUT_TOKENS'),
439
+ requestOutputTokens: number('AGENTKIT_ENGINE_MODEL_REQUEST_OUTPUT_TOKENS'), images: env.AGENTKIT_ENGINE_MODEL_IMAGES === '1' } };
440
+ }
441
+
442
+ function isMain() {
443
+ if (!process.argv[1]) return false;
444
+ try { return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]); }
445
+ catch { return false; }
446
+ }
447
+
448
+ if (isMain()) {
449
+ let startup;
450
+ try { startup = engineStartupFromArgs(process.argv.slice(2), process.env); }
451
+ catch (error) { process.stderr.write(`agentkit-engine: ${error.message}\n`); process.exit(2); }
452
+ serveEngine({ input: process.stdin, output: process.stdout, startup, log: message => process.stderr.write(`agentkit-engine: ${message}\n`) })
453
+ .then(() => process.exit(0), error => { process.stderr.write(`agentkit-engine: ${publicErrorMessage(error)}\n`); process.exit(1); });
454
+ }