@kingsoftcloud/agentkit-harness-node 0.0.18 → 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.
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
  };
@@ -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
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-node",
3
- "version": "0.0.18",
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.",
@@ -154,7 +154,7 @@
154
154
  "src/package-integrity.mjs"
155
155
  ],
156
156
  "dependencies": {
157
- "@kingsoftcloud/agentkit-harness-core": "0.0.18",
157
+ "@kingsoftcloud/agentkit-harness-core": "0.0.19",
158
158
  "@astral-sh/ruff-wasm-nodejs": "0.16.8",
159
159
  "parse5": "7.3.0",
160
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 });
@@ -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
+ }
@@ -184,7 +184,7 @@ export function admitHostTools(tools, reserved, durableApprovals = false, hostRe
184
184
  * tool and resolves to `{ status: 'ok' | 'error', content }`. */
185
185
  export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId, scope, model, authorize, callHostTool,
186
186
  callHostContext, callHostHook, callHostVerification, callHostReceipt, owner = `engine-${process.pid}`,
187
- fetchImpl = fetch, sourceEnv = process.env, commandSandbox, subAgents, runStore } = {}) {
187
+ fetchImpl = fetch, sourceEnv = process.env, commandSandbox, subAgents, runStore, onStream } = {}) {
188
188
  invariant(text(workspaceRoot) && text(stateDir) && text(sessionId) && typeof authorize === 'function'
189
189
  && scope && ['tenantId', 'workspaceId', 'userId', 'agentId'].every(key => text(scope[key])), 'engine_runtime_invalid');
190
190
  const root = realpathSync(resolve(workspaceRoot));
@@ -362,7 +362,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
362
362
  return engineUserObservations(store, request.scope, snapshot, { indexes });
363
363
  }),
364
364
  artifacts, background, ...(children ? { children: children.owner } : {}) };
365
- const kernel = new NativeKernel({ store, owner, digest, ports });
365
+ const kernel = new NativeKernel({ store, owner, digest, ports, onStream });
366
366
 
367
367
  function prepareRun({ runId, objective, conversation, inputImages, hostInstructions = '', hostTools, toolPolicy,
368
368
  hostContext, hostHooks, hostVerification, executionPolicy, preset: presetName, maxModelCalls = null,
@@ -27,7 +27,7 @@ import { readFileSync, realpathSync } from 'node:fs';
27
27
  import * as readline from 'node:readline';
28
28
  import { setTimeout as wait } from 'node:timers/promises';
29
29
  import { fileURLToPath } from 'node:url';
30
- import { isNativeError, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
30
+ import { currentDeliveryManifest, FINAL_SUBMISSION_TOOL, isNativeError, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
31
31
  import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
32
32
  import { createEngineRuntime, engineApprovalSubject, ENGINE_APPROVAL_CONTRACT, ENGINE_EXECUTION_POLICY,
33
33
  ENGINE_INPUT_IMAGES } from './engine-runtime.mjs';
@@ -37,17 +37,23 @@ import { ENGINE_CONTEXT } from './engine-context.mjs';
37
37
  import { ENGINE_HOOKS } from './engine-hooks.mjs';
38
38
  import { ENGINE_HOST_EFFECT, hostReceiptReply, hostReceiptSource, waitForHostReceipt } from './engine-host-effects.mjs';
39
39
  import { ENGINE_VERIFICATION } from './engine-verification.mjs';
40
+ import { nativeTodoPlan } from './activity-status.mjs';
41
+ import { engineDeliveryEvidence } from './engine-delivery-evidence.mjs';
40
42
  export { ENGINE_VIEW_CONTRACT };
41
43
 
42
44
  export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
43
45
  export const ENGINE_EVENT_SCHEMA = 'agentkit.engine-event/v1';
46
+ const THINKING_PAGE_CHARS = 8192;
47
+ const THINKING_HISTORY_CHARS = 128 * 1024;
44
48
  const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/cancel', 'ui/view', 'shutdown'];
45
49
  const DURABLE_APPROVAL_METHOD = 'run/approve';
46
50
  const HOST_OBSERVATIONS_METHOD = 'run/host-observations';
47
51
  const ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602, internalError: -32603,
48
52
  notInitialized: -32010, runNotFound: -32011, runBusy: -32012 };
49
53
  const text = value => typeof value === 'string' && value.trim().length > 0;
54
+ const toolName = /^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/;
50
55
  const sleep = ms => new Promise(done => setTimeout(done, ms));
56
+ const publicRequestId = operationKey => createHash('sha256').update(operationKey).digest('hex');
51
57
 
52
58
  /** The engine's own task view, built by agentkit-harness-ui into this package's dist. */
53
59
  let viewCache;
@@ -67,14 +73,35 @@ function packageVersion() {
67
73
 
68
74
  /** Stable, host-renderable projection. Engine-internal payloads stay in the Run
69
75
  * store; a host renders `kind`, `title` and `detail` without knowing each kind. */
70
- export function projectEngineEvent(event, requiredVerification = false) {
76
+ export function projectEngineEvent(event, requiredVerification = false, thinkingPresentation = false) {
71
77
  const payload = event.payload ?? {}, base = { schema: ENGINE_EVENT_SCHEMA, seq: event.seq, kind: event.kind };
78
+ const modelRequest = thinkingPresentation && typeof payload.operationKey === 'string'
79
+ ? { requestId: publicRequestId(payload.operationKey) } : {};
72
80
  switch (event.kind) {
73
- case 'model.completed': return { ...base, category: 'model', title: payload.kind ?? 'model',
81
+ case 'todo.initialized':
82
+ case 'todo.updated':
83
+ return { ...base, category: 'todo',
84
+ ...(thinkingPresentation && Array.isArray(payload.todos) ? { plan: nativeTodoPlan(payload.todos) } : {}) };
85
+ case 'effect.prepared':
86
+ case 'effect.settled':
87
+ return thinkingPresentation && payload.kind === 'model' ? { ...base, category: 'model', title: 'request', ...modelRequest }
88
+ : { ...base, category: 'effect' };
89
+ case 'model.completed':
90
+ case 'model.stream_interrupted': {
91
+ let thinking = '';
92
+ for (const { event: display } of thinkingPresentation ? payload.displayStream?.records ?? [] : []) {
93
+ if (display?.kind !== 'thinking' || typeof display.text !== 'string') continue;
94
+ thinking += display.text.slice(0, THINKING_HISTORY_CHARS - thinking.length);
95
+ if (thinking.length === THINKING_HISTORY_CHARS) break;
96
+ }
97
+ if (event.kind === 'model.stream_interrupted') return { ...base, category: 'model', ...(text(thinking) ? { thinking, ...modelRequest } : {}) };
98
+ return { ...base, category: 'model', title: payload.kind ?? 'model',
99
+ ...(text(thinking) ? { thinking, ...modelRequest } : {}),
74
100
  ...(text(payload.text) && !(requiredVerification && payload.kind === 'final_candidate') ? { detail: payload.text } : {}),
75
101
  ...(Array.isArray(payload.toolCalls) && payload.toolCalls.length ? { tools: payload.toolCalls.map(call => call.name),
76
102
  calls: payload.toolCalls.map(call => ({ callId: call.callId, name: call.name, arguments: bounded(call.arguments) })) } : {}),
77
103
  ...(payload.usage ? { usage: { inputTokens: payload.usage.inputTokens, outputTokens: payload.usage.outputTokens } } : {}) };
104
+ }
78
105
  case 'tool.completed': return { ...base, category: 'tool', title: payload.name, status: payload.status,
79
106
  ...(text(payload.callId) ? { callId: payload.callId } : {}), ...(payload.content === undefined ? {} : { result: bounded(payload.content) }) };
80
107
  case 'approval.requested': return { ...base, category: 'approval', title: payload.name, status: 'pending',
@@ -108,6 +135,28 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
108
135
  const frames = readline.createInterface({ input, crlfDelay: Infinity });
109
136
  const send = frame => output.write(`${JSON.stringify(frame)}\n`);
110
137
  const pending = new Map(), active = new Map(), driven = new Set(), receiptWaits = new Map();
138
+ const liveModelDisplay = new Map();
139
+ function captureModelDisplay({ runId, operationKey }, event) {
140
+ if (!['thinking', 'tool_delta'].includes(event.kind)) return;
141
+ let current = liveModelDisplay.get(runId);
142
+ if (current?.operationKey !== operationKey) {
143
+ current = { operationKey, id: randomUUID(), text: '', end: 0, tools: new Map(), draftRevision: 0 };
144
+ liveModelDisplay.set(runId, current);
145
+ }
146
+ if (event.kind === 'thinking') {
147
+ current.end += event.text.length;
148
+ current.text = (current.text + event.text).slice(-THINKING_HISTORY_CHARS);
149
+ return;
150
+ }
151
+ // A draft has no call ID, argument data, or authority to execute.
152
+ const { index, name } = event.metadata ?? {};
153
+ if (!Number.isSafeInteger(index) || index < 0 || !current.tools.has(index) && current.tools.size >= 16) return;
154
+ if (name === FINAL_SUBMISSION_TOOL) return;
155
+ const label = typeof name === 'string' && toolName.test(name) ? name : current.tools.get(index) ?? 'tool';
156
+ if (current.tools.get(index) === label) return;
157
+ current.tools.set(index, label);
158
+ current.draftRevision++;
159
+ }
111
160
  let host = null, runtime = null, runtimePromise, closing = false;
112
161
  const viewRef = viewStore ? viewStore.archive(engineView()) : null;
113
162
 
@@ -217,7 +266,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
217
266
  if (!detachOnShutdown || !controller.signal.aborted)
218
267
  log(`run ${runId} stopped: ${isNativeError(error) ? error.code : publicErrorMessage(error)}`);
219
268
  })
220
- .finally(() => active.delete(runId));
269
+ .finally(() => { active.delete(runId); liveModelDisplay.delete(runId); });
221
270
  active.set(runId, { controller, done });
222
271
  };
223
272
  const lookup = runId => {
@@ -240,7 +289,9 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
240
289
  async initialize(params) {
241
290
  const offered = Array.isArray(params?.protocolVersions) ? params.protocolVersions : [];
242
291
  if (!offered.includes(ENGINE_PROTOCOL)) throw rpcError(ERRORS.params, 'no common protocol version', { supported: [ENGINE_PROTOCOL] });
243
- host = { name: text(params.host?.name) ? params.host.name : 'unknown',
292
+ // A history reader can open a cold session without replacing the
293
+ // callbacks and approval authority of a concurrent execution owner.
294
+ if (params.host?.observeOnly !== true || !host) host = { name: text(params.host?.name) ? params.host.name : 'unknown',
244
295
  services: { approvals: params.services?.approvals === true, tools: params.services?.tools === true,
245
296
  context: detachOnShutdown && params.services?.context === ENGINE_CONTEXT,
246
297
  hooks: detachOnShutdown && params.services?.hooks === ENGINE_HOOKS,
@@ -251,7 +302,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
251
302
  durableApprovals: detachOnShutdown && params.services?.durableApprovals === true } };
252
303
  runtimePromise ??= createEngineRuntime({ workspaceRoot: startup.workspace, stateDir: startup.stateDir, sessionId: startup.sessionId,
253
304
  scope: startup.scope, authorize, callHostTool, callHostContext, callHostHook, callHostVerification, callHostReceipt, fetchImpl, sourceEnv: env,
254
- commandSandbox: startup.commandSandbox,
305
+ commandSandbox: startup.commandSandbox, onStream: captureModelDisplay,
255
306
  subAgents: detachOnShutdown ? startup.subAgents : undefined,
256
307
  model: { ...startup.model, apiKey: async () => env[startup.model.apiKeyEnv] ?? '' } })
257
308
  .catch(error => { runtimePromise = null; throw error; });
@@ -259,7 +310,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
259
310
  return { protocolVersion: ENGINE_PROTOCOL, engine: { name: '@kingsoftcloud/agentkit-harness-node', version: packageVersion(), ...runtime.info() },
260
311
  capabilities: { methods: detachOnShutdown ? [...METHODS, DURABLE_APPROVAL_METHOD,
261
312
  ...(host.services.toolEffects ? [HOST_OBSERVATIONS_METHOD] : [])] : METHODS,
262
- eventSchema: ENGINE_EVENT_SCHEMA, hostServices: ['approvals', 'tools'],
313
+ eventSchema: ENGINE_EVENT_SCHEMA, liveThinking: true, liveToolDrafts: true, hostServices: ['approvals', 'tools'],
263
314
  approvals: host.services.durableApprovals ? 'durable' : host.services.approvals ? 'host' : startup.approval,
264
315
  hostTools: host.services.tools, toolPolicy: ENGINE_TOOL_POLICY, executionPolicy: ENGINE_EXECUTION_POLICY,
265
316
  ...(detachOnShutdown ? { scopedHostRequests: true } : {}),
@@ -301,7 +352,12 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
301
352
  if (!params.hostContext?.sources?.length && !params.hostHooks?.hooks?.length && !hostEffects && !params.hostVerification) drive(runId);
302
353
  return { ...status(runId), preset: started.preset, hostTools: started.hostTools, existing: false };
303
354
  },
304
- async 'run/status'(params) { requireRun(params); return status(params.runId); },
355
+ async 'run/status'(params) {
356
+ requireRun(params);
357
+ const rest = status(params.runId);
358
+ return params.deliveryPresentation === true && rest.phase === 'completed' && text(rest.finalText)
359
+ ? { ...rest, deliveryEvidence: engineDeliveryEvidence(runtime.load(params.runId)) } : rest;
360
+ },
305
361
  async [HOST_OBSERVATIONS_METHOD](params) {
306
362
  if (!host.services.toolEffects) throw rpcError(ERRORS.method, 'host observations unavailable');
307
363
  requireRun(params);
@@ -319,15 +375,45 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
319
375
  if (!idle || hasReceipt || runtime.pendingCommands(runId).length) drive(runId);
320
376
  }
321
377
  const cursor = Number.isSafeInteger(params.cursor) && params.cursor >= 0 ? params.cursor : 0;
378
+ const thinkingPresentation = typeof params.thinkingCursor === 'string';
379
+ const draftPresentation = typeof params.toolDraftCursor === 'string';
380
+ const thinkingCursor = thinkingPresentation ? /^([\da-f-]{36}):(\d{1,16})$/.exec(params.thinkingCursor) : null;
322
381
  const deadline = Date.now() + Math.min(Math.max(Number(params.waitMs) || 0, 0), 30000);
323
382
  // The wait reads only the journal suffix; the Run record is loaded once, on return.
324
383
  for (;;) {
325
384
  const running = active.has(params.runId), events = runtime.events(params.runId, cursor);
326
- if (events.length || !running || Date.now() >= deadline) {
385
+ const live = (thinkingPresentation || draftPresentation) && running ? liveModelDisplay.get(runId) : null;
386
+ let thinking, toolDraft;
387
+ if (live) {
388
+ const first = live.end - live.text.length;
389
+ const after = thinkingCursor?.[1] === live.id ? Number(thinkingCursor[2]) : first;
390
+ const start = Math.max(first, after);
391
+ const draftCursor = `${live.id}:${live.draftRevision}`;
392
+ const hasThinking = thinkingPresentation && start < live.end;
393
+ const hasDraft = draftPresentation && live.draftRevision > 0 && draftCursor !== params.toolDraftCursor;
394
+ if ((hasThinking || hasDraft) && runtime.authority(runId).snapshot.pendingIntent === live.operationKey) {
395
+ if (hasThinking) {
396
+ const chunk = live.text.slice(start - first, start - first + THINKING_PAGE_CHARS);
397
+ thinking = { id: live.id, cursor: `${live.id}:${start + chunk.length}`, text: chunk };
398
+ }
399
+ if (hasDraft) toolDraft = { cursor: draftCursor, requestId: publicRequestId(live.operationKey),
400
+ tools: [...live.tools].map(([index, name]) => ({ index, name })) };
401
+ }
402
+ }
403
+ if (events.length || thinking || toolDraft || !running || Date.now() >= deadline) {
327
404
  const next = events.length ? events.at(-1).seq : cursor;
328
405
  if (next > (seen.get(params.runId) ?? 0)) seen.set(params.runId, next);
329
- return { events: events.map(event => projectEngineEvent(event, !!configuration.hostVerification)), cursor: next,
330
- terminal: runtime.terminal(runtime.authority(runId).snapshot), running: active.has(runId) };
406
+ const { snapshot } = runtime.authority(runId);
407
+ return { events: events.map(event => {
408
+ const projected = projectEngineEvent(event, !!configuration.hostVerification, thinkingPresentation || draftPresentation);
409
+ if (projected.kind !== 'run.terminal' || projected.title !== 'completed' || !text(projected.detail)) return projected;
410
+ const artifacts = currentDeliveryManifest(snapshot)?.artifacts;
411
+ return { ...projected, ...(artifacts?.length ? { deliverables: artifacts } : {}),
412
+ ...((thinkingPresentation || draftPresentation) ? { deliveryEvidence: engineDeliveryEvidence(runtime.load(runId)) } : {}) };
413
+ }), cursor: next,
414
+ ...(thinking ? { thinking } : {}),
415
+ ...(toolDraft ? { toolDraft } : {}),
416
+ terminal: runtime.terminal(snapshot), running: active.has(runId) };
331
417
  }
332
418
  await sleep(250);
333
419
  }