@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.
Files changed (41) hide show
  1. package/dist/engine-view.html +566 -0
  2. package/dist/index.mjs +22 -14
  3. package/dist/rpc-entry.mjs +22 -14
  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/model-provider-compat.mjs +12 -7
  26. package/src/native/native-kernel-events.mjs +103 -0
  27. package/src/native/native-kernel-permit.mjs +95 -0
  28. package/src/native/native-managed-execution-grants.mjs +232 -0
  29. package/src/native/native-managed-injection.mjs +53 -0
  30. package/src/native/native-managed-interaction.mjs +192 -0
  31. package/src/native/native-managed-kernel-http.mjs +122 -0
  32. package/src/native/native-managed-kernel.mjs +922 -0
  33. package/src/native/native-managed-scoped-control.mjs +116 -0
  34. package/src/native/native-managed-session-frames.mjs +43 -0
  35. package/src/native/native-managed-teams-context.mjs +126 -0
  36. package/src/native/native-teams-callback-authority.mjs +73 -0
  37. package/src/native/native-teams-context-contract.mjs +272 -0
  38. package/src/native/native-teams-json.mjs +38 -0
  39. package/src/native/native-terminal-failure.mjs +53 -0
  40. package/src/native/sqlite-store.mjs +1 -0
  41. package/src/native/workspace-tools.mjs +2 -0
@@ -0,0 +1,281 @@
1
+ #!/usr/bin/env node
2
+ import { spawnSync } from 'node:child_process';
3
+ import { createHash, timingSafeEqual } from 'node:crypto';
4
+ import { mkdirSync, readFileSync, realpathSync } from 'node:fs';
5
+ import { createServer } from 'node:http';
6
+ import { createServer as createTlsServer } from 'node:https';
7
+ import { join } from 'node:path';
8
+ import { createInterface } from 'node:readline';
9
+ import { PassThrough } from 'node:stream';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { engineStartupFromArgs, engineView, serveEngine } from './engine-server.mjs';
12
+ import { ENGINE_EXECUTION_POLICY } from './engine-runtime.mjs';
13
+ import { createEngineViewStore } from './engine-view-store.mjs';
14
+ import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
15
+ import { ENGINE_CONTEXT } from './engine-context.mjs';
16
+ import { ENGINE_HOOKS } from './engine-hooks.mjs';
17
+ import { ENGINE_HOST_EFFECT } from './engine-host-effects.mjs';
18
+ import { ENGINE_VERIFICATION } from './engine-verification.mjs';
19
+ import { createEngineManagedService, MANAGED_NATIVE_KERNEL_CONTRACT, MANAGED_NATIVE_KERNEL_PATH } from './engine-managed-service.mjs';
20
+ import { isAgentKernelPlatformPath } from './native-managed-kernel-http.mjs';
21
+ import { ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
22
+
23
+ export const ENGINE_SERVICE_CONTRACT = 'agentkit.engine-service/v1';
24
+ // Bound the authenticated frame separately from the current-turn media budget.
25
+ const MAX_BODY_BYTES = 8 * 1024 * 1024;
26
+ const SESSION_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
27
+ const hash = value => createHash('sha256').update(value).digest();
28
+
29
+ function respond(response, status, value) {
30
+ if (response.destroyed) return;
31
+ response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
32
+ response.end(JSON.stringify(value));
33
+ }
34
+
35
+ async function readFrame(request) {
36
+ const chunks = [];
37
+ let bytes = 0;
38
+ for await (const chunk of request) {
39
+ bytes += chunk.length;
40
+ if (bytes > MAX_BODY_BYTES) throw new Error('frame_too_large');
41
+ chunks.push(chunk);
42
+ }
43
+ const frame = JSON.parse(Buffer.concat(chunks).toString('utf8'));
44
+ if (!frame || typeof frame !== 'object' || Array.isArray(frame) || frame.jsonrpc !== '2.0'
45
+ || typeof frame.id !== 'string' || !frame.id || frame.id.length > 128) throw new Error('invalid_frame');
46
+ return frame;
47
+ }
48
+
49
+ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
50
+ const input = new PassThrough(), output = new PassThrough();
51
+ const frames = createInterface({ input: output, crlfDelay: Infinity });
52
+ const pending = new Map(), hostRequests = new Map(), hostWaiters = new Set();
53
+ const pruneHostRequests = now => {
54
+ for (const [id, request] of hostRequests) {
55
+ if (request.frame.expiresAt <= now) hostRequests.delete(id);
56
+ }
57
+ };
58
+ const done = serveEngine({
59
+ input, output, env, fetchImpl, log, viewStore, detachOnShutdown: true,
60
+ startup: { ...startup, sessionId, stateDir: join(startup.stateDir, hash(sessionId).toString('hex')) },
61
+ }).finally(() => {
62
+ for (const resolve of pending.values()) resolve(null);
63
+ for (const waiter of hostWaiters) waiter(true);
64
+ pending.clear();
65
+ output.end();
66
+ });
67
+ // The server owns the worker lifetime independently of HTTP request lifetime.
68
+ done.catch(() => log('engine session stopped'));
69
+ frames.on('line', line => {
70
+ const frame = JSON.parse(line);
71
+ if (typeof frame.method === 'string') {
72
+ pruneHostRequests(Date.now());
73
+ hostRequests.set(frame.id, { frame, claimed: false });
74
+ for (const waiter of hostWaiters) waiter();
75
+ } else if (pending.has(frame.id)) {
76
+ const resolve = pending.get(frame.id);
77
+ pending.delete(frame.id);
78
+ resolve(frame);
79
+ }
80
+ });
81
+ const takeHostRequests = runId => {
82
+ pruneHostRequests(Date.now());
83
+ const ready = [];
84
+ for (const request of hostRequests.values()) {
85
+ if (!request.claimed && (runId === undefined || request.frame.params?.runId === runId)) {
86
+ request.claimed = true;
87
+ ready.push(request.frame);
88
+ }
89
+ }
90
+ return ready;
91
+ };
92
+ return {
93
+ request(frame) {
94
+ if (pending.has(frame.id)) return null;
95
+ return new Promise(resolve => {
96
+ pending.set(frame.id, resolve);
97
+ input.write(JSON.stringify(frame) + '\n');
98
+ });
99
+ },
100
+ async takeHostRequests(runId, waitMs, response) {
101
+ const available = takeHostRequests(runId);
102
+ if (available.length || !waitMs || response.destroyed) return available;
103
+ return new Promise(resolve => {
104
+ const finish = frames => {
105
+ clearTimeout(timer);
106
+ hostWaiters.delete(notify);
107
+ response.off('close', cancel);
108
+ resolve(frames);
109
+ };
110
+ const cancel = () => finish([]);
111
+ const notify = stopped => {
112
+ if (stopped || response.destroyed) return cancel();
113
+ const ready = takeHostRequests(runId);
114
+ if (ready.length) finish(ready);
115
+ };
116
+ const timer = setTimeout(cancel, waitMs);
117
+ response.once('close', cancel);
118
+ hostWaiters.add(notify);
119
+ });
120
+ },
121
+ reply(frame) {
122
+ const request = hostRequests.get(frame.id);
123
+ if (!request?.claimed || !hostRequests.delete(frame.id) || request.frame.expiresAt <= Date.now()) return false;
124
+ input.write(JSON.stringify(frame) + '\n');
125
+ return true;
126
+ },
127
+ async close() {
128
+ input.end();
129
+ await done;
130
+ },
131
+ };
132
+ }
133
+
134
+ /** One service instance owns one configured workspace and trust boundary.
135
+ * Cloud deployers allocate one instance per isolated runtime. The caller
136
+ * chooses only the opaque session ID, never paths, model URLs or credentials. */
137
+ export function createEngineService({ startup, token, env = process.env, fetchImpl = fetch, log = () => {}, maxSessions = 128, tls, managed }) {
138
+ if (typeof token !== 'string' || token.length < 24) throw new Error('engine_service_token_required');
139
+ if (!Number.isSafeInteger(maxSessions) || maxSessions < 1) throw new Error('invalid_session_limit');
140
+ const auth = hash('Bearer ' + token), sessions = new Map();
141
+ mkdirSync(startup.stateDir, { recursive: true, mode: 0o700 });
142
+ const stateDir = realpathSync(startup.stateDir);
143
+ const workspace = realpathSync(startup.workspace);
144
+ if (workspace === stateDir || workspace.startsWith(stateDir + '/') || stateDir.startsWith(workspace + '/'))
145
+ throw new Error('engine_service_workspace_state_overlap');
146
+ if (startup.commandSandbox !== undefined) {
147
+ if (startup.commandSandbox !== ISOLATED_COMMAND_SHELL) throw new Error('engine_service_sandbox_invalid');
148
+ const [command, ...args] = shellCommandArgv(':', startup.commandSandbox, { workspaceRoot: workspace, cwd: workspace });
149
+ const probe = spawnSync(command, args, { cwd: workspace, env: { PATH: '/bin:/usr/bin' }, timeout: 5000, stdio: 'ignore' });
150
+ if (probe.status !== 0) throw new Error('engine_service_sandbox_unavailable');
151
+ }
152
+ const viewStore = createEngineViewStore(join(stateDir, 'engine-views'));
153
+ const viewRef = viewStore.archive(engineView());
154
+ const managedRuntime = managed && createEngineManagedService({ startup, stateDir, workspace,
155
+ config: managed, env, fetchImpl, log, serviceToken: token, viewStore, viewRef });
156
+ let closing = false;
157
+ const handleRequest = async (request, response) => {
158
+ if (request.method === 'GET' && request.url === '/healthz') {
159
+ return respond(response, closing ? 503 : 200, {
160
+ contract: ENGINE_SERVICE_CONTRACT, ready: !closing,
161
+ capabilities: { scopedHostRequests: true, toolPolicy: ENGINE_TOOL_POLICY,
162
+ hostContext: ENGINE_CONTEXT, hostHooks: ENGINE_HOOKS, hostToolEffects: ENGINE_HOST_EFFECT,
163
+ executionPolicy: ENGINE_EXECUTION_POLICY, hostVerification: ENGINE_VERIFICATION,
164
+ ...(managedRuntime ? { managedCommands: MANAGED_NATIVE_KERNEL_CONTRACT,
165
+ managedToolApprovals: managedRuntime.platformApprovals } : {}) },
166
+ });
167
+ }
168
+ const platformRoute = isAgentKernelPlatformPath(request.url);
169
+ if (!timingSafeEqual(hash(request.headers.authorization ?? ''), auth)
170
+ && !(platformRoute && managedRuntime?.authorizesPlatformTransport(request.headers.authorization)))
171
+ return respond(response, 401, { error: 'unauthorized' });
172
+ if (closing) return respond(response, 503, { error: 'service_stopping' });
173
+ if (request.method === 'GET' && request.url === '/agent-kernel/v1/health' && managedRuntime?.platformHealth) {
174
+ const health = managedRuntime.platformHealth();
175
+ return respond(response, health.ready ? 200 : 503, health);
176
+ }
177
+ if (managedRuntime && (request.url?.startsWith(MANAGED_NATIVE_KERNEL_PATH + '/') || platformRoute))
178
+ return managedRuntime.handle(request, response);
179
+ const viewMatch = /^\/v1\/views\/([a-f0-9]{64})$/.exec(request.url ?? '');
180
+ if (viewMatch && ['GET', 'HEAD'].includes(request.method)) {
181
+ try {
182
+ const view = viewStore.get(viewMatch[1]);
183
+ if (!view) return respond(response, 404, { error: 'view_not_found' });
184
+ response.writeHead(200, {
185
+ 'content-type': view.contentType, 'cache-control': 'private, max-age=31536000, immutable',
186
+ 'content-security-policy': "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; sandbox allow-scripts",
187
+ 'x-content-type-options': 'nosniff', 'referrer-policy': 'no-referrer',
188
+ });
189
+ return response.end(request.method === 'HEAD' ? undefined : view.html);
190
+ } catch {
191
+ return respond(response, 500, { error: 'view_unavailable' });
192
+ }
193
+ }
194
+ const [pathname, query] = (request.url ?? '').split('?', 2);
195
+ const match = /^\/v1\/sessions\/([^/]+)\/(rpc|host-requests|host-reply)$/.exec(pathname);
196
+ if (!match || !SESSION_PATTERN.test(match[1])) return respond(response, 404, { error: 'not_found' });
197
+ const [, id, action] = match;
198
+ try {
199
+ if (request.method === 'GET' && action === 'host-requests') {
200
+ const session = sessions.get(id);
201
+ if (!session) return respond(response, 404, { error: 'session_not_found' });
202
+ const search = new URLSearchParams(query);
203
+ const runId = search.get('runId') ?? undefined;
204
+ const waitMs = Math.min(Math.max(Number(search.get('waitMs')) || 0, 0), 5000);
205
+ const requests = await session.takeHostRequests(runId, waitMs, response);
206
+ return respond(response, 200, { requests });
207
+ }
208
+ if (query !== undefined) return respond(response, 400, { error: 'invalid_query' });
209
+ if (request.method !== 'POST' || action === 'host-requests')
210
+ return respond(response, 405, { error: 'method_not_allowed' });
211
+ const frame = await readFrame(request);
212
+ let session = sessions.get(id);
213
+ if (action === 'host-reply') {
214
+ if (Object.hasOwn(frame, 'method') || Object.hasOwn(frame, 'result') === Object.hasOwn(frame, 'error'))
215
+ return respond(response, 400, { error: 'invalid_host_reply' });
216
+ if (!session?.reply(frame)) return respond(response, 404, { error: 'host_request_not_found' });
217
+ return respond(response, 200, { accepted: true });
218
+ }
219
+ if (typeof frame.method !== 'string' || frame.method === 'shutdown')
220
+ return respond(response, 400, { error: 'invalid_method' });
221
+ if (!session) {
222
+ if (frame.method !== 'initialize') return respond(response, 404, { error: 'session_not_found' });
223
+ if (sessions.size >= maxSessions) return respond(response, 503, { error: 'session_capacity' });
224
+ session = openSession(id, { ...startup, stateDir }, env, fetchImpl, log, viewStore);
225
+ sessions.set(id, session);
226
+ }
227
+ const result = await session.request(frame);
228
+ if (closing) return respond(response, 503, { error: 'service_stopping' });
229
+ if (!result) return respond(response, 409, { error: 'request_unavailable' });
230
+ return respond(response, 200, result);
231
+ } catch {
232
+ return respond(response, 400, { error: 'invalid_request' });
233
+ }
234
+ };
235
+ const server = tls ? createTlsServer(tls, handleRequest) : createServer(handleRequest);
236
+ return {
237
+ server,
238
+ async close() {
239
+ closing = true;
240
+ const stopped = new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
241
+ await Promise.allSettled([...sessions.values()].map(session => session.close()).concat(managedRuntime?.close() ?? []));
242
+ server.closeAllConnections();
243
+ await stopped;
244
+ },
245
+ };
246
+ }
247
+
248
+ function isMain() {
249
+ if (!process.argv[1]) return false;
250
+ try { return fileURLToPath(import.meta.url) === realpathSync(process.argv[1]); }
251
+ catch { return false; }
252
+ }
253
+
254
+ if (isMain()) {
255
+ try {
256
+ const startup = engineStartupFromArgs(process.argv.slice(2), process.env);
257
+ if (process.env.AGENTKIT_ENGINE_COMMAND_SANDBOX !== undefined)
258
+ startup.commandSandbox = process.env.AGENTKIT_ENGINE_COMMAND_SANDBOX;
259
+ const certFile = process.env.AGENTKIT_ENGINE_SERVICE_CERT_FILE;
260
+ const keyFile = process.env.AGENTKIT_ENGINE_SERVICE_KEY_FILE;
261
+ if (Boolean(certFile) !== Boolean(keyFile)) throw new Error('engine_service_tls_pair_required');
262
+ const tls = certFile ? { cert: readFileSync(certFile), key: readFileSync(keyFile) } : undefined;
263
+ const managedFile = process.env.AGENTKIT_ENGINE_MANAGED_CONFIG_FILE;
264
+ const managed = managedFile ? JSON.parse(readFileSync(managedFile, 'utf8')) : undefined;
265
+ const service = createEngineService({ startup, tls, managed, token: process.env.AGENTKIT_ENGINE_SERVICE_TOKEN,
266
+ log: message => process.stderr.write('agentkit-engine-service: ' + message + '\n') });
267
+ const port = Number(process.env.AGENTKIT_ENGINE_SERVICE_PORT ?? '8787');
268
+ if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error('invalid_service_port');
269
+ service.server.on('error', error => {
270
+ process.stderr.write('agentkit-engine-service: ' + (error.code ?? 'listen_failed') + '\n');
271
+ process.exitCode = 1;
272
+ });
273
+ service.server.listen(port, process.env.AGENTKIT_ENGINE_SERVICE_HOST ?? '127.0.0.1');
274
+ for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => {
275
+ service.close().catch(() => { process.exitCode = 1; });
276
+ });
277
+ } catch (error) {
278
+ process.stderr.write('agentkit-engine-service: ' + error.message + '\n');
279
+ process.exitCode = 2;
280
+ }
281
+ }
@@ -0,0 +1,29 @@
1
+ import { invariant } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ export const ENGINE_TOOL_POLICY = 'agentkit.native-agent-policy/v1';
4
+
5
+ export function admitEngineToolPolicy(value, durableApprovals) {
6
+ if (value === undefined) return null;
7
+ invariant(value && typeof value === 'object' && !Array.isArray(value)
8
+ && Object.keys(value).every(key => ['contract', 'mode', 'rules'].includes(key))
9
+ && value.contract === ENGINE_TOOL_POLICY && ['strict', 'custom'].includes(value.mode)
10
+ && value.rules && typeof value.rules === 'object' && !Array.isArray(value.rules),
11
+ 'engine_tool_policy_invalid');
12
+ const rules = Object.entries(value.rules);
13
+ invariant(rules.length <= 512 && (value.mode === 'custom' || rules.length === 0)
14
+ && rules.every(([name, action]) => /^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/.test(name)
15
+ && ['inherit', 'ask', 'deny'].includes(action)), 'engine_tool_policy_invalid');
16
+ invariant(durableApprovals || value.mode === 'custom' && rules.every(([, action]) => action !== 'ask'),
17
+ 'engine_tool_policy_requires_durable_approvals');
18
+ return { mode: value.mode, rules: new Map(rules) };
19
+ }
20
+
21
+ export function restrictEngineTools(definitions, policy, approvalPolicy) {
22
+ if (!policy) return definitions;
23
+ return definitions.flatMap(tool => {
24
+ const action = policy.rules.get(tool.name)
25
+ ?? (tool.readOnly ? 'inherit' : policy.mode === 'strict' ? 'ask' : 'deny');
26
+ if (action === 'deny') return [];
27
+ return [action === 'ask' ? { ...tool, approvalPolicy, hostApprovalRequired: true } : tool];
28
+ });
29
+ }
@@ -0,0 +1,111 @@
1
+ import { CONTEXT_CONTRIBUTION_CONTRACT, canonical, invariant } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ export const ENGINE_VERIFICATION = 'agentkit.engine-verification/v1';
4
+ const TIMEOUT_MS = 5000;
5
+ const EVIDENCE_BYTES = 256 * 1024;
6
+ const ID = /^[a-zA-Z0-9._-]{1,128}$/;
7
+
8
+ export function admitEngineVerification(input) {
9
+ if (input === undefined) return undefined;
10
+ invariant(input && input.contract === ENGINE_VERIFICATION
11
+ && Object.keys(input).every(key => ['contract', 'verifierRef', 'verifierVersion', 'bindingDigest',
12
+ 'evidenceTools', 'contextSourceId'].includes(key))
13
+ && typeof input.verifierRef === 'string' && ID.test(input.verifierRef)
14
+ && typeof input.verifierVersion === 'string' && ID.test(input.verifierVersion)
15
+ && typeof input.bindingDigest === 'string' && /^sha256:[a-f0-9]{64}$/.test(input.bindingDigest)
16
+ && Array.isArray(input.evidenceTools) && input.evidenceTools.length <= 16
17
+ && new Set(input.evidenceTools).size === input.evidenceTools.length
18
+ && input.evidenceTools.every(name => typeof name === 'string' && ID.test(name))
19
+ && (input.contextSourceId === null || typeof input.contextSourceId === 'string' && ID.test(input.contextSourceId)),
20
+ 'engine_verification_binding_invalid');
21
+ const { contract: _contract, ...binding } = input;
22
+ return binding;
23
+ }
24
+
25
+ function verificationEvidence(record, definition) {
26
+ const { configuration, events, intents, receipts } = record;
27
+ const tools = new Set(definition.evidenceTools);
28
+ const source = configuration.contextSources.find(item => item.sourceId === definition.contextSourceId);
29
+ const intentByKey = new Map(intents.map(intent => [intent.operationKey, intent]));
30
+ const receiptByKey = new Map(receipts.map(receipt => [receipt.operationKey, receipt]));
31
+ const calls = [], context = [];
32
+ let available = EVIDENCE_BYTES, contextSeen = false;
33
+ const append = (target, item) => {
34
+ const size = Buffer.byteLength(canonical(item));
35
+ if (size > available) return;
36
+ available -= size;
37
+ target.push(item);
38
+ };
39
+ for (let index = events.length - 1; index >= 0 && available > 0; index--) {
40
+ const event = events[index];
41
+ if (event.kind !== 'effect.settled' || event.payload.status !== 'committed') continue;
42
+ const { operationKey, kind } = event.payload;
43
+ const receipt = receiptByKey.get(operationKey);
44
+ if (receipt?.status !== 'committed') continue;
45
+ if (source && !contextSeen && kind === 'context' && receipt.result.action === 'ready') {
46
+ contextSeen = true;
47
+ for (const message of receipt.result.messages ?? []) {
48
+ if (message.kind !== 'context_contribution') continue;
49
+ let fragment;
50
+ try { fragment = JSON.parse(message.content); } catch { continue; }
51
+ if (fragment.schemaVersion === CONTEXT_CONTRIBUTION_CONTRACT
52
+ && fragment.sourceId === source.sourceId && fragment.bindingDigest === source.bindingDigest
53
+ && fragment.purpose === 'context_only' && (fragment.expiresAt === undefined || fragment.expiresAt > Date.now())) {
54
+ append(context, { sourceId: source.sourceId, item: fragment.item });
55
+ }
56
+ }
57
+ }
58
+ if (kind !== 'tool') continue;
59
+ const admitted = intentByKey.get(operationKey)?.payload.calls, results = receipt.result.results;
60
+ if (!Array.isArray(admitted) || !Array.isArray(results) || admitted.length !== results.length) continue;
61
+ for (let offset = 0; offset < admitted.length && calls.length < 64; offset++) {
62
+ const call = admitted[offset], result = results[offset];
63
+ if (!tools.has(call.name) || !result || result.status === 'approval_required') continue;
64
+ append(calls, { operationKey: admitted.length > 1 ? `${operationKey}:call:${offset + 1}` : operationKey,
65
+ eventId: event.eventId, call, status: result.status, content: result.content ?? null });
66
+ }
67
+ }
68
+ return { calls, context };
69
+ }
70
+
71
+ export function engineVerificationPort(store, callHostVerification, digest) {
72
+ return {
73
+ available: configuration => !!configuration.hostVerification,
74
+ async verify(request) {
75
+ const record = store.load(request.scope, request.runId);
76
+ const definition = record.configuration.hostVerification;
77
+ const item = request.contract.acceptance[0];
78
+ const candidate = request.candidate;
79
+ invariant(definition && item?.verifierRef === definition.verifierRef
80
+ && item.verifierVersion === definition.verifierVersion && candidate.binding, 'engine_verification_unbound');
81
+ const input = { contract: ENGINE_VERIFICATION, runId: request.runId,
82
+ operationKey: request.operationKey, definition, candidateId: candidate.candidateId,
83
+ contractRevision: request.contract.revision, candidateBinding: candidate.binding,
84
+ goal: request.snapshot.goal, goalRevision: request.snapshot.goalRevision,
85
+ evidence: verificationEvidence(record, definition) };
86
+ const inputDigest = digest(input);
87
+ const base = { candidateId: candidate.candidateId, contractRevision: request.contract.revision,
88
+ binding: candidate.binding, workspaceRevision: candidate.workspaceRevision, workspaceDependency: 'none' };
89
+ const unavailable = { status: 'blocked', reason: 'host_verification_unavailable',
90
+ safeSummary: 'The bound host could not verify the requested result.', evidenceRefs: [] };
91
+ let result = unavailable;
92
+ try {
93
+ const reply = await callHostVerification({ ...input, inputDigest }, TIMEOUT_MS, request.signal);
94
+ if (reply?.contract === ENGINE_VERIFICATION && reply.operationKey === request.operationKey
95
+ && reply.inputDigest === inputDigest && ['passed', 'failed', 'blocked'].includes(reply.status)
96
+ && typeof reply.reason === 'string' && ID.test(reply.reason)
97
+ && typeof reply.safeSummary === 'string' && reply.safeSummary.length <= 2048
98
+ && Array.isArray(reply.evidenceRefs) && reply.evidenceRefs.length <= 16
99
+ && reply.evidenceRefs.every(ref => typeof ref === 'string' && ref.trim() && ref.length <= 256)
100
+ && (reply.status === 'blocked' || reply.evidenceRefs.length > 0)) result = reply;
101
+ } catch {
102
+ request.signal.throwIfAborted();
103
+ }
104
+ return { ...base, status: result.status === 'blocked' ? 'unverified' : result.status,
105
+ reason: result.reason, failureFingerprint: digest([definition, result.status, result.reason]),
106
+ checks: [{ id: item.id, status: result.status, verifierId: item.verifierRef, verifierVersion: item.verifierVersion,
107
+ verificationMethod: item.verificationMethod, evidence: { reason: result.reason }, evidenceRefs: result.evidenceRefs,
108
+ safeSummary: result.safeSummary, repairable: result.status === 'failed' }] };
109
+ },
110
+ };
111
+ }
@@ -0,0 +1,63 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, readFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { atomicPrivate, openPrivate, privateDirectory } from './local-command-state.mjs';
5
+
6
+ export const ENGINE_VIEW_CONTRACT = 'agentkit.engine-view/v1';
7
+ const SHA256 = /^[a-f0-9]{64}$/;
8
+ const digest = value => createHash('sha256').update(value).digest('hex');
9
+ const MAX_VIEW_BYTES = 1024 * 1024;
10
+
11
+ function read(path, limit) {
12
+ let fd;
13
+ try {
14
+ fd = openPrivate(path, constants.O_RDONLY);
15
+ if (fstatSync(fd).size > limit) throw new Error('engine_view_archive_too_large');
16
+ return readFileSync(fd, 'utf8');
17
+ } catch (error) { if (error.code === 'ENOENT') return null; throw error; }
18
+ finally { if (fd !== undefined) closeSync(fd); }
19
+ }
20
+
21
+ function write(path, value) {
22
+ privateDirectory(dirname(path), true);
23
+ atomicPrivate(path, value);
24
+ }
25
+
26
+ export function createEngineViewStore(directory) {
27
+ const file = sha256 => join(directory, 'assets', sha256 + '.json');
28
+ const reference = (stateDir, runId) => join(stateDir, 'view-references', digest(runId));
29
+
30
+ function get(sha256) {
31
+ if (typeof sha256 !== 'string' || !SHA256.test(sha256)) return null;
32
+ const encoded = read(file(sha256), 6 * MAX_VIEW_BYTES + 1024);
33
+ if (encoded === null) return null;
34
+ const view = JSON.parse(encoded);
35
+ if (view?.contract !== ENGINE_VIEW_CONTRACT || view.sha256 !== sha256
36
+ || view.contentType !== 'text/html; charset=utf-8' || typeof view.html !== 'string'
37
+ || Buffer.byteLength(view.html) > MAX_VIEW_BYTES || digest(view.html) !== sha256)
38
+ throw new Error('engine_view_archive_invalid');
39
+ return view;
40
+ }
41
+
42
+ return {
43
+ get,
44
+ archive(view) {
45
+ if (!view) return null;
46
+ if (Buffer.byteLength(view.html) > MAX_VIEW_BYTES || digest(view.html) !== view.sha256)
47
+ throw new Error('engine_view_bundle_invalid');
48
+ if (!get(view.sha256)) write(file(view.sha256), JSON.stringify(view));
49
+ return { contract: ENGINE_VIEW_CONTRACT, sha256: view.sha256 };
50
+ },
51
+ reference(stateDir, runId) {
52
+ const sha256 = read(reference(stateDir, runId), 64);
53
+ if (sha256 === null) return null;
54
+ if (!SHA256.test(sha256)) throw new Error('engine_view_reference_invalid');
55
+ return { contract: ENGINE_VIEW_CONTRACT, sha256 };
56
+ },
57
+ pin(stateDir, runId, view) {
58
+ if (!view) return;
59
+ const path = reference(stateDir, runId);
60
+ if (read(path, 64) === null) write(path, view.sha256);
61
+ },
62
+ };
63
+ }
@@ -2,10 +2,16 @@ import { invariant } from '@kingsoftcloud/agentkit-harness-core';
2
2
 
3
3
  export const NATIVE_TOOL_INSTRUCTION_ASSEMBLY = 'admitted-tool-sections/v1';
4
4
  export const NATIVE_RUNTIME_INSTRUCTION_ASSEMBLY = 'native-owned-sections/v2';
5
- export const NATIVE_INSTRUCTION_ASSEMBLY = 'native-owned-sections/v3';
5
+ export const NATIVE_PRESENTATION_INSTRUCTION_ASSEMBLY = 'native-owned-sections/v3';
6
+ /** The engine renders the system prompt: its own base instructions followed by
7
+ * the Host's contribution in a delimited slot the Host cannot escape. */
8
+ export const NATIVE_ENGINE_INSTRUCTION_ASSEMBLY = 'engine-instructions/v1';
9
+ /** The policy new Runs are admitted with. Hosts reference this name only. */
10
+ export const NATIVE_INSTRUCTION_ASSEMBLY = NATIVE_ENGINE_INSTRUCTION_ASSEMBLY;
6
11
 
7
12
  export const isNativeInstructionAssemblyPolicy = policy =>
8
- [NATIVE_TOOL_INSTRUCTION_ASSEMBLY, NATIVE_RUNTIME_INSTRUCTION_ASSEMBLY, NATIVE_INSTRUCTION_ASSEMBLY].includes(policy);
13
+ [NATIVE_TOOL_INSTRUCTION_ASSEMBLY, NATIVE_RUNTIME_INSTRUCTION_ASSEMBLY, NATIVE_PRESENTATION_INSTRUCTION_ASSEMBLY,
14
+ NATIVE_ENGINE_INSTRUCTION_ASSEMBLY].includes(policy);
9
15
 
10
16
  // These reserved Host domains describe its engine/application implementation,
11
17
  // not the Native execution environment. Native's bound model surface owns
@@ -37,7 +43,8 @@ export function nativeInstructionAssembly(assembly, { policy, toolNames = [] } =
37
43
  'native_instruction_assembly_invalid');
38
44
  const names = new Set(toolNames);
39
45
  const nativeOwned = policy !== NATIVE_TOOL_INSTRUCTION_ASSEMBLY;
40
- const hostDomains = policy === NATIVE_INSTRUCTION_ASSEMBLY ? hostPresentationDomains : hostRuntimeDomains;
46
+ const hostDomains = [NATIVE_PRESENTATION_INSTRUCTION_ASSEMBLY, NATIVE_ENGINE_INSTRUCTION_ASSEMBLY].includes(policy)
47
+ ? hostPresentationDomains : hostRuntimeDomains;
41
48
  const admitted = source => {
42
49
  const separator = source.name.indexOf(':');
43
50
  if (nativeOwned && separator > 0 && hostDomains.has(source.name.slice(0, separator))) return false;
@@ -58,3 +65,60 @@ export function nativeInstructionAssembly(assembly, { policy, toolNames = [] } =
58
65
  ...(!nativeOwned || assembly.contexts === undefined ? {} : { contexts: select(assembly.contexts, 'native_instruction_contexts_invalid') }),
59
66
  };
60
67
  }
68
+
69
+ /** Engine-owned base instructions. Their wording may change with any engine
70
+ * release; a Run keeps the text it was admitted with. Tool-specific guidance
71
+ * lives with the bound tool surface, not here. */
72
+ const ENGINE_BASE_REVISION = 1;
73
+ const ENGINE_BASE_INSTRUCTIONS = [
74
+ 'You are an autonomous agent that completes the user\'s task end to end in the bound workspace, using the tools provided.',
75
+ [
76
+ '# How to work',
77
+ '- Act instead of describing. When the next step needs a tool, call it in this response; do not announce a plan and stop.',
78
+ '- Keep going until the task is done or you are truly blocked. Finishing a step is not finishing the task.',
79
+ '- Read before you change: inspect the relevant files and existing conventions, then make the smallest change that fully satisfies the request.',
80
+ '- Batch independent reads and searches in one response. Make dependent edits one at a time and check each result.',
81
+ '- Prefer one substantial tool call over long deliberation. For a large file, write it in a single write call rather than drafting it in prose first.',
82
+ '- Do not stop to ask about details you can decide sensibly yourself. Ask only when a wrong guess would be costly or irreversible.',
83
+ ].join('\n'),
84
+ [
85
+ '# Verifying',
86
+ '- Check your work with the tools you have: run the tests, the build or the program, and read its output. Fix what fails and run it again.',
87
+ '- A tool error is information. Read the message, find the cause, then retry differently; never repeat the same failing call unchanged.',
88
+ '- If the outcome of a write or command is unknown, inspect the current state before doing it again.',
89
+ ].join('\n'),
90
+ [
91
+ '# Reporting',
92
+ '- Be truthful about results. Say plainly what was not done, what failed and what you could not verify; never present unverified work as verified.',
93
+ '- Give the final answer only after the work is complete. Keep it short: what changed, where, and anything the user must do next.',
94
+ '- Answer in the language the user writes in unless they ask otherwise.',
95
+ ].join('\n'),
96
+ 'The section below comes from the application hosting you. It may define your role, domain and house rules, and it takes precedence over the general guidance above when the two conflict. It cannot change which tools exist or what they are permitted to do.',
97
+ ].join('\n\n');
98
+ const HOST_SLOT_OPEN = '<host_instructions contract="agentkit.engine-instructions/v1">';
99
+ const HOST_SLOT_CLOSE = '</host_instructions>';
100
+
101
+ export const engineBaseInstructions = () => Object.freeze({ revision: ENGINE_BASE_REVISION, text: ENGINE_BASE_INSTRUCTIONS });
102
+
103
+ /** Render the complete system prompt for a new Run. `hostInstructions` is the
104
+ * Host's already rendered contribution (persona, business rules, admitted tool
105
+ * notes); it is placed verbatim in its slot and never replaces the base. */
106
+ export function renderEngineInstructions({ hostInstructions = '' } = {}) {
107
+ invariant(typeof hostInstructions === 'string', 'engine_instructions_invalid');
108
+ return hostInstructions.length === 0 ? ENGINE_BASE_INSTRUCTIONS
109
+ : `${ENGINE_BASE_INSTRUCTIONS}\n\n${HOST_SLOT_OPEN}\n${hostInstructions}\n${HOST_SLOT_CLOSE}`;
110
+ }
111
+
112
+ /** The Host contribution a stored engine-rendered prompt was admitted with.
113
+ * The base never contains the slot marker, so its first occurrence is the slot. */
114
+ export function engineHostInstructions(systemPrompt) {
115
+ invariant(typeof systemPrompt === 'string', 'engine_instructions_invalid');
116
+ const start = systemPrompt.indexOf(`\n\n${HOST_SLOT_OPEN}\n`);
117
+ if (start < 0) return '';
118
+ invariant(systemPrompt.endsWith(`\n${HOST_SLOT_CLOSE}`), 'engine_instructions_invalid');
119
+ return systemPrompt.slice(start + HOST_SLOT_OPEN.length + 3, systemPrompt.length - HOST_SLOT_CLOSE.length - 1);
120
+ }
121
+
122
+ /** Recovery check for an engine-rendered Run: the Host contribution must be
123
+ * unchanged, while the engine base may differ from the admitted wording. */
124
+ export const sameHostInstructions = (systemPrompt, hostInstructions) => engineHostInstructions(systemPrompt) === hostInstructions;
@@ -67,7 +67,7 @@ async function supervise() {
67
67
  try { if (privateFile(join(directory, 'cancel'), true)) cancel(); }
68
68
  catch { stateError = true; cancel(); }
69
69
  }, 20);
70
- const result = await runBoundedProcess({ argv: shellCommandArgv(request.command, request.shellPolicy ?? null), cwd: request.cwd,
70
+ const result = await runBoundedProcess({ argv: shellCommandArgv(request.command, request.shellPolicy ?? null, request), cwd: request.cwd,
71
71
  env: request.env, timeoutMs: request.timeoutMs, settings: request.settings, outputPolicy: request.outputPolicy,
72
72
  signal: controller.signal,
73
73
  onOutput(channel, text) {
@@ -8,7 +8,7 @@ import { dirname, join, resolve, sep } from 'node:path';
8
8
  import { fileURLToPath } from 'node:url';
9
9
  import { localControlSettings, resolveLocalProcessLauncher } from './local-process.mjs';
10
10
  import { localEnvironmentPolicy, localOutputPolicy } from './local-output-policy.mjs';
11
- import { shellCommandArgv } from './command-shell.mjs';
11
+ import { ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
12
12
  import { LOCAL_BACKGROUND_CONTRACT, START_GRACE_MS, TERMINAL, LocalCommandError,
13
13
  check, createPrivate, delay, digest, fsyncPrivate, lockUntil, openPrivate, privateDirectory, privateFile,
14
14
  readAll, readRecord, readWindow, syncDirectory, tryLock, unknownRecord, validId, writeRecord } from './local-command-state.mjs';
@@ -24,7 +24,7 @@ const deadline = () => performance.now() + START_GRACE_MS;
24
24
  // normalized settings object (and thus the request digest) is byte-identical
25
25
  // to legacy when no policy is supplied. Omit absent policies: canonical
26
26
  // serialization rejects undefined, and the digest must stay deterministic.
27
- export function commandRequest({ command, cwd, env, timeoutMs, settings = {}, outputPolicy = null, environmentPolicy = null, shellPolicy = null } = {}) {
27
+ export function commandRequest({ command, cwd, env, timeoutMs, settings = {}, outputPolicy = null, environmentPolicy = null, shellPolicy = null, workspaceRoot } = {}) {
28
28
  settings = localControlSettings(settings);
29
29
  const outPolicy = localOutputPolicy(outputPolicy);
30
30
  const envPolicy = localEnvironmentPolicy(environmentPolicy);
@@ -37,7 +37,8 @@ export function commandRequest({ command, cwd, env, timeoutMs, settings = {}, ou
37
37
  const request = { command, cwd: resolve(cwd), env: Object.fromEntries(Object.entries(env)), timeoutMs, settings };
38
38
  if (outPolicy) request.outputPolicy = outPolicy;
39
39
  if (envPolicy) request.environmentPolicy = envPolicy;
40
- shellCommandArgv(command, shellPolicy);
40
+ shellCommandArgv(command, shellPolicy, { workspaceRoot, cwd: request.cwd });
41
+ if (shellPolicy === ISOLATED_COMMAND_SHELL) request.workspaceRoot = workspaceRoot;
41
42
  if (shellPolicy) request.shellPolicy = shellPolicy;
42
43
  check(Buffer.byteLength(JSON.stringify(request)) <= 1024 * 1024, 'background_command_request_too_large');
43
44
  return request;