@kingsoftcloud/agentkit-harness-node 0.0.17 → 0.0.19

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 (43) hide show
  1. package/dist/engine-view.html +642 -0
  2. package/dist/index.mjs +18 -10
  3. package/dist/rpc-entry.mjs +18 -10
  4. package/package.json +16 -2
  5. package/src/native/activity-status.mjs +13 -8
  6. package/src/native/browser-workspace-server.mjs +22 -7
  7. package/src/native/child-owner.mjs +8 -4
  8. package/src/native/children.mjs +12 -7
  9. package/src/native/command-shell.mjs +28 -3
  10. package/src/native/engine-client.mjs +83 -0
  11. package/src/native/engine-context.mjs +47 -0
  12. package/src/native/engine-delivery-evidence.mjs +37 -0
  13. package/src/native/engine-hooks.mjs +53 -0
  14. package/src/native/engine-host-effects.mjs +98 -0
  15. package/src/native/engine-managed-delivery.mjs +65 -0
  16. package/src/native/engine-managed-host.mjs +75 -0
  17. package/src/native/engine-managed-service.mjs +249 -0
  18. package/src/native/engine-runtime.mjs +480 -0
  19. package/src/native/engine-server.mjs +540 -0
  20. package/src/native/engine-service.mjs +281 -0
  21. package/src/native/engine-tool-policy.mjs +29 -0
  22. package/src/native/engine-verification.mjs +111 -0
  23. package/src/native/engine-view-store.mjs +63 -0
  24. package/src/native/instruction-assembly.mjs +67 -3
  25. package/src/native/local-background-supervisor.mjs +1 -1
  26. package/src/native/local-background.mjs +4 -3
  27. package/src/native/local-command-tools.mjs +10 -7
  28. package/src/native/native-kernel-events.mjs +103 -0
  29. package/src/native/native-kernel-permit.mjs +95 -0
  30. package/src/native/native-managed-execution-grants.mjs +232 -0
  31. package/src/native/native-managed-injection.mjs +53 -0
  32. package/src/native/native-managed-interaction.mjs +192 -0
  33. package/src/native/native-managed-kernel-http.mjs +122 -0
  34. package/src/native/native-managed-kernel.mjs +922 -0
  35. package/src/native/native-managed-scoped-control.mjs +116 -0
  36. package/src/native/native-managed-session-frames.mjs +43 -0
  37. package/src/native/native-managed-teams-context.mjs +126 -0
  38. package/src/native/native-teams-callback-authority.mjs +73 -0
  39. package/src/native/native-teams-context-contract.mjs +272 -0
  40. package/src/native/native-teams-json.mjs +38 -0
  41. package/src/native/native-terminal-failure.mjs +53 -0
  42. package/src/native/sqlite-store.mjs +1 -0
  43. package/src/native/workspace-tools.mjs +2 -0
package/dist/index.mjs CHANGED
@@ -385,16 +385,25 @@ function foregroundReceiptState(record, ref, intent) {
385
385
  if (receipt?.status !== "committed" || result?.status !== "ok" || result.backgroundCommandFinished !== true || !result.backgroundCommandRef || canonical4(result.backgroundCommandRef) !== canonical4(ref) || result.content?.task_id !== ref.taskId || result.content.evidence_incomplete === true || !settledCommandStates.has(result.content.status)) return null;
386
386
  return result.content.status;
387
387
  }
388
- function nativeActivityStatus(record, { driving = false } = {}) {
389
- if (!record) return null;
390
- const { snapshot } = record;
391
- const todos = snapshot.todos?.items ?? [], occurrences = /* @__PURE__ */ new Map();
388
+ function nativeTodoPlan(todos) {
389
+ if (!todos.length) return null;
390
+ const occurrences = /* @__PURE__ */ new Map();
392
391
  const items = todos.slice(0, 512).map((todo) => {
393
392
  const digest = createHash2("sha256").update(todo.content).digest("hex");
394
393
  const occurrence = occurrences.get(digest) ?? 0;
395
394
  occurrences.set(digest, occurrence + 1);
396
395
  return { id: `todo:${digest}:${occurrence}`, content: todo.content, status: todo.status };
397
396
  });
397
+ return {
398
+ items,
399
+ completedCount: todos.filter((todo) => todo.status === "completed").length,
400
+ totalCount: todos.length,
401
+ omittedItems: Math.max(0, todos.length - items.length)
402
+ };
403
+ }
404
+ function nativeActivityStatus(record, { driving = false } = {}) {
405
+ if (!record) return null;
406
+ const { snapshot } = record;
398
407
  const observations = /* @__PURE__ */ new Map();
399
408
  for (const event of record.events ?? []) if (event.kind === "background.commands_observed")
400
409
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
@@ -418,12 +427,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
418
427
  runId: snapshot.runId,
419
428
  snapshotRevision: snapshot.revision,
420
429
  isRunning: driving,
421
- plan: todos.length ? {
422
- items,
423
- completedCount: todos.filter((todo) => todo.status === "completed").length,
424
- totalCount: todos.length,
425
- omittedItems: Math.max(0, todos.length - items.length)
426
- } : null,
430
+ plan: nativeTodoPlan(snapshot.todos?.items ?? []),
427
431
  terminals,
428
432
  omittedTerminals: commands.length - terminals.length
429
433
  };
@@ -1293,6 +1297,10 @@ var SqliteRunStore = class extends TransactionalRunStore {
1293
1297
  return scope;
1294
1298
  });
1295
1299
  };
1300
+ this.probe = () => {
1301
+ open();
1302
+ db.prepare("SELECT version FROM native_schema LIMIT 1").get();
1303
+ };
1296
1304
  this.close = () => {
1297
1305
  if (!closed) {
1298
1306
  db.close();
@@ -396,16 +396,25 @@ function foregroundReceiptState(record, ref, intent) {
396
396
  if (receipt?.status !== "committed" || result?.status !== "ok" || result.backgroundCommandFinished !== true || !result.backgroundCommandRef || canonical4(result.backgroundCommandRef) !== canonical4(ref) || result.content?.task_id !== ref.taskId || result.content.evidence_incomplete === true || !settledCommandStates.has(result.content.status)) return null;
397
397
  return result.content.status;
398
398
  }
399
- function nativeActivityStatus(record, { driving = false } = {}) {
400
- if (!record) return null;
401
- const { snapshot } = record;
402
- const todos = snapshot.todos?.items ?? [], occurrences = /* @__PURE__ */ new Map();
399
+ function nativeTodoPlan(todos) {
400
+ if (!todos.length) return null;
401
+ const occurrences = /* @__PURE__ */ new Map();
403
402
  const items = todos.slice(0, 512).map((todo) => {
404
403
  const digest2 = createHash2("sha256").update(todo.content).digest("hex");
405
404
  const occurrence = occurrences.get(digest2) ?? 0;
406
405
  occurrences.set(digest2, occurrence + 1);
407
406
  return { id: `todo:${digest2}:${occurrence}`, content: todo.content, status: todo.status };
408
407
  });
408
+ return {
409
+ items,
410
+ completedCount: todos.filter((todo) => todo.status === "completed").length,
411
+ totalCount: todos.length,
412
+ omittedItems: Math.max(0, todos.length - items.length)
413
+ };
414
+ }
415
+ function nativeActivityStatus(record, { driving = false } = {}) {
416
+ if (!record) return null;
417
+ const { snapshot } = record;
409
418
  const observations = /* @__PURE__ */ new Map();
410
419
  for (const event of record.events ?? []) if (event.kind === "background.commands_observed")
411
420
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
@@ -429,12 +438,7 @@ function nativeActivityStatus(record, { driving = false } = {}) {
429
438
  runId: snapshot.runId,
430
439
  snapshotRevision: snapshot.revision,
431
440
  isRunning: driving,
432
- plan: todos.length ? {
433
- items,
434
- completedCount: todos.filter((todo) => todo.status === "completed").length,
435
- totalCount: todos.length,
436
- omittedItems: Math.max(0, todos.length - items.length)
437
- } : null,
441
+ plan: nativeTodoPlan(snapshot.todos?.items ?? []),
438
442
  terminals,
439
443
  omittedTerminals: commands.length - terminals.length
440
444
  };
@@ -1304,6 +1308,10 @@ var SqliteRunStore = class extends TransactionalRunStore {
1304
1308
  return scope;
1305
1309
  });
1306
1310
  };
1311
+ this.probe = () => {
1312
+ open2();
1313
+ db.prepare("SELECT version FROM native_schema LIMIT 1").get();
1314
+ };
1307
1315
  this.close = () => {
1308
1316
  if (!closed) {
1309
1317
  db.close();
package/package.json CHANGED
@@ -1,12 +1,24 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-node",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Standalone Native Harness Node adapters: a durable SQLite run store, a one-request model HTTP port, and a minimal versioned JSON-RPC 2.0 over NDJSON process entry. Reuses the shared Native adapter implementations and externalizes @kingsoftcloud/agentkit-harness-core; depends on no Studio/DSH code at runtime.",
7
7
  "exports": {
8
8
  ".": "./dist/index.mjs",
9
9
  "./rpc-entry": "./dist/rpc-entry.mjs",
10
+ "./native/engine-runtime": "./src/native/engine-runtime.mjs",
11
+ "./native/engine-server": "./src/native/engine-server.mjs",
12
+ "./native/engine-client": "./src/native/engine-client.mjs",
13
+ "./native/managed-kernel": "./src/native/native-managed-kernel.mjs",
14
+ "./native/managed-kernel-http": "./src/native/native-managed-kernel-http.mjs",
15
+ "./native/managed-scoped-control": "./src/native/native-managed-scoped-control.mjs",
16
+ "./native/teams-callback-authority": "./src/native/native-teams-callback-authority.mjs",
17
+ "./native/teams-context-contract": "./src/native/native-teams-context-contract.mjs",
18
+ "./native/kernel-events": "./src/native/native-kernel-events.mjs",
19
+ "./native/terminal-failure": "./src/native/native-terminal-failure.mjs",
20
+ "./native/kernel-permit": "./src/native/native-kernel-permit.mjs",
21
+ "./native/teams-json": "./src/native/native-teams-json.mjs",
10
22
  "./native/a2a-tools": "./src/native/a2a-tools.mjs",
11
23
  "./native/artifact-codec": "./src/native/artifact-codec.mjs",
12
24
  "./native/artifact-store": "./src/native/artifact-store.mjs",
@@ -127,6 +139,8 @@
127
139
  "./package-integrity": "./src/package-integrity.mjs"
128
140
  },
129
141
  "bin": {
142
+ "agentkit-engine": "./src/native/engine-server.mjs",
143
+ "agentkit-engine-service": "./src/native/engine-service.mjs",
130
144
  "agentkit-native-rpc": "./dist/rpc-entry.mjs"
131
145
  },
132
146
  "files": [
@@ -140,7 +154,7 @@
140
154
  "src/package-integrity.mjs"
141
155
  ],
142
156
  "dependencies": {
143
- "@kingsoftcloud/agentkit-harness-core": "0.0.17",
157
+ "@kingsoftcloud/agentkit-harness-core": "0.0.19",
144
158
  "@astral-sh/ruff-wasm-nodejs": "0.16.8",
145
159
  "parse5": "7.3.0",
146
160
  "playwright-core": "1.58.2",
@@ -31,16 +31,23 @@ function foregroundReceiptState(record, ref, intent) {
31
31
  return result.content.status;
32
32
  }
33
33
 
34
- /** Content and lifecycle facts from committed task state; no control authority. */
35
- export function nativeActivityStatus(record, { driving = false } = {}) {
36
- if (!record) return null;
37
- const { snapshot } = record;
38
- const todos = snapshot.todos?.items ?? [], occurrences = new Map();
34
+ /** A bounded presentation of the committed task checklist. */
35
+ export function nativeTodoPlan(todos) {
36
+ if (!todos.length) return null;
37
+ const occurrences = new Map();
39
38
  const items = todos.slice(0, 512).map(todo => {
40
39
  const digest = createHash('sha256').update(todo.content).digest('hex');
41
40
  const occurrence = occurrences.get(digest) ?? 0; occurrences.set(digest, occurrence + 1);
42
41
  return { id: `todo:${digest}:${occurrence}`, content: todo.content, status: todo.status };
43
42
  });
43
+ return { items, completedCount: todos.filter(todo => todo.status === 'completed').length,
44
+ totalCount: todos.length, omittedItems: Math.max(0, todos.length - items.length) };
45
+ }
46
+
47
+ /** Content and lifecycle facts from committed task state; no control authority. */
48
+ export function nativeActivityStatus(record, { driving = false } = {}) {
49
+ if (!record) return null;
50
+ const { snapshot } = record;
44
51
  const observations = new Map();
45
52
  for (const event of record.events ?? []) if (event.kind === 'background.commands_observed')
46
53
  for (const command of event.payload.commands ?? []) observations.set(command.taskId, command);
@@ -56,8 +63,6 @@ export function nativeActivityStatus(record, { driving = false } = {}) {
56
63
  state: observed?.status ?? foregroundReceiptState(record, ref, intent) ?? 'unknown', canCancel: false };
57
64
  });
58
65
  return { contract: 'agentkit.native-activity-status/v1', runId: snapshot.runId, snapshotRevision: snapshot.revision,
59
- isRunning: driving, plan: todos.length ? { items,
60
- completedCount: todos.filter(todo => todo.status === 'completed').length, totalCount: todos.length,
61
- omittedItems: Math.max(0, todos.length - items.length) } : null,
66
+ isRunning: driving, plan: nativeTodoPlan(snapshot.todos?.items ?? []),
62
67
  terminals, omittedTerminals: commands.length - terminals.length };
63
68
  }
@@ -2,7 +2,7 @@
2
2
  import { createHash, randomBytes } from 'node:crypto';
3
3
  import { createServer } from 'node:http';
4
4
  import { constants, closeSync, fstatSync, lstatSync, openSync, readSync, readdirSync, realpathSync, statSync } from 'node:fs';
5
- import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
5
+ import { dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
6
  import { allowsWorkspaceBrowserUrl } from './browser-workspace-policy.mjs';
7
7
 
8
8
  const within = (root, path) => path === root || path.startsWith(root + sep);
@@ -65,11 +65,18 @@ export function resolveBrowserWorkspaceEntry(root, path) {
65
65
  }
66
66
 
67
67
  export async function createBrowserWorkspaceServer({ root, path, maxFileBytes = 32 * 1024 * 1024,
68
- maxFiles = 4096, signal } = {}) {
68
+ maxFiles = 4096, signal, interactivePreview = false, projectRoot, previewHost } = {}) {
69
69
  signal?.throwIfAborted();
70
70
  if (!Number.isSafeInteger(maxFileBytes) || maxFileBytes < 1 || maxFileBytes > 2 ** 30
71
71
  || !Number.isSafeInteger(maxFiles) || maxFiles < 1 || maxFiles > 65536) fail('browser_server_limits_invalid');
72
- const { workspace, entry, servedRoot } = resolveBrowserWorkspaceEntry(root, path);
72
+ const { workspace, entry, servedRoot: entryDirectory } = resolveBrowserWorkspaceEntry(root, path);
73
+ const servedRoot = projectRoot === undefined ? entryDirectory : bound(workspace, resolve(workspace, safeRelative(projectRoot)));
74
+ if (!within(servedRoot, entry) || !statSync(servedRoot).isDirectory()) fail('workspace_path_outside_scope');
75
+ const entryPath = relative(servedRoot, entry).split(sep);
76
+ const visible = path => path.split('/').every(part => !part.startsWith('.') && !ignored.has(part));
77
+ if (interactivePreview && (!visible(path) || !visible(relative(workspace, entry).split(sep).join('/')))) fail('workspace_path_invalid');
78
+ if (previewHost !== undefined && !/^(?:localhost|127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/i.test(previewHost))
79
+ fail('browser_preview_host_invalid');
73
80
  const prefix = `/${randomBytes(24).toString('hex')}/`, generated = new Map();
74
81
  let origin, closed = false, closing;
75
82
 
@@ -91,7 +98,12 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
91
98
  walk(servedRoot); return digest.digest('hex');
92
99
  }
93
100
 
94
- const initialRevision = revision();
101
+ const initialRevision = interactivePreview ? null : revision();
102
+ const frameAncestors = previewHost ? `http://${previewHost} https://${previewHost}` : "'none'";
103
+ const previewHeaders = interactivePreview ? {
104
+ 'content-security-policy': `default-src 'none'; script-src 'self' 'unsafe-inline' https:; style-src 'self' 'unsafe-inline' https:; img-src 'self' https: data: blob:; font-src 'self' https: data:; media-src 'self' https: data: blob:; connect-src 'self'; worker-src 'self' blob:; frame-ancestors ${frameAncestors}; base-uri 'self'; form-action 'none'`,
105
+ 'cross-origin-opener-policy': 'same-origin', 'cross-origin-resource-policy': 'same-origin', 'referrer-policy': 'no-referrer',
106
+ } : {};
95
107
  const server = createServer((request, response) => {
96
108
  const reply = (status, text) => { response.writeHead(status, { 'content-type': 'text/plain; charset=utf-8',
97
109
  'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }); response.end(text); };
@@ -102,6 +114,7 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
102
114
  const raw = request.url;
103
115
  if (!raw?.startsWith(prefix)) return reply(403, 'Outside browser page');
104
116
  const rawPath = raw.split('?')[0], pathname = decodeURIComponent(rawPath.slice(prefix.length));
117
+ if (interactivePreview && !visible(pathname)) return reply(403, 'Outside browser page');
105
118
  const lexical = resolve(servedRoot, pathname ? safeRelative(pathname) : '.');
106
119
  if (!within(servedRoot, lexical)) return reply(403, 'Outside browser page');
107
120
  let target = bound(servedRoot, lexical);
@@ -116,8 +129,9 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
116
129
  }
117
130
  }
118
131
  const { bytes, target: actual } = readBoundFile(servedRoot, target, maxFileBytes);
132
+ if (interactivePreview && !visible(relative(servedRoot, actual).split(sep).join('/'))) return reply(403, 'Outside browser page');
119
133
  response.writeHead(200, { 'content-type': types[extname(actual).toLowerCase()] ?? 'application/octet-stream',
120
- 'content-length': bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' });
134
+ 'content-length': bytes.length, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...previewHeaders });
121
135
  response.end(request.method === 'HEAD' ? undefined : bytes);
122
136
  } catch (error) {
123
137
  const status = error.code === 'browser_file_too_large' ? 413
@@ -135,7 +149,8 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
135
149
  const ready = () => { server.off('error', error); resolve(); };
136
150
  server.once('error', error); server.once('listening', ready); server.listen(0, '127.0.0.1');
137
151
  });
138
- origin = `http://127.0.0.1:${server.address().port}`;
152
+ const hostname = interactivePreview ? `preview-${randomBytes(12).toString('hex')}.localhost` : '127.0.0.1';
153
+ origin = `http://${hostname}:${server.address().port}`;
139
154
  signal?.throwIfAborted();
140
155
  } catch (error) { server.close(); server.closeAllConnections(); throw error; }
141
156
 
@@ -149,7 +164,7 @@ export async function createBrowserWorkspaceServer({ root, path, maxFileBytes =
149
164
  };
150
165
  const abort = () => { void close().catch(() => {}); };
151
166
  signal?.addEventListener('abort', abort, { once: true });
152
- return { workspace, servedRoot, entry, origin, url: `${origin}${prefix}${encodeURIComponent(basename(entry))}`, initialRevision,
167
+ return { workspace, servedRoot, entry, origin, url: `${origin}${prefix}${entryPath.map(encodeURIComponent).join('/')}`, initialRevision,
153
168
  revision, close,
154
169
  allows(value) {
155
170
  return allowsWorkspaceBrowserUrl(value, { origin, prefix, closed });
@@ -34,7 +34,7 @@ async function observeWhileLive(operation, signal) {
34
34
  * an environment/profile fallback. This service does not advertise model tools.
35
35
  */
36
36
  export function createNativeChildOwner({ scope, childScopes = [scope], store, resolveChild, restoreChild, waitForIdle, canWaitForReceipt, onStream, now = Date.now,
37
- childAllocationPolicy, admitRequirements, owner = `native-children-${randomUUID()}` }) {
37
+ childAllocationPolicy, admitRequirements, detachSignal, owner = `native-children-${randomUUID()}` }) {
38
38
  const parentScope = copy(scope), entries = new Map();
39
39
  scopeKey(parentScope);
40
40
  check(childAllocationPolicy === undefined || childAllocationPolicy === CHILD_ALLOCATION_POLICY, 'invalid_child_owner_allocation_policy');
@@ -120,15 +120,16 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
120
120
  entry.error = null;
121
121
  entry.promise = (async () => {
122
122
  for (;;) {
123
- const snapshot = await entry.kernel.runUntilIdle(entry.scope, entry.runId);
123
+ const snapshot = await entry.kernel.runUntilIdle(entry.scope, entry.runId, { detachSignal });
124
124
  if (terminal(snapshot.phase)) { entry.ports.tools.settleQuestions?.(snapshot); return; }
125
125
  const record = store.load(entry.scope, entry.runId);
126
126
  if (!canWaitForReceipt?.(record) || !entry.admitted()) return;
127
127
  const idle = new AbortController(); entry.idle = idle;
128
128
  try {
129
+ const signal = detachSignal ? AbortSignal.any([idle.signal, detachSignal]) : idle.signal;
129
130
  const command = await observeWhileLive(Promise.resolve().then(() => waitForIdle({
130
- snapshot: copy(snapshot), tools: entry.ports.tools, signal: idle.signal,
131
- })), idle.signal);
131
+ snapshot: copy(snapshot), tools: entry.ports.tools, signal,
132
+ })), signal);
132
133
  idle.signal.throwIfAborted();
133
134
  check(entry.admitted() && same(store.load(entry.scope, entry.runId).snapshot, snapshot), 'child_idle_authority_lost');
134
135
  if (!command) return;
@@ -629,6 +630,9 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
629
630
  }
630
631
  for (const entry of owned) entries.delete(entry.runId);
631
632
  },
633
+ async drain() {
634
+ await Promise.all([...entries.values()].map(entry => entry.promise));
635
+ },
632
636
  async closeRun(request) {
633
637
  check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
634
638
  const parent = store.load(parentScope, request.runId);
@@ -112,7 +112,7 @@ export function nativeChildRoles(spec = {}, { childAllocationPolicy } = {}) {
112
112
 
113
113
  /** Bind every child to a declared role and its own scoped tool state. */
114
114
  export async function createNativeChildren({ roles, scope, sessionId, store, tools, hasSkills, hasMcp, mcpBinding, skillBinding, skillInstructions, workspaceContext, instructionTimeoutRecovery,
115
- resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, outputRestartPolicy, approvalOutcomePolicy, conversationPresentation, toolExecutionPolicy, toolAdmissionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }) }) {
115
+ resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, detachSignal, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, outputRestartPolicy, approvalOutcomePolicy, conversationPresentation, toolExecutionPolicy, toolAdmissionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }), restrictTools }) {
116
116
  if (!roles.length) return null;
117
117
  if (workspaceContext !== undefined) {
118
118
  validateNativeWorkspaceContext(workspaceContext);
@@ -124,9 +124,9 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
124
124
  invariant(toolAdmissionPolicy === undefined || toolAdmissionPolicy === 'discover-before-retry/v1', 'studio_native_child_admission_policy_invalid');
125
125
  invariant(toolExecutionPolicy === undefined || toolExecutionPolicy === 'owner-execution/v1', 'studio_native_child_execution_policy_invalid');
126
126
  invariant(providerRecoveryPolicy === undefined || providerRecoveryPolicy === 'provider-recovery/v2', 'native_child_provider_recovery_policy_invalid');
127
- invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
127
+ invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
128
128
  invariant(outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(outputRestartPolicy)
129
- && ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'native_child_output_restart_policy_invalid');
129
+ && ['response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(outputRecoveryPolicy), 'native_child_output_restart_policy_invalid');
130
130
  invariant(approvalOutcomePolicy === undefined || approvalOutcomePolicy === 'owner-outcome/v1', 'native_child_approval_outcome_policy_invalid');
131
131
  if (conversationPresentation !== undefined) validateConversationPresentation(conversationPresentation);
132
132
  invariant(childTaskPolicy === undefined || childTaskPolicy === CHILD_TASK_POLICY, 'studio_native_child_task_policy_invalid');
@@ -187,14 +187,16 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
187
187
  ? createStudioNativeChildMerge({ scope, sessionId, store, roles, fileWorkspaces, isClosed,
188
188
  previousPublication: previousChildPublication, authorize: async () => 'allow' }) : null;
189
189
  const readers = createNativeChildResultTools({ scope, childScopes: roles.map(childScope), store, roles: roles.map(role => role.name) });
190
- const owner = createNativeChildOwner({ scope, onStream, childScopes: roles.map(childScope), store,
190
+ const owner = createNativeChildOwner({ scope, onStream, detachSignal, childScopes: roles.map(childScope), store,
191
191
  ...(childCapabilityPolicy ? { admitRequirements: args => admitChildCapabilities(
192
192
  [...bindings].map(([role, bound]) => ({ role, tools: bound.tools.map(tool => tool.name).sort() })), args.role, args.required_tools) } : {}),
193
193
  ...(childAllocationPolicy ? { childAllocationPolicy } : {}),
194
194
  ...(waitForChildReceipt ? { canWaitForReceipt: record => !!nativeA2aReceiptWaitSource(record), waitForIdle: waitForChildReceipt } : {}),
195
195
  resolveChild: async request => {
196
- const role = byName.get(request.role), bound = bindings.get(request.role);
197
- invariant(role && bound, 'studio_native_child_role_unbound');
196
+ const role = byName.get(request.role), available = bindings.get(request.role);
197
+ invariant(role && available, 'studio_native_child_role_unbound');
198
+ const bound = restrictTools ? { ...available, tools: restrictTools(available.tools,
199
+ store.authority(request.parent.scope, request.parent.runId).configuration) } : available;
198
200
  const args = request.call.arguments;
199
201
  const refs = args.media ?? [];
200
202
  invariant(Array.isArray(refs) && refs.length <= 20 && refs.every(ref => ref && typeof ref === 'object'
@@ -299,8 +301,10 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
299
301
  input: ports.input, store, scope: child, sessionId: request.childSessionId, tools: bound.tools }), verification } };
300
302
  },
301
303
  restoreChild: async ({ identity, configuration, binding }) => {
302
- const bound = bindings.get(binding.role), role = byName.get(binding.role);
304
+ const available = bindings.get(binding.role), role = byName.get(binding.role);
303
305
  const parent = store.load(binding.parent.scope, binding.parent.runId);
306
+ const bound = available && restrictTools
307
+ ? { ...available, tools: restrictTools(available.tools, parent.configuration) } : available;
304
308
  const call = parent.intents.find(item => item.operationKey === binding.parentOperationKey)?.payload.calls
305
309
  ?.find(item => item.callId === binding.parentToolCallId);
306
310
  invariant(call && role, 'studio_native_child_restore_binding_changed');
@@ -324,6 +328,7 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
324
328
  // Reconstruct the same normalized profile, rather than comparing it to
325
329
  // the Host's deliberately partial input and rejecting every live child.
326
330
  const profile = bound && configure({ profile: bound.model.profile, contract: configuration.contract,
331
+ limits: { effectTimeoutMs: configuration.limits.effectTimeoutMs },
327
332
  hostBindingDigest: configuration.hostBindingDigest }).profile;
328
333
  invariant(bound && role && canonical(configuration.tools) === canonical(bound.tools)
329
334
  && configuration.outputRecoveryPolicy === outputRecoveryPolicy
@@ -1,9 +1,34 @@
1
+ import { isAbsolute, relative, resolve, sep } from 'node:path';
2
+
1
3
  export const LOCAL_COMMAND_SHELL = 'bash-execution/v1';
4
+ export const ISOLATED_COMMAND_SHELL = 'bubblewrap-workspace/v1';
2
5
 
3
6
  /** A missing policy belongs to a persisted legacy request. Never reinterpret
4
7
  * it under a new shell during supervision/recovery. No PATH-based fallback.
5
8
  */
6
- export function shellCommandArgv(command, policy = null) {
7
- if (policy !== null && policy !== LOCAL_COMMAND_SHELL) throw Error('unsupported_command_shell');
8
- return [policy === LOCAL_COMMAND_SHELL ? '/bin/bash' : '/bin/sh', '-c', command];
9
+ export function shellCommandArgv(command, policy = null, { workspaceRoot, cwd } = {}) {
10
+ if (policy === null) return ['/bin/sh', '-c', command];
11
+ if (policy === LOCAL_COMMAND_SHELL) return ['/bin/bash', '-c', command];
12
+ if (policy !== ISOLATED_COMMAND_SHELL) throw Error('unsupported_command_shell');
13
+ if (process.platform !== 'linux' || typeof workspaceRoot !== 'string' || typeof cwd !== 'string'
14
+ || !isAbsolute(workspaceRoot) || !isAbsolute(cwd) || resolve(workspaceRoot) !== workspaceRoot
15
+ || resolve(cwd) !== cwd
16
+ || (workspaceRoot !== '/data/workspace' && !workspaceRoot.startsWith('/data/workspace/')))
17
+ throw Error('isolated_command_workspace_invalid');
18
+ const within = relative(workspaceRoot, cwd);
19
+ if (within === '..' || within.startsWith('..' + sep) || isAbsolute(within))
20
+ throw Error('isolated_command_cwd_outside_workspace');
21
+
22
+ // The managed image supplies Debian's usr-merged filesystem. Only the
23
+ // workspace and disposable tmpfs are writable. Neither the state volume nor
24
+ // the engine's PID namespace or deployment credential mounts are visible.
25
+ return ['/usr/bin/bwrap', '--unshare-user', '--unshare-pid', '--unshare-ipc', '--unshare-uts',
26
+ '--unshare-net', '--die-with-parent', '--new-session', '--cap-drop', 'ALL',
27
+ '--ro-bind', '/usr', '/usr', '--symlink', 'usr/bin', '/bin', '--symlink', 'usr/sbin', '/sbin',
28
+ '--symlink', 'usr/lib', '/lib', '--symlink', 'usr/lib64', '/lib64',
29
+ '--dir', '/proc', '--dev', '/dev', '--tmpfs', '/tmp',
30
+ '--ro-bind', '/etc/passwd', '/etc/passwd', '--ro-bind', '/etc/group', '/etc/group',
31
+ '--bind', workspaceRoot, workspaceRoot, '--chdir', cwd,
32
+ '--clearenv', '--setenv', 'PATH', '/usr/local/bin:/usr/bin:/bin', '--setenv', 'HOME', '/tmp',
33
+ '--setenv', 'LANG', 'C.UTF-8', '--setenv', 'CI', '1', '--', '/bin/bash', '-c', command];
9
34
  }
@@ -0,0 +1,83 @@
1
+ // Thin host-side client for agentkit.engine/v1.
2
+ //
3
+ // This file contains no engine logic and imports none: it frames JSON-RPC over
4
+ // a child process's stdio. A host may vendor it, or reimplement it in another
5
+ // language from the protocol alone. It needs to change only when the protocol
6
+ // major version changes.
7
+ import { spawn } from 'node:child_process';
8
+ import * as readline from 'node:readline';
9
+
10
+ export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
11
+
12
+ /** Connect to an engine over a pair of streams (a spawned process, a socket, or an in-memory pair in tests). */
13
+ export function connectEngine({ input, output, onApproveTool, onCallTool, hostName = 'host' }) {
14
+ let next = 1, closed = false;
15
+ const pending = new Map();
16
+ const send = frame => output.write(`${JSON.stringify(frame)}\n`);
17
+ const frames = readline.createInterface({ input, crlfDelay: Infinity });
18
+ const finished = (async () => {
19
+ for await (const line of frames) {
20
+ if (!line.trim()) continue;
21
+ let frame;
22
+ try { frame = JSON.parse(line); } catch { continue; }
23
+ if (frame.method !== undefined) {
24
+ // Engine -> host request. Unknown methods are refused, never guessed.
25
+ if (frame.method === 'host/approveTool' && typeof onApproveTool === 'function') {
26
+ Promise.resolve().then(() => onApproveTool(frame.params ?? {}))
27
+ .then(decision => send({ jsonrpc: '2.0', id: frame.id, result: { decision: decision === 'allow' ? 'allow' : 'deny' } }),
28
+ () => send({ jsonrpc: '2.0', id: frame.id, result: { decision: 'deny' } }));
29
+ } else if (frame.method === 'host/callTool' && typeof onCallTool === 'function') {
30
+ Promise.resolve().then(() => onCallTool(frame.params ?? {}))
31
+ .then(reply => send({ jsonrpc: '2.0', id: frame.id, result: { status: reply?.status === 'error' ? 'error' : 'ok', content: reply?.content ?? null } }),
32
+ error => send({ jsonrpc: '2.0', id: frame.id, result: { status: 'error', content: { code: 'host_tool_failed', message: String(error?.message ?? error).slice(0, 2000) } } }));
33
+ } else if (frame.id !== undefined) send({ jsonrpc: '2.0', id: frame.id, error: { code: -32601, message: 'Method not found' } });
34
+ continue;
35
+ }
36
+ const waiter = pending.get(frame.id);
37
+ if (!waiter) continue;
38
+ pending.delete(frame.id);
39
+ if (frame.error) waiter.reject(Object.assign(new Error(frame.error.message), { code: frame.error.code, data: frame.error.data }));
40
+ else waiter.resolve(frame.result);
41
+ }
42
+ closed = true;
43
+ for (const waiter of pending.values()) waiter.reject(new Error('engine connection closed'));
44
+ pending.clear();
45
+ })();
46
+ const call = (method, params = {}) => new Promise((resolve, reject) => {
47
+ if (closed) { reject(new Error('engine connection closed')); return; }
48
+ const id = next++;
49
+ pending.set(id, { resolve, reject });
50
+ send({ jsonrpc: '2.0', id, method, params });
51
+ });
52
+ return {
53
+ call, finished,
54
+ initialize: () => call('initialize', { protocolVersions: [ENGINE_PROTOCOL], host: { name: hostName },
55
+ services: { approvals: typeof onApproveTool === 'function', tools: typeof onCallTool === 'function' } }),
56
+ startRun: params => call('run/start', params),
57
+ status: runId => call('run/status', { runId }),
58
+ events: (runId, cursor = 0, waitMs = 0) => call('run/events', { runId, cursor, waitMs }),
59
+ resume: runId => call('run/resume', { runId }),
60
+ cancel: runId => call('run/cancel', { runId }),
61
+ view: () => call('ui/view'),
62
+ shutdown: () => call('shutdown'),
63
+ /** Follow a Run to rest, handing each projected event to `onEvent`. */
64
+ async follow(runId, onEvent = () => {}, { waitMs = 5000 } = {}) {
65
+ for (let cursor = 0; ;) {
66
+ const page = await call('run/events', { runId, cursor, waitMs });
67
+ for (const event of page.events) onEvent(event);
68
+ cursor = page.cursor;
69
+ if (!page.running && page.events.length === 0) return call('run/status', { runId });
70
+ }
71
+ },
72
+ };
73
+ }
74
+
75
+ /** Start an engine executable and connect to it. `command` is host configuration, not host code. */
76
+ export function spawnEngine({ command, args = [], env, onApproveTool, onCallTool, hostName, onLog = () => {} }) {
77
+ const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
78
+ child.stderr.setEncoding('utf8').on('data', chunk => onLog(chunk));
79
+ const client = connectEngine({ input: child.stdout, output: child.stdin, onApproveTool, onCallTool, hostName });
80
+ const exited = new Promise(resolve => child.once('exit', code => resolve(code)));
81
+ return { ...client, child, exited,
82
+ async close() { try { await client.shutdown(); } catch { /* already gone */ } child.stdin.end(); return exited; } };
83
+ }
@@ -0,0 +1,47 @@
1
+ import { invariant } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ export const ENGINE_CONTEXT = 'agentkit.engine-context/v1';
4
+ const MAX_SOURCES = 32;
5
+ const MAX_SOURCE_MS = 30000;
6
+ const SOURCE_ID = /^[a-z][a-z0-9._-]{0,127}$/;
7
+ const DIGEST = /^sha256:[a-f0-9]{64}$/;
8
+
9
+ export function admitEngineContextSources(value) {
10
+ if (value === undefined) return [];
11
+ invariant(value?.contract === ENGINE_CONTEXT
12
+ && Object.keys(value).every(key => key === 'contract' || key === 'sources') && Array.isArray(value.sources)
13
+ && value.sources.length <= MAX_SOURCES, 'engine_context_sources_invalid');
14
+ const seen = new Set();
15
+ return value.sources.map(source => {
16
+ invariant(source && typeof source === 'object'
17
+ && Object.keys(source).every(key => ['sourceId', 'bindingDigest', 'timeoutMs', 'maxTokens', 'maxBytes',
18
+ 'failureMode', 'allowInstructions'].includes(key))
19
+ && typeof source.sourceId === 'string' && SOURCE_ID.test(source.sourceId) && !seen.has(source.sourceId)
20
+ && typeof source.bindingDigest === 'string' && DIGEST.test(source.bindingDigest)
21
+ && Number.isSafeInteger(source.timeoutMs) && source.timeoutMs >= 1 && source.timeoutMs <= MAX_SOURCE_MS
22
+ && Number.isSafeInteger(source.maxTokens) && source.maxTokens >= 1 && source.maxTokens <= 1048576
23
+ && Number.isSafeInteger(source.maxBytes) && source.maxBytes >= 1 && source.maxBytes <= 131072
24
+ && ['skip', 'warn', 'fail'].includes(source.failureMode) && typeof source.allowInstructions === 'boolean',
25
+ 'engine_context_source_invalid');
26
+ seen.add(source.sourceId);
27
+ return { contract: 'agentkit.native-context-source/v1', sourceId: source.sourceId,
28
+ bindingDigest: source.bindingDigest, priority: 0, timeoutMs: source.timeoutMs, maxTokens: source.maxTokens,
29
+ maxBytes: source.maxBytes, required: source.failureMode === 'fail',
30
+ hostProjection: source.allowInstructions ? 'instructions-and-data/v1' : 'data/v1',
31
+ ...(source.failureMode === 'warn' ? { warnOnFailure: true } : {}) };
32
+ });
33
+ }
34
+
35
+ export function engineContextPort(port, callHostContext) {
36
+ return { ...port, async readSource({ source, snapshot, operationKey, signal, remainingTokens }) {
37
+ invariant(source.hostProjection && typeof callHostContext === 'function', 'engine_context_unavailable');
38
+ const reply = await callHostContext({
39
+ contract: ENGINE_CONTEXT, runId: snapshot.runId, turnId: snapshot.turnId, operationKey,
40
+ sourceId: source.sourceId, bindingDigest: source.bindingDigest,
41
+ goal: snapshot.goal, goalRevision: snapshot.goalRevision, remainingTokens,
42
+ }, source.timeoutMs, signal);
43
+ invariant(reply?.contract === ENGINE_CONTEXT && reply.sourceId === source.sourceId
44
+ && reply.bindingDigest === source.bindingDigest && Array.isArray(reply.items), 'engine_context_result_invalid');
45
+ return { items: reply.items };
46
+ } };
47
+ }
@@ -0,0 +1,37 @@
1
+ import { currentDeliveryManifest } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ const safePath = path => typeof path === 'string' && path.length <= 2048
4
+ && !/[\\:\u0000-\u001f\u007f?#]/u.test(path) && path.split('/').every(part => part && part !== '.' && part !== '..');
5
+ const screenshotPath = path => safePath(path) && /\.(?:png|jpe?g|webp)$/i.test(path);
6
+
7
+ /** Committed effects for this Run only. The snapshot's workspaceModifiedPaths
8
+ * also contains paths inherited from earlier Turns. */
9
+ export function engineDeliveryEvidence(record) {
10
+ const changes = new Map();
11
+ const screenshots = new Set();
12
+ for (const artifact of currentDeliveryManifest(record.snapshot)?.artifacts ?? []) {
13
+ if (artifact.kind === 'file' && screenshotPath(artifact.path)) screenshots.add(artifact.path);
14
+ }
15
+ const intents = new Map(record.intents.map(intent => [intent.operationKey, intent]));
16
+ for (const receipt of record.receipts) {
17
+ const intent = intents.get(receipt.operationKey);
18
+ if (receipt.status !== 'committed' || intent?.kind !== 'tool' || !Array.isArray(receipt.result?.results)) continue;
19
+ for (const [index, result] of receipt.result.results.entries()) {
20
+ const tool = intent.payload.calls?.[index]?.name;
21
+ const { path, diff_additions: added, diff_deletions: removed, screenshot_path: screenshot } = result.content ?? {};
22
+ if (tool === 'browser_inspect_workspace' && ['ok', 'error'].includes(result.status) && screenshotPath(screenshot)) screenshots.add(screenshot);
23
+ if (result.status !== 'ok') continue;
24
+ for (const changed of result.workspaceChangedPaths ?? []) {
25
+ if (!safePath(changed)) continue;
26
+ const counts = changed === path && [added, removed].every(value => Number.isSafeInteger(value) && value >= 0)
27
+ ? { added, removed } : {};
28
+ // Overlapping edits cannot be counted as a net diff from their tool deltas.
29
+ const first = !changes.has(changed);
30
+ changes.set(changed, { path: changed, ...(first ? counts : {}),
31
+ ...(tool === 'delete_workspace_file' ? { deleted: true } : {}) });
32
+ }
33
+ }
34
+ }
35
+ const files = [...changes.values()].filter(file => !screenshots.has(file.path));
36
+ return { files: files.slice(0, 96), screenshots: [...screenshots].slice(-8), truncated: files.length > 96 };
37
+ }