@kingsoftcloud/agentkit-harness-node 0.0.20 → 0.0.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -23,6 +23,8 @@ import { ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
23
23
  export const ENGINE_SERVICE_CONTRACT = 'agentkit.engine-service/v1';
24
24
  // Bound the authenticated frame separately from the current-turn media budget.
25
25
  const MAX_BODY_BYTES = 8 * 1024 * 1024;
26
+ const SESSION_IDLE_MS = 10 * 60_000;
27
+ const RPC_TIMEOUT_MS = 40_000;
26
28
  const SESSION_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
27
29
  const hash = value => createHash('sha256').update(value).digest();
28
30
 
@@ -46,6 +48,18 @@ async function readFrame(request) {
46
48
  return frame;
47
49
  }
48
50
 
51
+ export function parseEngineSessionFrame(line) {
52
+ try {
53
+ const frame = JSON.parse(line);
54
+ if (frame?.jsonrpc !== '2.0' || typeof frame.id !== 'string' || !frame.id) return null;
55
+ if (Object.hasOwn(frame, 'method')) {
56
+ return typeof frame.method === 'string' && frame.method.startsWith('host/')
57
+ && Number.isSafeInteger(frame.expiresAt) ? frame : null;
58
+ }
59
+ return Object.hasOwn(frame, 'result') !== Object.hasOwn(frame, 'error') ? frame : null;
60
+ } catch { return null; }
61
+ }
62
+
49
63
  function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
50
64
  const input = new PassThrough(), output = new PassThrough();
51
65
  const frames = createInterface({ input: output, crlfDelay: Infinity });
@@ -55,19 +69,31 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
55
69
  if (request.frame.expiresAt <= now) hostRequests.delete(id);
56
70
  }
57
71
  };
72
+ let lastUsed = Date.now(), busy = false, stopped = false;
73
+ const stop = () => { stopped = true; input.end(); };
58
74
  const done = serveEngine({
59
75
  input, output, env, fetchImpl, log, viewStore, detachOnShutdown: true,
76
+ onActivity: value => { busy = value; lastUsed = Date.now(); },
60
77
  startup: { ...startup, sessionId, stateDir: join(startup.stateDir, hash(sessionId).toString('hex')) },
61
78
  }).finally(() => {
79
+ stopped = true;
80
+ lastUsed = Date.now();
62
81
  for (const resolve of pending.values()) resolve(null);
63
82
  for (const waiter of hostWaiters) waiter(true);
64
83
  pending.clear();
84
+ hostRequests.clear();
65
85
  output.end();
66
86
  });
67
87
  // The server owns the worker lifetime independently of HTTP request lifetime.
68
88
  done.catch(() => log('engine session stopped'));
69
89
  frames.on('line', line => {
70
- const frame = JSON.parse(line);
90
+ if (stopped) return;
91
+ const frame = parseEngineSessionFrame(line);
92
+ if (!frame) {
93
+ stop();
94
+ log('invalid engine session output frame');
95
+ return;
96
+ }
71
97
  if (typeof frame.method === 'string') {
72
98
  pruneHostRequests(Date.now());
73
99
  hostRequests.set(frame.id, { frame, claimed: false });
@@ -93,14 +119,29 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
93
119
  return ready;
94
120
  };
95
121
  return {
122
+ get lastUsed() { return lastUsed; },
123
+ get stopped() { return stopped; },
124
+ isIdle(now) {
125
+ pruneHostRequests(now);
126
+ return !busy && !pending.size && !hostRequests.size && !hostWaiters.size;
127
+ },
96
128
  request(frame) {
97
- if (pending.has(frame.id)) return null;
129
+ if (stopped || pending.has(frame.id)) return null;
130
+ lastUsed = Date.now();
98
131
  return new Promise(resolve => {
99
- pending.set(frame.id, resolve);
132
+ const finish = value => {
133
+ clearTimeout(timer);
134
+ pending.delete(frame.id);
135
+ resolve(value);
136
+ };
137
+ const timer = setTimeout(() => finish(null), RPC_TIMEOUT_MS);
138
+ pending.set(frame.id, finish);
100
139
  input.write(JSON.stringify(frame) + '\n');
101
140
  });
102
141
  },
103
142
  async takeHostRequests(runId, waitMs, response, receiver) {
143
+ if (stopped) return [];
144
+ lastUsed = Date.now();
104
145
  const available = takeHostRequests(runId, receiver);
105
146
  if (available.length || !waitMs || response.destroyed) return available;
106
147
  return new Promise(resolve => {
@@ -122,13 +163,15 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
122
163
  });
123
164
  },
124
165
  reply(frame) {
166
+ if (stopped) return false;
167
+ lastUsed = Date.now();
125
168
  const request = hostRequests.get(frame.id);
126
169
  if (!request?.claimed || !hostRequests.delete(frame.id) || request.frame.expiresAt <= Date.now()) return false;
127
170
  input.write(JSON.stringify(frame) + '\n');
128
171
  return true;
129
172
  },
130
173
  async close() {
131
- input.end();
174
+ stop();
132
175
  await done;
133
176
  },
134
177
  };
@@ -157,6 +200,26 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
157
200
  const managedRuntime = managed && createEngineManagedService({ startup, stateDir, workspace,
158
201
  config: managed, env, fetchImpl, log, serviceToken: token, viewStore, viewRef });
159
202
  let closing = false;
203
+ const retirements = new Map();
204
+ function retire(id, session) {
205
+ if (retirements.has(id)) return retirements.get(id);
206
+ const retirement = session.close().catch(() => {}).finally(() => {
207
+ sessions.delete(id);
208
+ retirements.delete(id);
209
+ });
210
+ retirements.set(id, retirement);
211
+ return retirement;
212
+ }
213
+ function oldestIdle(now) {
214
+ return [...sessions].filter(([id, session]) => !retirements.has(id) && session.isIdle(now))
215
+ .sort(([, a], [, b]) => a.lastUsed - b.lastUsed)[0];
216
+ }
217
+ const cleanup = setInterval(() => {
218
+ const now = Date.now();
219
+ for (const [id, session] of sessions) {
220
+ if (session.isIdle(now) && now - session.lastUsed >= SESSION_IDLE_MS) void retire(id, session);
221
+ }
222
+ }, SESSION_IDLE_MS).unref();
160
223
  const handleRequest = async (request, response) => {
161
224
  if (request.method === 'GET' && request.url === '/healthz') {
162
225
  return respond(response, closing ? 503 : 200, {
@@ -201,7 +264,7 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
201
264
  try {
202
265
  if (request.method === 'GET' && action === 'host-requests') {
203
266
  const session = sessions.get(id);
204
- if (!session) return respond(response, 404, { error: 'session_not_found' });
267
+ if (!session || session.stopped) return respond(response, 404, { error: 'session_not_found' });
205
268
  const search = new URLSearchParams(query);
206
269
  const runId = search.get('runId') ?? undefined;
207
270
  const waitMs = Math.min(Math.max(Number(search.get('waitMs')) || 0, 0), 5000);
@@ -225,11 +288,20 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
225
288
  }
226
289
  if (typeof frame.method !== 'string' || frame.method === 'shutdown')
227
290
  return respond(response, 400, { error: 'invalid_method' });
228
- if (!session) {
291
+ while (!session || session.stopped) {
229
292
  if (frame.method !== 'initialize') return respond(response, 404, { error: 'session_not_found' });
230
- if (sessions.size >= maxSessions) return respond(response, 503, { error: 'session_capacity' });
231
- session = openSession(id, { ...startup, stateDir }, env, fetchImpl, log, viewStore);
232
- sessions.set(id, session);
293
+ if (session) await retire(id, session);
294
+ else if (sessions.size >= maxSessions) {
295
+ const victim = oldestIdle(Date.now());
296
+ if (!victim) return respond(response, 503, { error: 'session_capacity' });
297
+ await retire(...victim);
298
+ } else {
299
+ session = openSession(id, { ...startup, stateDir }, env, fetchImpl, log, viewStore);
300
+ sessions.set(id, session);
301
+ break;
302
+ }
303
+ if (closing) return respond(response, 503, { error: 'service_stopping' });
304
+ session = sessions.get(id);
233
305
  }
234
306
  const result = await session.request(frame);
235
307
  if (closing) return respond(response, 503, { error: 'service_stopping' });
@@ -244,6 +316,7 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
244
316
  server,
245
317
  async close() {
246
318
  closing = true;
319
+ clearInterval(cleanup);
247
320
  const stopped = new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
248
321
  await Promise.allSettled([...sessions.values()].map(session => session.close()).concat(managedRuntime?.close() ?? []));
249
322
  server.closeAllConnections();
@@ -1,6 +1,7 @@
1
1
  import { CONTEXT_CONTRIBUTION_CONTRACT, canonical, invariant } from '@kingsoftcloud/agentkit-harness-core';
2
2
 
3
3
  export const ENGINE_VERIFICATION = 'agentkit.engine-verification/v1';
4
+ export const ENGINE_COMMAND_VERIFIER = 'engine.workspace-command-receipt';
4
5
  const TIMEOUT_MS = 5000;
5
6
  const EVIDENCE_BYTES = 256 * 1024;
6
7
  const ID = /^[a-zA-Z0-9._-]{1,128}$/;
@@ -24,6 +25,7 @@ export function admitEngineVerification(input) {
24
25
 
25
26
  function verificationEvidence(record, definition) {
26
27
  const { configuration, events, intents, receipts } = record;
28
+ const commandVerifier = definition.verifierRef === ENGINE_COMMAND_VERIFIER;
27
29
  const tools = new Set(definition.evidenceTools);
28
30
  const source = configuration.contextSources.find(item => item.sourceId === definition.contextSourceId);
29
31
  const intentByKey = new Map(intents.map(intent => [intent.operationKey, intent]));
@@ -61,14 +63,27 @@ function verificationEvidence(record, definition) {
61
63
  for (let offset = 0; offset < admitted.length && calls.length < 64; offset++) {
62
64
  const call = admitted[offset], result = results[offset];
63
65
  if (!tools.has(call.name) || !result || result.status === 'approval_required') continue;
66
+ // A command-based verifier needs the exact admitted arguments and the
67
+ // observed workspace revision, not model-authored output or a preview.
68
+ const boundCommand = commandVerifier && call.name === 'run_command';
69
+ if (boundCommand && typeof call.arguments.command !== 'string') continue;
64
70
  append(calls, { operationKey: admitted.length > 1 ? `${operationKey}:call:${offset + 1}` : operationKey,
65
- eventId: event.eventId, call, status: result.status, content: result.content ?? null });
71
+ eventId: event.eventId, call: boundCommand ? { name: call.name, arguments: {
72
+ command: call.arguments.command,
73
+ ...(call.arguments.cwd === undefined ? {} : { cwd: call.arguments.cwd }),
74
+ ...(call.arguments.background === undefined ? {} : { background: call.arguments.background }),
75
+ ...(call.arguments.env && Object.keys(call.arguments.env).length ? { hasEnvironmentOverride: true } : {}),
76
+ } } : call, status: result.status,
77
+ content: boundCommand ? { exit_code: result.content?.exit_code ?? null,
78
+ status: result.content?.status ?? null, evidence_incomplete: result.content?.evidence_incomplete ?? true }
79
+ : result.content ?? null,
80
+ ...(boundCommand ? { workspaceChangeObservation: result.workspaceChangeObservation ?? null } : {}) });
66
81
  }
67
82
  }
68
83
  return { calls, context };
69
84
  }
70
85
 
71
- export function engineVerificationPort(store, callHostVerification, digest) {
86
+ export function engineVerificationPort(store, callHostVerification, digest, captureWorkspaceRevision) {
72
87
  return {
73
88
  available: configuration => !!configuration.hostVerification,
74
89
  async verify(request) {
@@ -78,14 +93,22 @@ export function engineVerificationPort(store, callHostVerification, digest) {
78
93
  const candidate = request.candidate;
79
94
  invariant(definition && item?.verifierRef === definition.verifierRef
80
95
  && item.verifierVersion === definition.verifierVersion && candidate.binding, 'engine_verification_unbound');
96
+ const commandVerifier = definition.verifierRef === ENGINE_COMMAND_VERIFIER;
97
+ let workspaceRevision = null;
98
+ if (commandVerifier) {
99
+ try { workspaceRevision = captureWorkspaceRevision(request); }
100
+ catch { request.signal.throwIfAborted(); }
101
+ }
81
102
  const input = { contract: ENGINE_VERIFICATION, runId: request.runId,
82
103
  operationKey: request.operationKey, definition, candidateId: candidate.candidateId,
83
104
  contractRevision: request.contract.revision, candidateBinding: candidate.binding,
84
105
  goal: request.snapshot.goal, goalRevision: request.snapshot.goalRevision,
85
- evidence: verificationEvidence(record, definition) };
106
+ evidence: verificationEvidence(record, definition),
107
+ ...(commandVerifier ? { workspaceRevision } : {}) };
86
108
  const inputDigest = digest(input);
87
109
  const base = { candidateId: candidate.candidateId, contractRevision: request.contract.revision,
88
- binding: candidate.binding, workspaceRevision: candidate.workspaceRevision, workspaceDependency: 'none' };
110
+ binding: candidate.binding, workspaceRevision: candidate.workspaceRevision,
111
+ workspaceDependency: commandVerifier ? 'required' : 'none' };
89
112
  const unavailable = { status: 'blocked', reason: 'host_verification_unavailable',
90
113
  safeSummary: 'The bound host could not verify the requested result.', evidenceRefs: [] };
91
114
  let result = unavailable;
@@ -97,7 +120,10 @@ export function engineVerificationPort(store, callHostVerification, digest) {
97
120
  && typeof reply.safeSummary === 'string' && reply.safeSummary.length <= 2048
98
121
  && Array.isArray(reply.evidenceRefs) && reply.evidenceRefs.length <= 16
99
122
  && reply.evidenceRefs.every(ref => typeof ref === 'string' && ref.trim() && ref.length <= 256)
100
- && (reply.status === 'blocked' || reply.evidenceRefs.length > 0)) result = reply;
123
+ && (reply.status === 'blocked' || reply.evidenceRefs.length > 0)) {
124
+ if (!commandVerifier || reply.status === 'blocked'
125
+ || workspaceRevision && workspaceRevision === captureWorkspaceRevision(request)) result = reply;
126
+ }
101
127
  } catch {
102
128
  request.signal.throwIfAborted();
103
129
  }
@@ -46,13 +46,13 @@ function inside(path) {
46
46
  function gatewayPolicy(args) {
47
47
  for (let i = 0; i + 1 < args.length; i++) if (args[i] === 'rm'
48
48
  && args.slice(i + 1, i + 3).some(flag => flag.startsWith('-') && /[rR]/.test(flag)))
49
- return finding('command_rejected', 'recursive rm is not allowed without explicit approval');
49
+ return finding('command_rejected', 'recursive removal is blocked by the command policy');
50
50
  if (args.some(arg => ['sudo', 'kubectl', 'docker'].includes(arg)))
51
51
  return finding('command_rejected', `${args[0]} command is not allowed by default policy`);
52
52
  if (args[0] === 'git' && args.length > 1) {
53
53
  if (['status', 'diff', 'log', 'show', 'branch', 'ls-files'].includes(args[1])) return null;
54
54
  if (['reset', 'clean', 'push', 'checkout'].includes(args[1]))
55
- return finding('command_rejected', `git ${args[1]} is not allowed without explicit approval`);
55
+ return finding('command_rejected', `git ${args[1]} is blocked by the command policy`);
56
56
  }
57
57
  if (args.join(' ').includes('169.254.169.254') || args.join(' ').includes('metadata.google.internal'))
58
58
  return finding('command_rejected', 'metadata/private endpoint access is not allowed by default policy');
@@ -58,7 +58,8 @@ 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, shellPolicy = LOCAL_COMMAND_SHELL } = {}) {
61
+ durableForeground = false, outputPolicy = null, environmentPolicy = null, shellPolicy = LOCAL_COMMAND_SHELL,
62
+ classifyApproval = false } = {}) {
62
63
  invariant(typeof authorize === 'function' && typeof resolveOwnedCommand === 'function'
63
64
  && typeof captureWorkspace === 'function' && typeof assertAuthority === 'function'
64
65
  && typeof durableForeground === 'boolean', 'local_command_host_capabilities_missing');
@@ -161,7 +162,23 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
161
162
  const rejection = toolInputRejection(definition, request.call);
162
163
  if (rejection) return { status: 'error', content: rejection };
163
164
  const args = structuredClone(request.call.arguments);
164
- const decision = await authorize(request); guard();
165
+ let command, cwd, readOnlyCommand = false;
166
+ if (request.call.name === 'run_command') {
167
+ command = args.command.trim();
168
+ if (!command) return errorResult('command_required');
169
+ if (!args.background && args.background_timeout != null) return errorResult('background_timeout_requires_background');
170
+ cwd = cwdFor(args.cwd || args.env?.KSADK_COMMAND_CWD);
171
+ const finding = await checkGovernedCommand(command, { cwd, allowedRoots: [root], signal: request.signal });
172
+ guard();
173
+ if (finding) return errorResult('command_policy_blocked', { finding, exit_code: 126, executed: false, retryable: false });
174
+ if (request.planMode !== undefined && !await checkPlanMode(request))
175
+ return { status: 'error', content: { code: 'plan_mode_write_denied', executed: false } };
176
+ if (classifyApproval && request.definition.approvalPolicy && !request.definition.hostApprovalRequired
177
+ && !request.interaction && !args.background && !args.env)
178
+ readOnlyCommand = await checkPlanCommand(command, { cwd, workspaceRoot: root, signal: request.signal });
179
+ }
180
+ guard();
181
+ const decision = await authorize(request, { readOnlyCommand }); guard();
165
182
  if (decision !== 'allow') return decision?.status === 'approval_required' && typeof decision.interactionId === 'string'
166
183
  ? decision : errorResult('policy_denied');
167
184
  if (request.call.name === 'sandbox_status') return { status: 'ok', content: { ok: true, backend: 'local_process', enabled: true,
@@ -191,16 +208,6 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
191
208
  }
192
209
  guard(); const result = await budget(known, request); guard(); return result;
193
210
  }
194
- const command = args.command.trim();
195
- if (!command) return errorResult('command_required');
196
- if (!args.background && args.background_timeout != null) return errorResult('background_timeout_requires_background');
197
- const cwd = cwdFor(args.cwd || args.env?.KSADK_COMMAND_CWD);
198
- const finding = await checkGovernedCommand(command, { cwd, allowedRoots: [root], signal: request.signal });
199
- guard();
200
- if (finding) return errorResult('command_policy_blocked', { finding, exit_code: 126, executed: false });
201
- if (request.planMode !== undefined && !await checkPlanMode(request))
202
- return { status: 'error', content: { code: 'plan_mode_write_denied', executed: false } };
203
- guard();
204
211
  request.signal.throwIfAborted(); checkRoot(); cwdFor(args.cwd || args.env?.KSADK_COMMAND_CWD);
205
212
  const env = buildScriptEnvironment({ ...environment, ...args.env }, { settings: policy, environmentPolicy: envPolicy });
206
213
  const observedChanges = request.definition?.workspaceChangePolicy === 'observed-command/v1';
@@ -12,6 +12,8 @@ const normalizeModel = value => String(value ?? '').toLowerCase().replaceAll('_'
12
12
  const pythonLeftSpace = /^[\u0009-\u000d\u001c-\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]*/u;
13
13
  const startsThinking = text => text.replace(pythonLeftSpace, '').startsWith('<think>');
14
14
 
15
+ export const isProviderCompatibilityRule = value => rules.has(value);
16
+
15
17
  export function admitInlineReasoningPolicy(override, { contract = 'profiled-content/v2' } = {}) {
16
18
  if (!['profiled-content/v1', 'profiled-content/v2'].includes(contract)) throw new Error('invalid_inline_reasoning_policy');
17
19
  const rule = typeof override === 'string' ? override.trim() : '';