@kingsoftcloud/agentkit-harness-node 0.0.19 → 0.0.21
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/engine-view.html +31 -23
- package/dist/index.mjs +77 -26
- package/dist/rpc-entry.mjs +77 -26
- package/package.json +2 -2
- package/src/native/engine-client.mjs +15 -4
- package/src/native/engine-delivery-evidence.mjs +72 -4
- package/src/native/engine-host-effects.mjs +26 -16
- package/src/native/engine-managed-service.mjs +12 -5
- package/src/native/engine-runtime.mjs +67 -14
- package/src/native/engine-server.mjs +148 -33
- package/src/native/engine-service.mjs +99 -19
- package/src/native/engine-verification.mjs +31 -5
- package/src/native/local-command-policy-worker.mjs +2 -2
- package/src/native/local-command-tools.mjs +19 -12
- package/src/native/model-inline-reasoning.mjs +2 -0
- package/src/native/model-port.mjs +72 -31
- package/src/native/native-terminal-failure.mjs +15 -4
- package/src/native/workspace-tools.mjs +32 -8
|
@@ -17,7 +17,9 @@ import { createNativeModelPort, nativeModelRecoveryPolicy } from './model-port.m
|
|
|
17
17
|
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
|
+
import { isProviderCompatibilityRule } from './model-inline-reasoning.mjs';
|
|
20
21
|
import { bindNativeContext, nativeContextDefaults } from './context-profile.mjs';
|
|
22
|
+
import { createEngineDeliveryJournal, engineDeliveryEvidence } from './engine-delivery-evidence.mjs';
|
|
21
23
|
import { createNativeWorkspaceTools } from './workspace-tools.mjs';
|
|
22
24
|
import { createNativeLocalCommandTools } from './local-command-tools.mjs';
|
|
23
25
|
import { createOwnedCommandResolver } from './owned-command.mjs';
|
|
@@ -39,7 +41,7 @@ import { admitEngineToolPolicy, restrictEngineTools } from './engine-tool-policy
|
|
|
39
41
|
import { admitEngineContextSources, engineContextPort } from './engine-context.mjs';
|
|
40
42
|
import { admitEngineHooks, engineHookPort } from './engine-hooks.mjs';
|
|
41
43
|
import { ENGINE_HOST_EFFECT, completedHostObservations, engineUserObservations } from './engine-host-effects.mjs';
|
|
42
|
-
import { admitEngineVerification, engineVerificationPort } from './engine-verification.mjs';
|
|
44
|
+
import { admitEngineVerification, ENGINE_COMMAND_VERIFIER, engineVerificationPort } from './engine-verification.mjs';
|
|
43
45
|
|
|
44
46
|
export const ENGINE_RUNTIME_CONTRACT = 'agentkit.engine-runtime/v1';
|
|
45
47
|
export const ENGINE_EXECUTION_POLICY = 'agentkit.engine-execution-policy/v1';
|
|
@@ -52,7 +54,14 @@ export const engineApprovalSubject = ({ arguments: args = {} }) => {
|
|
|
52
54
|
return subject ? redactDiagnosticText(subject, 500) : null;
|
|
53
55
|
};
|
|
54
56
|
|
|
55
|
-
|
|
57
|
+
const approvalDenialMessages = {
|
|
58
|
+
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.',
|
|
59
|
+
approval_rejected: 'The user declined this action. Do not retry it with different arguments or use another tool to bypass the decision.',
|
|
60
|
+
approval_unavailable: 'No approval responder is available for this action. Changing the arguments cannot grant permission. Continue with permitted work and report the limitation.',
|
|
61
|
+
approval_cancelled: 'This approval was cancelled. The action did not run. Do not request it again unless the user asks to continue.',
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
function durableDecision(record, request, explainDenial = false, workspaceWriteSafe = false) {
|
|
56
65
|
const { call, operationKey } = request;
|
|
57
66
|
const interactionId = `engine-permission-${digest({ runId: request.runId, call, definition: request.definition })}`;
|
|
58
67
|
// Walk backward only within the lifetime of this call. A reused provider
|
|
@@ -65,12 +74,17 @@ function durableDecision(record, request) {
|
|
|
65
74
|
const intentKey = payload.interactionId?.slice(0, -':approval'.length);
|
|
66
75
|
if (!intentKey || intentKey === operationKey) continue;
|
|
67
76
|
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
|
-
|
|
77
|
+
if (receipt?.result.results?.some(result => result.status === 'approval_required' && result.interactionId === interactionId)) {
|
|
78
|
+
if (payload.decision === 'allow') return 'allow';
|
|
79
|
+
if (explainDenial && Object.hasOwn(approvalDenialMessages, payload.denialReason))
|
|
80
|
+
return { status: 'error', content: { code: payload.denialReason, executed: false, retryable: false,
|
|
81
|
+
message: approvalDenialMessages[payload.denialReason] } };
|
|
82
|
+
return 'deny';
|
|
83
|
+
}
|
|
70
84
|
}
|
|
71
85
|
return { status: 'approval_required', approvalPolicy: DURABLE_APPROVAL, interactionId,
|
|
72
86
|
content: { contract: ENGINE_APPROVAL_CONTRACT, code: 'approval_required', argumentDigest: digest(call.arguments),
|
|
73
|
-
subject: engineApprovalSubject(call) } };
|
|
87
|
+
subject: engineApprovalSubject(call), ...(workspaceWriteSafe ? { workspaceWriteSafe } : {}) } };
|
|
74
88
|
}
|
|
75
89
|
|
|
76
90
|
function admitExecutionPolicy(policy, legacyMaxModelCalls) {
|
|
@@ -92,15 +106,26 @@ export function admitEngineModel(model) {
|
|
|
92
106
|
&& (model.maxOutputTokens == null || Number.isSafeInteger(model.maxOutputTokens) && model.maxOutputTokens > 0)
|
|
93
107
|
&& (model.requestOutputTokens == null || Number.isSafeInteger(model.requestOutputTokens) && model.requestOutputTokens > 0)
|
|
94
108
|
&& (model.images === undefined || typeof model.images === 'boolean')
|
|
109
|
+
&& (model.compatibilityRule === undefined || isProviderCompatibilityRule(model.compatibilityRule))
|
|
95
110
|
&& typeof model.apiKey === 'function', 'engine_model_invalid');
|
|
96
111
|
const contextWindow = model.contextWindow ?? 128000;
|
|
97
112
|
return { protocol: model.protocol ?? 'openai-chat', modelName: model.name, baseUrl: model.baseUrl, parameters: {},
|
|
113
|
+
...(model.compatibilityRule === undefined ? {} : { compatibilityRule: model.compatibilityRule }),
|
|
98
114
|
input: model.images ? ['text', 'image'] : ['text'], contextWindow,
|
|
99
115
|
maxOutputTokens: presetRequestOutputTokens({ configured: model.requestOutputTokens ?? null,
|
|
100
116
|
modelMaxOutputTokens: model.maxOutputTokens ?? null, contextWindow }),
|
|
101
117
|
requestTimeoutMs: model.requestTimeoutMs ?? 180000 };
|
|
102
118
|
}
|
|
103
119
|
|
|
120
|
+
export function engineProviderCompatibilityRule(description) {
|
|
121
|
+
if (description.compatibilityRule || description.protocol !== 'openai-chat'
|
|
122
|
+
|| description.modelName.trim().toLowerCase() !== 'glm-5.3-flash') return description.compatibilityRule;
|
|
123
|
+
const hostname = new URL(description.baseUrl).hostname;
|
|
124
|
+
if (/(^|\.)kspmas(?:-internal)?\.ksyun\.com$/.test(hostname)) return 'kspmas-gateway';
|
|
125
|
+
if (/(^|\.)(z\.ai|bigmodel\.cn)$/.test(hostname)) return 'zai';
|
|
126
|
+
return 'permissive';
|
|
127
|
+
}
|
|
128
|
+
|
|
104
129
|
const CONVERSATION_TURNS = 64, CONVERSATION_CHARS = 60000;
|
|
105
130
|
export const ENGINE_INPUT_IMAGES = Object.freeze({ maxCount: 8, maxEncodedBytes: 6 * 1024 * 1024 });
|
|
106
131
|
|
|
@@ -193,8 +218,9 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
193
218
|
const roles = nativeChildRoles({ subAgents });
|
|
194
219
|
const supportsImages = description.input.includes('image');
|
|
195
220
|
const store = runStore ?? new SqliteRunStore(join(stateDir, 'runs.sqlite'));
|
|
196
|
-
const decide = async request => {
|
|
197
|
-
if (request.definition?.approvalPolicy === DURABLE_APPROVAL)
|
|
221
|
+
const decide = async (request, explainDenial = false, workspaceWriteSafe = false) => {
|
|
222
|
+
if (request.definition?.approvalPolicy === DURABLE_APPROVAL)
|
|
223
|
+
return durableDecision(store.load(request.scope, request.runId), request, explainDenial, workspaceWriteSafe);
|
|
198
224
|
return await authorize(request) === 'allow' ? 'allow' : 'deny';
|
|
199
225
|
};
|
|
200
226
|
const artifacts = await createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope });
|
|
@@ -202,10 +228,12 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
202
228
|
const executionOptions = { modern: true, resourceProfile: 'local-development/v2' };
|
|
203
229
|
const local = execution.localExecution(executionOptions);
|
|
204
230
|
const workspace = createNativeWorkspaceTools({ workspaceRoot: root, stateDir: join(stateDir, 'workspace'), sessionId, authorize: decide });
|
|
231
|
+
const deliveries = createEngineDeliveryJournal(join(stateDir, 'delivery'), () => workspace.captureDelivery());
|
|
205
232
|
const commands = createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
|
|
206
233
|
settings: local.settings, sourceEnv: local.environment, outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy,
|
|
207
234
|
shellPolicy: commandSandbox,
|
|
208
|
-
artifacts, authorize:
|
|
235
|
+
artifacts, authorize: (request, info) => decide(request, true, info?.readOnlyCommand),
|
|
236
|
+
classifyApproval: true, captureWorkspace: request => workspace.capture(request),
|
|
209
237
|
resolveOwnedCommand: createOwnedCommandResolver({ scope, store }) });
|
|
210
238
|
const web = createNativeWebTools({ fetch: fetchImpl, providerConfig: { provider: '' }, authorize: decide, sessionId, inlineMaxChars: 6000 });
|
|
211
239
|
const owners = [workspace, commands, web];
|
|
@@ -218,19 +246,20 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
218
246
|
const effectBound = request.definition?.hostEffectProtocol === ENGINE_HOST_EFFECT;
|
|
219
247
|
const record = effectBound ? store.load(request.scope, request.runId) : null;
|
|
220
248
|
const decision = record && request.definition.approvalPolicy === DURABLE_APPROVAL
|
|
221
|
-
? durableDecision(record, request) : null;
|
|
249
|
+
? durableDecision(record, request, true) : null;
|
|
222
250
|
if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
|
|
251
|
+
if (decision?.status === 'error') return decision;
|
|
223
252
|
const effect = record ? {
|
|
224
253
|
contract: ENGINE_HOST_EFFECT, operationKey: request.operationKey,
|
|
225
254
|
sourceEventId: record.events.at(-1)?.eventId ?? null,
|
|
226
255
|
goal: record.snapshot.goal, goalRevision: record.snapshot.goalRevision,
|
|
227
256
|
observations: engineUserObservations(store, request.scope, record.snapshot),
|
|
228
|
-
approved: decision === 'allow', canRequestApproval:
|
|
257
|
+
approved: decision === 'allow', canRequestApproval: decision?.status === 'approval_required',
|
|
229
258
|
} : undefined;
|
|
230
259
|
const reply = await callHostTool({ runId: request.runId, callId: request.call.callId, name: request.call.name,
|
|
231
260
|
arguments: request.call.arguments ?? {}, signal: request.signal, timeoutMs: request.definition?.timeoutMs ?? 120000, effect });
|
|
232
261
|
if (effectBound && reply?.status === 'approval_required') {
|
|
233
|
-
return decision
|
|
262
|
+
return decision?.status === 'approval_required' ? decision
|
|
234
263
|
: { status: 'error', content: { code: 'host_tool_approval_unavailable', executed: false } };
|
|
235
264
|
}
|
|
236
265
|
if (effectBound && reply?.status === 'uncertain')
|
|
@@ -260,7 +289,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
260
289
|
const preflight = async (request, dispatch) => {
|
|
261
290
|
if (request.definition.approvalPolicy === DURABLE_APPROVAL
|
|
262
291
|
&& (!request.definition.hostEffectProtocol || request.definition.hostApprovalRequired)) {
|
|
263
|
-
const decision = await decide(request);
|
|
292
|
+
const decision = await decide(request, true);
|
|
264
293
|
if (decision === 'deny') return { status: 'error', content: { code: 'policy_denied', executed: false } };
|
|
265
294
|
if (decision !== 'allow') return decision;
|
|
266
295
|
}
|
|
@@ -284,12 +313,15 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
284
313
|
};
|
|
285
314
|
const context = bindNativeContext({ description, context: {}, ...nativeContextDefaults(undefined) });
|
|
286
315
|
const chatUsage = admitChatUsagePolicy(description.protocol);
|
|
316
|
+
// On opaque proxies the model name alone does not establish support for the
|
|
317
|
+
// Z.ai thinking switch. An explicitly bound provider takes precedence.
|
|
318
|
+
const providerRule = engineProviderCompatibilityRule(description);
|
|
287
319
|
const profile = { profileId: 'engine', profileVersion: digest(description), providerFamily: description.protocol,
|
|
288
320
|
compatibilityDigest: digest(description), supportsImages, discoveredToolExposure: 'direct-after-search/v1', streamTimeoutPolicy: 'idle/v1',
|
|
289
321
|
...(chatUsage ? { chatUsagePolicy: chatUsage } : {}), maxRetries: 2, maxProviderRetries: 10, ...context.profile,
|
|
290
322
|
maxOutputTokens: description.maxOutputTokens, contextWindow: description.contextWindow,
|
|
291
323
|
requestTimeoutMs: description.requestTimeoutMs, providerReplayMode: 'reasoning_content',
|
|
292
|
-
providerCompatibilityPolicy: admitProviderCompatibilityPolicy() };
|
|
324
|
+
providerCompatibilityPolicy: admitProviderCompatibilityPolicy(providerRule) };
|
|
293
325
|
const modelSurface = bindNativeModelSurface({ environment: execution.executionEnvironment(executionOptions), description });
|
|
294
326
|
const modelPort = createNativeModelPort({ fetchImpl, resolveProfile: async () => ({ protocol: description.protocol, baseUrl: description.baseUrl,
|
|
295
327
|
apiKey: await model.apiKey(), model: description.modelName, parameters: description.parameters }) });
|
|
@@ -355,7 +387,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
355
387
|
}
|
|
356
388
|
const ports = { model: modelPort, tools, workspace,
|
|
357
389
|
context: engineContextPort(context.port, callHostContext),
|
|
358
|
-
verification: engineVerificationPort(store, callHostVerification, digest
|
|
390
|
+
verification: engineVerificationPort(store, callHostVerification, digest,
|
|
391
|
+
request => workspace.capture(request).revision),
|
|
359
392
|
hooks: engineHookPort(callHostHook, request => {
|
|
360
393
|
const { snapshot } = store.authority(request.scope, request.runId);
|
|
361
394
|
const indexes = new Set(request.input.compaction.messageRefs.map(ref => Number(ref.split(':', 3)[1])));
|
|
@@ -392,6 +425,10 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
392
425
|
const contextSources = admitEngineContextSources(hostContext);
|
|
393
426
|
const hooks = admitEngineHooks(hostHooks);
|
|
394
427
|
const verification = admitEngineVerification(hostVerification);
|
|
428
|
+
if (verification?.verifierRef === ENGINE_COMMAND_VERIFIER) {
|
|
429
|
+
invariant(verification.evidenceTools.length === 0, 'engine_command_verification_evidence_invalid');
|
|
430
|
+
if (runtimeTools.some(tool => tool.name === 'run_command')) verification.evidenceTools = ['run_command'];
|
|
431
|
+
}
|
|
395
432
|
const effectBound = hosted.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT);
|
|
396
433
|
const scopedCallbacks = contextSources.length || hooks.definitions.length || effectBound || !!verification;
|
|
397
434
|
const inputMessages = effectBound || originalInput ? [
|
|
@@ -401,6 +438,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
401
438
|
] : [{ role: 'user', content: task, ...(media.length ? { media } : {}) }];
|
|
402
439
|
const configuration = configure({ profile, tools: runtimeTools, contextSources, hooks: hooks.definitions,
|
|
403
440
|
...hooks.configuration,
|
|
441
|
+
guidancePolicy: 'boundary-guide/v1',
|
|
404
442
|
...(verification ? { hostVerification: verification } : {}),
|
|
405
443
|
...(executionPolicy?.strategy === 'plan-act-observe' ? { initialPlanPolicy: 'plan-act-observe/v1' } : {}),
|
|
406
444
|
contract: { objective: scopedCallbacks ? objective : task,
|
|
@@ -432,6 +470,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
432
470
|
/** Admit a new Run. The Run freezes the preset and instructions it starts with. */
|
|
433
471
|
function start(input) {
|
|
434
472
|
const { identity, configuration, preset, hostTools } = prepareRun(input);
|
|
473
|
+
try { deliveries.begin(input.runId); } catch { /* Optional presentation evidence. */ }
|
|
435
474
|
kernel.start(initialSnapshot(identity, configuration, digest(configuration)), configuration);
|
|
436
475
|
return { runId: input.runId, preset, hostTools };
|
|
437
476
|
}
|
|
@@ -450,6 +489,9 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
450
489
|
start, prepareRun, ports,
|
|
451
490
|
async run(runId, options) {
|
|
452
491
|
const snapshot = await kernel.runUntilIdle(scope, runId, options);
|
|
492
|
+
if (terminal(snapshot.phase)) {
|
|
493
|
+
try { deliveries.seal(store.load(scope, runId)); } catch { /* Preserve the completed Run. */ }
|
|
494
|
+
}
|
|
453
495
|
if (children && terminal(snapshot.phase)) await children.owner.releaseRun({ scope, runId });
|
|
454
496
|
return snapshot;
|
|
455
497
|
},
|
|
@@ -463,12 +505,23 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
463
505
|
const tools = snapshot.childApproval
|
|
464
506
|
? store.authority(snapshot.childApproval.childScope, snapshot.childApproval.childRunId).configuration.tools
|
|
465
507
|
: configuration.tools;
|
|
508
|
+
const commandApproval = !snapshot.childApproval && call.name === 'run_command'
|
|
509
|
+
? store.load(scope, snapshot.runId).receipts.find(receipt => receipt.operationKey === pending.operationKey
|
|
510
|
+
&& receipt.status === 'committed')?.result.results?.find(result => result.interactionId === pending.hostInteractionId)?.content
|
|
511
|
+
: null;
|
|
466
512
|
return { interactionId: pending.interactionId, callId: pending.callId, tool: call.name,
|
|
467
513
|
...(tools.some(tool => tool.name === call.name && (tool.hostApprovalRequired
|
|
468
514
|
|| tool.hostEffectProtocol === ENGINE_HOST_EFFECT)) ? { requiresUserApproval: true } : {}),
|
|
469
515
|
...(snapshot.childApproval ? { childRunId: snapshot.childApproval.childRunId } : {}),
|
|
516
|
+
...(!snapshot.childApproval && (commandApproval?.workspaceWriteSafe === true || route.get(call.name) === workspace
|
|
517
|
+
&& ['write_workspace_file', 'write_workspace_files', 'edit_workspace_file',
|
|
518
|
+
'multi_edit_workspace_file', 'apply_workspace_patch'].includes(call.name)) ? { workspaceWriteSafe: true } : {}),
|
|
470
519
|
...(subject ? { subject } : {}) };
|
|
471
520
|
},
|
|
521
|
+
deliveryEvidence(runId) {
|
|
522
|
+
const record = store.load(scope, runId);
|
|
523
|
+
try { return deliveries.read(record); } catch { return engineDeliveryEvidence(record); }
|
|
524
|
+
},
|
|
472
525
|
load: runId => store.load(scope, runId),
|
|
473
526
|
completedHostObservations: record => completedHostObservations(store, scope, record),
|
|
474
527
|
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 { currentDeliveryManifest, FINAL_SUBMISSION_TOOL, isNativeError, TOOL_RECEIPT_OBSERVATION_CONTRACT
|
|
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';
|
|
@@ -35,25 +36,29 @@ import { ENGINE_VIEW_CONTRACT } from './engine-view-store.mjs';
|
|
|
35
36
|
import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
|
|
36
37
|
import { ENGINE_CONTEXT } from './engine-context.mjs';
|
|
37
38
|
import { ENGINE_HOOKS } from './engine-hooks.mjs';
|
|
38
|
-
import { ENGINE_HOST_EFFECT, hostReceiptReply, hostReceiptSource, waitForHostReceipt } from './engine-host-effects.mjs';
|
|
39
|
-
import { ENGINE_VERIFICATION } from './engine-verification.mjs';
|
|
39
|
+
import { ENGINE_HOST_EFFECT, RECEIPT_WAIT_MS, hostReceiptReply, hostReceiptSource, waitForHostReceipt } from './engine-host-effects.mjs';
|
|
40
|
+
import { ENGINE_COMMAND_VERIFIER, ENGINE_VERIFICATION } from './engine-verification.mjs';
|
|
40
41
|
import { nativeTodoPlan } from './activity-status.mjs';
|
|
41
|
-
import {
|
|
42
|
+
import { nativeModelStopMessage } from './native-terminal-failure.mjs';
|
|
42
43
|
export { ENGINE_VIEW_CONTRACT };
|
|
43
44
|
|
|
44
45
|
export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
|
|
45
46
|
export const ENGINE_EVENT_SCHEMA = 'agentkit.engine-event/v1';
|
|
46
47
|
const THINKING_PAGE_CHARS = 8192;
|
|
47
48
|
const THINKING_HISTORY_CHARS = 128 * 1024;
|
|
48
|
-
const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/cancel', 'ui/view', 'shutdown'];
|
|
49
|
+
const METHODS = ['initialize', 'run/start', 'run/status', 'run/events', 'run/resume', 'run/guide', 'run/cancel', 'ui/view', 'shutdown'];
|
|
49
50
|
const DURABLE_APPROVAL_METHOD = 'run/approve';
|
|
50
51
|
const HOST_OBSERVATIONS_METHOD = 'run/host-observations';
|
|
51
52
|
const ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602, internalError: -32603,
|
|
52
53
|
notInitialized: -32010, runNotFound: -32011, runBusy: -32012 };
|
|
53
54
|
const text = value => typeof value === 'string' && value.trim().length > 0;
|
|
54
55
|
const toolName = /^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/;
|
|
55
|
-
const sleep = ms => new Promise(done => setTimeout(done, ms));
|
|
56
56
|
const publicRequestId = operationKey => createHash('sha256').update(operationKey).digest('hex');
|
|
57
|
+
const modelUsageFields = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'cacheWriteInputTokens', 'reasoningTokens'];
|
|
58
|
+
function modelUsage(usage) {
|
|
59
|
+
return Object.fromEntries(modelUsageFields.filter(key => Number.isSafeInteger(usage[key]) && usage[key] >= 0)
|
|
60
|
+
.map(key => [key, usage[key]]));
|
|
61
|
+
}
|
|
57
62
|
|
|
58
63
|
/** The engine's own task view, built by agentkit-harness-ui into this package's dist. */
|
|
59
64
|
let viewCache;
|
|
@@ -84,7 +89,9 @@ export function projectEngineEvent(event, requiredVerification = false, thinking
|
|
|
84
89
|
...(thinkingPresentation && Array.isArray(payload.todos) ? { plan: nativeTodoPlan(payload.todos) } : {}) };
|
|
85
90
|
case 'effect.prepared':
|
|
86
91
|
case 'effect.settled':
|
|
87
|
-
return
|
|
92
|
+
return payload.kind === 'model' ? { ...base, category: 'model', title: 'request', ...modelRequest,
|
|
93
|
+
...(event.kind === 'effect.prepared' && payload.retry === true ? { retry: true } : {}),
|
|
94
|
+
...(event.kind === 'effect.prepared' && payload.purpose === 'compaction' ? { purpose: 'compaction' } : {}) }
|
|
88
95
|
: { ...base, category: 'effect' };
|
|
89
96
|
case 'model.completed':
|
|
90
97
|
case 'model.stream_interrupted': {
|
|
@@ -96,14 +103,22 @@ export function projectEngineEvent(event, requiredVerification = false, thinking
|
|
|
96
103
|
}
|
|
97
104
|
if (event.kind === 'model.stream_interrupted') return { ...base, category: 'model', ...(text(thinking) ? { thinking, ...modelRequest } : {}) };
|
|
98
105
|
return { ...base, category: 'model', title: payload.kind ?? 'model',
|
|
99
|
-
...(text(thinking) ? { thinking
|
|
106
|
+
...modelRequest, ...(text(thinking) ? { thinking } : {}),
|
|
100
107
|
...(text(payload.text) && !(requiredVerification && payload.kind === 'final_candidate') ? { detail: payload.text } : {}),
|
|
101
108
|
...(Array.isArray(payload.toolCalls) && payload.toolCalls.length ? { tools: payload.toolCalls.map(call => call.name),
|
|
102
109
|
calls: payload.toolCalls.map(call => ({ callId: call.callId, name: call.name, arguments: bounded(call.arguments) })) } : {}),
|
|
103
|
-
...(payload.usage ? { usage:
|
|
110
|
+
...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
|
|
104
111
|
}
|
|
112
|
+
case 'model.retry_scheduled':
|
|
113
|
+
return { ...base, category: 'model', title: 'waiting',
|
|
114
|
+
...(Number.isSafeInteger(payload.retryAt) && payload.retryAt > 0 ? { retryAt: payload.retryAt } : {}),
|
|
115
|
+
...(Number.isSafeInteger(payload.failure?.httpStatus) ? { httpStatus: payload.failure.httpStatus } : {}) };
|
|
116
|
+
case 'context.summary_completed':
|
|
117
|
+
case 'completion.delivery_review_completed':
|
|
118
|
+
return { ...base, category: 'model', ...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
|
|
105
119
|
case 'tool.completed': return { ...base, category: 'tool', title: payload.name, status: payload.status,
|
|
106
|
-
...(text(payload.callId) ? { callId: payload.callId } : {}),
|
|
120
|
+
...(text(payload.callId) ? { callId: payload.callId } : {}),
|
|
121
|
+
...(payload.content === undefined ? {} : { result: boundedToolResult(payload.name, payload.content) }) };
|
|
107
122
|
case 'approval.requested': return { ...base, category: 'approval', title: payload.name, status: 'pending',
|
|
108
123
|
callId: payload.callId, interactionId: payload.interactionId,
|
|
109
124
|
...(payload.source === 'child_tool' ? { approvalContract: ENGINE_APPROVAL_CONTRACT,
|
|
@@ -112,16 +127,34 @@ export function projectEngineEvent(event, requiredVerification = false, thinking
|
|
|
112
127
|
...(text(payload.content.subject) ? { detail: payload.content.subject } : {}) } : {}) };
|
|
113
128
|
case 'approval.resolved': return { ...base, category: 'approval', status: payload.decision,
|
|
114
129
|
callId: payload.callId, interactionId: payload.interactionId };
|
|
115
|
-
case '
|
|
130
|
+
case 'input.guidance_applied':
|
|
131
|
+
return { ...base, category: 'input', inputId: payload.inputId };
|
|
132
|
+
case 'command.applied':
|
|
133
|
+
return payload.kind === 'guide' ? { ...base, category: 'command', inputId: payload.commandId, status: payload.reason }
|
|
134
|
+
: { ...base, category: 'command' };
|
|
135
|
+
case 'model.failure_observed': {
|
|
136
|
+
try { validateModelFailure(payload); } catch { return { ...base, category: 'model', title: 'model_failure' }; }
|
|
137
|
+
return { ...base, category: 'model', title: 'model_failure', detail: payload.code,
|
|
138
|
+
...(payload.httpStatus === undefined ? {} : { httpStatus: payload.httpStatus }),
|
|
139
|
+
...(payload.gateway ? { gateway: payload.gateway } : {}) };
|
|
140
|
+
}
|
|
141
|
+
case 'model.retry_exhausted': return { ...base, category: 'model', reason: 'provider_unavailable',
|
|
142
|
+
modelError: nativeModelStopMessage('provider_unavailable') };
|
|
116
143
|
case 'run.started': return { ...base, category: 'run', title: 'started' };
|
|
117
144
|
case 'run.terminal': return { ...base, category: 'run', title: payload.phase, status: payload.outcome,
|
|
118
145
|
...(requiredVerification ? { requiredVerification: true } : {}),
|
|
119
146
|
...(payload.reason ? { reason: payload.reason } : {}),
|
|
147
|
+
...modelStopFields(payload.reason, payload.modelFailure),
|
|
120
148
|
...(text(payload.finalText) && (!requiredVerification || payload.outcome === 'verified') ? { detail: payload.finalText } : {}) };
|
|
121
149
|
default: return { ...base, category: event.kind.split('.')[0] };
|
|
122
150
|
}
|
|
123
151
|
}
|
|
124
152
|
|
|
153
|
+
function modelStopFields(reason, failure) {
|
|
154
|
+
const modelError = nativeModelStopMessage(reason, failure);
|
|
155
|
+
return modelError ? { modelError } : {};
|
|
156
|
+
}
|
|
157
|
+
|
|
125
158
|
/** Bound a value carried in a projected event: views show previews, never whole files. */
|
|
126
159
|
const PREVIEW_CHARS = 4000;
|
|
127
160
|
function bounded(value) {
|
|
@@ -131,16 +164,52 @@ function bounded(value) {
|
|
|
131
164
|
return { truncated: true, preview: encoded.slice(0, PREVIEW_CHARS), chars: encoded.length };
|
|
132
165
|
}
|
|
133
166
|
|
|
134
|
-
|
|
167
|
+
function boundedToolResult(name, value) {
|
|
168
|
+
const result = bounded(value);
|
|
169
|
+
if (typeof result?.preview !== 'string' || value?.ok !== true) return result;
|
|
170
|
+
// Keep the actual range and match locations when the raw result exceeds the
|
|
171
|
+
// event budget. Source lines can otherwise crowd out all of that metadata.
|
|
172
|
+
let observation;
|
|
173
|
+
if (name === 'read_workspace_file') {
|
|
174
|
+
const range = value.read_range;
|
|
175
|
+
observation = {
|
|
176
|
+
start_line: Number.isSafeInteger(range?.start) ? range.start : undefined,
|
|
177
|
+
end_line: Number.isSafeInteger(range?.end) ? range.end : undefined,
|
|
178
|
+
line_count: Number.isSafeInteger(value.line_count) ? value.line_count : undefined,
|
|
179
|
+
};
|
|
180
|
+
} else if (name === 'search_workspace_files' && Array.isArray(value.results)) {
|
|
181
|
+
const locations = [];
|
|
182
|
+
let locationBudget = 2200;
|
|
183
|
+
for (const hit of value.results.slice(0, 12)) {
|
|
184
|
+
if (typeof hit?.path !== 'string' || !Number.isSafeInteger(hit.line)) continue;
|
|
185
|
+
const location = { path: hit.path, line: hit.line };
|
|
186
|
+
const size = JSON.stringify(location).length + 1;
|
|
187
|
+
if (size > locationBudget) continue;
|
|
188
|
+
locations.push(location);
|
|
189
|
+
locationBudget -= size;
|
|
190
|
+
}
|
|
191
|
+
observation = {
|
|
192
|
+
searched_path: typeof value.searched_path === 'string' && value.searched_path.length <= 512 ? value.searched_path : undefined,
|
|
193
|
+
match_count: Number.isSafeInteger(value.match_count) ? value.match_count : undefined,
|
|
194
|
+
results: locations,
|
|
195
|
+
locations_truncated: value.truncated === true || locations.length < value.results.length,
|
|
196
|
+
};
|
|
197
|
+
} else return result;
|
|
198
|
+
return { ...result, ...observation, preview: result.preview.slice(0, PREVIEW_CHARS - JSON.stringify(observation).length) };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export async function serveEngine({ input, output, log = () => {}, startup, env = process.env, fetchImpl = fetch, detachOnShutdown = false, viewStore, onActivity = () => {} }) {
|
|
135
202
|
const frames = readline.createInterface({ input, crlfDelay: Infinity });
|
|
136
203
|
const send = frame => output.write(`${JSON.stringify(frame)}\n`);
|
|
137
204
|
const pending = new Map(), active = new Map(), driven = new Set(), receiptWaits = new Map();
|
|
205
|
+
const handlersInFlight = new Set(), lifetime = new AbortController();
|
|
206
|
+
const reportActivity = () => onActivity(handlersInFlight.size > 0 || active.size > 0);
|
|
138
207
|
const liveModelDisplay = new Map();
|
|
139
208
|
function captureModelDisplay({ runId, operationKey }, event) {
|
|
140
|
-
if (!['thinking', 'tool_delta'].includes(event.kind)) return;
|
|
209
|
+
if (!['text', 'thinking', 'tool_delta'].includes(event.kind)) return;
|
|
141
210
|
let current = liveModelDisplay.get(runId);
|
|
142
211
|
if (current?.operationKey !== operationKey) {
|
|
143
|
-
current = { operationKey, id: randomUUID(), text: '', end: 0, tools: new Map(), draftRevision: 0 };
|
|
212
|
+
current = { operationKey, id: randomUUID(), text: '', end: 0, body: '', bodyEnd: 0, tools: new Map(), draftRevision: 0 };
|
|
144
213
|
liveModelDisplay.set(runId, current);
|
|
145
214
|
}
|
|
146
215
|
if (event.kind === 'thinking') {
|
|
@@ -148,6 +217,11 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
148
217
|
current.text = (current.text + event.text).slice(-THINKING_HISTORY_CHARS);
|
|
149
218
|
return;
|
|
150
219
|
}
|
|
220
|
+
if (event.kind === 'text') {
|
|
221
|
+
current.bodyEnd += event.text.length;
|
|
222
|
+
current.body = (current.body + event.text).slice(-THINKING_HISTORY_CHARS);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
151
225
|
// A draft has no call ID, argument data, or authority to execute.
|
|
152
226
|
const { index, name } = event.metadata ?? {};
|
|
153
227
|
if (!Number.isSafeInteger(index) || index < 0 || !current.tools.has(index) && current.tools.size >= 16) return;
|
|
@@ -219,6 +293,8 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
219
293
|
const pendingApproval = runtime.pendingApproval(snapshot, configuration);
|
|
220
294
|
return { runId, phase: snapshot.phase, outcome: snapshot.outcome ?? null, reason: snapshot.reason ?? null,
|
|
221
295
|
terminal: runtime.terminal(snapshot), running: active.has(runId), usage: snapshot.usage,
|
|
296
|
+
...(['paused', 'failed', 'completed'].includes(snapshot.phase)
|
|
297
|
+
? modelStopFields(snapshot.reason, snapshot.diagnostics.lastModelFailure) : {}),
|
|
222
298
|
finalText: configuration.hostVerification && snapshot.outcome !== 'verified' ? null
|
|
223
299
|
: snapshot.finalText ?? snapshot.candidate?.text ?? null, cursor: tail(runId),
|
|
224
300
|
...(pendingApproval ? { pendingApproval } : {}),
|
|
@@ -230,7 +306,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
230
306
|
const controller = new AbortController();
|
|
231
307
|
const runOptions = detachOnShutdown ? { detachSignal: controller.signal } : { signal: controller.signal };
|
|
232
308
|
const execute = async () => {
|
|
233
|
-
let deadline;
|
|
309
|
+
let deadline, receiptDeadline;
|
|
234
310
|
for (;;) {
|
|
235
311
|
try {
|
|
236
312
|
const snapshot = await runtime.run(runId, runOptions);
|
|
@@ -238,15 +314,19 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
238
314
|
const record = runtime.load(runId);
|
|
239
315
|
if (!hostReceiptSource(record)) return snapshot;
|
|
240
316
|
if (runtime.pendingCommands(runId).length) continue;
|
|
317
|
+
receiptDeadline ??= Date.now() + RECEIPT_WAIT_MS;
|
|
318
|
+
const waitMs = receiptDeadline - Date.now();
|
|
319
|
+
if (waitMs <= 0) return snapshot;
|
|
241
320
|
const idle = new AbortController();
|
|
242
321
|
receiptWaits.set(runId, idle);
|
|
243
322
|
const signal = AbortSignal.any([idle.signal, controller.signal]);
|
|
244
323
|
try {
|
|
245
324
|
const command = await waitForHostReceipt(record, {
|
|
246
325
|
read: (call, operationKey, receiptSignal) => readHostReceipt(runId, call, operationKey, receiptSignal),
|
|
247
|
-
signal, assertCurrent: () => signal.throwIfAborted(),
|
|
326
|
+
signal, waitMs, assertCurrent: () => signal.throwIfAborted(),
|
|
248
327
|
});
|
|
249
|
-
if (command)
|
|
328
|
+
if (!command) return snapshot;
|
|
329
|
+
runtime.submit(runId, command);
|
|
250
330
|
} catch (error) {
|
|
251
331
|
if (controller.signal.aborted || !idle.signal.aborted) throw error;
|
|
252
332
|
} finally { receiptWaits.delete(runId); }
|
|
@@ -266,8 +346,9 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
266
346
|
if (!detachOnShutdown || !controller.signal.aborted)
|
|
267
347
|
log(`run ${runId} stopped: ${isNativeError(error) ? error.code : publicErrorMessage(error)}`);
|
|
268
348
|
})
|
|
269
|
-
.finally(() => { active.delete(runId); liveModelDisplay.delete(runId); });
|
|
349
|
+
.finally(() => { active.delete(runId); liveModelDisplay.delete(runId); reportActivity(); });
|
|
270
350
|
active.set(runId, { controller, done });
|
|
351
|
+
reportActivity();
|
|
271
352
|
};
|
|
272
353
|
const lookup = runId => {
|
|
273
354
|
try { return runtime.authority(runId); }
|
|
@@ -310,13 +391,13 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
310
391
|
return { protocolVersion: ENGINE_PROTOCOL, engine: { name: '@kingsoftcloud/agentkit-harness-node', version: packageVersion(), ...runtime.info() },
|
|
311
392
|
capabilities: { methods: detachOnShutdown ? [...METHODS, DURABLE_APPROVAL_METHOD,
|
|
312
393
|
...(host.services.toolEffects ? [HOST_OBSERVATIONS_METHOD] : [])] : METHODS,
|
|
313
|
-
eventSchema: ENGINE_EVENT_SCHEMA, liveThinking: true, liveToolDrafts: true, hostServices: ['approvals', 'tools'],
|
|
394
|
+
eventSchema: ENGINE_EVENT_SCHEMA, liveThinking: true, liveToolDrafts: true, liveText: true, hostServices: ['approvals', 'tools'],
|
|
314
395
|
approvals: host.services.durableApprovals ? 'durable' : host.services.approvals ? 'host' : startup.approval,
|
|
315
396
|
hostTools: host.services.tools, toolPolicy: ENGINE_TOOL_POLICY, executionPolicy: ENGINE_EXECUTION_POLICY,
|
|
316
397
|
...(detachOnShutdown ? { scopedHostRequests: true } : {}),
|
|
317
398
|
...(host.services.context ? { hostContext: ENGINE_CONTEXT } : {}),
|
|
318
399
|
...(host.services.hooks ? { hostHooks: ENGINE_HOOKS } : {}),
|
|
319
|
-
...(host.services.verification ? { hostVerification: ENGINE_VERIFICATION } : {}),
|
|
400
|
+
...(host.services.verification ? { hostVerification: ENGINE_VERIFICATION, workspaceCommandVerification: ENGINE_COMMAND_VERIFIER } : {}),
|
|
320
401
|
...(host.services.toolEffects ? { hostToolEffects: ENGINE_HOST_EFFECT } : {}),
|
|
321
402
|
...(host.services.toolReceipts ? { hostToolReceipts: TOOL_RECEIPT_OBSERVATION_CONTRACT } : {}),
|
|
322
403
|
...(runtime.info().model.images ? { inputImages: ENGINE_INPUT_IMAGES } : {}),
|
|
@@ -356,7 +437,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
356
437
|
requireRun(params);
|
|
357
438
|
const rest = status(params.runId);
|
|
358
439
|
return params.deliveryPresentation === true && rest.phase === 'completed' && text(rest.finalText)
|
|
359
|
-
? { ...rest, deliveryEvidence:
|
|
440
|
+
? { ...rest, deliveryEvidence: runtime.deliveryEvidence(params.runId) } : rest;
|
|
360
441
|
},
|
|
361
442
|
async [HOST_OBSERVATIONS_METHOD](params) {
|
|
362
443
|
if (!host.services.toolEffects) throw rpcError(ERRORS.method, 'host observations unavailable');
|
|
@@ -377,13 +458,16 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
377
458
|
const cursor = Number.isSafeInteger(params.cursor) && params.cursor >= 0 ? params.cursor : 0;
|
|
378
459
|
const thinkingPresentation = typeof params.thinkingCursor === 'string';
|
|
379
460
|
const draftPresentation = typeof params.toolDraftCursor === 'string';
|
|
461
|
+
const textPresentation = typeof params.textCursor === 'string';
|
|
462
|
+
const textCursor = textPresentation ? /^([\da-f-]{36}):(\d{1,16})$/.exec(params.textCursor) : null;
|
|
380
463
|
const thinkingCursor = thinkingPresentation ? /^([\da-f-]{36}):(\d{1,16})$/.exec(params.thinkingCursor) : null;
|
|
381
464
|
const deadline = Date.now() + Math.min(Math.max(Number(params.waitMs) || 0, 0), 30000);
|
|
382
465
|
// The wait reads only the journal suffix; the Run record is loaded once, on return.
|
|
383
466
|
for (;;) {
|
|
467
|
+
lifetime.signal.throwIfAborted();
|
|
384
468
|
const running = active.has(params.runId), events = runtime.events(params.runId, cursor);
|
|
385
|
-
const live = (thinkingPresentation || draftPresentation) && running ? liveModelDisplay.get(runId) : null;
|
|
386
|
-
let thinking, toolDraft;
|
|
469
|
+
const live = (thinkingPresentation || draftPresentation || textPresentation) && running ? liveModelDisplay.get(runId) : null;
|
|
470
|
+
let thinking, toolDraft, body;
|
|
387
471
|
if (live) {
|
|
388
472
|
const first = live.end - live.text.length;
|
|
389
473
|
const after = thinkingCursor?.[1] === live.id ? Number(thinkingCursor[2]) : first;
|
|
@@ -391,7 +475,15 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
391
475
|
const draftCursor = `${live.id}:${live.draftRevision}`;
|
|
392
476
|
const hasThinking = thinkingPresentation && start < live.end;
|
|
393
477
|
const hasDraft = draftPresentation && live.draftRevision > 0 && draftCursor !== params.toolDraftCursor;
|
|
394
|
-
|
|
478
|
+
const bodyFirst = live.bodyEnd - live.body.length;
|
|
479
|
+
const bodyAfter = textCursor?.[1] === live.id ? Number(textCursor[2]) : bodyFirst;
|
|
480
|
+
const bodyStart = Math.max(bodyFirst, bodyAfter);
|
|
481
|
+
const hasText = textPresentation && bodyStart < live.bodyEnd;
|
|
482
|
+
if ((hasThinking || hasDraft || hasText) && runtime.authority(runId).snapshot.pendingIntent === live.operationKey) {
|
|
483
|
+
if (hasText) {
|
|
484
|
+
const chunk = live.body.slice(bodyStart - bodyFirst, bodyStart - bodyFirst + THINKING_PAGE_CHARS);
|
|
485
|
+
body = { requestId: publicRequestId(live.operationKey), cursor: `${live.id}:${bodyStart + chunk.length}`, offset: bodyStart, text: chunk };
|
|
486
|
+
}
|
|
395
487
|
if (hasThinking) {
|
|
396
488
|
const chunk = live.text.slice(start - first, start - first + THINKING_PAGE_CHARS);
|
|
397
489
|
thinking = { id: live.id, cursor: `${live.id}:${start + chunk.length}`, text: chunk };
|
|
@@ -400,22 +492,23 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
400
492
|
tools: [...live.tools].map(([index, name]) => ({ index, name })) };
|
|
401
493
|
}
|
|
402
494
|
}
|
|
403
|
-
if (events.length || thinking || toolDraft || !running || Date.now() >= deadline) {
|
|
495
|
+
if (events.length || thinking || toolDraft || body || !running || Date.now() >= deadline) {
|
|
404
496
|
const next = events.length ? events.at(-1).seq : cursor;
|
|
405
497
|
if (next > (seen.get(params.runId) ?? 0)) seen.set(params.runId, next);
|
|
406
498
|
const { snapshot } = runtime.authority(runId);
|
|
407
499
|
return { events: events.map(event => {
|
|
408
|
-
const projected = projectEngineEvent(event, !!configuration.hostVerification, thinkingPresentation || draftPresentation);
|
|
500
|
+
const projected = projectEngineEvent(event, !!configuration.hostVerification, thinkingPresentation || draftPresentation || textPresentation);
|
|
409
501
|
if (projected.kind !== 'run.terminal' || projected.title !== 'completed' || !text(projected.detail)) return projected;
|
|
410
502
|
const artifacts = currentDeliveryManifest(snapshot)?.artifacts;
|
|
411
503
|
return { ...projected, ...(artifacts?.length ? { deliverables: artifacts } : {}),
|
|
412
|
-
...((thinkingPresentation || draftPresentation) ? { deliveryEvidence:
|
|
504
|
+
...((thinkingPresentation || draftPresentation) ? { deliveryEvidence: runtime.deliveryEvidence(runId) } : {}) };
|
|
413
505
|
}), cursor: next,
|
|
414
506
|
...(thinking ? { thinking } : {}),
|
|
415
507
|
...(toolDraft ? { toolDraft } : {}),
|
|
508
|
+
...(body ? { text: body } : {}),
|
|
416
509
|
terminal: runtime.terminal(snapshot), running: active.has(runId) };
|
|
417
510
|
}
|
|
418
|
-
await
|
|
511
|
+
await wait(250, undefined, { signal: lifetime.signal });
|
|
419
512
|
}
|
|
420
513
|
},
|
|
421
514
|
async 'run/resume'(params) {
|
|
@@ -426,17 +519,32 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
426
519
|
if (!before.terminal) continueOnSubscription(params.runId, record);
|
|
427
520
|
return status(params.runId);
|
|
428
521
|
},
|
|
522
|
+
async 'run/guide'(params) {
|
|
523
|
+
const record = requireRun(params);
|
|
524
|
+
const { runId, inputId, text: input } = params;
|
|
525
|
+
if (record.configuration.guidancePolicy !== 'boundary-guide/v1') return { status: 'unsupported' };
|
|
526
|
+
if (!/^guide-[a-f0-9]{64}$/.test(inputId ?? '') || !text(input) || input.length > 32768)
|
|
527
|
+
throw rpcError(ERRORS.params, 'invalid run guidance');
|
|
528
|
+
// Recover the revision from the original command when its reply was
|
|
529
|
+
// lost. The store still checks that replay uses identical input.
|
|
530
|
+
const previous = runtime.load(runId).commands.find(row => row.command.commandId === inputId);
|
|
531
|
+
return runtime.submit(runId, { commandId: inputId, kind: 'guide',
|
|
532
|
+
payload: { text: input, expectedGoalRevision: previous?.command.payload.expectedGoalRevision ?? record.snapshot.goalRevision } });
|
|
533
|
+
},
|
|
429
534
|
async [DURABLE_APPROVAL_METHOD](params) {
|
|
430
535
|
requireRun(params);
|
|
431
536
|
if (!detachOnShutdown || !text(params.interactionId) || !['allow', 'deny'].includes(params.decision))
|
|
432
537
|
throw rpcError(ERRORS.params, 'interactionId and approval decision are required');
|
|
433
|
-
const { runId, interactionId, decision } = params;
|
|
538
|
+
const { runId, interactionId, decision, denialReason } = params;
|
|
539
|
+
if (denialReason !== undefined && (decision !== 'deny' || !isApprovalDenialReason(denialReason)))
|
|
540
|
+
throw rpcError(ERRORS.params, 'invalid approval denial reason');
|
|
434
541
|
const commandId = `approval-${createHash('sha256').update(interactionId).digest('hex')}`;
|
|
435
542
|
const record = runtime.load(runId);
|
|
436
543
|
if (!record.commands.some(row => row.command.commandId === commandId)
|
|
437
544
|
&& runtime.pendingApproval(record.snapshot, record.configuration)?.interactionId !== interactionId)
|
|
438
545
|
throw rpcError(ERRORS.params, 'interaction_mismatch');
|
|
439
|
-
const receipt = runtime.submit(runId, { commandId, kind: 'submit_interaction',
|
|
546
|
+
const receipt = runtime.submit(runId, { commandId, kind: 'submit_interaction',
|
|
547
|
+
payload: { interactionId, decision, ...(denialReason === undefined ? {} : { denialReason }) } });
|
|
440
548
|
if (receipt.status !== 'rejected') {
|
|
441
549
|
const continueRun = () => { if (!closing && !status(runId).terminal) continueOnSubscription(runId, record); };
|
|
442
550
|
const running = active.get(runId);
|
|
@@ -480,7 +588,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
480
588
|
send({ jsonrpc: '2.0', id: frame?.id ?? null, error: { code: ERRORS.request, message: 'Invalid Request' } }); continue;
|
|
481
589
|
}
|
|
482
590
|
// Requests run concurrently so a long poll never blocks a cancel or an approval reply.
|
|
483
|
-
|
|
591
|
+
const task = (async () => {
|
|
484
592
|
const reply = body => { if (frame.id !== undefined) send({ jsonrpc: '2.0', id: frame.id, ...body }); };
|
|
485
593
|
try {
|
|
486
594
|
if (!Object.hasOwn(handlers, frame.method)) throw rpcError(ERRORS.method, 'Method not found');
|
|
@@ -491,12 +599,18 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
491
599
|
message: isNativeError(error) ? error.code : publicErrorMessage(error) } });
|
|
492
600
|
}
|
|
493
601
|
if (closing) frames.close();
|
|
494
|
-
})()
|
|
602
|
+
})().finally(() => {
|
|
603
|
+
handlersInFlight.delete(task);
|
|
604
|
+
reportActivity();
|
|
605
|
+
});
|
|
606
|
+
handlersInFlight.add(task);
|
|
607
|
+
reportActivity();
|
|
495
608
|
}
|
|
496
609
|
closing = true;
|
|
610
|
+
lifetime.abort();
|
|
497
611
|
for (const { controller } of active.values()) controller.abort();
|
|
498
612
|
for (const waiter of pending.values()) waiter.reject(new Error('engine closing'));
|
|
499
|
-
await Promise.allSettled([...active.values()].map(item => item.done));
|
|
613
|
+
await Promise.allSettled([...handlersInFlight, ...[...active.values()].map(item => item.done)]);
|
|
500
614
|
await (await runtimePromise?.catch(() => null))?.close();
|
|
501
615
|
}
|
|
502
616
|
function rpcError(code, message, data) { return Object.assign(new Error(message), { rpc: { code, message, ...(data ? { data } : {}) } }); }
|
|
@@ -519,6 +633,7 @@ export function engineStartupFromArgs(argv, env) {
|
|
|
519
633
|
sessionId: values.session ?? 'engine-session', approval, approvalTimeoutMs: number('AGENTKIT_ENGINE_APPROVAL_TIMEOUT_MS') ?? 600000,
|
|
520
634
|
scope: { tenantId: values.tenant ?? 'local', workspaceId: 'local', userId: values.user ?? 'local-user', agentId: values.agent ?? 'engine' },
|
|
521
635
|
model: { protocol: env.AGENTKIT_ENGINE_MODEL_PROTOCOL ?? 'openai-chat', name: need(env.AGENTKIT_ENGINE_MODEL_NAME, 'AGENTKIT_ENGINE_MODEL_NAME'),
|
|
636
|
+
compatibilityRule: env.AGENTKIT_ENGINE_MODEL_COMPAT_RULE ?? env.KSADK_MODEL_COMPAT_RULE,
|
|
522
637
|
baseUrl: need(env.AGENTKIT_ENGINE_MODEL_BASE_URL, 'AGENTKIT_ENGINE_MODEL_BASE_URL'),
|
|
523
638
|
apiKeyEnv: env.AGENTKIT_ENGINE_MODEL_API_KEY_ENV ?? 'AGENTKIT_ENGINE_MODEL_API_KEY',
|
|
524
639
|
contextWindow: number('AGENTKIT_ENGINE_MODEL_CONTEXT_WINDOW'), maxOutputTokens: number('AGENTKIT_ENGINE_MODEL_MAX_OUTPUT_TOKENS'),
|