@kingsoftcloud/agentkit-harness-node 0.0.20 → 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 +15 -15
- package/package.json +2 -2
- package/src/native/engine-client.mjs +2 -1
- package/src/native/engine-delivery-evidence.mjs +2 -1
- package/src/native/engine-host-effects.mjs +26 -16
- package/src/native/engine-managed-service.mjs +12 -5
- package/src/native/engine-runtime.mjs +37 -8
- package/src/native/engine-server.mjs +56 -22
- package/src/native/engine-service.mjs +82 -9
- 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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kingsoftcloud/agentkit-harness-node",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.21",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Standalone Native Harness Node adapters: a durable SQLite run store, a one-request model HTTP port, and a minimal versioned JSON-RPC 2.0 over NDJSON process entry. Reuses the shared Native adapter implementations and externalizes @kingsoftcloud/agentkit-harness-core; depends on no Studio/DSH code at runtime.",
|
|
@@ -154,7 +154,7 @@
|
|
|
154
154
|
"src/package-integrity.mjs"
|
|
155
155
|
],
|
|
156
156
|
"dependencies": {
|
|
157
|
-
"@kingsoftcloud/agentkit-harness-core": "0.0.
|
|
157
|
+
"@kingsoftcloud/agentkit-harness-core": "0.0.21",
|
|
158
158
|
"@astral-sh/ruff-wasm-nodejs": "0.16.8",
|
|
159
159
|
"parse5": "7.3.0",
|
|
160
160
|
"playwright-core": "1.58.2",
|
|
@@ -55,7 +55,8 @@ export function connectEngine({ input, output, onApproveTool, onCallTool, hostNa
|
|
|
55
55
|
services: { approvals: typeof onApproveTool === 'function', tools: typeof onCallTool === 'function' } }),
|
|
56
56
|
startRun: params => call('run/start', params),
|
|
57
57
|
status: runId => call('run/status', { runId }),
|
|
58
|
-
events: (runId, cursor = 0, waitMs = 0
|
|
58
|
+
events: (runId, cursor = 0, waitMs = 0, thinkingCursor, toolDraftCursor, textCursor) =>
|
|
59
|
+
call('run/events', { runId, cursor, waitMs, thinkingCursor, toolDraftCursor, textCursor }),
|
|
59
60
|
resume: runId => call('run/resume', { runId }),
|
|
60
61
|
guide: (runId, inputId, text) => call('run/guide', { runId, inputId, text }),
|
|
61
62
|
cancel: runId => call('run/cancel', { runId }),
|
|
@@ -8,6 +8,7 @@ import { currentDeliveryManifest } from '@kingsoftcloud/agentkit-harness-core';
|
|
|
8
8
|
const safePath = path => typeof path === 'string' && path.length <= 2048
|
|
9
9
|
&& !/[\\:\u0000-\u001f\u007f?#]/u.test(path) && path.split('/').every(part => part && part !== '.' && part !== '..');
|
|
10
10
|
const screenshotPath = path => safePath(path) && /\.(?:png|jpe?g|webp)$/i.test(path);
|
|
11
|
+
const generatedPythonCache = path => path.split('/').includes('__pycache__') && /\.py[co]$/i.test(path);
|
|
11
12
|
|
|
12
13
|
/** Committed effects for this Run only. The snapshot's workspaceModifiedPaths
|
|
13
14
|
* also contains paths inherited from earlier Turns. */
|
|
@@ -27,7 +28,7 @@ export function engineDeliveryEvidence(record, netChanges) {
|
|
|
27
28
|
if (tool === 'browser_inspect_workspace' && ['ok', 'error'].includes(result.status) && screenshotPath(screenshot)) screenshots.add(screenshot);
|
|
28
29
|
if (result.status !== 'ok') continue;
|
|
29
30
|
for (const changed of result.workspaceChangedPaths ?? []) {
|
|
30
|
-
if (!safePath(changed)) continue;
|
|
31
|
+
if (!safePath(changed) || tool === 'run_command' && generatedPythonCache(changed)) continue;
|
|
31
32
|
const counts = changed === path && [added, removed].every(value => Number.isSafeInteger(value) && value >= 0)
|
|
32
33
|
? { added, removed } : {};
|
|
33
34
|
// Overlapping edits cannot be counted as a net diff from their tool deltas.
|
|
@@ -5,6 +5,7 @@ import { canonical, invariant, isNativeError, toolReceiptSource } from '@kingsof
|
|
|
5
5
|
export const ENGINE_HOST_EFFECT = 'agentkit.engine-host-tool-effect/v1';
|
|
6
6
|
const MAX_INPUT_BYTES = 128 * 1024;
|
|
7
7
|
const MAX_INPUTS = 64;
|
|
8
|
+
export const RECEIPT_WAIT_MS = 30_000;
|
|
8
9
|
|
|
9
10
|
export function hostReceiptSource(record) {
|
|
10
11
|
const originalOperationKey = record.snapshot.toolReconciliation?.operationKey;
|
|
@@ -27,28 +28,37 @@ export function hostReceiptReply(reply, observationId) {
|
|
|
27
28
|
|
|
28
29
|
/** Idle reads inspect a durable checkpoint. The Kernel claims the original
|
|
29
30
|
* remote receipt query separately from the initial mutation. */
|
|
30
|
-
export async function waitForHostReceipt(record, { read, signal, assertCurrent }) {
|
|
31
|
+
export async function waitForHostReceipt(record, { read, signal, assertCurrent, waitMs = RECEIPT_WAIT_MS }) {
|
|
31
32
|
const source = hostReceiptSource(record);
|
|
32
33
|
if (!source) return null;
|
|
33
34
|
const { call, originalOperationKey } = source, { runId } = record.snapshot;
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
35
|
+
const deadline = AbortSignal.timeout(waitMs);
|
|
36
|
+
const polling = AbortSignal.any([signal, deadline]);
|
|
37
|
+
try {
|
|
38
|
+
while (!polling.aborted) {
|
|
39
|
+
assertCurrent();
|
|
40
|
+
const ready = await read(call, originalOperationKey, polling).catch(() => null);
|
|
41
|
+
polling.throwIfAborted();
|
|
42
|
+
assertCurrent();
|
|
43
|
+
if (ready) {
|
|
44
|
+
const digest = createHash('sha256').update(canonical({ runId, originalOperationKey, token: ready.token })).digest('hex');
|
|
45
|
+
const prefix = 'host-receipt-' + digest;
|
|
46
|
+
const attempts = record.commands.filter(row => row.consumed && row.command.commandId.startsWith(prefix + '-')).length;
|
|
47
|
+
// A terminal fact has a different checkpoint token. Give the host a
|
|
48
|
+
// bounded window to publish it before leaving the durable Run idle.
|
|
49
|
+
if (ready.settled ? attempts < 3 : attempts === 0 || Date.now() < ready.retryUntil) {
|
|
50
|
+
if (attempts) await delay(Math.min(1500 * attempts, 5000), undefined, { signal: polling });
|
|
51
|
+
assertCurrent();
|
|
52
|
+
return { commandId: prefix + '-' + attempts, kind: 'reconcile_tool', payload: { originalOperationKey } };
|
|
53
|
+
}
|
|
48
54
|
}
|
|
55
|
+
await delay(1000, undefined, { signal: polling });
|
|
49
56
|
}
|
|
50
|
-
|
|
57
|
+
} catch (error) {
|
|
58
|
+
if (!deadline.aborted || signal.aborted) throw error;
|
|
51
59
|
}
|
|
60
|
+
assertCurrent();
|
|
61
|
+
return null;
|
|
52
62
|
}
|
|
53
63
|
|
|
54
64
|
/** The host receives original user text and stable identities, never imported prose or media. */
|
|
@@ -2,7 +2,7 @@ import { createHash, createPublicKey, timingSafeEqual } from 'node:crypto';
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { canonical, configure, invariant, parseNativeJson, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
|
|
4
4
|
import { createEngineRuntime } from './engine-runtime.mjs';
|
|
5
|
-
import { ENGINE_HOST_EFFECT, waitForHostReceipt } from './engine-host-effects.mjs';
|
|
5
|
+
import { ENGINE_HOST_EFFECT, RECEIPT_WAIT_MS, waitForHostReceipt } from './engine-host-effects.mjs';
|
|
6
6
|
import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
|
|
7
7
|
import { createManagedSessionDelivery, MANAGED_SESSION_DELIVERY, projectManagedSessionEvent } from './engine-managed-delivery.mjs';
|
|
8
8
|
import { createManagedEngineHost, MANAGED_HOST_RESOURCES } from './engine-managed-host.mjs';
|
|
@@ -150,12 +150,19 @@ export function createEngineManagedService({ startup, stateDir, workspace, confi
|
|
|
150
150
|
}) : {};
|
|
151
151
|
const hasHostReceipts = configuration.tools.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT
|
|
152
152
|
&& tool.recoveryPolicy === 'receipt-observation/v1');
|
|
153
|
-
function
|
|
154
|
-
|
|
155
|
-
return
|
|
153
|
+
function executeWithReceipts({ execute }) {
|
|
154
|
+
let deadline;
|
|
155
|
+
return execute({ onIdle(_snapshot, { signal: idleSignal, assertCurrent }) {
|
|
156
|
+
assertCurrent();
|
|
157
|
+
deadline ??= Date.now() + RECEIPT_WAIT_MS;
|
|
158
|
+
const waitMs = deadline - Date.now();
|
|
159
|
+
return waitMs <= 0 ? null : waitForHostReceipt(store.load(scope, runId), {
|
|
160
|
+
read: readReceipt, signal: idleSignal, assertCurrent, waitMs,
|
|
161
|
+
});
|
|
162
|
+
} });
|
|
156
163
|
}
|
|
157
164
|
return { scope, buildId, configuration, ports: engine.ports, ...delivery,
|
|
158
|
-
...(hasHostReceipts ? { withExecution:
|
|
165
|
+
...(hasHostReceipts ? { withExecution: executeWithReceipts } : {}),
|
|
159
166
|
release: () => engine.close() };
|
|
160
167
|
} catch (error) {
|
|
161
168
|
await engine.close();
|
|
@@ -17,6 +17,7 @@ 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';
|
|
21
22
|
import { createEngineDeliveryJournal, engineDeliveryEvidence } from './engine-delivery-evidence.mjs';
|
|
22
23
|
import { createNativeWorkspaceTools } from './workspace-tools.mjs';
|
|
@@ -40,7 +41,7 @@ import { admitEngineToolPolicy, restrictEngineTools } from './engine-tool-policy
|
|
|
40
41
|
import { admitEngineContextSources, engineContextPort } from './engine-context.mjs';
|
|
41
42
|
import { admitEngineHooks, engineHookPort } from './engine-hooks.mjs';
|
|
42
43
|
import { ENGINE_HOST_EFFECT, completedHostObservations, engineUserObservations } from './engine-host-effects.mjs';
|
|
43
|
-
import { admitEngineVerification, engineVerificationPort } from './engine-verification.mjs';
|
|
44
|
+
import { admitEngineVerification, ENGINE_COMMAND_VERIFIER, engineVerificationPort } from './engine-verification.mjs';
|
|
44
45
|
|
|
45
46
|
export const ENGINE_RUNTIME_CONTRACT = 'agentkit.engine-runtime/v1';
|
|
46
47
|
export const ENGINE_EXECUTION_POLICY = 'agentkit.engine-execution-policy/v1';
|
|
@@ -60,7 +61,7 @@ const approvalDenialMessages = {
|
|
|
60
61
|
approval_cancelled: 'This approval was cancelled. The action did not run. Do not request it again unless the user asks to continue.',
|
|
61
62
|
};
|
|
62
63
|
|
|
63
|
-
function durableDecision(record, request, explainDenial = false) {
|
|
64
|
+
function durableDecision(record, request, explainDenial = false, workspaceWriteSafe = false) {
|
|
64
65
|
const { call, operationKey } = request;
|
|
65
66
|
const interactionId = `engine-permission-${digest({ runId: request.runId, call, definition: request.definition })}`;
|
|
66
67
|
// Walk backward only within the lifetime of this call. A reused provider
|
|
@@ -83,7 +84,7 @@ function durableDecision(record, request, explainDenial = false) {
|
|
|
83
84
|
}
|
|
84
85
|
return { status: 'approval_required', approvalPolicy: DURABLE_APPROVAL, interactionId,
|
|
85
86
|
content: { contract: ENGINE_APPROVAL_CONTRACT, code: 'approval_required', argumentDigest: digest(call.arguments),
|
|
86
|
-
subject: engineApprovalSubject(call) } };
|
|
87
|
+
subject: engineApprovalSubject(call), ...(workspaceWriteSafe ? { workspaceWriteSafe } : {}) } };
|
|
87
88
|
}
|
|
88
89
|
|
|
89
90
|
function admitExecutionPolicy(policy, legacyMaxModelCalls) {
|
|
@@ -105,15 +106,26 @@ export function admitEngineModel(model) {
|
|
|
105
106
|
&& (model.maxOutputTokens == null || Number.isSafeInteger(model.maxOutputTokens) && model.maxOutputTokens > 0)
|
|
106
107
|
&& (model.requestOutputTokens == null || Number.isSafeInteger(model.requestOutputTokens) && model.requestOutputTokens > 0)
|
|
107
108
|
&& (model.images === undefined || typeof model.images === 'boolean')
|
|
109
|
+
&& (model.compatibilityRule === undefined || isProviderCompatibilityRule(model.compatibilityRule))
|
|
108
110
|
&& typeof model.apiKey === 'function', 'engine_model_invalid');
|
|
109
111
|
const contextWindow = model.contextWindow ?? 128000;
|
|
110
112
|
return { protocol: model.protocol ?? 'openai-chat', modelName: model.name, baseUrl: model.baseUrl, parameters: {},
|
|
113
|
+
...(model.compatibilityRule === undefined ? {} : { compatibilityRule: model.compatibilityRule }),
|
|
111
114
|
input: model.images ? ['text', 'image'] : ['text'], contextWindow,
|
|
112
115
|
maxOutputTokens: presetRequestOutputTokens({ configured: model.requestOutputTokens ?? null,
|
|
113
116
|
modelMaxOutputTokens: model.maxOutputTokens ?? null, contextWindow }),
|
|
114
117
|
requestTimeoutMs: model.requestTimeoutMs ?? 180000 };
|
|
115
118
|
}
|
|
116
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
|
+
|
|
117
129
|
const CONVERSATION_TURNS = 64, CONVERSATION_CHARS = 60000;
|
|
118
130
|
export const ENGINE_INPUT_IMAGES = Object.freeze({ maxCount: 8, maxEncodedBytes: 6 * 1024 * 1024 });
|
|
119
131
|
|
|
@@ -206,8 +218,9 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
206
218
|
const roles = nativeChildRoles({ subAgents });
|
|
207
219
|
const supportsImages = description.input.includes('image');
|
|
208
220
|
const store = runStore ?? new SqliteRunStore(join(stateDir, 'runs.sqlite'));
|
|
209
|
-
const decide = async (request, explainDenial = false) => {
|
|
210
|
-
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);
|
|
211
224
|
return await authorize(request) === 'allow' ? 'allow' : 'deny';
|
|
212
225
|
};
|
|
213
226
|
const artifacts = await createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope });
|
|
@@ -219,7 +232,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
219
232
|
const commands = createNativeLocalCommandTools({ workspaceRoot: root, stateRoot: join(stateDir, 'commands'), sessionId,
|
|
220
233
|
settings: local.settings, sourceEnv: local.environment, outputPolicy: local.outputPolicy, environmentPolicy: local.environmentPolicy,
|
|
221
234
|
shellPolicy: commandSandbox,
|
|
222
|
-
artifacts, authorize:
|
|
235
|
+
artifacts, authorize: (request, info) => decide(request, true, info?.readOnlyCommand),
|
|
236
|
+
classifyApproval: true, captureWorkspace: request => workspace.capture(request),
|
|
223
237
|
resolveOwnedCommand: createOwnedCommandResolver({ scope, store }) });
|
|
224
238
|
const web = createNativeWebTools({ fetch: fetchImpl, providerConfig: { provider: '' }, authorize: decide, sessionId, inlineMaxChars: 6000 });
|
|
225
239
|
const owners = [workspace, commands, web];
|
|
@@ -299,12 +313,15 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
299
313
|
};
|
|
300
314
|
const context = bindNativeContext({ description, context: {}, ...nativeContextDefaults(undefined) });
|
|
301
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);
|
|
302
319
|
const profile = { profileId: 'engine', profileVersion: digest(description), providerFamily: description.protocol,
|
|
303
320
|
compatibilityDigest: digest(description), supportsImages, discoveredToolExposure: 'direct-after-search/v1', streamTimeoutPolicy: 'idle/v1',
|
|
304
321
|
...(chatUsage ? { chatUsagePolicy: chatUsage } : {}), maxRetries: 2, maxProviderRetries: 10, ...context.profile,
|
|
305
322
|
maxOutputTokens: description.maxOutputTokens, contextWindow: description.contextWindow,
|
|
306
323
|
requestTimeoutMs: description.requestTimeoutMs, providerReplayMode: 'reasoning_content',
|
|
307
|
-
providerCompatibilityPolicy: admitProviderCompatibilityPolicy() };
|
|
324
|
+
providerCompatibilityPolicy: admitProviderCompatibilityPolicy(providerRule) };
|
|
308
325
|
const modelSurface = bindNativeModelSurface({ environment: execution.executionEnvironment(executionOptions), description });
|
|
309
326
|
const modelPort = createNativeModelPort({ fetchImpl, resolveProfile: async () => ({ protocol: description.protocol, baseUrl: description.baseUrl,
|
|
310
327
|
apiKey: await model.apiKey(), model: description.modelName, parameters: description.parameters }) });
|
|
@@ -370,7 +387,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
370
387
|
}
|
|
371
388
|
const ports = { model: modelPort, tools, workspace,
|
|
372
389
|
context: engineContextPort(context.port, callHostContext),
|
|
373
|
-
verification: engineVerificationPort(store, callHostVerification, digest
|
|
390
|
+
verification: engineVerificationPort(store, callHostVerification, digest,
|
|
391
|
+
request => workspace.capture(request).revision),
|
|
374
392
|
hooks: engineHookPort(callHostHook, request => {
|
|
375
393
|
const { snapshot } = store.authority(request.scope, request.runId);
|
|
376
394
|
const indexes = new Set(request.input.compaction.messageRefs.map(ref => Number(ref.split(':', 3)[1])));
|
|
@@ -407,6 +425,10 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
407
425
|
const contextSources = admitEngineContextSources(hostContext);
|
|
408
426
|
const hooks = admitEngineHooks(hostHooks);
|
|
409
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
|
+
}
|
|
410
432
|
const effectBound = hosted.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT);
|
|
411
433
|
const scopedCallbacks = contextSources.length || hooks.definitions.length || effectBound || !!verification;
|
|
412
434
|
const inputMessages = effectBound || originalInput ? [
|
|
@@ -483,10 +505,17 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
|
|
|
483
505
|
const tools = snapshot.childApproval
|
|
484
506
|
? store.authority(snapshot.childApproval.childScope, snapshot.childApproval.childRunId).configuration.tools
|
|
485
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;
|
|
486
512
|
return { interactionId: pending.interactionId, callId: pending.callId, tool: call.name,
|
|
487
513
|
...(tools.some(tool => tool.name === call.name && (tool.hostApprovalRequired
|
|
488
514
|
|| tool.hostEffectProtocol === ENGINE_HOST_EFFECT)) ? { requiresUserApproval: true } : {}),
|
|
489
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 } : {}),
|
|
490
519
|
...(subject ? { subject } : {}) };
|
|
491
520
|
},
|
|
492
521
|
deliveryEvidence(runId) {
|
|
@@ -36,8 +36,8 @@ import { ENGINE_VIEW_CONTRACT } from './engine-view-store.mjs';
|
|
|
36
36
|
import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
|
|
37
37
|
import { ENGINE_CONTEXT } from './engine-context.mjs';
|
|
38
38
|
import { ENGINE_HOOKS } from './engine-hooks.mjs';
|
|
39
|
-
import { ENGINE_HOST_EFFECT, hostReceiptReply, hostReceiptSource, waitForHostReceipt } from './engine-host-effects.mjs';
|
|
40
|
-
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';
|
|
41
41
|
import { nativeTodoPlan } from './activity-status.mjs';
|
|
42
42
|
import { nativeModelStopMessage } from './native-terminal-failure.mjs';
|
|
43
43
|
export { ENGINE_VIEW_CONTRACT };
|
|
@@ -53,7 +53,6 @@ const ERRORS = { parse: -32700, request: -32600, method: -32601, params: -32602,
|
|
|
53
53
|
notInitialized: -32010, runNotFound: -32011, runBusy: -32012 };
|
|
54
54
|
const text = value => typeof value === 'string' && value.trim().length > 0;
|
|
55
55
|
const toolName = /^[A-Za-z][A-Za-z0-9_.:/-]{0,127}$/;
|
|
56
|
-
const sleep = ms => new Promise(done => setTimeout(done, ms));
|
|
57
56
|
const publicRequestId = operationKey => createHash('sha256').update(operationKey).digest('hex');
|
|
58
57
|
const modelUsageFields = ['inputTokens', 'outputTokens', 'cachedInputTokens', 'cacheWriteInputTokens', 'reasoningTokens'];
|
|
59
58
|
function modelUsage(usage) {
|
|
@@ -104,12 +103,16 @@ export function projectEngineEvent(event, requiredVerification = false, thinking
|
|
|
104
103
|
}
|
|
105
104
|
if (event.kind === 'model.stream_interrupted') return { ...base, category: 'model', ...(text(thinking) ? { thinking, ...modelRequest } : {}) };
|
|
106
105
|
return { ...base, category: 'model', title: payload.kind ?? 'model',
|
|
107
|
-
...(text(thinking) ? { thinking
|
|
106
|
+
...modelRequest, ...(text(thinking) ? { thinking } : {}),
|
|
108
107
|
...(text(payload.text) && !(requiredVerification && payload.kind === 'final_candidate') ? { detail: payload.text } : {}),
|
|
109
108
|
...(Array.isArray(payload.toolCalls) && payload.toolCalls.length ? { tools: payload.toolCalls.map(call => call.name),
|
|
110
109
|
calls: payload.toolCalls.map(call => ({ callId: call.callId, name: call.name, arguments: bounded(call.arguments) })) } : {}),
|
|
111
110
|
...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
|
|
112
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 } : {}) };
|
|
113
116
|
case 'context.summary_completed':
|
|
114
117
|
case 'completion.delivery_review_completed':
|
|
115
118
|
return { ...base, category: 'model', ...(payload.usage ? { usage: modelUsage(payload.usage) } : {}) };
|
|
@@ -195,16 +198,18 @@ function boundedToolResult(name, value) {
|
|
|
195
198
|
return { ...result, ...observation, preview: result.preview.slice(0, PREVIEW_CHARS - JSON.stringify(observation).length) };
|
|
196
199
|
}
|
|
197
200
|
|
|
198
|
-
export async function serveEngine({ input, output, log = () => {}, startup, env = process.env, fetchImpl = fetch, detachOnShutdown = false, viewStore }) {
|
|
201
|
+
export async function serveEngine({ input, output, log = () => {}, startup, env = process.env, fetchImpl = fetch, detachOnShutdown = false, viewStore, onActivity = () => {} }) {
|
|
199
202
|
const frames = readline.createInterface({ input, crlfDelay: Infinity });
|
|
200
203
|
const send = frame => output.write(`${JSON.stringify(frame)}\n`);
|
|
201
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);
|
|
202
207
|
const liveModelDisplay = new Map();
|
|
203
208
|
function captureModelDisplay({ runId, operationKey }, event) {
|
|
204
|
-
if (!['thinking', 'tool_delta'].includes(event.kind)) return;
|
|
209
|
+
if (!['text', 'thinking', 'tool_delta'].includes(event.kind)) return;
|
|
205
210
|
let current = liveModelDisplay.get(runId);
|
|
206
211
|
if (current?.operationKey !== operationKey) {
|
|
207
|
-
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 };
|
|
208
213
|
liveModelDisplay.set(runId, current);
|
|
209
214
|
}
|
|
210
215
|
if (event.kind === 'thinking') {
|
|
@@ -212,6 +217,11 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
212
217
|
current.text = (current.text + event.text).slice(-THINKING_HISTORY_CHARS);
|
|
213
218
|
return;
|
|
214
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
|
+
}
|
|
215
225
|
// A draft has no call ID, argument data, or authority to execute.
|
|
216
226
|
const { index, name } = event.metadata ?? {};
|
|
217
227
|
if (!Number.isSafeInteger(index) || index < 0 || !current.tools.has(index) && current.tools.size >= 16) return;
|
|
@@ -296,7 +306,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
296
306
|
const controller = new AbortController();
|
|
297
307
|
const runOptions = detachOnShutdown ? { detachSignal: controller.signal } : { signal: controller.signal };
|
|
298
308
|
const execute = async () => {
|
|
299
|
-
let deadline;
|
|
309
|
+
let deadline, receiptDeadline;
|
|
300
310
|
for (;;) {
|
|
301
311
|
try {
|
|
302
312
|
const snapshot = await runtime.run(runId, runOptions);
|
|
@@ -304,15 +314,19 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
304
314
|
const record = runtime.load(runId);
|
|
305
315
|
if (!hostReceiptSource(record)) return snapshot;
|
|
306
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;
|
|
307
320
|
const idle = new AbortController();
|
|
308
321
|
receiptWaits.set(runId, idle);
|
|
309
322
|
const signal = AbortSignal.any([idle.signal, controller.signal]);
|
|
310
323
|
try {
|
|
311
324
|
const command = await waitForHostReceipt(record, {
|
|
312
325
|
read: (call, operationKey, receiptSignal) => readHostReceipt(runId, call, operationKey, receiptSignal),
|
|
313
|
-
signal, assertCurrent: () => signal.throwIfAborted(),
|
|
326
|
+
signal, waitMs, assertCurrent: () => signal.throwIfAborted(),
|
|
314
327
|
});
|
|
315
|
-
if (command)
|
|
328
|
+
if (!command) return snapshot;
|
|
329
|
+
runtime.submit(runId, command);
|
|
316
330
|
} catch (error) {
|
|
317
331
|
if (controller.signal.aborted || !idle.signal.aborted) throw error;
|
|
318
332
|
} finally { receiptWaits.delete(runId); }
|
|
@@ -332,8 +346,9 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
332
346
|
if (!detachOnShutdown || !controller.signal.aborted)
|
|
333
347
|
log(`run ${runId} stopped: ${isNativeError(error) ? error.code : publicErrorMessage(error)}`);
|
|
334
348
|
})
|
|
335
|
-
.finally(() => { active.delete(runId); liveModelDisplay.delete(runId); });
|
|
349
|
+
.finally(() => { active.delete(runId); liveModelDisplay.delete(runId); reportActivity(); });
|
|
336
350
|
active.set(runId, { controller, done });
|
|
351
|
+
reportActivity();
|
|
337
352
|
};
|
|
338
353
|
const lookup = runId => {
|
|
339
354
|
try { return runtime.authority(runId); }
|
|
@@ -376,13 +391,13 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
376
391
|
return { protocolVersion: ENGINE_PROTOCOL, engine: { name: '@kingsoftcloud/agentkit-harness-node', version: packageVersion(), ...runtime.info() },
|
|
377
392
|
capabilities: { methods: detachOnShutdown ? [...METHODS, DURABLE_APPROVAL_METHOD,
|
|
378
393
|
...(host.services.toolEffects ? [HOST_OBSERVATIONS_METHOD] : [])] : METHODS,
|
|
379
|
-
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'],
|
|
380
395
|
approvals: host.services.durableApprovals ? 'durable' : host.services.approvals ? 'host' : startup.approval,
|
|
381
396
|
hostTools: host.services.tools, toolPolicy: ENGINE_TOOL_POLICY, executionPolicy: ENGINE_EXECUTION_POLICY,
|
|
382
397
|
...(detachOnShutdown ? { scopedHostRequests: true } : {}),
|
|
383
398
|
...(host.services.context ? { hostContext: ENGINE_CONTEXT } : {}),
|
|
384
399
|
...(host.services.hooks ? { hostHooks: ENGINE_HOOKS } : {}),
|
|
385
|
-
...(host.services.verification ? { hostVerification: ENGINE_VERIFICATION } : {}),
|
|
400
|
+
...(host.services.verification ? { hostVerification: ENGINE_VERIFICATION, workspaceCommandVerification: ENGINE_COMMAND_VERIFIER } : {}),
|
|
386
401
|
...(host.services.toolEffects ? { hostToolEffects: ENGINE_HOST_EFFECT } : {}),
|
|
387
402
|
...(host.services.toolReceipts ? { hostToolReceipts: TOOL_RECEIPT_OBSERVATION_CONTRACT } : {}),
|
|
388
403
|
...(runtime.info().model.images ? { inputImages: ENGINE_INPUT_IMAGES } : {}),
|
|
@@ -443,13 +458,16 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
443
458
|
const cursor = Number.isSafeInteger(params.cursor) && params.cursor >= 0 ? params.cursor : 0;
|
|
444
459
|
const thinkingPresentation = typeof params.thinkingCursor === 'string';
|
|
445
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;
|
|
446
463
|
const thinkingCursor = thinkingPresentation ? /^([\da-f-]{36}):(\d{1,16})$/.exec(params.thinkingCursor) : null;
|
|
447
464
|
const deadline = Date.now() + Math.min(Math.max(Number(params.waitMs) || 0, 0), 30000);
|
|
448
465
|
// The wait reads only the journal suffix; the Run record is loaded once, on return.
|
|
449
466
|
for (;;) {
|
|
467
|
+
lifetime.signal.throwIfAborted();
|
|
450
468
|
const running = active.has(params.runId), events = runtime.events(params.runId, cursor);
|
|
451
|
-
const live = (thinkingPresentation || draftPresentation) && running ? liveModelDisplay.get(runId) : null;
|
|
452
|
-
let thinking, toolDraft;
|
|
469
|
+
const live = (thinkingPresentation || draftPresentation || textPresentation) && running ? liveModelDisplay.get(runId) : null;
|
|
470
|
+
let thinking, toolDraft, body;
|
|
453
471
|
if (live) {
|
|
454
472
|
const first = live.end - live.text.length;
|
|
455
473
|
const after = thinkingCursor?.[1] === live.id ? Number(thinkingCursor[2]) : first;
|
|
@@ -457,7 +475,15 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
457
475
|
const draftCursor = `${live.id}:${live.draftRevision}`;
|
|
458
476
|
const hasThinking = thinkingPresentation && start < live.end;
|
|
459
477
|
const hasDraft = draftPresentation && live.draftRevision > 0 && draftCursor !== params.toolDraftCursor;
|
|
460
|
-
|
|
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
|
+
}
|
|
461
487
|
if (hasThinking) {
|
|
462
488
|
const chunk = live.text.slice(start - first, start - first + THINKING_PAGE_CHARS);
|
|
463
489
|
thinking = { id: live.id, cursor: `${live.id}:${start + chunk.length}`, text: chunk };
|
|
@@ -466,12 +492,12 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
466
492
|
tools: [...live.tools].map(([index, name]) => ({ index, name })) };
|
|
467
493
|
}
|
|
468
494
|
}
|
|
469
|
-
if (events.length || thinking || toolDraft || !running || Date.now() >= deadline) {
|
|
495
|
+
if (events.length || thinking || toolDraft || body || !running || Date.now() >= deadline) {
|
|
470
496
|
const next = events.length ? events.at(-1).seq : cursor;
|
|
471
497
|
if (next > (seen.get(params.runId) ?? 0)) seen.set(params.runId, next);
|
|
472
498
|
const { snapshot } = runtime.authority(runId);
|
|
473
499
|
return { events: events.map(event => {
|
|
474
|
-
const projected = projectEngineEvent(event, !!configuration.hostVerification, thinkingPresentation || draftPresentation);
|
|
500
|
+
const projected = projectEngineEvent(event, !!configuration.hostVerification, thinkingPresentation || draftPresentation || textPresentation);
|
|
475
501
|
if (projected.kind !== 'run.terminal' || projected.title !== 'completed' || !text(projected.detail)) return projected;
|
|
476
502
|
const artifacts = currentDeliveryManifest(snapshot)?.artifacts;
|
|
477
503
|
return { ...projected, ...(artifacts?.length ? { deliverables: artifacts } : {}),
|
|
@@ -479,9 +505,10 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
479
505
|
}), cursor: next,
|
|
480
506
|
...(thinking ? { thinking } : {}),
|
|
481
507
|
...(toolDraft ? { toolDraft } : {}),
|
|
508
|
+
...(body ? { text: body } : {}),
|
|
482
509
|
terminal: runtime.terminal(snapshot), running: active.has(runId) };
|
|
483
510
|
}
|
|
484
|
-
await
|
|
511
|
+
await wait(250, undefined, { signal: lifetime.signal });
|
|
485
512
|
}
|
|
486
513
|
},
|
|
487
514
|
async 'run/resume'(params) {
|
|
@@ -561,7 +588,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
561
588
|
send({ jsonrpc: '2.0', id: frame?.id ?? null, error: { code: ERRORS.request, message: 'Invalid Request' } }); continue;
|
|
562
589
|
}
|
|
563
590
|
// Requests run concurrently so a long poll never blocks a cancel or an approval reply.
|
|
564
|
-
|
|
591
|
+
const task = (async () => {
|
|
565
592
|
const reply = body => { if (frame.id !== undefined) send({ jsonrpc: '2.0', id: frame.id, ...body }); };
|
|
566
593
|
try {
|
|
567
594
|
if (!Object.hasOwn(handlers, frame.method)) throw rpcError(ERRORS.method, 'Method not found');
|
|
@@ -572,12 +599,18 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
|
|
|
572
599
|
message: isNativeError(error) ? error.code : publicErrorMessage(error) } });
|
|
573
600
|
}
|
|
574
601
|
if (closing) frames.close();
|
|
575
|
-
})()
|
|
602
|
+
})().finally(() => {
|
|
603
|
+
handlersInFlight.delete(task);
|
|
604
|
+
reportActivity();
|
|
605
|
+
});
|
|
606
|
+
handlersInFlight.add(task);
|
|
607
|
+
reportActivity();
|
|
576
608
|
}
|
|
577
609
|
closing = true;
|
|
610
|
+
lifetime.abort();
|
|
578
611
|
for (const { controller } of active.values()) controller.abort();
|
|
579
612
|
for (const waiter of pending.values()) waiter.reject(new Error('engine closing'));
|
|
580
|
-
await Promise.allSettled([...active.values()].map(item => item.done));
|
|
613
|
+
await Promise.allSettled([...handlersInFlight, ...[...active.values()].map(item => item.done)]);
|
|
581
614
|
await (await runtimePromise?.catch(() => null))?.close();
|
|
582
615
|
}
|
|
583
616
|
function rpcError(code, message, data) { return Object.assign(new Error(message), { rpc: { code, message, ...(data ? { data } : {}) } }); }
|
|
@@ -600,6 +633,7 @@ export function engineStartupFromArgs(argv, env) {
|
|
|
600
633
|
sessionId: values.session ?? 'engine-session', approval, approvalTimeoutMs: number('AGENTKIT_ENGINE_APPROVAL_TIMEOUT_MS') ?? 600000,
|
|
601
634
|
scope: { tenantId: values.tenant ?? 'local', workspaceId: 'local', userId: values.user ?? 'local-user', agentId: values.agent ?? 'engine' },
|
|
602
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,
|
|
603
637
|
baseUrl: need(env.AGENTKIT_ENGINE_MODEL_BASE_URL, 'AGENTKIT_ENGINE_MODEL_BASE_URL'),
|
|
604
638
|
apiKeyEnv: env.AGENTKIT_ENGINE_MODEL_API_KEY_ENV ?? 'AGENTKIT_ENGINE_MODEL_API_KEY',
|
|
605
639
|
contextWindow: number('AGENTKIT_ENGINE_MODEL_CONTEXT_WINDOW'), maxOutputTokens: number('AGENTKIT_ENGINE_MODEL_MAX_OUTPUT_TOKENS'),
|