@kingsoftcloud/agentkit-harness-node 0.0.17 → 0.0.18
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 +566 -0
- package/dist/index.mjs +4 -0
- package/dist/rpc-entry.mjs +4 -0
- package/package.json +16 -2
- 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-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 +454 -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
package/dist/index.mjs
CHANGED
|
@@ -1293,6 +1293,10 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1293
1293
|
return scope;
|
|
1294
1294
|
});
|
|
1295
1295
|
};
|
|
1296
|
+
this.probe = () => {
|
|
1297
|
+
open();
|
|
1298
|
+
db.prepare("SELECT version FROM native_schema LIMIT 1").get();
|
|
1299
|
+
};
|
|
1296
1300
|
this.close = () => {
|
|
1297
1301
|
if (!closed) {
|
|
1298
1302
|
db.close();
|
package/dist/rpc-entry.mjs
CHANGED
|
@@ -1304,6 +1304,10 @@ var SqliteRunStore = class extends TransactionalRunStore {
|
|
|
1304
1304
|
return scope;
|
|
1305
1305
|
});
|
|
1306
1306
|
};
|
|
1307
|
+
this.probe = () => {
|
|
1308
|
+
open2();
|
|
1309
|
+
db.prepare("SELECT version FROM native_schema LIMIT 1").get();
|
|
1310
|
+
};
|
|
1307
1311
|
this.close = () => {
|
|
1308
1312
|
if (!closed) {
|
|
1309
1313
|
db.close();
|
package/package.json
CHANGED
|
@@ -1,12 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kingsoftcloud/agentkit-harness-node",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.18",
|
|
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.",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./dist/index.mjs",
|
|
9
9
|
"./rpc-entry": "./dist/rpc-entry.mjs",
|
|
10
|
+
"./native/engine-runtime": "./src/native/engine-runtime.mjs",
|
|
11
|
+
"./native/engine-server": "./src/native/engine-server.mjs",
|
|
12
|
+
"./native/engine-client": "./src/native/engine-client.mjs",
|
|
13
|
+
"./native/managed-kernel": "./src/native/native-managed-kernel.mjs",
|
|
14
|
+
"./native/managed-kernel-http": "./src/native/native-managed-kernel-http.mjs",
|
|
15
|
+
"./native/managed-scoped-control": "./src/native/native-managed-scoped-control.mjs",
|
|
16
|
+
"./native/teams-callback-authority": "./src/native/native-teams-callback-authority.mjs",
|
|
17
|
+
"./native/teams-context-contract": "./src/native/native-teams-context-contract.mjs",
|
|
18
|
+
"./native/kernel-events": "./src/native/native-kernel-events.mjs",
|
|
19
|
+
"./native/terminal-failure": "./src/native/native-terminal-failure.mjs",
|
|
20
|
+
"./native/kernel-permit": "./src/native/native-kernel-permit.mjs",
|
|
21
|
+
"./native/teams-json": "./src/native/native-teams-json.mjs",
|
|
10
22
|
"./native/a2a-tools": "./src/native/a2a-tools.mjs",
|
|
11
23
|
"./native/artifact-codec": "./src/native/artifact-codec.mjs",
|
|
12
24
|
"./native/artifact-store": "./src/native/artifact-store.mjs",
|
|
@@ -127,6 +139,8 @@
|
|
|
127
139
|
"./package-integrity": "./src/package-integrity.mjs"
|
|
128
140
|
},
|
|
129
141
|
"bin": {
|
|
142
|
+
"agentkit-engine": "./src/native/engine-server.mjs",
|
|
143
|
+
"agentkit-engine-service": "./src/native/engine-service.mjs",
|
|
130
144
|
"agentkit-native-rpc": "./dist/rpc-entry.mjs"
|
|
131
145
|
},
|
|
132
146
|
"files": [
|
|
@@ -140,7 +154,7 @@
|
|
|
140
154
|
"src/package-integrity.mjs"
|
|
141
155
|
],
|
|
142
156
|
"dependencies": {
|
|
143
|
-
"@kingsoftcloud/agentkit-harness-core": "0.0.
|
|
157
|
+
"@kingsoftcloud/agentkit-harness-core": "0.0.18",
|
|
144
158
|
"@astral-sh/ruff-wasm-nodejs": "0.16.8",
|
|
145
159
|
"parse5": "7.3.0",
|
|
146
160
|
"playwright-core": "1.58.2",
|
|
@@ -34,7 +34,7 @@ async function observeWhileLive(operation, signal) {
|
|
|
34
34
|
* an environment/profile fallback. This service does not advertise model tools.
|
|
35
35
|
*/
|
|
36
36
|
export function createNativeChildOwner({ scope, childScopes = [scope], store, resolveChild, restoreChild, waitForIdle, canWaitForReceipt, onStream, now = Date.now,
|
|
37
|
-
childAllocationPolicy, admitRequirements, owner = `native-children-${randomUUID()}` }) {
|
|
37
|
+
childAllocationPolicy, admitRequirements, detachSignal, owner = `native-children-${randomUUID()}` }) {
|
|
38
38
|
const parentScope = copy(scope), entries = new Map();
|
|
39
39
|
scopeKey(parentScope);
|
|
40
40
|
check(childAllocationPolicy === undefined || childAllocationPolicy === CHILD_ALLOCATION_POLICY, 'invalid_child_owner_allocation_policy');
|
|
@@ -120,15 +120,16 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
|
|
|
120
120
|
entry.error = null;
|
|
121
121
|
entry.promise = (async () => {
|
|
122
122
|
for (;;) {
|
|
123
|
-
const snapshot = await entry.kernel.runUntilIdle(entry.scope, entry.runId);
|
|
123
|
+
const snapshot = await entry.kernel.runUntilIdle(entry.scope, entry.runId, { detachSignal });
|
|
124
124
|
if (terminal(snapshot.phase)) { entry.ports.tools.settleQuestions?.(snapshot); return; }
|
|
125
125
|
const record = store.load(entry.scope, entry.runId);
|
|
126
126
|
if (!canWaitForReceipt?.(record) || !entry.admitted()) return;
|
|
127
127
|
const idle = new AbortController(); entry.idle = idle;
|
|
128
128
|
try {
|
|
129
|
+
const signal = detachSignal ? AbortSignal.any([idle.signal, detachSignal]) : idle.signal;
|
|
129
130
|
const command = await observeWhileLive(Promise.resolve().then(() => waitForIdle({
|
|
130
|
-
snapshot: copy(snapshot), tools: entry.ports.tools, signal
|
|
131
|
-
})),
|
|
131
|
+
snapshot: copy(snapshot), tools: entry.ports.tools, signal,
|
|
132
|
+
})), signal);
|
|
132
133
|
idle.signal.throwIfAborted();
|
|
133
134
|
check(entry.admitted() && same(store.load(entry.scope, entry.runId).snapshot, snapshot), 'child_idle_authority_lost');
|
|
134
135
|
if (!command) return;
|
|
@@ -629,6 +630,9 @@ export function createNativeChildOwner({ scope, childScopes = [scope], store, re
|
|
|
629
630
|
}
|
|
630
631
|
for (const entry of owned) entries.delete(entry.runId);
|
|
631
632
|
},
|
|
633
|
+
async drain() {
|
|
634
|
+
await Promise.all([...entries.values()].map(entry => entry.promise));
|
|
635
|
+
},
|
|
632
636
|
async closeRun(request) {
|
|
633
637
|
check(same(request.scope, parentScope), 'child_parent_scope_mismatch');
|
|
634
638
|
const parent = store.load(parentScope, request.runId);
|
package/src/native/children.mjs
CHANGED
|
@@ -112,7 +112,7 @@ export function nativeChildRoles(spec = {}, { childAllocationPolicy } = {}) {
|
|
|
112
112
|
|
|
113
113
|
/** Bind every child to a declared role and its own scoped tool state. */
|
|
114
114
|
export async function createNativeChildren({ roles, scope, sessionId, store, tools, hasSkills, hasMcp, mcpBinding, skillBinding, skillInstructions, workspaceContext, instructionTimeoutRecovery,
|
|
115
|
-
resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, outputRestartPolicy, approvalOutcomePolicy, conversationPresentation, toolExecutionPolicy, toolAdmissionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }) }) {
|
|
115
|
+
resolveModel, bindTools, verificationFactory, fileWorkspaces, commandResource, isClosed, onStream, detachSignal, a2aBinding, waitForChildReceipt, mediaSources = new Map(), artifactPolicy, artifactFactory, sourceReadPolicy, childTaskPolicy, childPlanPolicy, childAllocationPolicy, childCapabilityPolicy, outputRecoveryPolicy, outputRestartPolicy, approvalOutcomePolicy, conversationPresentation, toolExecutionPolicy, toolAdmissionPolicy, providerRecoveryPolicy, modelSurface, goalContractFactory = ({ goal }) => ({ objective: goal }), restrictTools }) {
|
|
116
116
|
if (!roles.length) return null;
|
|
117
117
|
if (workspaceContext !== undefined) {
|
|
118
118
|
validateNativeWorkspaceContext(workspaceContext);
|
|
@@ -124,9 +124,9 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
|
|
|
124
124
|
invariant(toolAdmissionPolicy === undefined || toolAdmissionPolicy === 'discover-before-retry/v1', 'studio_native_child_admission_policy_invalid');
|
|
125
125
|
invariant(toolExecutionPolicy === undefined || toolExecutionPolicy === 'owner-execution/v1', 'studio_native_child_execution_policy_invalid');
|
|
126
126
|
invariant(providerRecoveryPolicy === undefined || providerRecoveryPolicy === 'provider-recovery/v2', 'native_child_provider_recovery_policy_invalid');
|
|
127
|
-
invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
|
|
127
|
+
invariant(outputRecoveryPolicy === undefined || ['response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(outputRecoveryPolicy), 'studio_native_child_output_policy_invalid');
|
|
128
128
|
invariant(outputRestartPolicy === undefined || ['per-response/v1', 'per-response/v2'].includes(outputRestartPolicy)
|
|
129
|
-
&& ['response-boundary/v2', 'response-boundary/v3'].includes(outputRecoveryPolicy), 'native_child_output_restart_policy_invalid');
|
|
129
|
+
&& ['response-boundary/v2', 'response-boundary/v3', 'response-boundary/v4', 'response-boundary/v5'].includes(outputRecoveryPolicy), 'native_child_output_restart_policy_invalid');
|
|
130
130
|
invariant(approvalOutcomePolicy === undefined || approvalOutcomePolicy === 'owner-outcome/v1', 'native_child_approval_outcome_policy_invalid');
|
|
131
131
|
if (conversationPresentation !== undefined) validateConversationPresentation(conversationPresentation);
|
|
132
132
|
invariant(childTaskPolicy === undefined || childTaskPolicy === CHILD_TASK_POLICY, 'studio_native_child_task_policy_invalid');
|
|
@@ -187,14 +187,16 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
|
|
|
187
187
|
? createStudioNativeChildMerge({ scope, sessionId, store, roles, fileWorkspaces, isClosed,
|
|
188
188
|
previousPublication: previousChildPublication, authorize: async () => 'allow' }) : null;
|
|
189
189
|
const readers = createNativeChildResultTools({ scope, childScopes: roles.map(childScope), store, roles: roles.map(role => role.name) });
|
|
190
|
-
const owner = createNativeChildOwner({ scope, onStream, childScopes: roles.map(childScope), store,
|
|
190
|
+
const owner = createNativeChildOwner({ scope, onStream, detachSignal, childScopes: roles.map(childScope), store,
|
|
191
191
|
...(childCapabilityPolicy ? { admitRequirements: args => admitChildCapabilities(
|
|
192
192
|
[...bindings].map(([role, bound]) => ({ role, tools: bound.tools.map(tool => tool.name).sort() })), args.role, args.required_tools) } : {}),
|
|
193
193
|
...(childAllocationPolicy ? { childAllocationPolicy } : {}),
|
|
194
194
|
...(waitForChildReceipt ? { canWaitForReceipt: record => !!nativeA2aReceiptWaitSource(record), waitForIdle: waitForChildReceipt } : {}),
|
|
195
195
|
resolveChild: async request => {
|
|
196
|
-
const role = byName.get(request.role),
|
|
197
|
-
invariant(role &&
|
|
196
|
+
const role = byName.get(request.role), available = bindings.get(request.role);
|
|
197
|
+
invariant(role && available, 'studio_native_child_role_unbound');
|
|
198
|
+
const bound = restrictTools ? { ...available, tools: restrictTools(available.tools,
|
|
199
|
+
store.authority(request.parent.scope, request.parent.runId).configuration) } : available;
|
|
198
200
|
const args = request.call.arguments;
|
|
199
201
|
const refs = args.media ?? [];
|
|
200
202
|
invariant(Array.isArray(refs) && refs.length <= 20 && refs.every(ref => ref && typeof ref === 'object'
|
|
@@ -299,8 +301,10 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
|
|
|
299
301
|
input: ports.input, store, scope: child, sessionId: request.childSessionId, tools: bound.tools }), verification } };
|
|
300
302
|
},
|
|
301
303
|
restoreChild: async ({ identity, configuration, binding }) => {
|
|
302
|
-
const
|
|
304
|
+
const available = bindings.get(binding.role), role = byName.get(binding.role);
|
|
303
305
|
const parent = store.load(binding.parent.scope, binding.parent.runId);
|
|
306
|
+
const bound = available && restrictTools
|
|
307
|
+
? { ...available, tools: restrictTools(available.tools, parent.configuration) } : available;
|
|
304
308
|
const call = parent.intents.find(item => item.operationKey === binding.parentOperationKey)?.payload.calls
|
|
305
309
|
?.find(item => item.callId === binding.parentToolCallId);
|
|
306
310
|
invariant(call && role, 'studio_native_child_restore_binding_changed');
|
|
@@ -324,6 +328,7 @@ export async function createNativeChildren({ roles, scope, sessionId, store, too
|
|
|
324
328
|
// Reconstruct the same normalized profile, rather than comparing it to
|
|
325
329
|
// the Host's deliberately partial input and rejecting every live child.
|
|
326
330
|
const profile = bound && configure({ profile: bound.model.profile, contract: configuration.contract,
|
|
331
|
+
limits: { effectTimeoutMs: configuration.limits.effectTimeoutMs },
|
|
327
332
|
hostBindingDigest: configuration.hostBindingDigest }).profile;
|
|
328
333
|
invariant(bound && role && canonical(configuration.tools) === canonical(bound.tools)
|
|
329
334
|
&& configuration.outputRecoveryPolicy === outputRecoveryPolicy
|
|
@@ -1,9 +1,34 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
2
|
+
|
|
1
3
|
export const LOCAL_COMMAND_SHELL = 'bash-execution/v1';
|
|
4
|
+
export const ISOLATED_COMMAND_SHELL = 'bubblewrap-workspace/v1';
|
|
2
5
|
|
|
3
6
|
/** A missing policy belongs to a persisted legacy request. Never reinterpret
|
|
4
7
|
* it under a new shell during supervision/recovery. No PATH-based fallback.
|
|
5
8
|
*/
|
|
6
|
-
export function shellCommandArgv(command, policy = null) {
|
|
7
|
-
if (policy
|
|
8
|
-
|
|
9
|
+
export function shellCommandArgv(command, policy = null, { workspaceRoot, cwd } = {}) {
|
|
10
|
+
if (policy === null) return ['/bin/sh', '-c', command];
|
|
11
|
+
if (policy === LOCAL_COMMAND_SHELL) return ['/bin/bash', '-c', command];
|
|
12
|
+
if (policy !== ISOLATED_COMMAND_SHELL) throw Error('unsupported_command_shell');
|
|
13
|
+
if (process.platform !== 'linux' || typeof workspaceRoot !== 'string' || typeof cwd !== 'string'
|
|
14
|
+
|| !isAbsolute(workspaceRoot) || !isAbsolute(cwd) || resolve(workspaceRoot) !== workspaceRoot
|
|
15
|
+
|| resolve(cwd) !== cwd
|
|
16
|
+
|| (workspaceRoot !== '/data/workspace' && !workspaceRoot.startsWith('/data/workspace/')))
|
|
17
|
+
throw Error('isolated_command_workspace_invalid');
|
|
18
|
+
const within = relative(workspaceRoot, cwd);
|
|
19
|
+
if (within === '..' || within.startsWith('..' + sep) || isAbsolute(within))
|
|
20
|
+
throw Error('isolated_command_cwd_outside_workspace');
|
|
21
|
+
|
|
22
|
+
// The managed image supplies Debian's usr-merged filesystem. Only the
|
|
23
|
+
// workspace and disposable tmpfs are writable. Neither the state volume nor
|
|
24
|
+
// the engine's PID namespace or deployment credential mounts are visible.
|
|
25
|
+
return ['/usr/bin/bwrap', '--unshare-user', '--unshare-pid', '--unshare-ipc', '--unshare-uts',
|
|
26
|
+
'--unshare-net', '--die-with-parent', '--new-session', '--cap-drop', 'ALL',
|
|
27
|
+
'--ro-bind', '/usr', '/usr', '--symlink', 'usr/bin', '/bin', '--symlink', 'usr/sbin', '/sbin',
|
|
28
|
+
'--symlink', 'usr/lib', '/lib', '--symlink', 'usr/lib64', '/lib64',
|
|
29
|
+
'--dir', '/proc', '--dev', '/dev', '--tmpfs', '/tmp',
|
|
30
|
+
'--ro-bind', '/etc/passwd', '/etc/passwd', '--ro-bind', '/etc/group', '/etc/group',
|
|
31
|
+
'--bind', workspaceRoot, workspaceRoot, '--chdir', cwd,
|
|
32
|
+
'--clearenv', '--setenv', 'PATH', '/usr/local/bin:/usr/bin:/bin', '--setenv', 'HOME', '/tmp',
|
|
33
|
+
'--setenv', 'LANG', 'C.UTF-8', '--setenv', 'CI', '1', '--', '/bin/bash', '-c', command];
|
|
9
34
|
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// Thin host-side client for agentkit.engine/v1.
|
|
2
|
+
//
|
|
3
|
+
// This file contains no engine logic and imports none: it frames JSON-RPC over
|
|
4
|
+
// a child process's stdio. A host may vendor it, or reimplement it in another
|
|
5
|
+
// language from the protocol alone. It needs to change only when the protocol
|
|
6
|
+
// major version changes.
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import * as readline from 'node:readline';
|
|
9
|
+
|
|
10
|
+
export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
|
|
11
|
+
|
|
12
|
+
/** Connect to an engine over a pair of streams (a spawned process, a socket, or an in-memory pair in tests). */
|
|
13
|
+
export function connectEngine({ input, output, onApproveTool, onCallTool, hostName = 'host' }) {
|
|
14
|
+
let next = 1, closed = false;
|
|
15
|
+
const pending = new Map();
|
|
16
|
+
const send = frame => output.write(`${JSON.stringify(frame)}\n`);
|
|
17
|
+
const frames = readline.createInterface({ input, crlfDelay: Infinity });
|
|
18
|
+
const finished = (async () => {
|
|
19
|
+
for await (const line of frames) {
|
|
20
|
+
if (!line.trim()) continue;
|
|
21
|
+
let frame;
|
|
22
|
+
try { frame = JSON.parse(line); } catch { continue; }
|
|
23
|
+
if (frame.method !== undefined) {
|
|
24
|
+
// Engine -> host request. Unknown methods are refused, never guessed.
|
|
25
|
+
if (frame.method === 'host/approveTool' && typeof onApproveTool === 'function') {
|
|
26
|
+
Promise.resolve().then(() => onApproveTool(frame.params ?? {}))
|
|
27
|
+
.then(decision => send({ jsonrpc: '2.0', id: frame.id, result: { decision: decision === 'allow' ? 'allow' : 'deny' } }),
|
|
28
|
+
() => send({ jsonrpc: '2.0', id: frame.id, result: { decision: 'deny' } }));
|
|
29
|
+
} else if (frame.method === 'host/callTool' && typeof onCallTool === 'function') {
|
|
30
|
+
Promise.resolve().then(() => onCallTool(frame.params ?? {}))
|
|
31
|
+
.then(reply => send({ jsonrpc: '2.0', id: frame.id, result: { status: reply?.status === 'error' ? 'error' : 'ok', content: reply?.content ?? null } }),
|
|
32
|
+
error => send({ jsonrpc: '2.0', id: frame.id, result: { status: 'error', content: { code: 'host_tool_failed', message: String(error?.message ?? error).slice(0, 2000) } } }));
|
|
33
|
+
} else if (frame.id !== undefined) send({ jsonrpc: '2.0', id: frame.id, error: { code: -32601, message: 'Method not found' } });
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
const waiter = pending.get(frame.id);
|
|
37
|
+
if (!waiter) continue;
|
|
38
|
+
pending.delete(frame.id);
|
|
39
|
+
if (frame.error) waiter.reject(Object.assign(new Error(frame.error.message), { code: frame.error.code, data: frame.error.data }));
|
|
40
|
+
else waiter.resolve(frame.result);
|
|
41
|
+
}
|
|
42
|
+
closed = true;
|
|
43
|
+
for (const waiter of pending.values()) waiter.reject(new Error('engine connection closed'));
|
|
44
|
+
pending.clear();
|
|
45
|
+
})();
|
|
46
|
+
const call = (method, params = {}) => new Promise((resolve, reject) => {
|
|
47
|
+
if (closed) { reject(new Error('engine connection closed')); return; }
|
|
48
|
+
const id = next++;
|
|
49
|
+
pending.set(id, { resolve, reject });
|
|
50
|
+
send({ jsonrpc: '2.0', id, method, params });
|
|
51
|
+
});
|
|
52
|
+
return {
|
|
53
|
+
call, finished,
|
|
54
|
+
initialize: () => call('initialize', { protocolVersions: [ENGINE_PROTOCOL], host: { name: hostName },
|
|
55
|
+
services: { approvals: typeof onApproveTool === 'function', tools: typeof onCallTool === 'function' } }),
|
|
56
|
+
startRun: params => call('run/start', params),
|
|
57
|
+
status: runId => call('run/status', { runId }),
|
|
58
|
+
events: (runId, cursor = 0, waitMs = 0) => call('run/events', { runId, cursor, waitMs }),
|
|
59
|
+
resume: runId => call('run/resume', { runId }),
|
|
60
|
+
cancel: runId => call('run/cancel', { runId }),
|
|
61
|
+
view: () => call('ui/view'),
|
|
62
|
+
shutdown: () => call('shutdown'),
|
|
63
|
+
/** Follow a Run to rest, handing each projected event to `onEvent`. */
|
|
64
|
+
async follow(runId, onEvent = () => {}, { waitMs = 5000 } = {}) {
|
|
65
|
+
for (let cursor = 0; ;) {
|
|
66
|
+
const page = await call('run/events', { runId, cursor, waitMs });
|
|
67
|
+
for (const event of page.events) onEvent(event);
|
|
68
|
+
cursor = page.cursor;
|
|
69
|
+
if (!page.running && page.events.length === 0) return call('run/status', { runId });
|
|
70
|
+
}
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Start an engine executable and connect to it. `command` is host configuration, not host code. */
|
|
76
|
+
export function spawnEngine({ command, args = [], env, onApproveTool, onCallTool, hostName, onLog = () => {} }) {
|
|
77
|
+
const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
78
|
+
child.stderr.setEncoding('utf8').on('data', chunk => onLog(chunk));
|
|
79
|
+
const client = connectEngine({ input: child.stdout, output: child.stdin, onApproveTool, onCallTool, hostName });
|
|
80
|
+
const exited = new Promise(resolve => child.once('exit', code => resolve(code)));
|
|
81
|
+
return { ...client, child, exited,
|
|
82
|
+
async close() { try { await client.shutdown(); } catch { /* already gone */ } child.stdin.end(); return exited; } };
|
|
83
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { invariant } from '@kingsoftcloud/agentkit-harness-core';
|
|
2
|
+
|
|
3
|
+
export const ENGINE_CONTEXT = 'agentkit.engine-context/v1';
|
|
4
|
+
const MAX_SOURCES = 32;
|
|
5
|
+
const MAX_SOURCE_MS = 30000;
|
|
6
|
+
const SOURCE_ID = /^[a-z][a-z0-9._-]{0,127}$/;
|
|
7
|
+
const DIGEST = /^sha256:[a-f0-9]{64}$/;
|
|
8
|
+
|
|
9
|
+
export function admitEngineContextSources(value) {
|
|
10
|
+
if (value === undefined) return [];
|
|
11
|
+
invariant(value?.contract === ENGINE_CONTEXT
|
|
12
|
+
&& Object.keys(value).every(key => key === 'contract' || key === 'sources') && Array.isArray(value.sources)
|
|
13
|
+
&& value.sources.length <= MAX_SOURCES, 'engine_context_sources_invalid');
|
|
14
|
+
const seen = new Set();
|
|
15
|
+
return value.sources.map(source => {
|
|
16
|
+
invariant(source && typeof source === 'object'
|
|
17
|
+
&& Object.keys(source).every(key => ['sourceId', 'bindingDigest', 'timeoutMs', 'maxTokens', 'maxBytes',
|
|
18
|
+
'failureMode', 'allowInstructions'].includes(key))
|
|
19
|
+
&& typeof source.sourceId === 'string' && SOURCE_ID.test(source.sourceId) && !seen.has(source.sourceId)
|
|
20
|
+
&& typeof source.bindingDigest === 'string' && DIGEST.test(source.bindingDigest)
|
|
21
|
+
&& Number.isSafeInteger(source.timeoutMs) && source.timeoutMs >= 1 && source.timeoutMs <= MAX_SOURCE_MS
|
|
22
|
+
&& Number.isSafeInteger(source.maxTokens) && source.maxTokens >= 1 && source.maxTokens <= 1048576
|
|
23
|
+
&& Number.isSafeInteger(source.maxBytes) && source.maxBytes >= 1 && source.maxBytes <= 131072
|
|
24
|
+
&& ['skip', 'warn', 'fail'].includes(source.failureMode) && typeof source.allowInstructions === 'boolean',
|
|
25
|
+
'engine_context_source_invalid');
|
|
26
|
+
seen.add(source.sourceId);
|
|
27
|
+
return { contract: 'agentkit.native-context-source/v1', sourceId: source.sourceId,
|
|
28
|
+
bindingDigest: source.bindingDigest, priority: 0, timeoutMs: source.timeoutMs, maxTokens: source.maxTokens,
|
|
29
|
+
maxBytes: source.maxBytes, required: source.failureMode === 'fail',
|
|
30
|
+
hostProjection: source.allowInstructions ? 'instructions-and-data/v1' : 'data/v1',
|
|
31
|
+
...(source.failureMode === 'warn' ? { warnOnFailure: true } : {}) };
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function engineContextPort(port, callHostContext) {
|
|
36
|
+
return { ...port, async readSource({ source, snapshot, operationKey, signal, remainingTokens }) {
|
|
37
|
+
invariant(source.hostProjection && typeof callHostContext === 'function', 'engine_context_unavailable');
|
|
38
|
+
const reply = await callHostContext({
|
|
39
|
+
contract: ENGINE_CONTEXT, runId: snapshot.runId, turnId: snapshot.turnId, operationKey,
|
|
40
|
+
sourceId: source.sourceId, bindingDigest: source.bindingDigest,
|
|
41
|
+
goal: snapshot.goal, goalRevision: snapshot.goalRevision, remainingTokens,
|
|
42
|
+
}, source.timeoutMs, signal);
|
|
43
|
+
invariant(reply?.contract === ENGINE_CONTEXT && reply.sourceId === source.sourceId
|
|
44
|
+
&& reply.bindingDigest === source.bindingDigest && Array.isArray(reply.items), 'engine_context_result_invalid');
|
|
45
|
+
return { items: reply.items };
|
|
46
|
+
} };
|
|
47
|
+
}
|
|
@@ -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
|
+
}
|