@kingsoftcloud/agentkit-harness-node 0.0.17 → 0.0.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/engine-view.html +642 -0
- package/dist/index.mjs +18 -10
- package/dist/rpc-entry.mjs +18 -10
- package/package.json +16 -2
- package/src/native/activity-status.mjs +13 -8
- package/src/native/browser-workspace-server.mjs +22 -7
- package/src/native/child-owner.mjs +8 -4
- package/src/native/children.mjs +12 -7
- package/src/native/command-shell.mjs +28 -3
- package/src/native/engine-client.mjs +83 -0
- package/src/native/engine-context.mjs +47 -0
- package/src/native/engine-delivery-evidence.mjs +37 -0
- package/src/native/engine-hooks.mjs +53 -0
- package/src/native/engine-host-effects.mjs +98 -0
- package/src/native/engine-managed-delivery.mjs +65 -0
- package/src/native/engine-managed-host.mjs +75 -0
- package/src/native/engine-managed-service.mjs +249 -0
- package/src/native/engine-runtime.mjs +480 -0
- package/src/native/engine-server.mjs +540 -0
- package/src/native/engine-service.mjs +281 -0
- package/src/native/engine-tool-policy.mjs +29 -0
- package/src/native/engine-verification.mjs +111 -0
- package/src/native/engine-view-store.mjs +63 -0
- package/src/native/instruction-assembly.mjs +67 -3
- package/src/native/local-background-supervisor.mjs +1 -1
- package/src/native/local-background.mjs +4 -3
- package/src/native/local-command-tools.mjs +10 -7
- package/src/native/native-kernel-events.mjs +103 -0
- package/src/native/native-kernel-permit.mjs +95 -0
- package/src/native/native-managed-execution-grants.mjs +232 -0
- package/src/native/native-managed-injection.mjs +53 -0
- package/src/native/native-managed-interaction.mjs +192 -0
- package/src/native/native-managed-kernel-http.mjs +122 -0
- package/src/native/native-managed-kernel.mjs +922 -0
- package/src/native/native-managed-scoped-control.mjs +116 -0
- package/src/native/native-managed-session-frames.mjs +43 -0
- package/src/native/native-managed-teams-context.mjs +126 -0
- package/src/native/native-teams-callback-authority.mjs +73 -0
- package/src/native/native-teams-context-contract.mjs +272 -0
- package/src/native/native-teams-json.mjs +38 -0
- package/src/native/native-terminal-failure.mjs +53 -0
- package/src/native/sqlite-store.mjs +1 -0
- package/src/native/workspace-tools.mjs +2 -0
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { hookResult, invariant, validateHookDefinition, validateHookResult } from '@kingsoftcloud/agentkit-harness-core';
|
|
2
|
+
|
|
3
|
+
export const ENGINE_HOOKS = 'agentkit.engine-hooks/v1';
|
|
4
|
+
|
|
5
|
+
export function admitEngineHooks(value) {
|
|
6
|
+
if (value === undefined) return { definitions: [], configuration: {}, timeoutMs: 0 };
|
|
7
|
+
invariant(value?.contract === ENGINE_HOOKS && Array.isArray(value.hooks)
|
|
8
|
+
&& value.hooks.length <= 32
|
|
9
|
+
&& Object.keys(value).every(key => ['contract', 'hooks', 'stopContinuationLimit'].includes(key)),
|
|
10
|
+
'engine_hooks_invalid');
|
|
11
|
+
const definitions = value.hooks.map(raw => {
|
|
12
|
+
const hook = validateHookDefinition(raw);
|
|
13
|
+
invariant(hook.timeoutMs <= 60000 && hook.maxInputBytes <= 4 * 1024 * 1024
|
|
14
|
+
&& hook.maxOutputBytes <= 1024 * 1024, 'engine_hook_limit_exceeded');
|
|
15
|
+
return hook;
|
|
16
|
+
});
|
|
17
|
+
const stop = definitions.some(hook => hook.events.includes('Stop'));
|
|
18
|
+
invariant(stop === (value.stopContinuationLimit !== undefined)
|
|
19
|
+
&& (!stop || Number.isSafeInteger(value.stopContinuationLimit) && value.stopContinuationLimit >= 0),
|
|
20
|
+
'engine_hook_stop_policy_invalid');
|
|
21
|
+
return { definitions,
|
|
22
|
+
configuration: stop ? { stopHookContinuationLimit: value.stopContinuationLimit } : {},
|
|
23
|
+
timeoutMs: Math.max(0, ...definitions.map(hook => Math.ceil(hook.timeoutMs) + 5000)),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function engineHookPort(callHostHook, compactionObservations) {
|
|
28
|
+
return { async invoke({ signal, ...request }) {
|
|
29
|
+
const failure = reason => hookResult(request, request.definition.readOnly ? 'failed' : 'uncertain', null, reason);
|
|
30
|
+
if (typeof callHostHook !== 'function') return hookResult(request, 'failed', null, 'binding_unavailable');
|
|
31
|
+
// The host establishes its own principal from the activation; the engine's
|
|
32
|
+
// internal storage scope grants no authority to a host callback.
|
|
33
|
+
const { scope: _scope, ...invocation } = request;
|
|
34
|
+
let reply;
|
|
35
|
+
try {
|
|
36
|
+
const observations = request.definition.compactionSourceProjection === 'canonical_user'
|
|
37
|
+
? compactionObservations(request) : undefined;
|
|
38
|
+
reply = await callHostHook({ contract: ENGINE_HOOKS, ...invocation, ...(observations ? { observations } : {}) },
|
|
39
|
+
Math.ceil(request.definition.timeoutMs) + 5000, signal);
|
|
40
|
+
} catch {
|
|
41
|
+
signal.throwIfAborted();
|
|
42
|
+
return failure('producer_timeout');
|
|
43
|
+
}
|
|
44
|
+
signal.throwIfAborted();
|
|
45
|
+
try {
|
|
46
|
+
invariant(reply?.contract === ENGINE_HOOKS && reply.operationKey === request.operationKey
|
|
47
|
+
&& reply.inputDigest === request.inputDigest, 'engine_hook_result_unbound');
|
|
48
|
+
return validateHookResult(request, hookResult(request, reply.status, reply.output, reply.reason));
|
|
49
|
+
} catch {
|
|
50
|
+
return failure('producer_invalid');
|
|
51
|
+
}
|
|
52
|
+
} };
|
|
53
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { canonical, invariant, isNativeError, toolReceiptSource } from '@kingsoftcloud/agentkit-harness-core';
|
|
4
|
+
|
|
5
|
+
export const ENGINE_HOST_EFFECT = 'agentkit.engine-host-tool-effect/v1';
|
|
6
|
+
const MAX_INPUT_BYTES = 128 * 1024;
|
|
7
|
+
const MAX_INPUTS = 64;
|
|
8
|
+
|
|
9
|
+
export function hostReceiptSource(record) {
|
|
10
|
+
const originalOperationKey = record.snapshot.toolReconciliation?.operationKey;
|
|
11
|
+
if (record.snapshot.phase !== 'awaiting_reconciliation' || !originalOperationKey) return null;
|
|
12
|
+
const { call, definition } = toolReceiptSource(record, originalOperationKey);
|
|
13
|
+
return definition.hostEffectProtocol === ENGINE_HOST_EFFECT ? { call, originalOperationKey } : null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function hostReceiptReply(reply, observationId) {
|
|
17
|
+
invariant(reply && typeof reply === 'object' && !Array.isArray(reply), 'engine_host_receipt_invalid');
|
|
18
|
+
if (observationId) {
|
|
19
|
+
invariant(reply.result === undefined || reply.result && ['ok', 'error'].includes(reply.result.status), 'engine_host_receipt_invalid');
|
|
20
|
+
return reply.result ?? null;
|
|
21
|
+
}
|
|
22
|
+
if (reply.token === undefined) return null;
|
|
23
|
+
invariant(typeof reply.token === 'string' && /^[0-9a-f]{64}$/u.test(reply.token) && typeof reply.settled === 'boolean'
|
|
24
|
+
&& (reply.settled || Number.isSafeInteger(reply.retryUntil) && reply.retryUntil > 0), 'engine_host_receipt_invalid');
|
|
25
|
+
return { token: reply.token, settled: reply.settled, retryUntil: reply.retryUntil };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Idle reads inspect a durable checkpoint. The Kernel claims the original
|
|
29
|
+
* remote receipt query separately from the initial mutation. */
|
|
30
|
+
export async function waitForHostReceipt(record, { read, signal, assertCurrent }) {
|
|
31
|
+
const source = hostReceiptSource(record);
|
|
32
|
+
if (!source) return null;
|
|
33
|
+
const { call, originalOperationKey } = source, { runId } = record.snapshot;
|
|
34
|
+
for (;;) {
|
|
35
|
+
assertCurrent();
|
|
36
|
+
const ready = await read(call, originalOperationKey, signal).catch(() => null);
|
|
37
|
+
assertCurrent();
|
|
38
|
+
if (ready) {
|
|
39
|
+
const digest = createHash('sha256').update(canonical({ runId, originalOperationKey, token: ready.token })).digest('hex');
|
|
40
|
+
const prefix = 'host-receipt-' + digest;
|
|
41
|
+
const attempts = record.commands.filter(row => row.consumed && row.command.commandId.startsWith(prefix + '-')).length;
|
|
42
|
+
// One initial read may find the original Task finished even after its
|
|
43
|
+
// deadline. Later terminal facts have a different checkpoint token.
|
|
44
|
+
if (ready.settled ? attempts < 3 : attempts === 0 || Date.now() < ready.retryUntil) {
|
|
45
|
+
if (attempts) await delay(Math.min(1500 * attempts, 5000), undefined, { signal });
|
|
46
|
+
assertCurrent();
|
|
47
|
+
return { commandId: prefix + '-' + attempts, kind: 'reconcile_tool', payload: { originalOperationKey } };
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
await delay(1000, undefined, { signal });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The host receives original user text and stable identities, never imported prose or media. */
|
|
55
|
+
export function engineUserObservations(store, scope, snapshot, { indexes, currentOnly = false } = {}) {
|
|
56
|
+
const owners = new Map([[snapshot.runId, snapshot]]), seen = new Set(), observations = [];
|
|
57
|
+
let bytes = 0;
|
|
58
|
+
for (let index = snapshot.messages.length - 1; index >= 0; index--) {
|
|
59
|
+
if (indexes && !indexes.has(index)) continue;
|
|
60
|
+
const message = snapshot.messages[index];
|
|
61
|
+
if (message.role !== 'user' || message.kind !== 'user_input' || !message.content.trim()) continue;
|
|
62
|
+
const { sourceRunId, sourceIndex } = message.history ?? { sourceRunId: snapshot.runId, sourceIndex: index };
|
|
63
|
+
if (currentOnly && sourceRunId !== snapshot.runId) continue;
|
|
64
|
+
const sourceEventId = `native-message://${sourceRunId}#message=${sourceIndex}`;
|
|
65
|
+
if (seen.has(sourceEventId)) continue;
|
|
66
|
+
if (!owners.has(sourceRunId)) {
|
|
67
|
+
try { owners.set(sourceRunId, store.load(scope, sourceRunId).snapshot); }
|
|
68
|
+
catch (error) { if (!isNativeError(error) || error.code !== 'run_not_found') throw error; continue; }
|
|
69
|
+
}
|
|
70
|
+
const owner = owners.get(sourceRunId), original = owner?.messages[sourceIndex];
|
|
71
|
+
if (!original || owner.sessionId !== snapshot.sessionId || original.history
|
|
72
|
+
|| original.kind !== 'user_input' || original.role !== 'user' || original.content !== message.content) continue;
|
|
73
|
+
bytes += Buffer.byteLength(original.content, 'utf8');
|
|
74
|
+
if (bytes > MAX_INPUT_BYTES || observations.length >= MAX_INPUTS) break;
|
|
75
|
+
seen.add(sourceEventId);
|
|
76
|
+
observations.push({ sourceEventId, sourceRunId, content: original.content,
|
|
77
|
+
sourceDigest: 'sha256:' + createHash('sha256').update(original.content).digest('hex') });
|
|
78
|
+
}
|
|
79
|
+
return observations.reverse();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export function completedHostObservations(store, scope, { snapshot, configuration, events }) {
|
|
83
|
+
const tools = new Set(configuration.tools.filter(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT)
|
|
84
|
+
.map(tool => tool.name));
|
|
85
|
+
if (!tools.size || snapshot.phase !== 'completed') return null;
|
|
86
|
+
const eligible = snapshot.outcome === 'verified' || snapshot.outcome === 'unverified'
|
|
87
|
+
&& (['required_acceptance_empty', 'verification_report_missing'].includes(snapshot.reason)
|
|
88
|
+
|| snapshot.reason === 'required_verification_incomplete' && snapshot.verification
|
|
89
|
+
&& !snapshot.verification.checks.some(item => ['failed', 'blocked'].includes(item.status)));
|
|
90
|
+
const effectTools = [...new Set(events.flatMap(event => {
|
|
91
|
+
if (event.kind === 'tool.completed') return [event.payload.name];
|
|
92
|
+
if (event.kind === 'model.completed') return (event.payload.toolCalls ?? []).map(call => call.name);
|
|
93
|
+
return [];
|
|
94
|
+
}).filter(name => tools.has(name)))];
|
|
95
|
+
return { contract: ENGINE_HOST_EFFECT, runId: snapshot.runId, effectTools,
|
|
96
|
+
observations: eligible && !configuration.hostVerification
|
|
97
|
+
? engineUserObservations(store, scope, snapshot, { currentOnly: true }) : [] };
|
|
98
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { closeSync, constants, fstatSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { canonical, invariant, parseNativeJson } from '@kingsoftcloud/agentkit-harness-core';
|
|
5
|
+
import { atomicPrivate, openPrivate, privateDirectory } from './local-command-state.mjs';
|
|
6
|
+
import { projectEngineEvent } from './engine-server.mjs';
|
|
7
|
+
|
|
8
|
+
export const MANAGED_SESSION_DELIVERY = 'agentkit.managed-session-delivery/v1';
|
|
9
|
+
export const MANAGED_SESSION_DELIVERY_LIMIT = 16 * 1024 ** 2;
|
|
10
|
+
const frameLimit = 64 * 1024;
|
|
11
|
+
const digest = value => createHash('sha256').update(value).digest('hex');
|
|
12
|
+
|
|
13
|
+
function storedPayload(path) {
|
|
14
|
+
let fd;
|
|
15
|
+
try {
|
|
16
|
+
fd = openPrivate(path, constants.O_RDONLY);
|
|
17
|
+
invariant(fstatSync(fd).size <= MANAGED_SESSION_DELIVERY_LIMIT, 'managed_delivery_outbox_invalid');
|
|
18
|
+
return readFileSync(fd, 'utf8');
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error.code !== 'ENOENT') throw error;
|
|
21
|
+
return null;
|
|
22
|
+
} finally { if (fd !== undefined) closeSync(fd); }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function projectManagedSessionEvent(event, configuration) {
|
|
26
|
+
let frame;
|
|
27
|
+
try { frame = projectEngineEvent(event, !!configuration.hostVerification); }
|
|
28
|
+
catch {
|
|
29
|
+
// Non-JSON diagnostic values in a tool preview cannot stop execution
|
|
30
|
+
// or prevent publishing the surrounding durable events.
|
|
31
|
+
return { schema: 'agentkit.engine-event/v1', seq: event.seq, kind: event.kind, category: event.kind.split('.')[0], truncated: true };
|
|
32
|
+
}
|
|
33
|
+
if (typeof frame.detail === 'string') frame.detail = frame.detail.slice(0, 8192);
|
|
34
|
+
if (Buffer.byteLength(canonical(frame)) <= frameLimit) return frame;
|
|
35
|
+
const { schema, seq, kind, category, title, status, detail } = frame;
|
|
36
|
+
return { schema, seq, kind, category,
|
|
37
|
+
...(typeof title === 'string' ? { title } : {}), ...(typeof status === 'string' ? { status } : {}),
|
|
38
|
+
...(typeof detail === 'string' ? { detail } : {}), truncated: true };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Retries deliver the same terminal transcript and view bytes even after
|
|
42
|
+
* the Engine is replaced. The remote Host owns its Session journal and ACK. */
|
|
43
|
+
export function createManagedSessionDelivery({ directory, host, ref, scope, sessionId, runId, input, source, readTerminalFrames, view }) {
|
|
44
|
+
const path = join(directory, digest(runId) + '.json');
|
|
45
|
+
const request = (configDigest) => ({ deliveryContract: MANAGED_SESSION_DELIVERY,
|
|
46
|
+
scope, sessionId, runId, ref, input, source, configDigest });
|
|
47
|
+
return {
|
|
48
|
+
async beforeExecute({ configDigest, signal }) {
|
|
49
|
+
await host.deliver('claim', { ...request(configDigest), follow: true, hostCancel: true }, signal);
|
|
50
|
+
},
|
|
51
|
+
async afterTerminal({ snapshot, signal }) {
|
|
52
|
+
let encoded = storedPayload(path);
|
|
53
|
+
if (encoded === null) {
|
|
54
|
+
const { phase, configDigest } = snapshot;
|
|
55
|
+
encoded = canonical({ ...request(configDigest), phase,
|
|
56
|
+
finalText: phase === 'completed' ? snapshot.finalText ?? '' : '',
|
|
57
|
+
view, events: readTerminalFrames(runId) });
|
|
58
|
+
invariant(Buffer.byteLength(encoded) < MANAGED_SESSION_DELIVERY_LIMIT - 1024, 'managed_delivery_outbox_too_large');
|
|
59
|
+
privateDirectory(directory, true);
|
|
60
|
+
atomicPrivate(path, encoded);
|
|
61
|
+
}
|
|
62
|
+
await host.deliver('finish', parseNativeJson(encoded), signal);
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { canonical, invariant, parseNativeJson } from '@kingsoftcloud/agentkit-harness-core';
|
|
2
|
+
import { MANAGED_SESSION_DELIVERY_LIMIT } from './engine-managed-delivery.mjs';
|
|
3
|
+
import { hostReceiptReply } from './engine-host-effects.mjs';
|
|
4
|
+
|
|
5
|
+
export const MANAGED_HOST_RESOURCES = 'agentkit.managed-host-resources/v1';
|
|
6
|
+
const PATH = '/_agentkit/managed-host/v1/';
|
|
7
|
+
const LIMIT = 2 * 1024 ** 2;
|
|
8
|
+
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
9
|
+
|
|
10
|
+
export function createManagedEngineHost(config, env, fetchImpl = fetch) {
|
|
11
|
+
invariant(object(config) && Object.keys(config).sort().join(',') === 'endpoint,tokenEnv'
|
|
12
|
+
&& typeof config.endpoint === 'string' && typeof config.tokenEnv === 'string'
|
|
13
|
+
&& /^[A-Z][A-Z0-9_]{0,127}$/.test(config.tokenEnv), 'engine_managed_host_config_invalid');
|
|
14
|
+
const origin = new URL(config.endpoint), token = env[config.tokenEnv];
|
|
15
|
+
invariant((origin.protocol === 'https:' || origin.protocol === 'http:'
|
|
16
|
+
&& ['127.0.0.1', 'localhost', '[::1]'].includes(origin.hostname))
|
|
17
|
+
&& origin.pathname === '/' && !origin.username && !origin.password && !origin.search && !origin.hash
|
|
18
|
+
&& typeof token === 'string' && token.length >= 32, 'engine_managed_host_config_invalid');
|
|
19
|
+
|
|
20
|
+
async function exchange(path, payload, signal, timeoutMs, limit = LIMIT) {
|
|
21
|
+
const body = canonical({ contract: MANAGED_HOST_RESOURCES, ...payload });
|
|
22
|
+
invariant(Buffer.byteLength(body) <= limit, 'engine_managed_host_request_too_large');
|
|
23
|
+
const response = await fetchImpl(origin.origin + PATH + path, {
|
|
24
|
+
method: 'POST', redirect: 'error', body,
|
|
25
|
+
headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' },
|
|
26
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]),
|
|
27
|
+
});
|
|
28
|
+
if (!response.ok || !response.body || !response.headers.get('content-type')?.startsWith('application/json')) {
|
|
29
|
+
await response.body?.cancel();
|
|
30
|
+
throw Object.assign(new Error('Managed host is unavailable'), { code: 'engine_managed_host_unavailable' });
|
|
31
|
+
}
|
|
32
|
+
const chunks = [];
|
|
33
|
+
let size = 0;
|
|
34
|
+
for await (const chunk of response.body) {
|
|
35
|
+
size += chunk.length;
|
|
36
|
+
invariant(size <= LIMIT, 'engine_managed_host_reply_too_large');
|
|
37
|
+
chunks.push(chunk);
|
|
38
|
+
}
|
|
39
|
+
const reply = parseNativeJson(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
|
|
40
|
+
invariant(object(reply) && reply.contract === MANAGED_HOST_RESOURCES, 'engine_managed_host_reply_invalid');
|
|
41
|
+
return reply;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return Object.freeze({
|
|
45
|
+
async admit({ scope, sessionId, runId, toolCatalog, signal }) {
|
|
46
|
+
const reply = await exchange('admit', { scope, sessionId, runId, toolCatalog }, signal, 20000);
|
|
47
|
+
invariant(typeof reply.ref === 'string' && reply.ref.length > 0 && reply.ref.length <= 8192
|
|
48
|
+
&& typeof reply.hostInstructions === 'string' && reply.hostInstructions.length <= 100000
|
|
49
|
+
&& Array.isArray(reply.hostTools), 'engine_managed_host_reply_invalid');
|
|
50
|
+
return { ref: reply.ref, hostInstructions: reply.hostInstructions, hostTools: reply.hostTools,
|
|
51
|
+
sessionDelivery: reply.sessionDelivery === true };
|
|
52
|
+
},
|
|
53
|
+
async deliver(path, payload, signal) {
|
|
54
|
+
try {
|
|
55
|
+
const reply = await exchange(path, payload, signal, 30000, MANAGED_SESSION_DELIVERY_LIMIT);
|
|
56
|
+
invariant(reply.received === true, 'engine_managed_host_delivery_not_confirmed');
|
|
57
|
+
} catch (error) {
|
|
58
|
+
signal.throwIfAborted();
|
|
59
|
+
throw Object.assign(new Error('Studio session delivery pending', { cause: error }), { code: 'NATIVE_KERNEL_REMOTE_HOST_RETRY' });
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
async callTool({ scope, sessionId, ref, runId, callId, name, arguments: args, effect, signal, timeoutMs }) {
|
|
63
|
+
invariant(effect === undefined || typeof effect?.operationKey === 'string', 'engine_managed_host_effect_invalid');
|
|
64
|
+
const reply = await exchange('tool', { scope, sessionId, ref, runId, callId, name, arguments: args,
|
|
65
|
+
...(effect ? { effect: { operationKey: effect.operationKey, approved: effect.approved,
|
|
66
|
+
canRequestApproval: effect.canRequestApproval } } : {}) }, signal, timeoutMs + 1000);
|
|
67
|
+
invariant(['ok', 'error', 'approval_required', 'uncertain'].includes(reply.status), 'engine_managed_host_reply_invalid');
|
|
68
|
+
return { status: reply.status, content: reply.content };
|
|
69
|
+
},
|
|
70
|
+
async receipt(payload, signal) {
|
|
71
|
+
const reply = await exchange('receipt', payload, signal, payload.observationId ? 12000 : 3000);
|
|
72
|
+
return hostReceiptReply(reply, payload.observationId);
|
|
73
|
+
},
|
|
74
|
+
});
|
|
75
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import { createHash, createPublicKey, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { canonical, configure, invariant, parseNativeJson, TOOL_RECEIPT_OBSERVATION_CONTRACT } from '@kingsoftcloud/agentkit-harness-core';
|
|
4
|
+
import { createEngineRuntime } from './engine-runtime.mjs';
|
|
5
|
+
import { ENGINE_HOST_EFFECT, waitForHostReceipt } from './engine-host-effects.mjs';
|
|
6
|
+
import { ENGINE_TOOL_POLICY } from './engine-tool-policy.mjs';
|
|
7
|
+
import { createManagedSessionDelivery, MANAGED_SESSION_DELIVERY, projectManagedSessionEvent } from './engine-managed-delivery.mjs';
|
|
8
|
+
import { createManagedEngineHost, MANAGED_HOST_RESOURCES } from './engine-managed-host.mjs';
|
|
9
|
+
import { createNativeKernelPermitVerifier } from './native-kernel-permit.mjs';
|
|
10
|
+
import { createManagedNativeKernel, MANAGED_NATIVE_KERNEL_CONTRACT } from './native-managed-kernel.mjs';
|
|
11
|
+
import { createManagedNativeKernelHttp, MANAGED_NATIVE_KERNEL_PATH } from './native-managed-kernel-http.mjs';
|
|
12
|
+
import { publicErrorMessage } from '@kingsoftcloud/agentkit-harness-core/error-presentation';
|
|
13
|
+
import { acquireWorkspaceMutationLock } from './workspace-mutation-lock.mjs';
|
|
14
|
+
|
|
15
|
+
export { MANAGED_NATIVE_KERNEL_CONTRACT, MANAGED_NATIVE_KERNEL_PATH };
|
|
16
|
+
const digest = value => createHash('sha256').update(canonical(value)).digest('hex');
|
|
17
|
+
const platformContractDigest = 'b610a25aae957306b9f84a2cc2c948b30d1ce6218585cfd2a91f96736b92d102';
|
|
18
|
+
const harnessCancelPolicy = { schema: 'agent-kernel/required-capabilities/v1', name: 'harness-cancel', required: ['cancel'] };
|
|
19
|
+
const validDigest = value => typeof value === 'string' && /^[0-9a-f]{64}$/u.test(value);
|
|
20
|
+
|
|
21
|
+
function managedInput(content) {
|
|
22
|
+
if (typeof content === 'string' && content.trim()) return { objective: content };
|
|
23
|
+
invariant(Array.isArray(content), 'NATIVE_MANAGED_STUDIO_INPUT_UNSUPPORTED');
|
|
24
|
+
const text = [], inputImages = [];
|
|
25
|
+
for (const part of content) {
|
|
26
|
+
if (typeof part === 'string') { text.push(part); continue; }
|
|
27
|
+
if (['text', 'input_text'].includes(part?.type) && typeof part.text === 'string') {
|
|
28
|
+
text.push(part.text);
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
invariant(['image_url', 'input_image'].includes(part?.type), 'NATIVE_MANAGED_STUDIO_INPUT_UNSUPPORTED');
|
|
32
|
+
const url = typeof part.image_url === 'string' ? part.image_url : part.image_url?.url;
|
|
33
|
+
invariant(typeof url === 'string' && url.startsWith('data:image/'), 'NATIVE_MANAGED_STUDIO_IMAGE_INVALID');
|
|
34
|
+
inputImages.push({ type: 'image_url', image_url: { url } });
|
|
35
|
+
}
|
|
36
|
+
const objective = text.join('');
|
|
37
|
+
invariant(objective.trim() || inputImages.length, 'NATIVE_MANAGED_STUDIO_INPUT_UNSUPPORTED');
|
|
38
|
+
return { objective: objective.trim() ? objective : 'Inspect the attached image.', inputImages };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The service owns the managed command journal and its execution store. */
|
|
42
|
+
export function createEngineManagedService({ startup, stateDir, workspace, config, env, fetchImpl, log, serviceToken, viewStore, viewRef }) {
|
|
43
|
+
const { buildId, controlPublicKeys, platformApprovals = false, platformKernel } = config;
|
|
44
|
+
const host = config.host === undefined ? undefined : createManagedEngineHost(config.host, env);
|
|
45
|
+
const transportEnv = platformKernel?.transportTokenEnv ?? (platformKernel && env.AGENTKIT_HARNESS_PLATFORM_TRANSPORT_TOKEN !== undefined
|
|
46
|
+
? 'AGENTKIT_HARNESS_PLATFORM_TRANSPORT_TOKEN' : undefined);
|
|
47
|
+
const transportToken = transportEnv === undefined ? undefined : env[transportEnv];
|
|
48
|
+
invariant(!host || env[config.host.tokenEnv] !== serviceToken
|
|
49
|
+
&& env[config.host.tokenEnv] !== env[startup.model.apiKeyEnv], 'engine_managed_host_config_invalid');
|
|
50
|
+
invariant(typeof buildId === 'string' && buildId.trim() && buildId.length <= 256
|
|
51
|
+
&& controlPublicKeys && typeof controlPublicKeys === 'object' && !Array.isArray(controlPublicKeys)
|
|
52
|
+
&& typeof platformApprovals === 'boolean'
|
|
53
|
+
&& (platformKernel === undefined || platformKernel && typeof platformKernel === 'object'
|
|
54
|
+
&& Object.keys(platformKernel).every(key => ['bundleDigest', 'transportTokenEnv', 'agentInstanceId'].includes(key))
|
|
55
|
+
&& validDigest(platformKernel.bundleDigest)
|
|
56
|
+
&& (platformKernel.agentInstanceId === undefined || typeof platformKernel.agentInstanceId === 'string'
|
|
57
|
+
&& /^[a-zA-Z0-9._-]{1,64}$/u.test(platformKernel.agentInstanceId)))
|
|
58
|
+
&& (config.authorizeInteraction === undefined || !platformApprovals && typeof config.authorizeInteraction === 'function'),
|
|
59
|
+
'engine_managed_config_invalid');
|
|
60
|
+
invariant(transportEnv === undefined || typeof transportEnv === 'string' && /^[A-Z][A-Z0-9_]*$/u.test(transportEnv)
|
|
61
|
+
&& typeof transportToken === 'string' && transportToken.length >= 24 && !/\s/u.test(transportToken)
|
|
62
|
+
&& ![serviceToken, env[startup.model.apiKeyEnv], host && env[config.host.tokenEnv]].includes(transportToken),
|
|
63
|
+
'engine_managed_platform_transport_invalid');
|
|
64
|
+
const transportDigest = transportToken === undefined ? null : createHash('sha256').update('Bearer ' + transportToken).digest();
|
|
65
|
+
const authorizeInteraction = platformApprovals
|
|
66
|
+
? ({ command, pending }) => pending.interactionId === command.payload.interaction_id && typeof pending.operationKey === 'string'
|
|
67
|
+
: config.authorizeInteraction;
|
|
68
|
+
const entries = Object.entries(controlPublicKeys);
|
|
69
|
+
invariant(entries.length > 0 && entries.length <= 32, 'engine_managed_config_invalid');
|
|
70
|
+
for (const [id, pem] of entries) {
|
|
71
|
+
invariant(/^[a-zA-Z0-9._-]{1,128}$/.test(id) && typeof pem === 'string'
|
|
72
|
+
&& pem.length <= 65536 && createPublicKey(pem).asymmetricKeyType === 'ed25519',
|
|
73
|
+
'engine_managed_control_key_invalid');
|
|
74
|
+
}
|
|
75
|
+
const verificationKeys = new Map(entries);
|
|
76
|
+
const scope = Object.freeze({ ...startup.scope });
|
|
77
|
+
const agentInstanceId = platformKernel?.agentInstanceId ?? scope.agentId;
|
|
78
|
+
const { name, protocol = 'openai-chat', baseUrl } = startup.model;
|
|
79
|
+
const target = { tenantId: scope.tenantId, agentInstanceId,
|
|
80
|
+
...(agentInstanceId === scope.agentId ? {} : { runScopeAgentId: scope.agentId }),
|
|
81
|
+
engineBinding: digest({ buildId, scope, workspace, model: { name, protocol, baseUrl },
|
|
82
|
+
commandSandbox: startup.commandSandbox ?? null, subAgents: startup.subAgents ?? [] }) };
|
|
83
|
+
const permitVerifier = createNativeKernelPermitVerifier({ target, verificationKeys: async () => verificationKeys,
|
|
84
|
+
requireBoundApproval: platformApprovals });
|
|
85
|
+
let current = true;
|
|
86
|
+
const resolveBinding = Object.assign(async ({ command, runId, store, admission, signal }) => {
|
|
87
|
+
signal.throwIfAborted();
|
|
88
|
+
const { objective, inputImages } = managedInput(command.payload.content);
|
|
89
|
+
const options = command.payload.runtime_options ?? {};
|
|
90
|
+
invariant(typeof options === 'object' && !Array.isArray(options)
|
|
91
|
+
&& Object.keys(options).every(key => ['model', 'tool_approval_mode'].includes(key)), 'engine_managed_options_invalid');
|
|
92
|
+
invariant(options.model === undefined || options.model === name, 'engine_managed_model_unavailable');
|
|
93
|
+
invariant(options.tool_approval_mode === undefined || ['ask', 'risk'].includes(options.tool_approval_mode), 'engine_managed_options_invalid');
|
|
94
|
+
const strictApproval = options.tool_approval_mode === 'ask';
|
|
95
|
+
invariant(!strictApproval || authorizeInteraction, 'engine_tool_policy_requires_durable_approvals');
|
|
96
|
+
const sessionId = command.session_id;
|
|
97
|
+
const recovered = admission?.configuration.hostRecoveryBinding;
|
|
98
|
+
invariant(recovered === undefined || host && recovered.contract === MANAGED_HOST_RESOURCES && typeof recovered.ref === 'string',
|
|
99
|
+
'engine_managed_host_binding_unavailable');
|
|
100
|
+
let bindingRef = recovered?.ref;
|
|
101
|
+
const readReceipt = (call, originalOperationKey, receiptSignal, observationId) => {
|
|
102
|
+
invariant(bindingRef, 'engine_managed_host_binding_unavailable');
|
|
103
|
+
return host.receipt({ scope, sessionId, runId, ref: bindingRef, originalOperationKey, callId: call.callId,
|
|
104
|
+
name: call.name, arguments: call.arguments, ...(observationId ? { observationId } : {}) }, receiptSignal);
|
|
105
|
+
};
|
|
106
|
+
const engine = await createEngineRuntime({
|
|
107
|
+
workspaceRoot: workspace, stateDir: join(stateDir, 'managed-resources', digest(sessionId)),
|
|
108
|
+
sessionId, scope, runStore: store, sourceEnv: env, fetchImpl,
|
|
109
|
+
callHostTool: host && (request => {
|
|
110
|
+
invariant(bindingRef && request.runId === runId, 'engine_managed_host_binding_unavailable');
|
|
111
|
+
return host.callTool({ ...request, scope, sessionId, ref: bindingRef });
|
|
112
|
+
}),
|
|
113
|
+
callHostReceipt: host && (async request => {
|
|
114
|
+
invariant(request.runId === runId, 'engine_managed_host_binding_unavailable');
|
|
115
|
+
const result = await readReceipt(request.call, request.originalOperationKey, request.signal, request.operationKey);
|
|
116
|
+
return { contract: request.contract, originalOperationKey: request.originalOperationKey, callId: request.call.callId, result };
|
|
117
|
+
}),
|
|
118
|
+
authorize: async () => 'deny', commandSandbox: startup.commandSandbox, subAgents: startup.subAgents,
|
|
119
|
+
model: { ...startup.model, apiKey: async () => env[startup.model.apiKeyEnv] ?? '' },
|
|
120
|
+
});
|
|
121
|
+
try {
|
|
122
|
+
signal.throwIfAborted();
|
|
123
|
+
let configuration = admission?.configuration;
|
|
124
|
+
let deliverSession = recovered?.sessionDelivery === true;
|
|
125
|
+
if (!configuration) {
|
|
126
|
+
let resources;
|
|
127
|
+
if (host) {
|
|
128
|
+
const { reservedToolNames: reserved, hostToolNamePattern: pattern } = engine.info();
|
|
129
|
+
resources = await host.admit({ scope, sessionId, runId,
|
|
130
|
+
toolCatalog: { reserved, pattern, receiptObservation: TOOL_RECEIPT_OBSERVATION_CONTRACT }, signal });
|
|
131
|
+
signal.throwIfAborted();
|
|
132
|
+
bindingRef = resources.ref;
|
|
133
|
+
deliverSession = resources.sessionDelivery;
|
|
134
|
+
if (deliverSession) viewStore.pin(stateDir, runId, viewRef);
|
|
135
|
+
}
|
|
136
|
+
configuration = engine.prepareRun({ runId, objective, inputImages, originalInput: true, durableApprovals: !!authorizeInteraction,
|
|
137
|
+
...(strictApproval ? { toolPolicy: { contract: ENGINE_TOOL_POLICY, mode: 'strict', rules: {} } } : {}),
|
|
138
|
+
...(resources ? { hostInstructions: resources.hostInstructions, hostTools: resources.hostTools.map(tool =>
|
|
139
|
+
tool.readOnly === true ? tool : { ...tool, readOnly: false, effectProtocol: ENGINE_HOST_EFFECT }) } : {}),
|
|
140
|
+
}).configuration;
|
|
141
|
+
if (resources) configuration = configure({ ...configuration,
|
|
142
|
+
hostRecoveryBinding: { contract: MANAGED_HOST_RESOURCES, ref: bindingRef,
|
|
143
|
+
...(deliverSession ? { sessionDelivery: true } : {}) } });
|
|
144
|
+
}
|
|
145
|
+
const delivery = deliverSession ? createManagedSessionDelivery({
|
|
146
|
+
directory: join(stateDir, 'managed-delivery'), host, ref: bindingRef, scope, sessionId, runId,
|
|
147
|
+
input: objective, source: { provider: 'agentkit-harness', model: name },
|
|
148
|
+
readTerminalFrames: run => runtime.terminalSessionFrames(run),
|
|
149
|
+
view: viewStore.reference(stateDir, runId)?.sha256 ?? null,
|
|
150
|
+
}) : {};
|
|
151
|
+
const hasHostReceipts = configuration.tools.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT
|
|
152
|
+
&& tool.recoveryPolicy === 'receipt-observation/v1');
|
|
153
|
+
function waitForReceipt(_snapshot, { signal: idleSignal, assertCurrent }) {
|
|
154
|
+
assertCurrent();
|
|
155
|
+
return waitForHostReceipt(store.load(scope, runId), { read: readReceipt, signal: idleSignal, assertCurrent });
|
|
156
|
+
}
|
|
157
|
+
return { scope, buildId, configuration, ports: engine.ports, ...delivery,
|
|
158
|
+
...(hasHostReceipts ? { withExecution: ({ execute }) => execute({ onIdle: waitForReceipt }) } : {}),
|
|
159
|
+
release: () => engine.close() };
|
|
160
|
+
} catch (error) {
|
|
161
|
+
await engine.close();
|
|
162
|
+
throw error;
|
|
163
|
+
}
|
|
164
|
+
}, {
|
|
165
|
+
enqueueContentFormats: Object.freeze(['text/plain']),
|
|
166
|
+
resolveInjectionScope: async ({ signal }) => { signal.throwIfAborted(); return scope; },
|
|
167
|
+
});
|
|
168
|
+
// The separate lock database is held for this process's lifetime. It is
|
|
169
|
+
// released by SQLite on process death and never blocks a contender's loop.
|
|
170
|
+
const releaseOwnership = acquireWorkspaceMutationLock(join(stateDir, 'managed-owner'), { timeoutMs: 0 });
|
|
171
|
+
let runtime;
|
|
172
|
+
try {
|
|
173
|
+
runtime = createManagedNativeKernel({
|
|
174
|
+
directory: join(stateDir, 'managed'), target, permitVerifier, resolveBinding, authorizeInteraction,
|
|
175
|
+
platformApprovals,
|
|
176
|
+
assertCurrent: () => current, projectSessionEvent: projectManagedSessionEvent,
|
|
177
|
+
onWorkerError: ({ error }) => log('managed execution failed: ' + publicErrorMessage(error)),
|
|
178
|
+
});
|
|
179
|
+
} catch (error) { releaseOwnership(); throw error; }
|
|
180
|
+
const transport = createManagedNativeKernelHttp(runtime);
|
|
181
|
+
async function handleSession(request, response, action) {
|
|
182
|
+
const json = (status, payload) => {
|
|
183
|
+
if (response.destroyed) return;
|
|
184
|
+
response.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
|
|
185
|
+
response.end(canonical(payload));
|
|
186
|
+
};
|
|
187
|
+
if (request.method !== 'POST') return json(405, { error: 'method_not_allowed' });
|
|
188
|
+
try {
|
|
189
|
+
const chunks = [];
|
|
190
|
+
let size = 0;
|
|
191
|
+
for await (const chunk of request.iterator({ destroyOnReturn: false })) {
|
|
192
|
+
size += chunk.length;
|
|
193
|
+
if (size > 32768) {
|
|
194
|
+
response.setHeader('connection', 'close');
|
|
195
|
+
return json(400, { error: 'invalid_request' });
|
|
196
|
+
}
|
|
197
|
+
chunks.push(chunk);
|
|
198
|
+
}
|
|
199
|
+
const body = parseNativeJson(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)));
|
|
200
|
+
invariant(body?.contract === MANAGED_SESSION_DELIVERY
|
|
201
|
+
&& typeof body.runId === 'string' && body.runId.length <= 256
|
|
202
|
+
&& typeof body.sessionId === 'string' && body.sessionId.length <= 256
|
|
203
|
+
&& (action === 'restore' || typeof body.ref === 'string' && body.ref.length <= 8192)
|
|
204
|
+
&& typeof body.configDigest === 'string' && /^[a-f0-9]{64}$/.test(body.configDigest),
|
|
205
|
+
'engine_managed_frame_request_invalid');
|
|
206
|
+
const identity = { scope, sessionId: body.sessionId, runId: body.runId, configDigest: body.configDigest };
|
|
207
|
+
if (action === 'restore') return json(200, { contract: MANAGED_SESSION_DELIVERY, hostCancel: true,
|
|
208
|
+
...runtime.restoreSessionDelivery(identity), source: { provider: 'agentkit-harness', model: name } });
|
|
209
|
+
if (action === 'cancel') return json(200, { contract: MANAGED_SESSION_DELIVERY,
|
|
210
|
+
...runtime.cancelSessionDelivery({ ...identity, ref: body.ref }) });
|
|
211
|
+
const events = runtime.readSessionFrames({ ...identity, ref: body.ref, after: body.after });
|
|
212
|
+
return json(200, { contract: MANAGED_SESSION_DELIVERY, cursor: events.at(-1)?.seq ?? body.after,
|
|
213
|
+
view: viewStore.reference(stateDir, body.runId)?.sha256 ?? null, events });
|
|
214
|
+
} catch (error) {
|
|
215
|
+
if (error.code === 'NATIVE_KERNEL_STATUS_IDENTITY_MISMATCH') return json(404, { error: 'run_not_found' });
|
|
216
|
+
return json(400, { error: 'invalid_request' });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return {
|
|
221
|
+
platformApprovals,
|
|
222
|
+
authorizesPlatformTransport(authorization) {
|
|
223
|
+
return transportDigest !== null && typeof authorization === 'string'
|
|
224
|
+
&& timingSafeEqual(transportDigest, createHash('sha256').update(authorization).digest());
|
|
225
|
+
},
|
|
226
|
+
platformHealth: platformKernel && (() => {
|
|
227
|
+
let check;
|
|
228
|
+
try { check = runtime.probePlatform(); } catch { /* Both ledgers must be readable before accepting platform traffic. */ }
|
|
229
|
+
const capabilities = check?.capabilities ?? {};
|
|
230
|
+
const worker = check?.workerRunning === true;
|
|
231
|
+
const capable = capabilities.cancel?.supported === true;
|
|
232
|
+
return { ready: current && worker && capable, store_ok: !!check, worker_running: worker, lease_healthy: current,
|
|
233
|
+
store_driver: 'sqlite-single-writer', agent_instance_id: agentInstanceId, contract_digest: platformContractDigest,
|
|
234
|
+
capability_digest: capable ? digest(harnessCancelPolicy) : digest(capabilities), bundle_digest: platformKernel.bundleDigest,
|
|
235
|
+
capabilities };
|
|
236
|
+
}),
|
|
237
|
+
handle(request, response) {
|
|
238
|
+
if (request.url === MANAGED_NATIVE_KERNEL_PATH + '/session-frames') return handleSession(request, response, 'frames');
|
|
239
|
+
if (request.url === MANAGED_NATIVE_KERNEL_PATH + '/session-restore') return handleSession(request, response, 'restore');
|
|
240
|
+
if (request.url === MANAGED_NATIVE_KERNEL_PATH + '/session-cancel') return handleSession(request, response, 'cancel');
|
|
241
|
+
return transport.handle(request, response);
|
|
242
|
+
},
|
|
243
|
+
async close() {
|
|
244
|
+
current = false;
|
|
245
|
+
transport.close();
|
|
246
|
+
try { await runtime.close(); } finally { releaseOwnership(); }
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
}
|