@kingsoftcloud/agentkit-harness-node 0.0.16 → 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.
Files changed (41) hide show
  1. package/dist/engine-view.html +566 -0
  2. package/dist/index.mjs +22 -14
  3. package/dist/rpc-entry.mjs +22 -14
  4. package/package.json +16 -2
  5. package/src/native/child-owner.mjs +8 -4
  6. package/src/native/children.mjs +12 -7
  7. package/src/native/command-shell.mjs +28 -3
  8. package/src/native/engine-client.mjs +83 -0
  9. package/src/native/engine-context.mjs +47 -0
  10. package/src/native/engine-hooks.mjs +53 -0
  11. package/src/native/engine-host-effects.mjs +98 -0
  12. package/src/native/engine-managed-delivery.mjs +65 -0
  13. package/src/native/engine-managed-host.mjs +75 -0
  14. package/src/native/engine-managed-service.mjs +249 -0
  15. package/src/native/engine-runtime.mjs +480 -0
  16. package/src/native/engine-server.mjs +454 -0
  17. package/src/native/engine-service.mjs +281 -0
  18. package/src/native/engine-tool-policy.mjs +29 -0
  19. package/src/native/engine-verification.mjs +111 -0
  20. package/src/native/engine-view-store.mjs +63 -0
  21. package/src/native/instruction-assembly.mjs +67 -3
  22. package/src/native/local-background-supervisor.mjs +1 -1
  23. package/src/native/local-background.mjs +4 -3
  24. package/src/native/local-command-tools.mjs +10 -7
  25. package/src/native/model-provider-compat.mjs +12 -7
  26. package/src/native/native-kernel-events.mjs +103 -0
  27. package/src/native/native-kernel-permit.mjs +95 -0
  28. package/src/native/native-managed-execution-grants.mjs +232 -0
  29. package/src/native/native-managed-injection.mjs +53 -0
  30. package/src/native/native-managed-interaction.mjs +192 -0
  31. package/src/native/native-managed-kernel-http.mjs +122 -0
  32. package/src/native/native-managed-kernel.mjs +922 -0
  33. package/src/native/native-managed-scoped-control.mjs +116 -0
  34. package/src/native/native-managed-session-frames.mjs +43 -0
  35. package/src/native/native-managed-teams-context.mjs +126 -0
  36. package/src/native/native-teams-callback-authority.mjs +73 -0
  37. package/src/native/native-teams-context-contract.mjs +272 -0
  38. package/src/native/native-teams-json.mjs +38 -0
  39. package/src/native/native-terminal-failure.mjs +53 -0
  40. package/src/native/sqlite-store.mjs +1 -0
  41. package/src/native/workspace-tools.mjs +2 -0
@@ -11,7 +11,7 @@ import { checkGovernedCommand, LOCAL_COMMAND_POLICY, GOVERNED_COMMAND_POLICY } f
11
11
  import { checkPlanCommand, PLAN_COMMAND_POLICY } from './command-plan.mjs';
12
12
  import { commandFailureEvidence, commandExceptionCause } from './local-command-evidence.mjs';
13
13
  import { captureCommandWorkspace, commandWorkspaceChange } from './command-workspace-observation.mjs';
14
- import { LOCAL_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
14
+ import { ISOLATED_COMMAND_SHELL, LOCAL_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
15
15
 
16
16
  export const LOCAL_COMMAND_TOOLS_CONTRACT = 'agentkit.local-command-tools/v1';
17
17
  export const LOCAL_COMMAND_PROGRESS_CONTRACT = 'agentkit.local-command-progress/v1';
@@ -58,7 +58,7 @@ function utf8Preview(text, maxBytes) {
58
58
  */
59
59
  export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionId, settings = {}, sourceEnv = {},
60
60
  authorize, resolveOwnedCommand, captureWorkspace, artifacts, assertAuthority = () => true,
61
- durableForeground = false, outputPolicy = null, environmentPolicy = null } = {}) {
61
+ durableForeground = false, outputPolicy = null, environmentPolicy = null, shellPolicy = LOCAL_COMMAND_SHELL } = {}) {
62
62
  invariant(typeof authorize === 'function' && typeof resolveOwnedCommand === 'function'
63
63
  && typeof captureWorkspace === 'function' && typeof assertAuthority === 'function'
64
64
  && typeof durableForeground === 'boolean', 'local_command_host_capabilities_missing');
@@ -70,6 +70,7 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
70
70
  const envPolicy = localEnvironmentPolicy(environmentPolicy);
71
71
  if (outPolicy) durableForeground = true;
72
72
  const root = realpathSync(workspaceRoot), policy = localControlSettings(settings), definitions = localCommandToolDefinitions(policy);
73
+ shellCommandArgv(':', shellPolicy, { workspaceRoot: root, cwd: root });
73
74
  // Under persisted-stream/v1 the automatic foreground receipt uses a bounded
74
75
  // window matching previewBytes (clamped to the 4..65536 UTF-8 cursor range).
75
76
  // Explicit read_command_output retains its own independent pagination.
@@ -164,9 +165,11 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
164
165
  if (decision !== 'allow') return decision?.status === 'approval_required' && typeof decision.interactionId === 'string'
165
166
  ? decision : errorResult('policy_denied');
166
167
  if (request.call.name === 'sandbox_status') return { status: 'ok', content: { ok: true, backend: 'local_process', enabled: true,
167
- isolated: false, sandbox_id: `local_process:${sessionId}`, timeout_seconds: policy.wallSeconds,
168
- boundary: 'Shares Host filesystem, allowlisted environment and network. Not an OS security sandbox.',
169
- shell: '/bin/bash', shell_policy: LOCAL_COMMAND_SHELL,
168
+ isolated: shellPolicy === ISOLATED_COMMAND_SHELL, sandbox_id: `local_process:${sessionId}`, timeout_seconds: policy.wallSeconds,
169
+ boundary: shellPolicy === ISOLATED_COMMAND_SHELL
170
+ ? 'Only the workspace and temporary files are writable. The command has no Host process or network access.'
171
+ : 'Shares Host filesystem, allowlisted environment and network. Not an OS security sandbox.',
172
+ shell: '/bin/bash', shell_policy: shellPolicy,
170
173
  contracts: [LOCAL_COMMAND_TOOLS_CONTRACT, LOCAL_PROCESS_CONTRACT, LOCAL_COMMAND_POLICY, GOVERNED_COMMAND_POLICY] } };
171
174
  if (request.call.name === 'read_command_output' || request.call.name === 'stop_command') {
172
175
  const owned = resolveOwnedCommand(request, args.task_id);
@@ -207,7 +210,7 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
207
210
  dispatched = true;
208
211
  const operationKey = request.operationKey, expectedTaskId = store.commandId(operationKey);
209
212
  known = { content: { backend: 'sandbox/local_process', task_id: expectedTaskId } };
210
- const handle = await store.start({ operationKey, command, cwd, env, settings: policy, shellPolicy: LOCAL_COMMAND_SHELL,
213
+ const handle = await store.start({ operationKey, command, cwd, env, settings: policy, shellPolicy, workspaceRoot: root,
211
214
  outputPolicy: outPolicy, environmentPolicy: envPolicy,
212
215
  timeoutMs: deadline(args.background ? args.background_timeout : args.timeout), assertCurrent: guard });
213
216
  if (!args.background) {
@@ -258,7 +261,7 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
258
261
  ? { backgroundCommandFinished: true } : {}) };
259
262
  } else {
260
263
  dispatched = true;
261
- const result = await runBoundedProcess({ argv: shellCommandArgv(command, LOCAL_COMMAND_SHELL), cwd, env, settings: policy, signal: request.signal,
264
+ const result = await runBoundedProcess({ argv: shellCommandArgv(command, shellPolicy, { workspaceRoot: root, cwd }), cwd, env, settings: policy, signal: request.signal,
262
265
  timeoutMs: deadline(args.timeout), onOutput: progress });
263
266
  const incomplete = result.controls.status === 'failed' || !!result.cleanupError;
264
267
  const resourceReason = result.exitCode === -osConstants.signals.SIGXCPU ? 'cpu_time'
@@ -1,5 +1,6 @@
1
1
  // Frozen Chat Completions request policy, ported from the pinned Python
2
2
  // model_proxy.compat and transform.model-effort-map/v2. No IO or retries here.
3
+ import { FINAL_SUBMISSION_TOOL } from '@kingsoftcloud/agentkit-harness-core';
3
4
  import { admitInlineReasoningPolicy, resolveCompatibilityRule } from './model-inline-reasoning.mjs';
4
5
  import { ProtocolError } from './model-normalize.mjs';
5
6
 
@@ -44,29 +45,30 @@ export function applyAnthropicThinking(payload, profile, binding) {
44
45
  }
45
46
 
46
47
  export function admitProviderCompatibilityPolicy(override) {
47
- return { contract: 'provider-compat/v4', rule: admitInlineReasoningPolicy(override).rule };
48
+ return { contract: 'provider-compat/v5', rule: admitInlineReasoningPolicy(override).rule };
48
49
  }
49
50
 
50
51
  export function resolveProviderCompatibility(policy, binding) {
51
52
  if (!policy) return null;
52
- if (!['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)) throw new ProtocolError('invalid_provider_compatibility_policy');
53
+ const version = ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4', 'provider-compat/v5'].indexOf(policy.contract) + 1;
54
+ if (!version) throw new ProtocolError('invalid_provider_compatibility_policy');
53
55
  const rule = resolveCompatibilityRule(policy.rule, binding);
54
56
  const name = String(binding.model ?? '').trim().toLowerCase();
55
57
  const kimi = ['kspmas-gateway', 'moonshot'].includes(rule)
56
58
  && ['kimi-k2.7-code', 'kimi-k2.7-code-highspeed'].includes(name);
57
- const modern = ['provider-compat/v3', 'provider-compat/v4'].includes(policy.contract);
59
+ const modern = version >= 3;
58
60
  const reasoningRequired = modern && rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
59
61
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === 'claude-haiku-5-5' ? ['low', 'medium', 'high'] : null;
60
62
  return { rule, supportsUsage: !strict.has(rule), supportsThinking: !strict.has(rule) && !kimi,
61
- supportsToolArgumentStreaming: ['provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4'].includes(policy.contract)
63
+ supportsToolArgumentStreaming: version >= 2
62
64
  && ['zai', 'kspmas-gateway'].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
63
- reasoningRequired, modern,
65
+ reasoningRequired, modern, firstToolLowEffort: version >= 5 && reasoningRequired,
64
66
  // This route already uses the supported non-thinking mode for tool work.
65
67
  // A bounded summary has no tools: omitting the switch can instead select
66
68
  // the provider's default high reasoning and consume its whole output cap.
67
69
  // Freeze this purpose-specific default only on new admissions; mandatory
68
70
  // thinking models and explicit caller choices remain authoritative.
69
- compactionThinkingOff: policy.contract === 'provider-compat/v4' && rule === 'kspmas-gateway' && !kimi,
71
+ compactionThinkingOff: version >= 4 && rule === 'kspmas-gateway' && !kimi,
70
72
  // Only the observed provider/model dialects may seal without [DONE].
71
73
  finishOnEof: modern && ['permissive', 'kspmas-gateway'].includes(rule)
72
74
  && ['minimax-m3', 'minimax-m2.5'].includes(name),
@@ -105,7 +107,11 @@ export function applyProviderChatCompatibility(payload, request, binding) {
105
107
  }
106
108
  const model = binding.model, name = normalized(model);
107
109
  const requested = options.reasoningEffort ?? result.reasoning_effort ?? null;
110
+ const mode = options.thinkingMode ?? result.thinking?.type;
108
111
  let effort = requested;
112
+ if (requested === null && mode === undefined && compat.firstToolLowEffort && request.beforeFirstTool
113
+ && !request.finalizationOnly && result.tool_choice !== 'none'
114
+ && result.tools?.some(tool => tool.type === 'function' && tool.function?.name !== FINAL_SUBMISSION_TOOL)) effort = 'low';
109
115
  if (requested === null && options.controllerReasoningPolicy === 'disclosed-delegate/v1'
110
116
  && ['zai', 'kspmas-gateway'].includes(compat.rule) && name.startsWith('glm-5.3')
111
117
  && result.tools?.some(tool => tool.type === 'function' && tool.function?.name === 'delegate_task')) effort = 'low';
@@ -119,7 +125,6 @@ export function applyProviderChatCompatibility(payload, request, binding) {
119
125
  result.stream_options = { ...result.stream_options }; delete result.stream_options.include_usage;
120
126
  if (!Object.keys(result.stream_options).length) delete result.stream_options;
121
127
  }
122
- const mode = options.thinkingMode ?? result.thinking?.type;
123
128
  if (mode === 'disabled' && compat.reasoningRequired) throw new ProtocolError('model_thinking_disable_unsupported');
124
129
  const mayDisable = compat.supportsThinking && (compat.disabledEfforts === null || compat.disabledEfforts.includes(effort));
125
130
  const summaryOff = request.purpose === 'compaction' && requested === null && compat.rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
@@ -0,0 +1,103 @@
1
+ /** Derive canonical Kernel facts from committed Native events, never live
2
+ * model callbacks. Projection receipts/cursors are committed by the owner. */
3
+ import { createHash } from 'node:crypto';
4
+ import { canonical } from '@kingsoftcloud/agentkit-harness-core';
5
+ import { nativePublicTerminalError } from './native-terminal-failure.mjs';
6
+
7
+ export function nativeKernelFactId(source, index) {
8
+ const hex = createHash('sha256').update(canonical([source, index])).digest('hex');
9
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-a${hex.slice(17, 20)}-${hex.slice(20, 32)}`;
10
+ }
11
+
12
+ export function projectNativeKernelEvent(event, { scopeId, commandId } = {}) {
13
+ const runId = event.runId, payload = event.payload, facts = [];
14
+ const runtime = value => facts.push({ family: 'runtime', family_version: 2, event_type: value.event_type,
15
+ payload: { schema_version: 2, run_id: runId, scope_id: scopeId, ...value } });
16
+ const transition = state => facts.push({ family: 'control', family_version: 1, event_type: 'control.run_transition',
17
+ causation_id: commandId, payload: { run_id: runId, state } });
18
+ const textItem = (id, text) => {
19
+ runtime({ event_type: 'item.updated', item_id: id, item_kind: 'message', op: 'replace',
20
+ update: { content_type: 'text', part_id: 'text', text } });
21
+ runtime({ event_type: 'item.completed', item_id: id, item_kind: 'message',
22
+ snapshot: { parts: [{ content_type: 'text', part_id: 'text', text }] } });
23
+ };
24
+ if (event.kind === 'run.started') {
25
+ transition('running'); runtime({ event_type: 'run.started', status: 'running' });
26
+ } else if (event.kind === 'model.completed') {
27
+ if (payload.candidateStatus !== 'rejected' && payload.text) textItem(event.eventId, payload.text);
28
+ if (payload.usageReported !== false && payload.usage) runtime({ event_type: 'usage.reported',
29
+ input_tokens: payload.usage.inputTokens, output_tokens: payload.usage.outputTokens,
30
+ total_tokens: payload.usage.inputTokens + payload.usage.outputTokens,
31
+ cached_tokens: payload.usage.cachedInputTokens ?? 0, reasoning_tokens: payload.usage.reasoningTokens ?? 0 });
32
+ // Appended after the message/usage facts so existing event_ids stay unchanged.
33
+ if (payload.candidateStatus !== 'rejected' && Array.isArray(payload.toolCalls)) {
34
+ for (const call of payload.toolCalls) {
35
+ if (!call?.callId || !call?.name) continue;
36
+ runtime({ event_type: 'item.completed', item_id: `call-${call.callId}`, item_kind: 'tool_call',
37
+ snapshot: { parts: [{ content_type: 'tool_call', part_id: 'call', call_id: call.callId,
38
+ name: call.name, arguments: call.arguments ?? {} }] } });
39
+ }
40
+ }
41
+ // displayStream thinking records are a committed capture, not a live token callback.
42
+ const thinkingText = (payload.displayStream?.records ?? [])
43
+ .filter(record => record.event?.kind === 'thinking' && record.event?.text)
44
+ .map(record => record.event.text);
45
+ if (thinkingText.length) runtime({ event_type: 'item.completed', item_id: `reasoning-${event.eventId}`,
46
+ item_kind: 'reasoning',
47
+ snapshot: { parts: [{ content_type: 'text', part_id: 'thinking', text: thinkingText.join('') }] } });
48
+ } else if (event.kind === 'tool.completed') {
49
+ if (payload.status === 'uncertain') {
50
+ runtime({ event_type: 'item.failed', item_id: `result-${payload.callId}`, item_kind: 'tool_result',
51
+ error: { code: 'NATIVE_TOOL_OUTCOME_UNKNOWN', source: 'agentkit-native', scope_id: scopeId } });
52
+ } else {
53
+ runtime({ event_type: 'item.completed', item_id: `result-${payload.callId}`, item_kind: 'tool_result',
54
+ snapshot: { parts: [{ content_type: 'tool_result', part_id: 'result', call_id: payload.callId,
55
+ result: Object.hasOwn(payload, 'content') ? payload.content : {}, is_error: payload.status === 'error' }] } });
56
+ }
57
+ } else if (event.kind === 'tool.rejected') {
58
+ runtime({ event_type: 'item.failed', item_id: `result-${payload.callId}`, item_kind: 'tool_result',
59
+ error: { code: 'NATIVE_TOOL_REJECTED', message: payload.reason ?? null, source: 'agentkit-native', scope_id: scopeId } });
60
+ } else if (event.kind === 'tool.not_dispatched') {
61
+ runtime({ event_type: 'item.failed', item_id: `result-${payload.callId}`, item_kind: 'tool_result',
62
+ error: { code: 'NATIVE_TOOL_NOT_DISPATCHED', message: payload.reason ?? null, source: 'agentkit-native', scope_id: scopeId } });
63
+ } else if (event.kind === 'approval.requested') {
64
+ facts.push({ family: 'interaction', family_version: 1, event_type: 'interaction.requested', payload: {
65
+ interaction_id: payload.interactionId, revision: 1, kind: 'approval', request: {
66
+ presentation: { title: 'Tool approval', description: `Allow ${payload.name}?` },
67
+ },
68
+ } });
69
+ transition('waiting');
70
+ } else if (event.kind === 'approval.resolved') {
71
+ facts.push({ family: 'interaction', family_version: 1, event_type: 'interaction.resolved', payload: {
72
+ interaction_id: payload.interactionId, revision: 2,
73
+ } }); transition('running');
74
+ } else if (event.kind === 'command.applied') {
75
+ if (payload.reason && !['applied', 'already_paused', 'not_paused'].includes(payload.reason)) {
76
+ facts.push({ family: 'control', family_version: 1, event_type: 'control.command_rejected',
77
+ causation_id: payload.commandId, payload: { command_id: payload.commandId, reason: payload.reason } });
78
+ }
79
+ // causation is the control command, not the original enqueue.
80
+ if (payload.reason === 'applied' && payload.kind === 'pause') {
81
+ facts.push({ family: 'control', family_version: 1, event_type: 'control.run_transition',
82
+ causation_id: payload.commandId, payload: { run_id: runId, state: 'paused' } });
83
+ } else if (payload.reason === 'applied' && payload.kind === 'resume') {
84
+ facts.push({ family: 'control', family_version: 1, event_type: 'control.run_transition',
85
+ causation_id: payload.commandId, payload: { run_id: runId, state: 'running' } });
86
+ }
87
+ } else if (event.kind === 'run.terminal') {
88
+ const state = payload.phase === 'canceled' ? 'cancelled' : payload.phase;
89
+ const output = [];
90
+ if (state === 'completed' && payload.finalText) {
91
+ // The final candidate may differ from an earlier draft after verification.
92
+ const itemId = `final-${runId}`; textItem(itemId, payload.finalText);
93
+ output.push({ scope_id: scopeId, item_id: itemId, part_id: 'text' });
94
+ }
95
+ runtime(state === 'completed' ? { event_type: 'run.completed', status: 'completed', output_refs: output }
96
+ : state === 'cancelled' ? { event_type: 'run.canceled', status: 'canceled', reason: 'Execution canceled' }
97
+ : state === 'interrupted' ? { event_type: 'run.interrupted', status: 'interrupted', reason: payload.reason ?? null }
98
+ : { event_type: 'run.failed', status: 'failed', error: {
99
+ ...nativePublicTerminalError('failed', payload.reason, payload.modelFailure), source: 'agentkit-native', scope_id: scopeId } });
100
+ transition(state);
101
+ }
102
+ return facts.map((fact, index) => ({ ...fact, event_id: nativeKernelFactId(event.eventId, index), run_id: runId }));
103
+ }
@@ -0,0 +1,95 @@
1
+ /** Server-issued AgentControlPermit/v1. Verification is deliberately separate
2
+ * from durable nonce consumption, which must commit with command admission. */
3
+ import { createHash, createPublicKey, verify as verifySignature } from 'node:crypto';
4
+ import { canonical, copy, invariant } from '@kingsoftcloud/agentkit-harness-core';
5
+
6
+ const code = 'NATIVE_KERNEL_PERMIT_INVALID';
7
+ const check = value => invariant(value, code);
8
+ const string = value => typeof value === 'string' && value.trim() && value.length <= 4096 && !value.includes('\0')
9
+ && [...value].every(c => c.codePointAt(0) < 0xd800 || c.codePointAt(0) > 0xdfff);
10
+ const object = value => value && typeof value === 'object' && !Array.isArray(value);
11
+ const operations = new Set(['enqueue', 'steer', 'inject', 'interrupt', 'pause', 'resume', 'submit_interaction', 'get_status', 'subscribe_events']);
12
+ function timestamp(value) {
13
+ check(typeof value === 'string');
14
+ const match = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d{1,6}))?(Z|[+-]\d\d:\d\d)?$/u.exec(value);
15
+ check(match);
16
+ const [, year, month, day, hour, minute, second, fraction = '', zone = 'Z'] = match;
17
+ const end = new Date(0); end.setUTCFullYear(Number(year), Number(month), 0);
18
+ check(Number(year) >= 1 && Number(month) >= 1 && Number(month) <= 12 && Number(day) >= 1 && Number(day) <= end.getUTCDate()
19
+ && Number(hour) < 24 && Number(minute) < 60 && Number(second) < 60);
20
+ const time = Date.parse(value + (zone === 'Z' && !value.endsWith('Z') ? 'Z' : ''));
21
+ check(Number.isFinite(time));
22
+ return { milliseconds: time, microseconds: BigInt(time) * 1000n + BigInt(fraction.padEnd(6, '0').slice(3)) };
23
+ }
24
+ // Python signs UTC second-normalized timestamps, even when the wire carries
25
+ // offsets or microseconds. The verifier still checks the original expiry.
26
+ export function nativeKernelPermitBytes(value) {
27
+ const data = copy(value); delete data.signature;
28
+ for (const name of ['issued_at', 'expires_at']) data[name] = new Date(timestamp(data[name]).milliseconds).toISOString().replace(/\.\d{3}Z$/u, 'Z');
29
+ // Known v1 fields have ASCII keys; additive string-keyed objects use Python's
30
+ // Unicode code-point ordering rather than JavaScript UTF-16 ordering.
31
+ const order = (a, b) => {
32
+ const left = [...a], right = [...b];
33
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
34
+ const difference = left[i].codePointAt(0) - right[i].codePointAt(0); if (difference) return difference;
35
+ }
36
+ return left.length - right.length;
37
+ };
38
+ const encode = item => Array.isArray(item) ? '[' + item.map(encode).join(',') + ']'
39
+ : object(item) ? '{' + Object.keys(item).sort(order).map(key => JSON.stringify(key) + ':' + encode(item[key])).join(',') + '}' : canonical(item);
40
+ return Buffer.from(encode(data));
41
+ }
42
+
43
+ export function nativePlatformToolApproval(command) {
44
+ const payload = command?.payload;
45
+ if (command?.command_type !== 'submit_interaction' || !object(payload?.response)
46
+ || !['approve', 'reject'].includes(payload.action) || !Number.isSafeInteger(payload.expected_revision)
47
+ || payload.expected_revision < 1 || ![command.command_id, command.idempotency_key, payload.run_id, payload.interaction_id].every(string)) return null;
48
+ return { contract: 'agentkit.tool-approval-command/v1', command_id: command.command_id,
49
+ idempotency_key: command.idempotency_key, run_id: payload.run_id, interaction_id: payload.interaction_id,
50
+ expected_revision: payload.expected_revision, action: payload.action };
51
+ }
52
+
53
+ export function createNativeKernelPermitVerifier({ verificationKeys, target, clock = Date.now, requireBoundApproval = false } = {}) {
54
+ check(typeof verificationKeys === 'function' && object(target) && string(target.tenantId) && string(target.agentInstanceId)
55
+ && typeof clock === 'function');
56
+ const binding = Object.freeze({ tenantId: target.tenantId, agentInstanceId: target.agentInstanceId });
57
+ return Object.freeze({ async verify(raw, request, operation) {
58
+ try {
59
+ // Copy before awaiting a rotating key provider. Caller mutation cannot
60
+ // change the command/permit that was actually authenticated.
61
+ const permit = copy(raw), expected = copy(request);
62
+ check(object(permit) && permit.schema_version === 1 && permit.alg === 'Ed25519' && operations.has(operation));
63
+ for (const name of ['permit_id', 'subject_ref', 'tenant_id', 'agent_instance_id', 'nonce', 'key_id', 'claims_digest', 'signature']) check(string(permit[name]));
64
+ check(permit.session_id === null || string(permit.session_id));
65
+ check(Array.isArray(permit.allowed_operations) && permit.allowed_operations.length > 0
66
+ && permit.allowed_operations.every(item => operations.has(item)) && permit.allowed_operations.includes(operation));
67
+ check(expected.authorization_ref === permit.permit_id && expected.tenant_id === binding.tenantId
68
+ && expected.agent_instance_id === binding.agentInstanceId && permit.tenant_id === expected.tenant_id
69
+ && permit.agent_instance_id === expected.agent_instance_id
70
+ && (permit.session_id === null || permit.session_id === expected.session_id));
71
+ const issued = timestamp(permit.issued_at).microseconds, expires = timestamp(permit.expires_at).microseconds, now = clock();
72
+ check(Number.isSafeInteger(now));
73
+ const current = BigInt(now) * 1000n;
74
+ check(issued <= current && expires > current && expires > issued && expires - issued <= 300_000_000n);
75
+ const keys = await verificationKeys(), pem = keys instanceof Map ? keys.get(permit.key_id)
76
+ : object(keys) && Object.hasOwn(keys, permit.key_id) ? keys[permit.key_id] : null;
77
+ check(typeof pem === 'string' && Buffer.byteLength(pem) <= 64 * 1024);
78
+ const key = createPublicKey(pem), signature = Buffer.from(permit.signature, 'base64url');
79
+ check(key.asymmetricKeyType === 'ed25519' && signature.length === 64 && signature.toString('base64url') === permit.signature
80
+ && verifySignature(null, nativeKernelPermitBytes(permit), key, signature));
81
+ if (requireBoundApproval && operation === 'submit_interaction') {
82
+ const approval = nativePlatformToolApproval(expected);
83
+ check(approval && permit.session_id === expected.session_id && expected.payload.token_ref === permit.permit_id);
84
+ // Match the Server's v1 claim digest with the normalized tool decision
85
+ // included. The signed permit keeps its existing wire shape.
86
+ const { claims_digest: signedDigest, ...claims } = permit;
87
+ const digest = createHash('sha256').update(nativeKernelPermitBytes({ ...claims, tool_approval: approval })).digest('hex');
88
+ check(digest === signedDigest);
89
+ }
90
+ const checkedAt = clock(); check(Number.isSafeInteger(checkedAt) && BigInt(checkedAt) * 1000n < expires);
91
+ return Object.freeze({ permitId: permit.permit_id, subjectRef: permit.subject_ref, claimsDigest: permit.claims_digest,
92
+ nonce: permit.nonce, keyId: permit.key_id, operation, sessionId: permit.session_id, expiresAt: Number(expires / 1000n) });
93
+ } catch { invariant(false, code); }
94
+ } });
95
+ }
@@ -0,0 +1,232 @@
1
+ /** Trusted Host execution admission. These ports are deliberately absent from
2
+ * the HTTP receiver: a signed enqueue may name a grant, never create one.
3
+ * Grant mutations and command qualification share the command-store transaction.
4
+ * Qualification is not a model effect, lease or permission to replay a tool. */
5
+ import { performance } from 'node:perf_hooks';
6
+ import { canonical, copy, invariant, parseNativeJson, terminal } from '@kingsoftcloud/agentkit-harness-core';
7
+
8
+ export const MANAGED_NATIVE_EXECUTION_GRANTS_CONTRACT = 'agentkit.managed-native-execution-grants/v1';
9
+ const validText = value => typeof value === 'string' && value.length > 0 && value === value.trim() && !value.includes('\0');
10
+ const positive = value => Number.isSafeInteger(value) && value >= 1;
11
+ const specFields = ['grant_id', 'tenant_id', 'agent_instance_id', 'session_id', 'owner_ref', 'attempt_epoch'];
12
+ const fail = reason => invariant(false, `execution_grant_${reason}`);
13
+ function specification(raw) {
14
+ invariant(raw && typeof raw === 'object' && !Array.isArray(raw)
15
+ && Object.keys(raw).every(key => specFields.includes(key)), 'execution_grant_spec_invalid');
16
+ const spec = copy(raw); spec.attempt_epoch ??= null;
17
+ invariant(specFields.slice(0, -1).every(key => validText(spec[key])) && spec.grant_id.length <= 512
18
+ && (spec.attempt_epoch === null || positive(spec.attempt_epoch)), 'execution_grant_spec_invalid');
19
+ return spec;
20
+ }
21
+ function absoluteTime(value) {
22
+ const match = typeof value === 'string' && /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(Z|[+-](\d{2}):(\d{2}))$/u.exec(value);
23
+ invariant(match && Number.isFinite(Date.parse(value)), 'execution_grant_expiry_invalid');
24
+ const [year, month, day, hour, minute, second] = match.slice(1, 7).map(item => Number(item ?? 0));
25
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
26
+ const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
27
+ invariant(year >= 1 && month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1]
28
+ && hour <= 23 && minute <= 59 && second <= 59 && Number(match[8] ?? 0) <= 23 && Number(match[9] ?? 0) <= 59,
29
+ 'execution_grant_expiry_invalid');
30
+ return new Date(value).toISOString();
31
+ }
32
+ export function managedExecutionGrantId(command) {
33
+ const id = command.payload.execution_grant_id;
34
+ if (id == null) {
35
+ invariant(command.payload.execution_grant_attempt_epoch == null, 'execution_grant_id_required'); return null;
36
+ }
37
+ invariant(command.command_type === 'enqueue' && validText(id) && id.length <= 512, 'execution_grant_id_invalid');
38
+ return id;
39
+ }
40
+
41
+ export function createManagedNativeExecutionGrants({ db, guard, transaction, target, clock, hash, wake, readRun,
42
+ monotonic = () => performance.now() } = {}) {
43
+ db.exec(`CREATE TABLE IF NOT EXISTS managed_execution_grants (grant_id TEXT PRIMARY KEY, data TEXT NOT NULL);
44
+ CREATE TABLE IF NOT EXISTS managed_grant_operations (grant_id TEXT NOT NULL, idem TEXT NOT NULL,
45
+ digest TEXT NOT NULL, receipt TEXT NOT NULL, PRIMARY KEY(grant_id,idem));
46
+ CREATE TABLE IF NOT EXISTS managed_command_claims (command_id TEXT PRIMARY KEY, claimed_at TEXT NOT NULL);`);
47
+ // Never reconstructed from persisted deadlines, duplicate receipts or reads.
48
+ const anchors = new Map();
49
+ const now = () => new Date(clock()).toISOString();
50
+ const load = id => { const row = db.prepare('SELECT data FROM managed_execution_grants WHERE grant_id=?').get(id);
51
+ return row ? parseNativeJson(row.data) : null; };
52
+ const claimed = id => Boolean(db.prepare('SELECT 1 FROM managed_command_claims WHERE command_id=?').get(id));
53
+ const persist = record => db.prepare('UPDATE managed_execution_grants SET data=? WHERE grant_id=?').run(canonical(record), record.grant_id);
54
+ function scoped(raw) {
55
+ guard(); const spec = specification(raw);
56
+ invariant(spec.tenant_id === target.tenantId && spec.agent_instance_id === target.agentInstanceId, 'execution_grant_scope_mismatch');
57
+ return spec;
58
+ }
59
+ function exact(spec) {
60
+ const record = load(spec.grant_id);
61
+ if (!record) fail('not_found');
62
+ invariant(specFields.every(key => record[key] === spec[key]), 'execution_grant_scope_mismatch'); return record;
63
+ }
64
+ function budget(seconds) {
65
+ if (seconds == null) return null;
66
+ invariant(typeof seconds === 'number' && Number.isFinite(seconds) && seconds >= 0, 'execution_grant_ttl_invalid');
67
+ return monotonic() + seconds * 1000;
68
+ }
69
+ function anchor(record, observedDeadline) {
70
+ if (record.expires_at === null) return;
71
+ const deadline = monotonic() + Math.max(0, Date.parse(record.expires_at) - clock());
72
+ anchors.set(record.grant_id, { expiry: record.expires_at, deadline: observedDeadline === null ? deadline : Math.min(deadline, observedDeadline) });
73
+ }
74
+ function localError(record) {
75
+ if (!record || record.expires_at === null) return null;
76
+ const entry = anchors.get(record.grant_id);
77
+ if (!entry || entry.expiry !== record.expires_at) return 'clock_unverified';
78
+ return monotonic() >= entry.deadline ? 'expired' : null;
79
+ }
80
+ const expired = record => record.expires_at !== null && clock() >= Date.parse(record.expires_at);
81
+ function requireActive(record) {
82
+ if (record.state !== 'active') fail(record.state);
83
+ if (expired(record)) fail('expired');
84
+ }
85
+ function requireLive(record) { requireActive(record); const error = localError(record); if (error) fail(error); }
86
+ function commandError(command) {
87
+ const id = managedExecutionGrantId(command); if (id === null) return null;
88
+ const record = load(id);
89
+ if (!record) return 'execution_grant_not_found';
90
+ if (['tenant_id', 'agent_instance_id', 'session_id'].some(key => record[key] !== command[key])) return 'execution_grant_scope_mismatch';
91
+ if (record.state === 'revoked') return 'execution_grant_revoked';
92
+ const epoch = command.payload.execution_grant_attempt_epoch ?? null;
93
+ if (epoch !== record.attempt_epoch || epoch !== null && !positive(epoch)) return 'execution_grant_attempt_epoch_mismatch';
94
+ if (expired(record)) return 'execution_grant_expired';
95
+ const error = localError(record); return error ? `execution_grant_${error}` : null;
96
+ }
97
+ function claimError(row) {
98
+ const command = parseNativeJson(row.data), id = managedExecutionGrantId(command);
99
+ if (id === null) return null;
100
+ const record = load(id), error = commandError(command), qualified = claimed(row.command_id);
101
+ // Legacy qualification survives revocation and suspension, including cold
102
+ // takeover. Expiring grants must remain live even when re-claiming work.
103
+ if (qualified && record?.expires_at === null && (error === null || error === 'execution_grant_revoked')) return null;
104
+ if (error) return error;
105
+ if (record.state === 'suspended') return 'execution_grant_suspended';
106
+ if (qualified) return null;
107
+ return record.admission_allowed ? null : 'execution_grant_admission_paused';
108
+ }
109
+ function qualify(row) {
110
+ return transaction(() => {
111
+ const current = db.prepare('SELECT * FROM managed_commands WHERE command_id=?').get(row.command_id);
112
+ if (!current || current.state !== 'accepted') return false;
113
+ const first = db.prepare("SELECT * FROM managed_commands WHERE session_id=? AND state='accepted' ORDER BY rowid").all(row.session_id)
114
+ .find(candidate => parseNativeJson(candidate.data).command_type === 'enqueue');
115
+ invariant(first?.command_id === row.command_id, 'execution_grant_queued');
116
+ const error = claimError(current); if (error) invariant(false, error);
117
+ db.prepare('INSERT OR IGNORE INTO managed_command_claims VALUES (?,?)').run(row.command_id, now()); return true;
118
+ });
119
+ }
120
+ function readySessions() {
121
+ guard(); const seen = new Set(), ready = [];
122
+ for (const row of db.prepare("SELECT * FROM managed_commands WHERE state='accepted' ORDER BY rowid").all()) {
123
+ if (seen.has(row.session_id) || parseNativeJson(row.data).command_type !== 'enqueue') continue;
124
+ seen.add(row.session_id); if (!claimError(row)) ready.push(row.session_id);
125
+ }
126
+ return ready;
127
+ }
128
+ function inspect(row) {
129
+ const command = parseNativeJson(row.data), id = managedExecutionGrantId(command);
130
+ if (id === null) return null;
131
+ const record = load(id);
132
+ return { contract: MANAGED_NATIVE_EXECUTION_GRANTS_CONTRACT, grantId: id,
133
+ attemptEpoch: record?.attempt_epoch ?? null, state: record?.state ?? 'missing',
134
+ revision: record?.revision ?? null, admissionAllowed: record?.admission_allowed ?? false,
135
+ admissionRevision: record?.admission_revision ?? null, expiresAt: record?.expires_at ?? null,
136
+ qualified: claimed(row.command_id), blockedReason: row.state === 'accepted' ? claimError(row) : null };
137
+ }
138
+ function barrier(record) {
139
+ const result = { grant: copy(record), queued_message_ids: [], in_flight_message_ids: [], discarded_message_ids: [], settled_message_ids: [], commands: [] };
140
+ for (const row of db.prepare('SELECT * FROM managed_commands WHERE session_id=? ORDER BY rowid').all(record.session_id)) {
141
+ const command = parseNativeJson(row.data);
142
+ if (managedExecutionGrantId(command) !== record.grant_id) continue;
143
+ const receipt = parseNativeJson(row.receipt), run = readRun(receipt.run_id), qualified = claimed(row.command_id);
144
+ const state = row.state === 'discarded' ? 'discarded' : !qualified ? 'accepted' : row.state === 'settled' ? 'completed' : 'claimed';
145
+ result.commands.push({ message_id: receipt.message_id, command_id: row.command_id, idempotency_key: row.idem,
146
+ inbox_state: state, run_id: run ? receipt.run_id : null, run_state: run?.snapshot.phase ?? null });
147
+ const key = state === 'discarded' ? 'discarded_message_ids' : state === 'accepted' ? 'queued_message_ids'
148
+ : run && terminal(run.snapshot.phase) ? 'settled_message_ids' : 'in_flight_message_ids';
149
+ result[key].push(receipt.message_id);
150
+ }
151
+ return result;
152
+ }
153
+ function original(spec, key, digest) {
154
+ const row = db.prepare('SELECT * FROM managed_grant_operations WHERE grant_id=? AND idem=?').get(spec.grant_id, key);
155
+ if (!row) return null;
156
+ if (digest !== undefined) invariant(row.digest === digest, 'execution_grant_idempotency_conflict');
157
+ return parseNativeJson(row.receipt);
158
+ }
159
+ function mutation(raw, key, operation, apply) {
160
+ const spec = scoped(raw);
161
+ invariant(validText(key) && key.length <= 4096, 'execution_grant_operation_invalid');
162
+ const digest = hash({ spec, ...operation });
163
+ const result = transaction(() => {
164
+ const record = exact(spec), previous = original(spec, key, digest); if (previous) return { receipt: previous, changed: false };
165
+ const updated = apply(record), receipt = barrier(updated);
166
+ db.prepare('INSERT INTO managed_grant_operations VALUES (?,?,?,?)').run(spec.grant_id, key, digest, canonical(receipt));
167
+ return { receipt, changed: true };
168
+ });
169
+ if (result.changed) wake(); return result;
170
+ }
171
+ const api = Object.freeze({ contract: MANAGED_NATIVE_EXECUTION_GRANTS_CONTRACT,
172
+ ensure(raw, { expires_at = null, remaining_ttl_seconds = null } = {}) {
173
+ const spec = scoped(raw), observed = budget(remaining_ttl_seconds);
174
+ if (expires_at !== null) expires_at = absoluteTime(expires_at);
175
+ const result = transaction(() => {
176
+ const previous = load(spec.grant_id);
177
+ if (previous) return { record: exact(spec), created: false };
178
+ invariant((expires_at === null) === (spec.attempt_epoch === null), 'execution_grant_epoch_expiry_required');
179
+ const record = { ...spec, expires_at, state: 'active', revision: 1, admission_allowed: true,
180
+ admission_revision: 1, created_at: now(), updated_at: now() };
181
+ db.prepare('INSERT INTO managed_execution_grants VALUES (?,?)').run(spec.grant_id, canonical(record));
182
+ return { record, created: true };
183
+ });
184
+ if (result.created) { anchor(result.record, observed); wake(); }
185
+ return copy(result.record);
186
+ },
187
+ get(raw) { const spec = scoped(raw); return transaction(() => barrier(exact(spec))); },
188
+ require(raw) { const spec = scoped(raw); return transaction(() => { const record = exact(spec); requireLive(record); return copy(record); }); },
189
+ lookup(raw, { idempotency_key } = {}) {
190
+ const spec = scoped(raw); invariant(validText(idempotency_key), 'execution_grant_operation_invalid');
191
+ return transaction(() => { exact(spec); return original(spec, idempotency_key); });
192
+ },
193
+ setState(raw, state, { expected_revision, idempotency_key } = {}) {
194
+ invariant(['active', 'suspended', 'revoked'].includes(state) && positive(expected_revision), 'execution_grant_operation_invalid');
195
+ return mutation(raw, idempotency_key, { operation: 'state', state, expected_revision }, record => {
196
+ invariant(record.revision === expected_revision, 'execution_grant_revision_conflict');
197
+ invariant(record.state !== 'revoked' || state === 'revoked', 'execution_grant_irreversible');
198
+ const updated = { ...record, state, revision: record.revision + 1, updated_at: now() }; persist(updated);
199
+ if (state === 'revoked') {
200
+ for (const row of db.prepare("SELECT * FROM managed_commands WHERE session_id=? AND state='accepted' AND command_id NOT IN (SELECT command_id FROM managed_command_claims)").all(record.session_id)) {
201
+ if (managedExecutionGrantId(parseNativeJson(row.data)) === record.grant_id)
202
+ db.prepare("UPDATE managed_commands SET state='discarded' WHERE command_id=?").run(row.command_id);
203
+ }
204
+ }
205
+ return updated;
206
+ }).receipt;
207
+ },
208
+ setAdmission(raw, allowed, { expected_revision, idempotency_key } = {}) {
209
+ invariant(typeof allowed === 'boolean' && positive(expected_revision), 'execution_grant_operation_invalid');
210
+ return mutation(raw, idempotency_key, { operation: 'admission', allowed, expected_revision }, record => {
211
+ requireLive(record); invariant(record.admission_revision === expected_revision, 'execution_grant_admission_revision_conflict');
212
+ const updated = { ...record, admission_allowed: allowed, admission_revision: record.admission_revision + 1, updated_at: now() };
213
+ persist(updated); return updated;
214
+ }).receipt;
215
+ },
216
+ renew(raw, { expected_revision, expires_at, renewal_id, remaining_ttl_seconds = null } = {}) {
217
+ const observed = budget(remaining_ttl_seconds); expires_at = absoluteTime(expires_at);
218
+ invariant(positive(expected_revision), 'execution_grant_operation_invalid');
219
+ const result = mutation(raw, renewal_id, { operation: 'renew', expected_revision, expires_at }, record => {
220
+ if (localError(record) === 'expired') fail('expired');
221
+ requireActive(record);
222
+ invariant(record.expires_at !== null && Date.parse(expires_at) > Date.parse(record.expires_at) && Date.parse(expires_at) > clock(),
223
+ 'execution_grant_renewal_invalid');
224
+ invariant(record.revision === expected_revision, 'execution_grant_revision_conflict');
225
+ const updated = { ...record, expires_at, revision: record.revision + 1, updated_at: now() }; persist(updated); return updated;
226
+ });
227
+ if (result.changed) anchor(result.receipt.grant, observed);
228
+ return result.receipt;
229
+ },
230
+ });
231
+ return { api, commandError, qualify, readySessions, claimError, inspect };
232
+ }
@@ -0,0 +1,53 @@
1
+ import { canonical, copy, invariant, parseNativeJson, scopeKey, validateSessionInjection } from '@kingsoftcloud/agentkit-harness-core';
2
+
3
+ /** A command-store outbox bridges admission to the Native RunStore inbox.
4
+ * Delivery is idempotent, never calls a binding/model port and never wakes a Run.
5
+ */
6
+ export function createManagedNativeInjection({ db, store, guard, transaction, target }) {
7
+ db.exec(`CREATE TABLE IF NOT EXISTS managed_injections (
8
+ command_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, scope TEXT NOT NULL, data TEXT NOT NULL);`);
9
+ const input = command => validateSessionInjection({ injectionId: command.command_id,
10
+ text: command.payload.content, source: { kind: command.source.kind, ref: command.source.ref || command.command_id } });
11
+ const deliver = sessionId => {
12
+ guard();
13
+ const rows = db.prepare(`SELECT i.*,c.state FROM managed_injections i JOIN managed_commands c ON c.command_id=i.command_id
14
+ WHERE c.state='injection_pending' ${sessionId === undefined ? '' : 'AND i.session_id=?'} ORDER BY c.rowid`)
15
+ .all(...(sessionId === undefined ? [] : [sessionId]));
16
+ for (const row of rows) {
17
+ guard();
18
+ try { store.inject(parseNativeJson(row.scope), row.session_id, parseNativeJson(row.data)); }
19
+ catch (error) {
20
+ // A full bounded inbox must not prevent its existing data from being
21
+ // consumed by the next turn. The accepted outbox row remains pending.
22
+ if (error.code === 'session_inbox_full') return;
23
+ throw error;
24
+ }
25
+ transaction(() => db.prepare("UPDATE managed_commands SET state='injected' WHERE command_id=? AND state='injection_pending'").run(row.command_id));
26
+ }
27
+ };
28
+ return {
29
+ input,
30
+ scope(command, supplied) {
31
+ const previous = db.prepare('SELECT scope FROM managed_runs WHERE session_id=? ORDER BY rowid DESC LIMIT 1').get(command.session_id);
32
+ const scope = supplied ?? (previous ? parseNativeJson(previous.scope) : null);
33
+ invariant(scope?.tenantId === target.tenantId && scope.agentId === target.agentInstanceId
34
+ && typeof scope.workspaceId === 'string' && scope.workspaceId.trim()
35
+ && typeof scope.userId === 'string' && scope.userId.trim()
36
+ && (!previous || canonical(scope) === previous.scope), 'NATIVE_MANAGED_INJECTION_BINDING_UNAVAILABLE');
37
+ scopeKey(scope);
38
+ return copy(scope);
39
+ },
40
+ hasCapacity(command) {
41
+ const pending = db.prepare(`SELECT COUNT(*) AS count,COALESCE(SUM(length(CAST(i.data AS BLOB))),0) AS bytes
42
+ FROM managed_injections i JOIN managed_commands c ON c.command_id=i.command_id
43
+ WHERE i.session_id=? AND c.state='injection_pending'`).get(command.session_id);
44
+ return pending.count < 1000 && pending.bytes + Buffer.byteLength(canonical(input(command))) <= 2 * 1024 * 1024;
45
+ },
46
+ admit(command, scope) {
47
+ db.prepare('INSERT INTO managed_injections VALUES (?,?,?,?)')
48
+ .run(command.command_id, command.session_id, canonical(scope), canonical(input(command)));
49
+ db.prepare("UPDATE managed_commands SET state='injection_pending' WHERE command_id=?").run(command.command_id);
50
+ },
51
+ deliver,
52
+ };
53
+ }