@kingsoftcloud/agentkit-harness-node 0.0.18 → 0.0.20

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.
@@ -0,0 +1,104 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { constants, closeSync, existsSync, readFileSync, unlinkSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { diffLines } from 'diff';
5
+ import { atomicPrivate, openPrivate, privateDirectory } from './local-command-state.mjs';
6
+ import { currentDeliveryManifest } from '@kingsoftcloud/agentkit-harness-core';
7
+
8
+ const safePath = path => typeof path === 'string' && path.length <= 2048
9
+ && !/[\\:\u0000-\u001f\u007f?#]/u.test(path) && path.split('/').every(part => part && part !== '.' && part !== '..');
10
+ const screenshotPath = path => safePath(path) && /\.(?:png|jpe?g|webp)$/i.test(path);
11
+
12
+ /** Committed effects for this Run only. The snapshot's workspaceModifiedPaths
13
+ * also contains paths inherited from earlier Turns. */
14
+ export function engineDeliveryEvidence(record, netChanges) {
15
+ const changes = new Map();
16
+ const screenshots = new Set();
17
+ for (const artifact of currentDeliveryManifest(record.snapshot)?.artifacts ?? []) {
18
+ if (artifact.kind === 'file' && screenshotPath(artifact.path)) screenshots.add(artifact.path);
19
+ }
20
+ const intents = new Map(record.intents.map(intent => [intent.operationKey, intent]));
21
+ for (const receipt of record.receipts) {
22
+ const intent = intents.get(receipt.operationKey);
23
+ if (receipt.status !== 'committed' || intent?.kind !== 'tool' || !Array.isArray(receipt.result?.results)) continue;
24
+ for (const [index, result] of receipt.result.results.entries()) {
25
+ const tool = intent.payload.calls?.[index]?.name;
26
+ const { path, diff_additions: added, diff_deletions: removed, screenshot_path: screenshot } = result.content ?? {};
27
+ if (tool === 'browser_inspect_workspace' && ['ok', 'error'].includes(result.status) && screenshotPath(screenshot)) screenshots.add(screenshot);
28
+ if (result.status !== 'ok') continue;
29
+ for (const changed of result.workspaceChangedPaths ?? []) {
30
+ if (!safePath(changed)) continue;
31
+ const counts = changed === path && [added, removed].every(value => Number.isSafeInteger(value) && value >= 0)
32
+ ? { added, removed } : {};
33
+ // Overlapping edits cannot be counted as a net diff from their tool deltas.
34
+ const first = !changes.has(changed);
35
+ changes.set(changed, { path: changed, ...(first ? counts : {}),
36
+ ...(tool === 'delete_workspace_file' ? { deleted: true } : {}) });
37
+ }
38
+ }
39
+ }
40
+ const files = [...changes.values()].filter(file => !screenshots.has(file.path)).flatMap(file => {
41
+ if (!netChanges) return [file];
42
+ const change = netChanges(file.path);
43
+ return change ? [change] : [];
44
+ });
45
+ return { files: files.slice(0, 96), screenshots: [...screenshots].slice(-8), truncated: files.length > 96,
46
+ ...(netChanges ? { basis: 'run-net-diff/v1' } : {}) };
47
+ }
48
+
49
+ /** Compare the two workspace observations, and only show paths evidenced by
50
+ * this Run's receipts. Never total individual edit deltas. */
51
+ export function deliveryNetChanges(before, after) {
52
+ return path => {
53
+ const old = Object.hasOwn(before, path) ? before[path] : null;
54
+ const next = Object.hasOwn(after, path) ? after[path] : null;
55
+ if (old?.digest === next?.digest) return null;
56
+ const file = { path, ...(!next ? { deleted: true } : {}) };
57
+ if (old && typeof old.text !== 'string' || next && typeof next.text !== 'string') return file;
58
+ const delta = diffLines(old?.text ?? '', next?.text ?? '', { timeout: 25, maxEditLength: 10000 });
59
+ if (!delta) return file;
60
+ let added = 0, removed = 0;
61
+ for (const part of delta) {
62
+ if (part.added) added += part.count;
63
+ if (part.removed) removed += part.count;
64
+ }
65
+ return { ...file, added, removed };
66
+ };
67
+ }
68
+
69
+ /** Private snapshots survive engine restart. Only the sealed summary is
70
+ * returned to the host. Runs without a baseline retain their legacy evidence. */
71
+ export function createEngineDeliveryJournal(directory, capture) {
72
+ const paths = runId => {
73
+ const key = createHash('sha256').update(runId).digest('hex');
74
+ return { baseline: join(directory, key + '.baseline'), summary: join(directory, key + '.json') };
75
+ };
76
+ const read = path => {
77
+ const fd = openPrivate(path, constants.O_RDONLY);
78
+ try { return JSON.parse(readFileSync(fd, 'utf8')); }
79
+ finally { closeSync(fd); }
80
+ };
81
+ return {
82
+ begin(runId) {
83
+ const { baseline } = paths(runId);
84
+ if (!existsSync(baseline)) {
85
+ privateDirectory(directory, true);
86
+ atomicPrivate(baseline, JSON.stringify(capture()));
87
+ }
88
+ },
89
+ seal(record) {
90
+ const { baseline, summary } = paths(record.snapshot.runId);
91
+ if (!existsSync(baseline)) return;
92
+ try {
93
+ if (record.snapshot.phase === 'completed' && !existsSync(summary)) {
94
+ const evidence = engineDeliveryEvidence(record, deliveryNetChanges(read(baseline), capture()));
95
+ atomicPrivate(summary, JSON.stringify(evidence));
96
+ }
97
+ } finally { unlinkSync(baseline); }
98
+ },
99
+ read(record) {
100
+ const { summary } = paths(record.snapshot.runId);
101
+ return existsSync(summary) ? read(summary) : engineDeliveryEvidence(record);
102
+ },
103
+ };
104
+ }
@@ -18,6 +18,7 @@ import { admitChatUsagePolicy } from './model-chat-usage.mjs';
18
18
  import { validateMediaBlock } from './model-media.mjs';
19
19
  import { admitProviderCompatibilityPolicy } from './model-provider-compat.mjs';
20
20
  import { bindNativeContext, nativeContextDefaults } from './context-profile.mjs';
21
+ import { createEngineDeliveryJournal, engineDeliveryEvidence } from './engine-delivery-evidence.mjs';
21
22
  import { createNativeWorkspaceTools } from './workspace-tools.mjs';
22
23
  import { createNativeLocalCommandTools } from './local-command-tools.mjs';
23
24
  import { createOwnedCommandResolver } from './owned-command.mjs';
@@ -52,7 +53,14 @@ export const engineApprovalSubject = ({ arguments: args = {} }) => {
52
53
  return subject ? redactDiagnosticText(subject, 500) : null;
53
54
  };
54
55
 
55
- function durableDecision(record, request) {
56
+ const approvalDenialMessages = {
57
+ approval_prompts_disabled: 'This action requires one-time authorization, but approval prompts are disabled in this session. Changing the arguments cannot grant permission. Do not retry the denied action or try to bypass approval; continue with permitted work, or tell the user to enable approval prompts before trying again.',
58
+ approval_rejected: 'The user declined this action. Do not retry it with different arguments or use another tool to bypass the decision.',
59
+ approval_unavailable: 'No approval responder is available for this action. Changing the arguments cannot grant permission. Continue with permitted work and report the limitation.',
60
+ approval_cancelled: 'This approval was cancelled. The action did not run. Do not request it again unless the user asks to continue.',
61
+ };
62
+
63
+ function durableDecision(record, request, explainDenial = false) {
56
64
  const { call, operationKey } = request;
57
65
  const interactionId = `engine-permission-${digest({ runId: request.runId, call, definition: request.definition })}`;
58
66
  // Walk backward only within the lifetime of this call. A reused provider
@@ -65,8 +73,13 @@ function durableDecision(record, request) {
65
73
  const intentKey = payload.interactionId?.slice(0, -':approval'.length);
66
74
  if (!intentKey || intentKey === operationKey) continue;
67
75
  const receipt = record.receipts.find(row => row.operationKey === intentKey && row.status === 'committed');
68
- if (receipt?.result.results?.some(result => result.status === 'approval_required' && result.interactionId === interactionId))
69
- return payload.decision === 'allow' ? 'allow' : 'deny';
76
+ if (receipt?.result.results?.some(result => result.status === 'approval_required' && result.interactionId === interactionId)) {
77
+ if (payload.decision === 'allow') return 'allow';
78
+ if (explainDenial && Object.hasOwn(approvalDenialMessages, payload.denialReason))
79
+ return { status: 'error', content: { code: payload.denialReason, executed: false, retryable: false,
80
+ message: approvalDenialMessages[payload.denialReason] } };
81
+ return 'deny';
82
+ }
70
83
  }
71
84
  return { status: 'approval_required', approvalPolicy: DURABLE_APPROVAL, interactionId,
72
85
  content: { contract: ENGINE_APPROVAL_CONTRACT, code: 'approval_required', argumentDigest: digest(call.arguments),
@@ -184,7 +197,7 @@ export function admitHostTools(tools, reserved, durableApprovals = false, hostRe
184
197
  * tool and resolves to `{ status: 'ok' | 'error', content }`. */
185
198
  export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId, scope, model, authorize, callHostTool,
186
199
  callHostContext, callHostHook, callHostVerification, callHostReceipt, owner = `engine-${process.pid}`,
187
- fetchImpl = fetch, sourceEnv = process.env, commandSandbox, subAgents, runStore } = {}) {
200
+ fetchImpl = fetch, sourceEnv = process.env, commandSandbox, subAgents, runStore, onStream } = {}) {
188
201
  invariant(text(workspaceRoot) && text(stateDir) && text(sessionId) && typeof authorize === 'function'
189
202
  && scope && ['tenantId', 'workspaceId', 'userId', 'agentId'].every(key => text(scope[key])), 'engine_runtime_invalid');
190
203
  const root = realpathSync(resolve(workspaceRoot));
@@ -193,8 +206,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
193
206
  const roles = nativeChildRoles({ subAgents });
194
207
  const supportsImages = description.input.includes('image');
195
208
  const store = runStore ?? new SqliteRunStore(join(stateDir, 'runs.sqlite'));
196
- const decide = async request => {
197
- if (request.definition?.approvalPolicy === DURABLE_APPROVAL) return durableDecision(store.load(request.scope, request.runId), request);
209
+ const decide = async (request, explainDenial = false) => {
210
+ if (request.definition?.approvalPolicy === DURABLE_APPROVAL) return durableDecision(store.load(request.scope, request.runId), request, explainDenial);
198
211
  return await authorize(request) === 'allow' ? 'allow' : 'deny';
199
212
  };
200
213
  const artifacts = await createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope });
@@ -202,6 +215,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
202
215
  const executionOptions = { modern: true, resourceProfile: 'local-development/v2' };
203
216
  const local = execution.localExecution(executionOptions);
204
217
  const workspace = createNativeWorkspaceTools({ workspaceRoot: root, stateDir: join(stateDir, 'workspace'), sessionId, authorize: decide });
218
+ const deliveries = createEngineDeliveryJournal(join(stateDir, 'delivery'), () => workspace.captureDelivery());
205
219
  const commands = createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
206
220
  settings: local.settings, sourceEnv: local.environment, outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy,
207
221
  shellPolicy: commandSandbox,
@@ -218,19 +232,20 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
218
232
  const effectBound = request.definition?.hostEffectProtocol === ENGINE_HOST_EFFECT;
219
233
  const record = effectBound ? store.load(request.scope, request.runId) : null;
220
234
  const decision = record && request.definition.approvalPolicy === DURABLE_APPROVAL
221
- ? durableDecision(record, request) : null;
235
+ ? durableDecision(record, request, true) : null;
222
236
  if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
237
+ if (decision?.status === 'error') return decision;
223
238
  const effect = record ? {
224
239
  contract: ENGINE_HOST_EFFECT, operationKey: request.operationKey,
225
240
  sourceEventId: record.events.at(-1)?.eventId ?? null,
226
241
  goal: record.snapshot.goal, goalRevision: record.snapshot.goalRevision,
227
242
  observations: engineUserObservations(store, request.scope, record.snapshot),
228
- approved: decision === 'allow', canRequestApproval: !!decision && typeof decision === 'object',
243
+ approved: decision === 'allow', canRequestApproval: decision?.status === 'approval_required',
229
244
  } : undefined;
230
245
  const reply = await callHostTool({ runId: request.runId, callId: request.call.callId, name: request.call.name,
231
246
  arguments: request.call.arguments ?? {}, signal: request.signal, timeoutMs: request.definition?.timeoutMs ?? 120000, effect });
232
247
  if (effectBound && reply?.status === 'approval_required') {
233
- return decision && typeof decision === 'object' ? decision
248
+ return decision?.status === 'approval_required' ? decision
234
249
  : { status: 'error', content: { code: 'host_tool_approval_unavailable', executed: false } };
235
250
  }
236
251
  if (effectBound && reply?.status === 'uncertain')
@@ -260,7 +275,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
260
275
  const preflight = async (request, dispatch) => {
261
276
  if (request.definition.approvalPolicy === DURABLE_APPROVAL
262
277
  && (!request.definition.hostEffectProtocol || request.definition.hostApprovalRequired)) {
263
- const decision = await decide(request);
278
+ const decision = await decide(request, true);
264
279
  if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
265
280
  if (decision !== 'allow') return decision;
266
281
  }
@@ -362,7 +377,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
362
377
  return engineUserObservations(store, request.scope, snapshot, { indexes });
363
378
  }),
364
379
  artifacts, background, ...(children ? { children: children.owner } : {}) };
365
- const kernel = new NativeKernel({ store, owner, digest, ports });
380
+ const kernel = new NativeKernel({ store, owner, digest, ports, onStream });
366
381
 
367
382
  function prepareRun({ runId, objective, conversation, inputImages, hostInstructions = '', hostTools, toolPolicy,
368
383
  hostContext, hostHooks, hostVerification, executionPolicy, preset: presetName, maxModelCalls = null,
@@ -401,6 +416,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
401
416
  ] : [{ role: 'user', content: task, ...(media.length ? { media } : {}) }];
402
417
  const configuration = configure({ profile, tools: runtimeTools, contextSources, hooks: hooks.definitions,
403
418
  ...hooks.configuration,
419
+ guidancePolicy: 'boundary-guide/v1',
404
420
  ...(verification ? { hostVerification: verification } : {}),
405
421
  ...(executionPolicy?.strategy === 'plan-act-observe' ? { initialPlanPolicy: 'plan-act-observe/v1' } : {}),
406
422
  contract: { objective: scopedCallbacks ? objective : task,
@@ -432,6 +448,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
432
448
  /** Admit a new Run. The Run freezes the preset and instructions it starts with. */
433
449
  function start(input) {
434
450
  const { identity, configuration, preset, hostTools } = prepareRun(input);
451
+ try { deliveries.begin(input.runId); } catch { /* Optional presentation evidence. */ }
435
452
  kernel.start(initialSnapshot(identity, configuration, digest(configuration)), configuration);
436
453
  return { runId: input.runId, preset, hostTools };
437
454
  }
@@ -450,6 +467,9 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
450
467
  start, prepareRun, ports,
451
468
  async run(runId, options) {
452
469
  const snapshot = await kernel.runUntilIdle(scope, runId, options);
470
+ if (terminal(snapshot.phase)) {
471
+ try { deliveries.seal(store.load(scope, runId)); } catch { /* Preserve the completed Run. */ }
472
+ }
453
473
  if (children && terminal(snapshot.phase)) await children.owner.releaseRun({ scope, runId });
454
474
  return snapshot;
455
475
  },
@@ -469,6 +489,10 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
469
489
  ...(snapshot.childApproval ? { childRunId: snapshot.childApproval.childRunId } : {}),
470
490
  ...(subject ? { subject } : {}) };
471
491
  },
492
+ deliveryEvidence(runId) {
493
+ const record = store.load(scope, runId);
494
+ try { return deliveries.read(record); } catch { return engineDeliveryEvidence(record); }
495
+ },
472
496
  load: runId => store.load(scope, runId),
473
497
  completedHostObservations: record => completedHostObservations(store, scope, record),
474
498
  authority: runId => store.authority(scope, runId),
@@ -27,7 +27,8 @@ 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, isApprovalDenialReason, isNativeError, TOOL_RECEIPT_OBSERVATION_CONTRACT,
31
+ validateModelFailure } from '@kingsoftcloud/agentkit-harness-core';
31
32
  import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
32
33
  import { createEngineRuntime, engineApprovalSubject, ENGINE_APPROVAL_CONTRACT, ENGINE_EXECUTION_POLICY,
33
34
  ENGINE_INPUT_IMAGES } from './engine-runtime.mjs';
@@ -37,17 +38,28 @@ import { ENGINE_CONTEXT } from './engine-context.mjs';
37
38
  import { ENGINE_HOOKS } from './engine-hooks.mjs';
38
39
  import { ENGINE_HOST_EFFECT, hostReceiptReply, hostReceiptSource, waitForHostReceipt } from './engine-host-effects.mjs';
39
40
  import { ENGINE_VERIFICATION } from './engine-verification.mjs';
41
+ import { nativeTodoPlan } from './activity-status.mjs';
42
+ import { nativeModelStopMessage } from './native-terminal-failure.mjs';
40
43
  export { ENGINE_VIEW_CONTRACT };
41
44
 
42
45
  export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
43
46
  export const ENGINE_EVENT_SCHEMA = 'agentkit.engine-event/v1';
44
- const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/cancel', 'ui/view', 'shutdown'];
47
+ const THINKING_PAGE_CHARS = 8192;
48
+ const THINKING_HISTORY_CHARS = 128 * 1024;
49
+ const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/guide', 'run/cancel', 'ui/view', 'shutdown'];
45
50
  const DURABLE_APPROVAL_METHOD = 'run/approve';
46
51
  const HOST_OBSERVATIONS_METHOD = 'run/host-observations';
47
52
  const ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602, internalError: -32603,
48
53
  notInitialized: -32010, runNotFound: -32011, runBusy: -32012 };
49
54
  const text = value => typeof value === 'string' && value.trim().length > 0;
55
+ const toolName = /^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/;
50
56
  const sleep = ms => new Promise(done => setTimeout(done, ms));
57
+ const publicRequestId = operationKey => createHash('sha256').update(operationKey).digest('hex');
58
+ const modelUsageFields = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'cacheWriteInputTokens', 'reasoningTokens'];
59
+ function modelUsage(usage) {
60
+ return Object.fromEntries(modelUsageFields.filter(key => Number.isSafeInteger(usage[key]) && usage[key] >= 0)
61
+ .map(key => [key, usage[key]]));
62
+ }
51
63
 
52
64
  /** The engine's own task view, built by agentkit-harness-ui into this package's dist. */
53
65
  let viewCache;
@@ -67,16 +79,43 @@ function packageVersion() {
67
79
 
68
80
  /** Stable, host-renderable projection. Engine-internal payloads stay in the Run
69
81
  * store; a host renders `kind`, `title` and `detail` without knowing each kind. */
70
- export function projectEngineEvent(event, requiredVerification = false) {
82
+ export function projectEngineEvent(event, requiredVerification = false, thinkingPresentation = false) {
71
83
  const payload = event.payload ?? {}, base = { schema: ENGINE_EVENT_SCHEMA, seq: event.seq, kind: event.kind };
84
+ const modelRequest = thinkingPresentation && typeof payload.operationKey === 'string'
85
+ ? { requestId: publicRequestId(payload.operationKey) } : {};
72
86
  switch (event.kind) {
73
- case 'model.completed': return { ...base, category: 'model', title: payload.kind ?? 'model',
87
+ case 'todo.initialized':
88
+ case 'todo.updated':
89
+ return { ...base, category: 'todo',
90
+ ...(thinkingPresentation && Array.isArray(payload.todos) ? { plan: nativeTodoPlan(payload.todos) } : {}) };
91
+ case 'effect.prepared':
92
+ case 'effect.settled':
93
+ return payload.kind === 'model' ? { ...base, category: 'model', title: 'request', ...modelRequest,
94
+ ...(event.kind === 'effect.prepared' && payload.retry === true ? { retry: true } : {}),
95
+ ...(event.kind === 'effect.prepared' && payload.purpose === 'compaction' ? { purpose: 'compaction' } : {}) }
96
+ : { ...base, category: 'effect' };
97
+ case 'model.completed':
98
+ case 'model.stream_interrupted': {
99
+ let thinking = '';
100
+ for (const { event: display } of thinkingPresentation ? payload.displayStream?.records ?? [] : []) {
101
+ if (display?.kind !== 'thinking' || typeof display.text !== 'string') continue;
102
+ thinking += display.text.slice(0, THINKING_HISTORY_CHARS - thinking.length);
103
+ if (thinking.length === THINKING_HISTORY_CHARS) break;
104
+ }
105
+ if (event.kind === 'model.stream_interrupted') return { ...base, category: 'model', ...(text(thinking) ? { thinking, ...modelRequest } : {}) };
106
+ return { ...base, category: 'model', title: payload.kind ?? 'model',
107
+ ...(text(thinking) ? { thinking, ...modelRequest } : {}),
74
108
  ...(text(payload.text) && !(requiredVerification && payload.kind === 'final_candidate') ? { detail: payload.text } : {}),
75
109
  ...(Array.isArray(payload.toolCalls) && payload.toolCalls.length ? { tools: payload.toolCalls.map(call => call.name),
76
110
  calls: payload.toolCalls.map(call => ({ callId: call.callId, name: call.name, arguments: bounded(call.arguments) })) } : {}),
77
- ...(payload.usage ? { usage: { inputTokens: payload.usage.inputTokens, outputTokens: payload.usage.outputTokens } } : {}) };
111
+ ...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
112
+ }
113
+ case 'context.summary_completed':
114
+ case 'completion.delivery_review_completed':
115
+ return { ...base, category: 'model', ...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
78
116
  case 'tool.completed': return { ...base, category: 'tool', title: payload.name, status: payload.status,
79
- ...(text(payload.callId) ? { callId: payload.callId } : {}), ...(payload.content === undefined ? {} : { result: bounded(payload.content) }) };
117
+ ...(text(payload.callId) ? { callId: payload.callId } : {}),
118
+ ...(payload.content === undefined ? {} : { result: boundedToolResult(payload.name, payload.content) }) };
80
119
  case 'approval.requested': return { ...base, category: 'approval', title: payload.name, status: 'pending',
81
120
  callId: payload.callId, interactionId: payload.interactionId,
82
121
  ...(payload.source === 'child_tool' ? { approvalContract: ENGINE_APPROVAL_CONTRACT,
@@ -85,16 +124,34 @@ export function projectEngineEvent(event, requiredVerification = false) {
85
124
  ...(text(payload.content.subject) ? { detail: payload.content.subject } : {}) } : {}) };
86
125
  case 'approval.resolved': return { ...base, category: 'approval', status: payload.decision,
87
126
  callId: payload.callId, interactionId: payload.interactionId };
88
- case 'model.failure_observed': return { ...base, category: 'model', title: 'model_failure', status: 'retrying', detail: payload.code };
127
+ case 'input.guidance_applied':
128
+ return { ...base, category: 'input', inputId: payload.inputId };
129
+ case 'command.applied':
130
+ return payload.kind === 'guide' ? { ...base, category: 'command', inputId: payload.commandId, status: payload.reason }
131
+ : { ...base, category: 'command' };
132
+ case 'model.failure_observed': {
133
+ try { validateModelFailure(payload); } catch { return { ...base, category: 'model', title: 'model_failure' }; }
134
+ return { ...base, category: 'model', title: 'model_failure', detail: payload.code,
135
+ ...(payload.httpStatus === undefined ? {} : { httpStatus: payload.httpStatus }),
136
+ ...(payload.gateway ? { gateway: payload.gateway } : {}) };
137
+ }
138
+ case 'model.retry_exhausted': return { ...base, category: 'model', reason: 'provider_unavailable',
139
+ modelError: nativeModelStopMessage('provider_unavailable') };
89
140
  case 'run.started': return { ...base, category: 'run', title: 'started' };
90
141
  case 'run.terminal': return { ...base, category: 'run', title: payload.phase, status: payload.outcome,
91
142
  ...(requiredVerification ? { requiredVerification: true } : {}),
92
143
  ...(payload.reason ? { reason: payload.reason } : {}),
144
+ ...modelStopFields(payload.reason, payload.modelFailure),
93
145
  ...(text(payload.finalText) && (!requiredVerification || payload.outcome === 'verified') ? { detail: payload.finalText } : {}) };
94
146
  default: return { ...base, category: event.kind.split('.')[0] };
95
147
  }
96
148
  }
97
149
 
150
+ function modelStopFields(reason, failure) {
151
+ const modelError = nativeModelStopMessage(reason, failure);
152
+ return modelError ? { modelError } : {};
153
+ }
154
+
98
155
  /** Bound a value carried in a projected event: views show previews, never whole files. */
99
156
  const PREVIEW_CHARS = 4000;
100
157
  function bounded(value) {
@@ -104,10 +161,66 @@ function bounded(value) {
104
161
  return { truncated: true, preview: encoded.slice(0, PREVIEW_CHARS), chars: encoded.length };
105
162
  }
106
163
 
164
+ function boundedToolResult(name, value) {
165
+ const result = bounded(value);
166
+ if (typeof result?.preview !== 'string' || value?.ok !== true) return result;
167
+ // Keep the actual range and match locations when the raw result exceeds the
168
+ // event budget. Source lines can otherwise crowd out all of that metadata.
169
+ let observation;
170
+ if (name === 'read_workspace_file') {
171
+ const range = value.read_range;
172
+ observation = {
173
+ start_line: Number.isSafeInteger(range?.start) ? range.start : undefined,
174
+ end_line: Number.isSafeInteger(range?.end) ? range.end : undefined,
175
+ line_count: Number.isSafeInteger(value.line_count) ? value.line_count : undefined,
176
+ };
177
+ } else if (name === 'search_workspace_files' && Array.isArray(value.results)) {
178
+ const locations = [];
179
+ let locationBudget = 2200;
180
+ for (const hit of value.results.slice(0, 12)) {
181
+ if (typeof hit?.path !== 'string' || !Number.isSafeInteger(hit.line)) continue;
182
+ const location = { path: hit.path, line: hit.line };
183
+ const size = JSON.stringify(location).length + 1;
184
+ if (size > locationBudget) continue;
185
+ locations.push(location);
186
+ locationBudget -= size;
187
+ }
188
+ observation = {
189
+ searched_path: typeof value.searched_path === 'string' && value.searched_path.length <= 512 ? value.searched_path : undefined,
190
+ match_count: Number.isSafeInteger(value.match_count) ? value.match_count : undefined,
191
+ results: locations,
192
+ locations_truncated: value.truncated === true || locations.length < value.results.length,
193
+ };
194
+ } else return result;
195
+ return { ...result, ...observation, preview: result.preview.slice(0, PREVIEW_CHARS - JSON.stringify(observation).length) };
196
+ }
197
+
107
198
  export async function serveEngine({ input, output, log = () => {}, startup, env = process.env, fetchImpl = fetch, detachOnShutdown = false, viewStore }) {
108
199
  const frames = readline.createInterface({ input, crlfDelay: Infinity });
109
200
  const send = frame => output.write(`${JSON.stringify(frame)}\n`);
110
201
  const pending = new Map(), active = new Map(), driven = new Set(), receiptWaits = new Map();
202
+ const liveModelDisplay = new Map();
203
+ function captureModelDisplay({ runId, operationKey }, event) {
204
+ if (!['thinking', 'tool_delta'].includes(event.kind)) return;
205
+ let current = liveModelDisplay.get(runId);
206
+ if (current?.operationKey !== operationKey) {
207
+ current = { operationKey, id: randomUUID(), text: '', end: 0, tools: new Map(), draftRevision: 0 };
208
+ liveModelDisplay.set(runId, current);
209
+ }
210
+ if (event.kind === 'thinking') {
211
+ current.end += event.text.length;
212
+ current.text = (current.text + event.text).slice(-THINKING_HISTORY_CHARS);
213
+ return;
214
+ }
215
+ // A draft has no call ID, argument data, or authority to execute.
216
+ const { index, name } = event.metadata ?? {};
217
+ if (!Number.isSafeInteger(index) || index < 0 || !current.tools.has(index) && current.tools.size >= 16) return;
218
+ if (name === FINAL_SUBMISSION_TOOL) return;
219
+ const label = typeof name === 'string' && toolName.test(name) ? name : current.tools.get(index) ?? 'tool';
220
+ if (current.tools.get(index) === label) return;
221
+ current.tools.set(index, label);
222
+ current.draftRevision++;
223
+ }
111
224
  let host = null, runtime = null, runtimePromise, closing = false;
112
225
  const viewRef = viewStore ? viewStore.archive(engineView()) : null;
113
226
 
@@ -170,6 +283,8 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
170
283
  const pendingApproval = runtime.pendingApproval(snapshot, configuration);
171
284
  return { runId, phase: snapshot.phase, outcome: snapshot.outcome ?? null, reason: snapshot.reason ?? null,
172
285
  terminal: runtime.terminal(snapshot), running: active.has(runId), usage: snapshot.usage,
286
+ ...(['paused', 'failed', 'completed'].includes(snapshot.phase)
287
+ ? modelStopFields(snapshot.reason, snapshot.diagnostics.lastModelFailure) : {}),
173
288
  finalText: configuration.hostVerification && snapshot.outcome !== 'verified' ? null
174
289
  : snapshot.finalText ?? snapshot.candidate?.text ?? null, cursor: tail(runId),
175
290
  ...(pendingApproval ? { pendingApproval } : {}),
@@ -217,7 +332,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
217
332
  if (!detachOnShutdown || !controller.signal.aborted)
218
333
  log(`run ${runId} stopped: ${isNativeError(error) ? error.code : publicErrorMessage(error)}`);
219
334
  })
220
- .finally(() => active.delete(runId));
335
+ .finally(() => { active.delete(runId); liveModelDisplay.delete(runId); });
221
336
  active.set(runId, { controller, done });
222
337
  };
223
338
  const lookup = runId => {
@@ -240,7 +355,9 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
240
355
  async initialize(params) {
241
356
  const offered = Array.isArray(params?.protocolVersions) ? params.protocolVersions : [];
242
357
  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',
358
+ // A history reader can open a cold session without replacing the
359
+ // callbacks and approval authority of a concurrent execution owner.
360
+ if (params.host?.observeOnly !== true || !host) host = { name: text(params.host?.name) ? params.host.name : 'unknown',
244
361
  services: { approvals: params.services?.approvals === true, tools: params.services?.tools === true,
245
362
  context: detachOnShutdown && params.services?.context === ENGINE_CONTEXT,
246
363
  hooks: detachOnShutdown && params.services?.hooks === ENGINE_HOOKS,
@@ -251,7 +368,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
251
368
  durableApprovals: detachOnShutdown && params.services?.durableApprovals === true } };
252
369
  runtimePromise ??= createEngineRuntime({ workspaceRoot: startup.workspace, stateDir: startup.stateDir, sessionId: startup.sessionId,
253
370
  scope: startup.scope, authorize, callHostTool, callHostContext, callHostHook, callHostVerification, callHostReceipt, fetchImpl, sourceEnv: env,
254
- commandSandbox: startup.commandSandbox,
371
+ commandSandbox: startup.commandSandbox, onStream: captureModelDisplay,
255
372
  subAgents: detachOnShutdown ? startup.subAgents : undefined,
256
373
  model: { ...startup.model, apiKey: async () => env[startup.model.apiKeyEnv] ?? '' } })
257
374
  .catch(error => { runtimePromise = null; throw error; });
@@ -259,7 +376,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
259
376
  return { protocolVersion: ENGINE_PROTOCOL, engine: { name: '@kingsoftcloud/agentkit-harness-node', version: packageVersion(), ...runtime.info() },
260
377
  capabilities: { methods: detachOnShutdown ? [...METHODS, DURABLE_APPROVAL_METHOD,
261
378
  ...(host.services.toolEffects ? [HOST_OBSERVATIONS_METHOD] : [])] : METHODS,
262
- eventSchema: ENGINE_EVENT_SCHEMA, hostServices: ['approvals', 'tools'],
379
+ eventSchema: ENGINE_EVENT_SCHEMA, liveThinking: true, liveToolDrafts: true, hostServices: ['approvals', 'tools'],
263
380
  approvals: host.services.durableApprovals ? 'durable' : host.services.approvals ? 'host' : startup.approval,
264
381
  hostTools: host.services.tools, toolPolicy: ENGINE_TOOL_POLICY, executionPolicy: ENGINE_EXECUTION_POLICY,
265
382
  ...(detachOnShutdown ? { scopedHostRequests: true } : {}),
@@ -301,7 +418,12 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
301
418
  if (!params.hostContext?.sources?.length && !params.hostHooks?.hooks?.length && !hostEffects && !params.hostVerification) drive(runId);
302
419
  return { ...status(runId), preset: started.preset, hostTools: started.hostTools, existing: false };
303
420
  },
304
- async 'run/status'(params) { requireRun(params); return status(params.runId); },
421
+ async 'run/status'(params) {
422
+ requireRun(params);
423
+ const rest = status(params.runId);
424
+ return params.deliveryPresentation === true && rest.phase === 'completed' && text(rest.finalText)
425
+ ? { ...rest, deliveryEvidence: runtime.deliveryEvidence(params.runId) } : rest;
426
+ },
305
427
  async [HOST_OBSERVATIONS_METHOD](params) {
306
428
  if (!host.services.toolEffects) throw rpcError(ERRORS.method, 'host observations unavailable');
307
429
  requireRun(params);
@@ -319,15 +441,45 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
319
441
  if (!idle || hasReceipt || runtime.pendingCommands(runId).length) drive(runId);
320
442
  }
321
443
  const cursor = Number.isSafeInteger(params.cursor) && params.cursor >= 0 ? params.cursor : 0;
444
+ const thinkingPresentation = typeof params.thinkingCursor === 'string';
445
+ const draftPresentation = typeof params.toolDraftCursor === 'string';
446
+ const thinkingCursor = thinkingPresentation ? /^([\da-f-]{36}):(\d{1,16})$/.exec(params.thinkingCursor) : null;
322
447
  const deadline = Date.now() + Math.min(Math.max(Number(params.waitMs) || 0, 0), 30000);
323
448
  // The wait reads only the journal suffix; the Run record is loaded once, on return.
324
449
  for (;;) {
325
450
  const running = active.has(params.runId), events = runtime.events(params.runId, cursor);
326
- if (events.length || !running || Date.now() >= deadline) {
451
+ const live = (thinkingPresentation || draftPresentation) && running ? liveModelDisplay.get(runId) : null;
452
+ let thinking, toolDraft;
453
+ if (live) {
454
+ const first = live.end - live.text.length;
455
+ const after = thinkingCursor?.[1] === live.id ? Number(thinkingCursor[2]) : first;
456
+ const start = Math.max(first, after);
457
+ const draftCursor = `${live.id}:${live.draftRevision}`;
458
+ const hasThinking = thinkingPresentation && start < live.end;
459
+ const hasDraft = draftPresentation && live.draftRevision > 0 && draftCursor !== params.toolDraftCursor;
460
+ if ((hasThinking || hasDraft) && runtime.authority(runId).snapshot.pendingIntent === live.operationKey) {
461
+ if (hasThinking) {
462
+ const chunk = live.text.slice(start - first, start - first + THINKING_PAGE_CHARS);
463
+ thinking = { id: live.id, cursor: `${live.id}:${start + chunk.length}`, text: chunk };
464
+ }
465
+ if (hasDraft) toolDraft = { cursor: draftCursor, requestId: publicRequestId(live.operationKey),
466
+ tools: [...live.tools].map(([index, name]) => ({ index, name })) };
467
+ }
468
+ }
469
+ if (events.length || thinking || toolDraft || !running || Date.now() >= deadline) {
327
470
  const next = events.length ? events.at(-1).seq : cursor;
328
471
  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) };
472
+ const { snapshot } = runtime.authority(runId);
473
+ return { events: events.map(event => {
474
+ const projected = projectEngineEvent(event, !!configuration.hostVerification, thinkingPresentation || draftPresentation);
475
+ if (projected.kind !== 'run.terminal' || projected.title !== 'completed' || !text(projected.detail)) return projected;
476
+ const artifacts = currentDeliveryManifest(snapshot)?.artifacts;
477
+ return { ...projected, ...(artifacts?.length ? { deliverables: artifacts } : {}),
478
+ ...((thinkingPresentation || draftPresentation) ? { deliveryEvidence: runtime.deliveryEvidence(runId) } : {}) };
479
+ }), cursor: next,
480
+ ...(thinking ? { thinking } : {}),
481
+ ...(toolDraft ? { toolDraft } : {}),
482
+ terminal: runtime.terminal(snapshot), running: active.has(runId) };
331
483
  }
332
484
  await sleep(250);
333
485
  }
@@ -340,17 +492,32 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
340
492
  if (!before.terminal) continueOnSubscription(params.runId, record);
341
493
  return status(params.runId);
342
494
  },
495
+ async 'run/guide'(params) {
496
+ const record = requireRun(params);
497
+ const { runId, inputId, text: input } = params;
498
+ if (record.configuration.guidancePolicy !== 'boundary-guide/v1') return { status: 'unsupported' };
499
+ if (!/^guide-[a-f0-9]{64}$/.test(inputId ?? '') || !text(input) || input.length > 32768)
500
+ throw rpcError(ERRORS.params, 'invalid run guidance');
501
+ // Recover the revision from the original command when its reply was
502
+ // lost. The store still checks that replay uses identical input.
503
+ const previous = runtime.load(runId).commands.find(row => row.command.commandId === inputId);
504
+ return runtime.submit(runId, { commandId: inputId, kind: 'guide',
505
+ payload: { text: input, expectedGoalRevision: previous?.command.payload.expectedGoalRevision ?? record.snapshot.goalRevision } });
506
+ },
343
507
  async [DURABLE_APPROVAL_METHOD](params) {
344
508
  requireRun(params);
345
509
  if (!detachOnShutdown || !text(params.interactionId) || !['allow', 'deny'].includes(params.decision))
346
510
  throw rpcError(ERRORS.params, 'interactionId and approval decision are required');
347
- const { runId, interactionId, decision } = params;
511
+ const { runId, interactionId, decision, denialReason } = params;
512
+ if (denialReason !== undefined && (decision !== 'deny' || !isApprovalDenialReason(denialReason)))
513
+ throw rpcError(ERRORS.params, 'invalid approval denial reason');
348
514
  const commandId = `approval-${createHash('sha256').update(interactionId).digest('hex')}`;
349
515
  const record = runtime.load(runId);
350
516
  if (!record.commands.some(row => row.command.commandId === commandId)
351
517
  && runtime.pendingApproval(record.snapshot, record.configuration)?.interactionId !== interactionId)
352
518
  throw rpcError(ERRORS.params, 'interaction_mismatch');
353
- const receipt = runtime.submit(runId, { commandId, kind: 'submit_interaction', payload: { interactionId, decision } });
519
+ const receipt = runtime.submit(runId, { commandId, kind: 'submit_interaction',
520
+ payload: { interactionId, decision, ...(denialReason === undefined ? {} : { denialReason }) } });
354
521
  if (receipt.status !== 'rejected') {
355
522
  const continueRun = () => { if (!closing && !status(runId).terminal) continueOnSubscription(runId, record); };
356
523
  const running = active.get(runId);
@@ -78,14 +78,17 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
78
78
  resolve(frame);
79
79
  }
80
80
  });
81
- const takeHostRequests = runId => {
82
- pruneHostRequests(Date.now());
81
+ const takeHostRequests = (runId, receiver) => {
82
+ const now = Date.now();
83
+ pruneHostRequests(now);
83
84
  const ready = [];
84
85
  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
- }
86
+ if (runId !== undefined && request.frame.params?.runId !== runId) continue;
87
+ if (request.claimed && (!receiver || request.receiver !== receiver || now < request.redeliverAt)) continue;
88
+ request.claimed = true;
89
+ request.receiver = receiver;
90
+ request.redeliverAt = now + 500;
91
+ ready.push(request.frame);
89
92
  }
90
93
  return ready;
91
94
  };
@@ -97,8 +100,8 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
97
100
  input.write(JSON.stringify(frame) + '\n');
98
101
  });
99
102
  },
100
- async takeHostRequests(runId, waitMs, response) {
101
- const available = takeHostRequests(runId);
103
+ async takeHostRequests(runId, waitMs, response, receiver) {
104
+ const available = takeHostRequests(runId, receiver);
102
105
  if (available.length || !waitMs || response.destroyed) return available;
103
106
  return new Promise(resolve => {
104
107
  const finish = frames => {
@@ -110,7 +113,7 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
110
113
  const cancel = () => finish([]);
111
114
  const notify = stopped => {
112
115
  if (stopped || response.destroyed) return cancel();
113
- const ready = takeHostRequests(runId);
116
+ const ready = takeHostRequests(runId, receiver);
114
117
  if (ready.length) finish(ready);
115
118
  };
116
119
  const timer = setTimeout(cancel, waitMs);
@@ -202,7 +205,11 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
202
205
  const search = new URLSearchParams(query);
203
206
  const runId = search.get('runId') ?? undefined;
204
207
  const waitMs = Math.min(Math.max(Number(search.get('waitMs')) || 0, 0), 5000);
205
- const requests = await session.takeHostRequests(runId, waitMs, response);
208
+ // Existing hosts use one-shot delivery. Only a Run-scoped client
209
+ // that deduplicates execution by frame ID can request redelivery.
210
+ const requestedReceiver = search.get('receiver');
211
+ const receiver = runId !== undefined && /^[a-f0-9-]{36}$/.test(requestedReceiver ?? '') ? requestedReceiver : null;
212
+ const requests = await session.takeHostRequests(runId, waitMs, response, receiver);
206
213
  return respond(response, 200, { requests });
207
214
  }
208
215
  if (query !== undefined) return respond(response, 400, { error: 'invalid_query' });