@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,249 @@
1
+ import { createHash, createPublicKey, timingSafeEqual } from 'node:crypto';
2
+ import { join } from 'node:path';
3
+ import { canonical, configure, invariant, parseNativeJson, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
4
+ import { createEngineRuntime } from './engine-runtime.mjs';
5
+ import { ENGINE_HOST_EFFECT, waitForHostReceipt } from './engine-host-effects.mjs';
6
+ import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
7
+ import { createManagedSessionDelivery, MANAGED_SESSION_DELIVERY, projectManagedSessionEvent } from './engine-managed-delivery.mjs';
8
+ import { createManagedEngineHost, MANAGED_HOST_RESOURCES } from './engine-managed-host.mjs';
9
+ import { createNativeKernelPermitVerifier } from './native-kernel-permit.mjs';
10
+ import { createManagedNativeKernel, MANAGED_NATIVE_KERNEL_CONTRACT } from './native-managed-kernel.mjs';
11
+ import { createManagedNativeKernelHttp, MANAGED_NATIVE_KERNEL_PATH } from './native-managed-kernel-http.mjs';
12
+ import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
13
+ import { acquireWorkspaceMutationLock } from './workspace-mutation-lock.mjs';
14
+
15
+ export { MANAGED_NATIVE_KERNEL_CONTRACT, MANAGED_NATIVE_KERNEL_PATH };
16
+ const digest = value => createHash('sha256').update(canonical(value)).digest('hex');
17
+ const platformContractDigest = 'b610a25aae957306b9f84a2cc2c948b30d1ce6218585cfd2a91f96736b92d102';
18
+ const harnessCancelPolicy = { schema: 'agent-kernel/required-capabilities/v1', name: 'harness-cancel', required: ['cancel'] };
19
+ const validDigest = value => typeof value === 'string' && /^[0-9a-f]{64}$/u.test(value);
20
+
21
+ function managedInput(content) {
22
+ if (typeof content === 'string' && content.trim()) return { objective: content };
23
+ invariant(Array.isArray(content), 'NATIVE_MANAGED_STUDIO_INPUT_UNSUPPORTED');
24
+ const text = [], inputImages = [];
25
+ for (const part of content) {
26
+ if (typeof part === 'string') { text.push(part); continue; }
27
+ if (['text', 'input_text'].includes(part?.type) && typeof part.text === 'string') {
28
+ text.push(part.text);
29
+ continue;
30
+ }
31
+ invariant(['image_url', 'input_image'].includes(part?.type), 'NATIVE_MANAGED_STUDIO_INPUT_UNSUPPORTED');
32
+ const url = typeof part.image_url === 'string' ? part.image_url : part.image_url?.url;
33
+ invariant(typeof url === 'string' && url.startsWith('data:image/'), 'NATIVE_MANAGED_STUDIO_IMAGE_INVALID');
34
+ inputImages.push({ type: 'image_url', image_url: { url } });
35
+ }
36
+ const objective = text.join('');
37
+ invariant(objective.trim() || inputImages.length, 'NATIVE_MANAGED_STUDIO_INPUT_UNSUPPORTED');
38
+ return { objective: objective.trim() ? objective : 'Inspect the attached image.', inputImages };
39
+ }
40
+
41
+ /** The service owns the managed command journal and its execution store. */
42
+ export function createEngineManagedService({ startup, stateDir, workspace, config, env, fetchImpl, log, serviceToken, viewStore, viewRef }) {
43
+ const { buildId, controlPublicKeys, platformApprovals = false, platformKernel } = config;
44
+ const host = config.host === undefined ? undefined : createManagedEngineHost(config.host, env);
45
+ const transportEnv = platformKernel?.transportTokenEnv ?? (platformKernel && env.AGENTKIT_HARNESS_PLATFORM_TRANSPORT_TOKEN !== undefined
46
+ ? 'AGENTKIT_HARNESS_PLATFORM_TRANSPORT_TOKEN' : undefined);
47
+ const transportToken = transportEnv === undefined ? undefined : env[transportEnv];
48
+ invariant(!host || env[config.host.tokenEnv] !== serviceToken
49
+ && env[config.host.tokenEnv] !== env[startup.model.apiKeyEnv], 'engine_managed_host_config_invalid');
50
+ invariant(typeof buildId === 'string' && buildId.trim() && buildId.length <= 256
51
+ && controlPublicKeys && typeof controlPublicKeys === 'object' && !Array.isArray(controlPublicKeys)
52
+ && typeof platformApprovals === 'boolean'
53
+ && (platformKernel === undefined || platformKernel && typeof platformKernel === 'object'
54
+ && Object.keys(platformKernel).every(key => ['bundleDigest', 'transportTokenEnv', 'agentInstanceId'].includes(key))
55
+ && validDigest(platformKernel.bundleDigest)
56
+ && (platformKernel.agentInstanceId === undefined || typeof platformKernel.agentInstanceId === 'string'
57
+ && /^[a-zA-Z0-9._-]{1,64}$/u.test(platformKernel.agentInstanceId)))
58
+ && (config.authorizeInteraction === undefined || !platformApprovals && typeof config.authorizeInteraction === 'function'),
59
+ 'engine_managed_config_invalid');
60
+ invariant(transportEnv === undefined || typeof transportEnv === 'string' && /^[A-Z][A-Z0-9_]*$/u.test(transportEnv)
61
+ && typeof transportToken === 'string' && transportToken.length >= 24 && !/\s/u.test(transportToken)
62
+ && ![serviceToken, env[startup.model.apiKeyEnv], host && env[config.host.tokenEnv]].includes(transportToken),
63
+ 'engine_managed_platform_transport_invalid');
64
+ const transportDigest = transportToken === undefined ? null : createHash('sha256').update('Bearer ' + transportToken).digest();
65
+ const authorizeInteraction = platformApprovals
66
+ ? ({ command, pending }) => pending.interactionId === command.payload.interaction_id && typeof pending.operationKey === 'string'
67
+ : config.authorizeInteraction;
68
+ const entries = Object.entries(controlPublicKeys);
69
+ invariant(entries.length > 0 && entries.length <= 32, 'engine_managed_config_invalid');
70
+ for (const [id, pem] of entries) {
71
+ invariant(/^[a-zA-Z0-9._-]{1,128}$/.test(id) && typeof pem === 'string'
72
+ && pem.length <= 65536 && createPublicKey(pem).asymmetricKeyType === 'ed25519',
73
+ 'engine_managed_control_key_invalid');
74
+ }
75
+ const verificationKeys = new Map(entries);
76
+ const scope = Object.freeze({ ...startup.scope });
77
+ const agentInstanceId = platformKernel?.agentInstanceId ?? scope.agentId;
78
+ const { name, protocol = 'openai-chat', baseUrl } = startup.model;
79
+ const target = { tenantId: scope.tenantId, agentInstanceId,
80
+ ...(agentInstanceId === scope.agentId ? {} : { runScopeAgentId: scope.agentId }),
81
+ engineBinding: digest({ buildId, scope, workspace, model: { name, protocol, baseUrl },
82
+ commandSandbox: startup.commandSandbox ?? null, subAgents: startup.subAgents ?? [] }) };
83
+ const permitVerifier = createNativeKernelPermitVerifier({ target, verificationKeys: async () => verificationKeys,
84
+ requireBoundApproval: platformApprovals });
85
+ let current = true;
86
+ const resolveBinding = Object.assign(async ({ command, runId, store, admission, signal }) => {
87
+ signal.throwIfAborted();
88
+ const { objective, inputImages } = managedInput(command.payload.content);
89
+ const options = command.payload.runtime_options ?? {};
90
+ invariant(typeof options === 'object' && !Array.isArray(options)
91
+ && Object.keys(options).every(key => ['model', 'tool_approval_mode'].includes(key)), 'engine_managed_options_invalid');
92
+ invariant(options.model === undefined || options.model === name, 'engine_managed_model_unavailable');
93
+ invariant(options.tool_approval_mode === undefined || ['ask', 'risk'].includes(options.tool_approval_mode), 'engine_managed_options_invalid');
94
+ const strictApproval = options.tool_approval_mode === 'ask';
95
+ invariant(!strictApproval || authorizeInteraction, 'engine_tool_policy_requires_durable_approvals');
96
+ const sessionId = command.session_id;
97
+ const recovered = admission?.configuration.hostRecoveryBinding;
98
+ invariant(recovered === undefined || host && recovered.contract === MANAGED_HOST_RESOURCES && typeof recovered.ref === 'string',
99
+ 'engine_managed_host_binding_unavailable');
100
+ let bindingRef = recovered?.ref;
101
+ const readReceipt = (call, originalOperationKey, receiptSignal, observationId) => {
102
+ invariant(bindingRef, 'engine_managed_host_binding_unavailable');
103
+ return host.receipt({ scope, sessionId, runId, ref: bindingRef, originalOperationKey, callId: call.callId,
104
+ name: call.name, arguments: call.arguments, ...(observationId ? { observationId } : {}) }, receiptSignal);
105
+ };
106
+ const engine = await createEngineRuntime({
107
+ workspaceRoot: workspace, stateDir: join(stateDir, 'managed-resources', digest(sessionId)),
108
+ sessionId, scope, runStore: store, sourceEnv: env, fetchImpl,
109
+ callHostTool: host && (request => {
110
+ invariant(bindingRef && request.runId === runId, 'engine_managed_host_binding_unavailable');
111
+ return host.callTool({ ...request, scope, sessionId, ref: bindingRef });
112
+ }),
113
+ callHostReceipt: host && (async request => {
114
+ invariant(request.runId === runId, 'engine_managed_host_binding_unavailable');
115
+ const result = await readReceipt(request.call, request.originalOperationKey, request.signal, request.operationKey);
116
+ return { contract: request.contract, originalOperationKey: request.originalOperationKey, callId: request.call.callId, result };
117
+ }),
118
+ authorize: async () => 'deny', commandSandbox: startup.commandSandbox, subAgents: startup.subAgents,
119
+ model: { ...startup.model, apiKey: async () => env[startup.model.apiKeyEnv] ?? '' },
120
+ });
121
+ try {
122
+ signal.throwIfAborted();
123
+ let configuration = admission?.configuration;
124
+ let deliverSession = recovered?.sessionDelivery === true;
125
+ if (!configuration) {
126
+ let resources;
127
+ if (host) {
128
+ const { reservedToolNames: reserved, hostToolNamePattern: pattern } = engine.info();
129
+ resources = await host.admit({ scope, sessionId, runId,
130
+ toolCatalog: { reserved, pattern, receiptObservation: TOOL_RECEIPT_OBSERVATION_CONTRACT }, signal });
131
+ signal.throwIfAborted();
132
+ bindingRef = resources.ref;
133
+ deliverSession = resources.sessionDelivery;
134
+ if (deliverSession) viewStore.pin(stateDir, runId, viewRef);
135
+ }
136
+ configuration = engine.prepareRun({ runId, objective, inputImages, originalInput: true, durableApprovals: !!authorizeInteraction,
137
+ ...(strictApproval ? { toolPolicy: { contract: ENGINE_TOOL_POLICY, mode: 'strict', rules: {} } } : {}),
138
+ ...(resources ? { hostInstructions: resources.hostInstructions, hostTools: resources.hostTools.map(tool =>
139
+ tool.readOnly === true ? tool : { ...tool, readOnly: false, effectProtocol: ENGINE_HOST_EFFECT }) } : {}),
140
+ }).configuration;
141
+ if (resources) configuration = configure({ ...configuration,
142
+ hostRecoveryBinding: { contract: MANAGED_HOST_RESOURCES, ref: bindingRef,
143
+ ...(deliverSession ? { sessionDelivery: true } : {}) } });
144
+ }
145
+ const delivery = deliverSession ? createManagedSessionDelivery({
146
+ directory: join(stateDir, 'managed-delivery'), host, ref: bindingRef, scope, sessionId, runId,
147
+ input: objective, source: { provider: 'agentkit-harness', model: name },
148
+ readTerminalFrames: run => runtime.terminalSessionFrames(run),
149
+ view: viewStore.reference(stateDir, runId)?.sha256 ?? null,
150
+ }) : {};
151
+ const hasHostReceipts = configuration.tools.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT
152
+ && tool.recoveryPolicy === 'receipt-observation/v1');
153
+ function waitForReceipt(_snapshot, { signal: idleSignal, assertCurrent }) {
154
+ assertCurrent();
155
+ return waitForHostReceipt(store.load(scope, runId), { read: readReceipt, signal: idleSignal, assertCurrent });
156
+ }
157
+ return { scope, buildId, configuration, ports: engine.ports, ...delivery,
158
+ ...(hasHostReceipts ? { withExecution: ({ execute }) => execute({ onIdle: waitForReceipt }) } : {}),
159
+ release: () => engine.close() };
160
+ } catch (error) {
161
+ await engine.close();
162
+ throw error;
163
+ }
164
+ }, {
165
+ enqueueContentFormats: Object.freeze(['text/plain']),
166
+ resolveInjectionScope: async ({ signal }) => { signal.throwIfAborted(); return scope; },
167
+ });
168
+ // The separate lock database is held for this process's lifetime. It is
169
+ // released by SQLite on process death and never blocks a contender's loop.
170
+ const releaseOwnership = acquireWorkspaceMutationLock(join(stateDir, 'managed-owner'), { timeoutMs: 0 });
171
+ let runtime;
172
+ try {
173
+ runtime = createManagedNativeKernel({
174
+ directory: join(stateDir, 'managed'), target, permitVerifier, resolveBinding, authorizeInteraction,
175
+ platformApprovals,
176
+ assertCurrent: () => current, projectSessionEvent: projectManagedSessionEvent,
177
+ onWorkerError: ({ error }) => log('managed execution failed: ' + publicErrorMessage(error)),
178
+ });
179
+ } catch (error) { releaseOwnership(); throw error; }
180
+ const transport = createManagedNativeKernelHttp(runtime);
181
+ async function handleSession(request, response, action) {
182
+ const json = (status, payload) => {
183
+ if (response.destroyed) return;
184
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
185
+ response.end(canonical(payload));
186
+ };
187
+ if (request.method !== 'POST') return json(405, { error: 'method_not_allowed' });
188
+ try {
189
+ const chunks = [];
190
+ let size = 0;
191
+ for await (const chunk of request.iterator({ destroyOnReturn: false })) {
192
+ size += chunk.length;
193
+ if (size > 32768) {
194
+ response.setHeader('connection', 'close');
195
+ return json(400, { error: 'invalid_request' });
196
+ }
197
+ chunks.push(chunk);
198
+ }
199
+ const body = parseNativeJson(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
200
+ invariant(body?.contract === MANAGED_SESSION_DELIVERY
201
+ && typeof body.runId === 'string' && body.runId.length <= 256
202
+ && typeof body.sessionId === 'string' && body.sessionId.length <= 256
203
+ && (action === 'restore' || typeof body.ref === 'string' && body.ref.length <= 8192)
204
+ && typeof body.configDigest === 'string' && /^[a-f0-9]{64}$/.test(body.configDigest),
205
+ 'engine_managed_frame_request_invalid');
206
+ const identity = { scope, sessionId: body.sessionId, runId: body.runId, configDigest: body.configDigest };
207
+ if (action === 'restore') return json(200, { contract: MANAGED_SESSION_DELIVERY, hostCancel: true,
208
+ ...runtime.restoreSessionDelivery(identity), source: { provider: 'agentkit-harness', model: name } });
209
+ if (action === 'cancel') return json(200, { contract: MANAGED_SESSION_DELIVERY,
210
+ ...runtime.cancelSessionDelivery({ ...identity, ref: body.ref }) });
211
+ const events = runtime.readSessionFrames({ ...identity, ref: body.ref, after: body.after });
212
+ return json(200, { contract: MANAGED_SESSION_DELIVERY, cursor: events.at(-1)?.seq ?? body.after,
213
+ view: viewStore.reference(stateDir, body.runId)?.sha256 ?? null, events });
214
+ } catch (error) {
215
+ if (error.code === 'NATIVE_KERNEL_STATUS_IDENTITY_MISMATCH') return json(404, { error: 'run_not_found' });
216
+ return json(400, { error: 'invalid_request' });
217
+ }
218
+ }
219
+
220
+ return {
221
+ platformApprovals,
222
+ authorizesPlatformTransport(authorization) {
223
+ return transportDigest !== null && typeof authorization === 'string'
224
+ && timingSafeEqual(transportDigest, createHash('sha256').update(authorization).digest());
225
+ },
226
+ platformHealth: platformKernel && (() => {
227
+ let check;
228
+ try { check = runtime.probePlatform(); } catch { /* Both ledgers must be readable before accepting platform traffic. */ }
229
+ const capabilities = check?.capabilities ?? {};
230
+ const worker = check?.workerRunning === true;
231
+ const capable = capabilities.cancel?.supported === true;
232
+ return { ready: current && worker && capable, store_ok: !!check, worker_running: worker, lease_healthy: current,
233
+ store_driver: 'sqlite-single-writer', agent_instance_id: agentInstanceId, contract_digest: platformContractDigest,
234
+ capability_digest: capable ? digest(harnessCancelPolicy) : digest(capabilities), bundle_digest: platformKernel.bundleDigest,
235
+ capabilities };
236
+ }),
237
+ handle(request, response) {
238
+ if (request.url === MANAGED_NATIVE_KERNEL_PATH + '/session-frames') return handleSession(request, response, 'frames');
239
+ if (request.url === MANAGED_NATIVE_KERNEL_PATH + '/session-restore') return handleSession(request, response, 'restore');
240
+ if (request.url === MANAGED_NATIVE_KERNEL_PATH + '/session-cancel') return handleSession(request, response, 'cancel');
241
+ return transport.handle(request, response);
242
+ },
243
+ async close() {
244
+ current = false;
245
+ transport.close();
246
+ try { await runtime.close(); } finally { releaseOwnership(); }
247
+ },
248
+ };
249
+ }