@kingsoftcloud/agentkit-harness-node 0.0.30 → 0.0.32

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kingsoftcloud/agentkit-harness-node",
3
- "version": "0.0.30",
3
+ "version": "0.0.32",
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.",
@@ -91,6 +91,7 @@
91
91
  "./native/model-request": "./src/native/model-request.mjs",
92
92
  "./native/model-responses": "./src/native/model-responses.mjs",
93
93
  "./native/model-sse": "./src/native/model-sse.mjs",
94
+ "./native/model-tool-view": "./src/native/model-tool-view.mjs",
94
95
  "./native/model-tool-search-policy": "./src/native/model-tool-search-policy.mjs",
95
96
  "./native/owned-child": "./src/native/owned-child.mjs",
96
97
  "./native/owned-command": "./src/native/owned-command.mjs",
@@ -154,7 +155,7 @@
154
155
  "src/package-integrity.mjs"
155
156
  ],
156
157
  "dependencies": {
157
- "@kingsoftcloud/agentkit-harness-core": "0.0.30",
158
+ "@kingsoftcloud/agentkit-harness-core": "0.0.32",
158
159
  "@astral-sh/ruff-wasm-nodejs": "0.16.8",
159
160
  "parse5": "7.3.0",
160
161
  "playwright-core": "1.58.2",
@@ -4,6 +4,7 @@
4
4
  import { BACKGROUND_COMMAND_CONTRACT, backgroundCommandObservation, backgroundCommandRef,
5
5
  commandProbe, canonical, copy, NativeError, BACKGROUND_NOTIFICATION_ADMISSION } from '@kingsoftcloud/agentkit-harness-core';
6
6
  import { ownedCommandReceipt } from './owned-command.mjs';
7
+ import { confirmedCommandStartFailure } from './local-command-state.mjs';
7
8
 
8
9
  const backends = new Set(['local_process', 'e2b']);
9
10
  const check = (value, code) => { if (!value) throw new NativeError(code); };
@@ -67,10 +68,10 @@ export function createBackgroundCommandPort({ scope, store, readers = {} }) {
67
68
  check(new Set(request.refs.map(ref => ref.taskId)).size === request.refs.length, 'background_command_owner_mismatch');
68
69
  // Verify the entire request before touching any external handle.
69
70
  const owned = request.refs.map(candidate => {
70
- return ownedCommandReceipt({ scope: pinnedScope, store, current, ref: backgroundCommandRef(candidate) });
71
+ return ownedCommandReceipt({ scope: pinnedScope, store, current, ref: backgroundCommandRef(candidate), verifyStartFailure: true });
71
72
  });
72
73
  const observations = [];
73
- for (const { ref, backend } of owned) {
74
+ for (const { ref, backend, requiresStartFailureProof } of owned) {
74
75
  signal.throwIfAborted();
75
76
  const unavailable = () => backgroundCommandObservation({ ref, status: 'unavailable' });
76
77
  if (!backend || !bindings[backend]) observations.push(unavailable());
@@ -81,6 +82,9 @@ export function createBackgroundCommandPort({ scope, store, readers = {} }) {
81
82
  signal.throwIfAborted();
82
83
  check(output && typeof output === 'object' && !Array.isArray(output), 'invalid_background_command_output');
83
84
  check(output.outputMayBeTruncated === undefined || typeof output.outputMayBeTruncated === 'boolean', 'invalid_background_command_output');
85
+ // An old uncertain launch receipt grants only this read. The
86
+ // backend owner's terminal pre-launch record is the evidence.
87
+ check(!requiresStartFailureProof || confirmedCommandStartFailure(output), 'command_start_failure_unconfirmed');
84
88
  if (['starting', 'running'].includes(output.status)) continue;
85
89
  observations.push(backgroundCommandObservation({ ...output, ref,
86
90
  outputMayBeTruncated: output.outputMayBeTruncated === true || output.stdoutCursor >= 8192 || output.stderrCursor >= 8192,
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { setImmediate } from 'node:timers/promises';
2
3
  import { canonical, invariant } from '@kingsoftcloud/agentkit-harness-core';
3
4
  import { buildNativeModelRequest } from './model-request.mjs';
4
5
 
@@ -124,6 +125,10 @@ export function createNativeContextPort({ protocol, model, parameters = {} } = {
124
125
  request.signal.throwIfAborted(); return count;
125
126
  },
126
127
  async countRequest(request) {
128
+ request.signal.throwIfAborted();
129
+ // Planning may count several large projections in one effect. Give the
130
+ // runtime's lease and cancellation timers a turn between projections.
131
+ await setImmediate();
127
132
  request.signal.throwIfAborted();
128
133
  const built = buildNativeModelRequest(binding, { ...request, finalizationOnly: false });
129
134
  const count = estimateNativeWireInput(JSON.parse(built.body), binding.protocol);
@@ -13,13 +13,14 @@ export function nativeContextDefaults(configuration) {
13
13
  pruningSummaryDefaults: !configuration || policy?.pruneSummaryPolicy === 'zcode-local/v1',
14
14
  pruningIdleDefaults: !configuration || policy?.pruneIdleThresholdMinutes !== undefined,
15
15
  preModelBudgetDefaults: !configuration || policy?.budgetTiming === 'before-model/v1',
16
- orderedContextDefaults: !configuration || policy?.continuityPlacement === 'after-history/v1',
16
+ orderedContextDefaults: !configuration || ['after-history/v1', 'split-after-history/v1'].includes(policy?.continuityPlacement),
17
+ splitContinuityDefaults: !configuration || policy?.continuityPlacement === 'split-after-history/v1',
17
18
  sourceReuseDefaults: !configuration || policy?.sourceReusePolicy === 'captured-source/v1',
18
19
  };
19
20
  }
20
21
 
21
22
  /** Bind budget, counter and policy from the resolved Agent revision/Frozen Build. */
22
- export function bindNativeContext({ description, context = {}, maxTokens, adaptiveSummaryDefaults = false, structuredContinuityDefaults = false, preModelBudgetDefaults = false, orderedContextDefaults = false, sourceReuseDefaults = false, readWorkingSetDefaults = false, recentToolBatchDefaults = false, pruningThresholdDefaults = false, pruningSummaryDefaults = false, pruningIdleDefaults = false } = {}) {
23
+ export function bindNativeContext({ description, context = {}, maxTokens, adaptiveSummaryDefaults = false, structuredContinuityDefaults = false, preModelBudgetDefaults = false, orderedContextDefaults = false, splitContinuityDefaults = false, sourceReuseDefaults = false, readWorkingSetDefaults = false, recentToolBatchDefaults = false, pruningThresholdDefaults = false, pruningSummaryDefaults = false, pruningIdleDefaults = false } = {}) {
23
24
  invariant(context && typeof context === 'object' && !Array.isArray(context), 'studio_native_context_invalid');
24
25
  const raw = context.compaction ?? {};
25
26
  invariant(raw && typeof raw === 'object' && !Array.isArray(raw), 'studio_native_compaction_invalid');
@@ -44,7 +45,8 @@ export function bindNativeContext({ description, context = {}, maxTokens, adapti
44
45
  summaryOutputCeiling: Math.min(raw.summaryMaxTokens ?? output, output) } : {}),
45
46
  ...(structuredContinuityDefaults ? { summaryFormatPolicy: 'task-continuity/v1' } : {}),
46
47
  ...(preModelBudgetDefaults ? { budgetTiming: 'before-model/v1' } : {}),
47
- ...(orderedContextDefaults && description.protocol === 'openai-chat' ? { continuityPlacement: 'after-history/v1' } : {}),
48
+ ...(orderedContextDefaults && description.protocol === 'openai-chat'
49
+ ? { continuityPlacement: splitContinuityDefaults ? 'split-after-history/v1' : 'after-history/v1' } : {}),
48
50
  ...(sourceReuseDefaults && description.protocol === 'openai-chat' ? { sourceReusePolicy: 'captured-source/v1' } : {}),
49
51
  enabled: raw.enabled ?? true, triggerRatio, targetRatio: raw.targetRatio ?? Math.min(.45, triggerRatio * .45 / .72),
50
52
  summaryMaxTokens: raw.summaryMaxTokens ?? Math.min(8192, output, Math.max(2048, Math.floor(contextWindow / 8))),
@@ -33,7 +33,7 @@
33
33
  // URL the detached child imports (transportModule).
34
34
  import { closeSync, constants, existsSync, fsyncSync, writeSync } from 'node:fs';
35
35
  import { join } from 'node:path';
36
- import { TERMINAL, check, openPrivate, atomicPrivate, readE2BRecord, tryLock, unknownRecord, writeRecord } from './e2b-command-state.mjs';
36
+ import { TERMINAL, check, openPrivate, atomicPrivate, readE2BRecord, lockUntil, unknownRecord, writeRecord } from './e2b-command-state.mjs';
37
37
 
38
38
  const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
39
39
  const validSandboxId = value => typeof value === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(value);
@@ -119,8 +119,13 @@ function fencedWrite(directory, owner, commandId, generation, patch) {
119
119
 
120
120
  export async function supervise(config, transport) {
121
121
  const directory = config.directory, generation = config.generation ?? 0;
122
- const release = tryLock(join(directory, 'supervisor.sqlite'));
123
- if (!release) return; // a live supervisor holds the lock
122
+ // Receipt readers briefly acquire this lock to check liveness. Give that
123
+ // probe time to release it before deciding another supervisor owns the task.
124
+ const release = await lockUntil(join(directory, 'supervisor.sqlite'), performance.now() + 5000).catch(error => {
125
+ if (error.code === 'background_command_lock_timeout') return null;
126
+ throw error;
127
+ });
128
+ if (!release) return;
124
129
  let settled = false, stream = null;
125
130
  // safeDisconnect is declared BEFORE the try block so the finally block can access it.
126
131
  // It references `stream` (set inside the try) via closure — the let is in scope.
@@ -324,15 +324,26 @@ export class E2BCommandStore {
324
324
  }));
325
325
  return;
326
326
  }
327
+ const recordSpawnFailure = () => {
328
+ // Reconnect never grants proof that the original remote command did not
329
+ // run. Fence the start verdict under the same lock as remote dispatch.
330
+ if (mode !== 'start') return;
331
+ const release = tryLock(join(handle.directory, 'supervisor.sqlite'));
332
+ if (!release) return;
333
+ try {
334
+ const record = handle._record();
335
+ if (record.status === 'starting' && record.generation === generation
336
+ && record.supervisorPid === undefined && record.pid === undefined)
337
+ unknownRecord(handle.directory, record, 'supervisor_launch_failed');
338
+ } finally { release(); }
339
+ };
327
340
  let child;
328
341
  try {
329
342
  child = spawn(process.execPath, ['--input-type=module', '-e',
330
343
  `import(${JSON.stringify(supervisor)}).then(m => m.runSupervisor()).catch(() => process.exit(1))`],
331
344
  { detached: true, stdio: ['pipe', 'ignore', 'ignore'], env: { ...process.env, NODE_NO_WARNINGS: '1' } });
332
- } catch { unknownRecord(handle.directory, handle._record(), 'supervisor_launch_failed'); return; }
333
- child.once('error', () => { const probe = tryLock(join(handle.directory, 'supervisor.sqlite'));
334
- try { if (probe) { probe(); const current = handle._record(); if (current.status === 'starting') unknownRecord(handle.directory, current, 'supervisor_launch_failed'); } }
335
- catch {} finally { /* probe already released if acquired */ } });
345
+ } catch { recordSpawnFailure(); return; }
346
+ child.once('error', () => { try { recordSpawnFailure(); } catch {} });
336
347
  child.stdin.on('error', () => {});
337
348
  child.stdin.end(JSON.stringify(config)); child.unref();
338
349
  }
@@ -36,5 +36,13 @@ export function readE2BRecord(directory, owner, commandId) {
36
36
  && (record.evidenceIncomplete === undefined || typeof record.evidenceIncomplete === 'boolean')
37
37
  && (record.observedExitCode === undefined || record.observedExitCode === null || Number.isSafeInteger(record.observedExitCode)),
38
38
  'invalid_background_record');
39
+ // Keep the v1 on-disk verdict for older readers. Only a failed local
40
+ // supervisor spawn with no remote dispatch identity proves non-execution.
41
+ if (record.status === 'unknown' && record.outcomeReason === 'supervisor_launch_failed'
42
+ && record.supervisorPid === undefined && record.pid === undefined
43
+ && record.exitCode === null && record.observedExitCode == null
44
+ && record.generation === 0 && record.recoveryClaimGeneration === undefined) {
45
+ return { ...record, status: 'failed', evidenceIncomplete: false };
46
+ }
39
47
  return record;
40
48
  }
@@ -15,6 +15,7 @@ import { publicToolExecution } from './public-tool-result.mjs';
15
15
  // truncated or dropped to fit a budget.
16
16
  import { canonical, copy, invariant, scopeKey, toolInputRejection } from '@kingsoftcloud/agentkit-harness-core';
17
17
  import { TERMINAL, delay } from './e2b-command-state.mjs';
18
+ import { confirmedCommandStartFailure } from './local-command-state.mjs';
18
19
  import { createHash } from 'node:crypto';
19
20
 
20
21
  export const E2B_COMMAND_TOOLS_CONTRACT = 'agentkit.native-e2b-command-tools/v1';
@@ -431,6 +432,8 @@ function createCommandTools({ sessionId, owner, storeFactory,
431
432
 
432
433
  if (args.background) {
433
434
  const observed = syncValue(handle.readOutput());
435
+ if (confirmedCommandStartFailure(observed))
436
+ return boundResult(errorResult('command_not_started', { executed: false, outcome_reason: observed.outcomeReason }));
434
437
  const uncertain = observed.status === 'unknown' || observed.evidenceIncomplete;
435
438
  known = { status: uncertain ? 'uncertain' : 'ok',
436
439
  content: { ok: !uncertain, backend: 'sandbox/e2b', sandbox_id: sandboxId,
@@ -447,6 +450,8 @@ function createCommandTools({ sessionId, owner, storeFactory,
447
450
  }
448
451
  const guardResult3 = guard(request, before, dispatched, known);
449
452
  if (guardResult3) return guardResult3;
453
+ if (confirmedCommandStartFailure(output))
454
+ return boundResult(errorResult('command_not_started', { executed: false, outcome_reason: output.outcomeReason }));
450
455
  // The model sees a bounded preview, but its artifact must contain all
451
456
  // retained foreground output while it fits the attachment budget.
452
457
  // Larger output stays available in the existing command spool.
@@ -8,11 +8,18 @@ import { spawn } from 'node:child_process';
8
8
  import * as readline from 'node:readline';
9
9
 
10
10
  export const ENGINE_PROTOCOL = 'agentkit.engine/v1';
11
+ const ENGINE_CONTEXT = 'agentkit.engine-context/v1';
12
+ const ENGINE_HOOKS = 'agentkit.engine-hooks/v1';
13
+ const ENGINE_VERIFICATION = 'agentkit.engine-verification/v1';
11
14
 
12
15
  /** 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' }) {
16
+ export function connectEngine({ input, output, onApproveTool, onCallTool, onReadContext, onInvokeHook, onVerifyGoal, runSignal, hostName = 'host' }) {
14
17
  let next = 1, closed = false;
15
18
  const pending = new Map();
19
+ const lifetime = new AbortController();
20
+ const callbackSignal = runSignal ? AbortSignal.any([runSignal, lifetime.signal]) : lifetime.signal;
21
+ const scopedCallbacks = new Map([['host/readContext', onReadContext], ['host/invokeHook', onInvokeHook],
22
+ ['host/verifyGoal', onVerifyGoal]]);
16
23
  const send = frame => output.write(`${JSON.stringify(frame)}\n`);
17
24
  const frames = readline.createInterface({ input, crlfDelay: Infinity });
18
25
  const finished = (async () => {
@@ -30,6 +37,16 @@ export function connectEngine({ input, output, onApproveTool, onCallTool, hostNa
30
37
  Promise.resolve().then(() => onCallTool(frame.params ?? {}))
31
38
  .then(reply => send({ jsonrpc: '2.0', id: frame.id, result: { status: reply?.status === 'error' ? 'error' : 'ok', content: reply?.content ?? null } }),
32
39
  error => send({ jsonrpc: '2.0', id: frame.id, result: { status: 'error', content: { code: 'host_tool_failed', message: String(error?.message ?? error).slice(0, 2000) } } }));
40
+ } else if (typeof scopedCallbacks.get(frame.method) === 'function' && frame.id !== undefined) {
41
+ const remainingMs = frame.expiresAt - Date.now();
42
+ if (!Number.isSafeInteger(remainingMs) || remainingMs <= 0 || remainingMs > 66000 || callbackSignal.aborted) continue;
43
+ const signal = AbortSignal.any([callbackSignal, AbortSignal.timeout(remainingMs)]);
44
+ const callback = scopedCallbacks.get(frame.method);
45
+ Promise.resolve().then(() => callback(frame.params, signal)).then(result => {
46
+ if (!signal.aborted) send({ jsonrpc: '2.0', id: frame.id, result });
47
+ }).catch(() => {
48
+ if (!signal.aborted) send({ jsonrpc: '2.0', id: frame.id, error: { code: -32603, message: 'Host callback unavailable' } });
49
+ });
33
50
  } else if (frame.id !== undefined) send({ jsonrpc: '2.0', id: frame.id, error: { code: -32601, message: 'Method not found' } });
34
51
  continue;
35
52
  }
@@ -40,6 +57,7 @@ export function connectEngine({ input, output, onApproveTool, onCallTool, hostNa
40
57
  else waiter.resolve(frame.result);
41
58
  }
42
59
  closed = true;
60
+ lifetime.abort();
43
61
  for (const waiter of pending.values()) waiter.reject(new Error('engine connection closed'));
44
62
  pending.clear();
45
63
  })();
@@ -52,7 +70,10 @@ export function connectEngine({ input, output, onApproveTool, onCallTool, hostNa
52
70
  return {
53
71
  call, finished,
54
72
  initialize: () => call('initialize', { protocolVersions: [ENGINE_PROTOCOL], host: { name: hostName },
55
- services: { approvals: typeof onApproveTool === 'function', tools: typeof onCallTool === 'function' } }),
73
+ services: { approvals: typeof onApproveTool === 'function', tools: typeof onCallTool === 'function',
74
+ ...(onReadContext ? { context: ENGINE_CONTEXT } : {}),
75
+ ...(onInvokeHook ? { hooks: ENGINE_HOOKS } : {}),
76
+ ...(onVerifyGoal ? { verification: ENGINE_VERIFICATION } : {}) } }),
56
77
  startRun: params => call('run/start', params),
57
78
  status: runId => call('run/status', { runId }),
58
79
  events: (runId, cursor = 0, waitMs = 0, thinkingCursor, toolDraftCursor, textCursor) =>
@@ -75,10 +96,11 @@ export function connectEngine({ input, output, onApproveTool, onCallTool, hostNa
75
96
  }
76
97
 
77
98
  /** Start an engine executable and connect to it. `command` is host configuration, not host code. */
78
- export function spawnEngine({ command, args = [], env, onApproveTool, onCallTool, hostName, onLog = () => {} }) {
99
+ export function spawnEngine({ command, args = [], env, onApproveTool, onCallTool, onReadContext, onInvokeHook, onVerifyGoal, runSignal, hostName, onLog = () => {} }) {
79
100
  const child = spawn(command, args, { env, stdio: ['pipe', 'pipe', 'pipe'] });
80
101
  child.stderr.setEncoding('utf8').on('data', chunk => onLog(chunk));
81
- const client = connectEngine({ input: child.stdout, output: child.stdin, onApproveTool, onCallTool, hostName });
102
+ const client = connectEngine({ input: child.stdout, output: child.stdin,
103
+ onApproveTool, onCallTool, onReadContext, onInvokeHook, onVerifyGoal, runSignal, hostName });
82
104
  const exited = new Promise(resolve => {
83
105
  child.once('exit', code => resolve({ code }));
84
106
  child.once('error', error => resolve({ error }));
@@ -229,7 +229,7 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
229
229
  };
230
230
  const artifacts = await createNativeArtifactStore({ directory: join(stateDir, 'artifacts'), scope });
231
231
  const execution = nativeLocalExecutionMethods({ enabled: true, settings: {}, sourceEnv, workspaceRoot: root, commandBackend: 'local_process' });
232
- const executionOptions = { modern: true, resourceProfile: 'local-development/v2' };
232
+ const executionOptions = { modern: true, resourceProfile: 'local-development/v3' };
233
233
  const local = execution.localExecution(executionOptions);
234
234
  const workspace = createNativeWorkspaceTools({ workspaceRoot: root, stateDir: join(stateDir, 'workspace'), sessionId, authorize: decide });
235
235
  const deliveries = createEngineDeliveryJournal(join(stateDir, 'delivery'), () => workspace.captureDelivery());
@@ -326,10 +326,12 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
326
326
  const providerRule = engineProviderCompatibilityRule(description);
327
327
  const profile = { profileId: 'engine', profileVersion: digest(description), providerFamily: description.protocol,
328
328
  compatibilityDigest: digest(description), supportsImages, discoveredToolExposure: 'direct-after-search/v1', streamTimeoutPolicy: 'idle/v1',
329
- ...(chatUsage ? { chatUsagePolicy: chatUsage } : {}), maxRetries: 2, maxProviderRetries: 10, ...context.profile,
329
+ ...(chatUsage ? { chatUsagePolicy: chatUsage } : {}), maxRetries: 2, maxProviderRetries: 3, ...context.profile,
330
330
  maxOutputTokens: description.maxOutputTokens, contextWindow: description.contextWindow,
331
331
  requestTimeoutMs: description.requestTimeoutMs, providerReplayMode: 'reasoning_content',
332
- providerCompatibilityPolicy: admitProviderCompatibilityPolicy(providerRule) };
332
+ providerCompatibilityPolicy: admitProviderCompatibilityPolicy(providerRule, {
333
+ protocol: description.protocol, model: description.modelName, baseUrl: description.baseUrl,
334
+ }) };
333
335
  const modelSurface = bindNativeModelSurface({ environment: execution.executionEnvironment(executionOptions), description });
334
336
  const modelPort = createNativeModelPort({ fetchImpl, resolveProfile: async () => ({ protocol: description.protocol, baseUrl: description.baseUrl,
335
337
  apiKey: await model.apiKey(), model: description.modelName, parameters: description.parameters }) });
@@ -465,7 +467,8 @@ export async function createEngineRuntime({ workspaceRoot, stateDir, sessionId,
465
467
  limits: { ...preset.limits, ...limits,
466
468
  effectTimeoutMs: Math.max(120000, description.requestTimeoutMs + 10000, hooks.timeoutMs + 1000,
467
469
  ...runtimeTools.map(tool => (tool.timeoutMs ?? 0) + 10000)) },
468
- modelRecoveryPolicy: nativeModelRecoveryPolicy(description), contextPolicy: context.policy, modelSurface,
470
+ modelRecoveryPolicy: nativeModelRecoveryPolicy(description), modelSurface,
471
+ contextPolicy: { ...context.policy, continuityProjection: 'decision-input/v1', commandOutputProjection: 'receipt-preview/v1' },
469
472
  backgroundNotificationPolicy: 'completed-before-model/v1', todoPolicy: 'session-todos/v1',
470
473
  ...(durableApprovals && children ? { childLifecyclePolicy: 'owned-background/v2', childApprovalPolicy: 'owned-child-approval/v1' } : {}),
471
474
  ...(searchable ? { toolDiscoveryPolicy: 'local-tool-search/v1' } : {}), instructions });
@@ -371,9 +371,16 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
371
371
  || record.configuration.contextSources.some(source => source.hostProjection)
372
372
  || record.configuration.tools.some(tool => tool.hostEffectProtocol === ENGINE_HOST_EFFECT);
373
373
  const continueOnSubscription = (runId, record) => {
374
- if (hasScopedCallbacks(record)) driven.delete(runId);
374
+ if (detachOnShutdown && hasScopedCallbacks(record)) driven.delete(runId);
375
375
  else drive(runId);
376
376
  };
377
+ function requireLocalCallbacks(record) {
378
+ if (detachOnShutdown) return;
379
+ if (record.configuration.hooks.length > 0 && !host.services.hooks
380
+ || record.configuration.contextSources.some(source => source.hostProjection) && !host.services.context
381
+ || record.configuration.hostVerification && !host.services.verification)
382
+ throw rpcError(ERRORS.params, 'the Run requires its original host services');
383
+ }
377
384
 
378
385
  const handlers = {
379
386
  async initialize(params) {
@@ -383,9 +390,9 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
383
390
  // callbacks and approval authority of a concurrent execution owner.
384
391
  if (params.host?.observeOnly !== true || !host) host = { name: text(params.host?.name) ? params.host.name : 'unknown',
385
392
  services: { approvals: params.services?.approvals === true, tools: params.services?.tools === true,
386
- context: detachOnShutdown && params.services?.context === ENGINE_CONTEXT,
387
- hooks: detachOnShutdown && params.services?.hooks === ENGINE_HOOKS,
388
- verification: detachOnShutdown && params.services?.verification === ENGINE_VERIFICATION,
393
+ context: params.services?.context === ENGINE_CONTEXT,
394
+ hooks: params.services?.hooks === ENGINE_HOOKS,
395
+ verification: params.services?.verification === ENGINE_VERIFICATION,
389
396
  toolEffects: detachOnShutdown && params.services?.toolEffects === ENGINE_HOST_EFFECT,
390
397
  toolReceipts: detachOnShutdown && params.services?.toolEffects === ENGINE_HOST_EFFECT
391
398
  && params.services?.toolReceipts === TOOL_RECEIPT_OBSERVATION_CONTRACT,
@@ -429,7 +436,10 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
429
436
  const runId = text(params.runId) ? params.runId : `run-${createHash('sha256').update(randomUUID()).digest('hex').slice(0, 24)}`;
430
437
  const existing = lookup(runId);
431
438
  if (existing) {
432
- if (!hasScopedCallbacks(existing)) drive(runId);
439
+ if (!runtime.terminal(existing.snapshot)) {
440
+ requireLocalCallbacks(existing);
441
+ if (!detachOnShutdown || !hasScopedCallbacks(existing)) drive(runId);
442
+ }
433
443
  return { ...status(runId), existing: true };
434
444
  }
435
445
  viewStore?.pin(startup.stateDir, runId, viewRef);
@@ -438,8 +448,10 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
438
448
  hostVerification: params.hostVerification,
439
449
  executionPolicy: params.executionPolicy,
440
450
  ...(params.preset === undefined ? {} : { preset: params.preset }), maxModelCalls: params.maxModelCalls ?? null });
441
- // A subscribed host is required to service budgeted context and Hook callbacks.
442
- if (!params.hostContext?.sources?.length && !params.hostHooks?.hooks?.length && !hostEffects && !params.hostVerification) drive(runId);
451
+ // HTTP needs a subscriber to serve run-scoped callbacks. The owned stdio
452
+ // pipe already has the necessary callback handlers on the other end.
453
+ if (!detachOnShutdown || !params.hostContext?.sources?.length && !params.hostHooks?.hooks?.length && !hostEffects && !params.hostVerification)
454
+ drive(runId);
443
455
  return { ...status(runId), preset: started.preset, hostTools: started.hostTools, existing: false };
444
456
  },
445
457
  async 'run/status'(params) {
@@ -524,6 +536,7 @@ export async function serveEngine({ input, output, log = () => {}, startup, env
524
536
  const record = requireRun(params);
525
537
  if (active.has(params.runId)) throw rpcError(ERRORS.runBusy, 'run is already running');
526
538
  const before = status(params.runId);
539
+ if (!before.terminal) requireLocalCallbacks(record);
527
540
  if (before.phase === 'paused') runtime.submit(params.runId, { commandId: `resume-${randomUUID()}`, kind: 'resume', payload: {} });
528
541
  if (!before.terminal) continueOnSubscription(params.runId, record);
529
542
  return status(params.runId);
@@ -6,7 +6,7 @@ import { commandRequest } from './local-background.mjs';
6
6
  import { runBoundedProcess } from './local-process.mjs';
7
7
  import { commandFailureEvidence, commandExceptionCause } from './local-command-evidence.mjs';
8
8
  import { shellCommandArgv } from './command-shell.mjs';
9
- import { START_GRACE_MS, TERMINAL, atomicPrivate, check, digest, fsyncPrivate, lockUntil, openPrivate,
9
+ import { START_GRACE_MS, TERMINAL, atomicPrivate, check, digest, failCommandStart, fsyncPrivate, lockUntil, openPrivate,
10
10
  privateDirectory, privateFile, readRecord, unknownRecord, validId, writeRecord } from './local-command-state.mjs';
11
11
 
12
12
  async function inputRequest() {
@@ -38,7 +38,7 @@ async function supervise() {
38
38
  record = readRecord(directory, owner, commandId);
39
39
  if (record.status !== 'starting') return;
40
40
  if (Date.now() - record.createdAt >= START_GRACE_MS) {
41
- unknownRecord(directory, record, 'supervisor_start_expired'); return;
41
+ failCommandStart(directory, record, 'supervisor_start_expired'); return;
42
42
  }
43
43
  const persistedStream = !!request.outputPolicy;
44
44
  const persist = (status, exitCode, stdout, stderr, metadata = {}) => {
@@ -84,7 +84,8 @@ async function supervise() {
84
84
  else if (result.outputLimitExceeded) { status = 'output_limit'; exitCode = 122; diagnostic = 'command output limit exceeded'; }
85
85
  commandEvidence = commandFailureEvidence(stage, { result, failures: [
86
86
  ...(outputError ? ['output_recording_failed'] : []), ...(stateError ? ['state_observation_failed'] : [])] });
87
- if (result.controls.status === 'failed' || result.cleanupError || outputError || stateError) {
87
+ const controlsFailed = result.controls.status === 'failed' && !result.canceledBeforeDispatch;
88
+ if (controlsFailed || result.cleanupError || outputError || stateError) {
88
89
  status = 'unknown'; exitCode = null; diagnostic = 'command supervision or cleanup failed';
89
90
  }
90
91
  // Under persisted-stream, result.stdout/stderr are bounded PREVIEWS; the full
@@ -95,7 +96,7 @@ async function supervise() {
95
96
  persist(status, exitCode, result.stdout, stderr, { controls: result.controls, outputLimitExceeded: result.outputLimitExceeded,
96
97
  ...(status === 'unknown' ? { commandEvidence } : {}),
97
98
  evidenceIncomplete: status === 'unknown', observedExitCode: status === 'unknown' ? result.exitCode : null,
98
- outcomeReason: status === 'unknown' ? 'process_supervision_failed' : '' });
99
+ outcomeReason: status === 'unknown' ? 'process_supervision_failed' : result.canceledBeforeDispatch ? 'canceled_before_start' : '' });
99
100
  } catch (error) {
100
101
  // Secrets/input exception strings never enter records or diagnostics.
101
102
  if (record && !TERMINAL.has(record.status)) unknownRecord(directory, { ...record,
@@ -10,8 +10,8 @@ import { localControlSettings, resolveLocalProcessLauncher } from './local-proce
10
10
  import { localEnvironmentPolicy, localOutputPolicy } from './local-output-policy.mjs';
11
11
  import { ISOLATED_COMMAND_SHELL, shellCommandArgv } from './command-shell.mjs';
12
12
  import { LOCAL_BACKGROUND_CONTRACT, START_GRACE_MS, TERMINAL, LocalCommandError,
13
- check, createPrivate, delay, digest, fsyncPrivate, lockUntil, openPrivate, privateDirectory, privateFile,
14
- readAll, readRecord, readWindow, syncDirectory, tryLock, unknownRecord, validId, writeRecord } from './local-command-state.mjs';
13
+ check, createPrivate, delay, digest, failCommandStart, fsyncPrivate, lockUntil, openPrivate, privateDirectory, privateFile,
14
+ readAll, readRecord, readWindow, syncDirectory, tryLock, validId, writeRecord } from './local-command-state.mjs';
15
15
 
16
16
  export { LOCAL_BACKGROUND_CONTRACT, LocalCommandError };
17
17
  const supervisor = fileURLToPath(new URL('./local-background-supervisor.mjs', import.meta.url));
@@ -19,6 +19,15 @@ const inside = (path, root) => path === root || path.startsWith(root + sep);
19
19
  const workerEnvironment = Object.freeze({ PATH: '/bin:/usr/bin', LANG: 'C.UTF-8', NODE_NO_WARNINGS: '1' });
20
20
  const deadline = () => performance.now() + START_GRACE_MS;
21
21
 
22
+ function failUnclaimedStart(handle, reason) {
23
+ const unlock = tryLock(join(handle.directory, 'supervisor.sqlite'));
24
+ if (!unlock) return;
25
+ try {
26
+ const record = readRecord(handle.directory, handle.owner, handle.commandId);
27
+ if (record.status === 'starting') failCommandStart(handle.directory, record, reason);
28
+ } finally { unlock(); }
29
+ }
30
+
22
31
  // commandRequest validates raw policy inputs at this public entrypoint. The
23
32
  // policies travel as separate optional fields, NOT inside settings, so the
24
33
  // normalized settings object (and thus the request digest) is byte-identical
@@ -168,17 +177,12 @@ export class LocalCommandStore {
168
177
  detached: true, cwd: directory, env: workerEnvironment, stdio: ['pipe', 'ignore', 'ignore'],
169
178
  });
170
179
  } catch {
171
- unknownRecord(directory, record, 'supervisor_launch_failed'); return handle;
180
+ failUnclaimedStart(handle, 'supervisor_launch_failed'); return handle;
172
181
  }
173
182
  child.once('error', () => {
174
183
  // A spawn error proves no child was created; a pipe failure does not.
175
- let unlock;
176
- try {
177
- unlock = tryLock(join(directory, 'supervisor.sqlite'));
178
- const current = readRecord(directory, this.owner, commandId);
179
- if (unlock && current.status === 'starting') unknownRecord(directory, current, 'supervisor_launch_failed');
180
- } catch { /* existing durable intent remains recoverably unknown */ }
181
- finally { unlock?.(); }
184
+ try { failUnclaimedStart(handle, 'supervisor_launch_failed'); }
185
+ catch { /* existing durable intent remains recoverably unknown */ }
182
186
  });
183
187
  child.stdin.on('error', () => { /* return the stable locator; never retry */ });
184
188
  // Secrets travel only through the private stdin pipe, never argv/record.
@@ -186,6 +190,10 @@ export class LocalCommandStore {
186
190
  } finally { release(); }
187
191
  const until = performance.now() + START_GRACE_MS;
188
192
  while (readRecord(handle.directory, this.owner, commandId).status === 'starting' && performance.now() < until) await delay(20);
193
+ // Fence a late supervisor before reporting a failure. A claimed command
194
+ // keeps its original ownership and may still publish a receipt.
195
+ if (readRecord(handle.directory, this.owner, commandId).status === 'starting')
196
+ failUnclaimedStart(handle, 'supervisor_start_expired');
189
197
  return handle;
190
198
  }
191
199
  }
@@ -10,6 +10,11 @@ import { validCommandEvidence } from './local-command-evidence.mjs';
10
10
  export const LOCAL_BACKGROUND_CONTRACT = 'agentkit.local-background-command/v1';
11
11
  export const START_GRACE_MS = 5000;
12
12
  export const TERMINAL = new Set(['completed', 'failed', 'canceled', 'timed_out', 'output_limit', 'unknown']);
13
+ const startFailureReason = reason => reason === 'supervisor_start_expired' || reason === 'supervisor_launch_failed';
14
+ const preLaunchFailure = record => startFailureReason(record.outcomeReason) && record.exitCode === null
15
+ && record.supervisorPid === undefined && record.observedExitCode == null;
16
+ export const confirmedCommandStartFailure = output => output.status === 'failed' && output.exitCode === null
17
+ && output.evidenceIncomplete === false && startFailureReason(output.outcomeReason);
13
18
  export class LocalCommandError extends Error { constructor(code) { super(code); this.name = 'LocalCommandError'; this.code = code; } }
14
19
  export const check = (condition, code) => { if (!condition) throw new LocalCommandError(code); };
15
20
  export const validId = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
@@ -124,7 +129,10 @@ export function readRecord(directory, owner, commandId) {
124
129
  && (record.observedExitCode === undefined || record.observedExitCode === null || Number.isSafeInteger(record.observedExitCode)),
125
130
  'invalid_background_record');
126
131
  check(record.commandEvidence === undefined || validCommandEvidence(record.commandEvidence), 'invalid_background_record');
127
- return record;
132
+ // Keep the v1 on-disk representation readable after a plugin rollback.
133
+ // The specific, durable pre-spawn reason is stronger evidence than its status.
134
+ return record.status === 'unknown' && preLaunchFailure(record)
135
+ ? { ...record, status: 'failed', evidenceIncomplete: false } : record;
128
136
  }
129
137
  export function writeRecord(directory, record) {
130
138
  atomicPrivate(join(directory, 'record.json'), JSON.stringify(record) + '\n');
@@ -134,6 +142,12 @@ export function unknownRecord(directory, record, outcomeReason) {
134
142
  writeRecord(directory, next); return next;
135
143
  }
136
144
 
145
+ /** Requires the supervisor lock and a still-unclaimed launch record. */
146
+ export function failCommandStart(directory, record, outcomeReason) {
147
+ check(record.status === 'starting' && startFailureReason(outcomeReason), 'invalid_background_start_failure');
148
+ unknownRecord(directory, record, outcomeReason);
149
+ }
150
+
137
151
  // Each command has a separate SQLite lock database. The supervisor holds its
138
152
  // write transaction for its entire lifetime; command records/output remain
139
153
  // independently readable. A crash releases the kernel lock, with no PID test.
@@ -4,7 +4,7 @@ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
4
4
  import { canonical, copy, invariant, toolInputRejection } from '@kingsoftcloud/agentkit-harness-core';
5
5
  import { constants as osConstants } from 'node:os';
6
6
  import { LocalCommandStore, createLocalBackgroundReader } from './local-background.mjs';
7
- import { TERMINAL, delay, readRecord } from './local-command-state.mjs';
7
+ import { TERMINAL, confirmedCommandStartFailure, delay, readRecord } from './local-command-state.mjs';
8
8
  import { buildScriptEnvironment, localControlSettings, runBoundedProcess, LOCAL_PROCESS_CONTRACT } from './local-process.mjs';
9
9
  import { localEnvironmentPolicy, localOutputPolicy, resolveOutputPolicy } from './local-output-policy.mjs';
10
10
  import { checkGovernedCommand, LOCAL_COMMAND_POLICY, GOVERNED_COMMAND_POLICY } from './local-command-policy.mjs';
@@ -251,6 +251,8 @@ export function createLocalCommandTransport({ workspaceRoot, stateRoot, sessionI
251
251
  // output into the receipt, so re-read with the bounded window instead.
252
252
  let observed = previewWindow ? handle.readOutput({ maxBytes: previewWindow })
253
253
  : handle.readOutput();
254
+ if (confirmedCommandStartFailure(observed))
255
+ return errorResult('command_not_started', { executed: false, outcome_reason: observed.outcomeReason });
254
256
  if (!args.background && TERMINAL.has(observed.status) && observed.status !== 'unknown'
255
257
  && !previewWindow)
256
258
  observed = await handle.wait({ timeoutMs: 100 });
@@ -224,10 +224,14 @@ export async function runBoundedProcess({ argv, cwd, env, settings: input = {},
224
224
  if (spawnError) throw new LocalProcessError(`local_process_spawn_failed:${spawnError.code ?? 'error'}`);
225
225
  const controls = controlReport(Buffer.concat(report).toString('utf8'), settings);
226
226
  const code = exitCode ?? (exitSignal && osConstants.signals[exitSignal] ? -osConstants.signals[exitSignal] : null);
227
+ // The verified launcher writes its complete control report before exec. A
228
+ // canceled, reliably drained launcher with an empty report never dispatched.
229
+ const preDispatch = canceled && (exitSignal === 'SIGTERM' || exitSignal === 'SIGKILL')
230
+ && closed && cleanupErrors.size === 0 && reportBytes === 0 ? { canceledBeforeDispatch: true } : {};
227
231
  if (!persistedStream)
228
232
  return { stdout: Buffer.concat(output.stdout).toString('utf8'), stderr: Buffer.concat(output.stderr).toString('utf8'),
229
233
  exitCode: outputLimitExceeded ? 122 : code, timedOut, canceled, outputLimitExceeded,
230
- stdoutTruncated: truncated.stdout, stderrTruncated: truncated.stderr, cleanupError: [...cleanupErrors].join(',') || null, controls };
234
+ stdoutTruncated: truncated.stdout, stderrTruncated: truncated.stderr, cleanupError: [...cleanupErrors].join(',') || null, controls, ...preDispatch };
231
235
  // persisted-stream/v1: stdout/stderr hold ONLY the bounded preview. The full
232
236
  // capped output lives in the supervisor-owned files (streamed via onOutput and
233
237
  // located by task_id/cursors). Honest truncation flags distinguish preview vs
@@ -242,5 +246,5 @@ export async function runBoundedProcess({ argv, cwd, env, settings: input = {},
242
246
  stdoutTruncated: preview.truncated.stdout, stderrTruncated: preview.truncated.stderr,
243
247
  stdoutPersistedTruncated: stream.truncated.stdout, stderrPersistedTruncated: stream.truncated.stderr,
244
248
  previewBytes: outPolicy.previewBytes, persistedBytes: outPolicy.persistedBytes,
245
- cleanupError: [...cleanupErrors].join(',') || null, controls };
249
+ cleanupError: [...cleanupErrors].join(',') || null, controls, ...preDispatch };
246
250
  }
@@ -2,6 +2,7 @@ import { NATIVE_LOCAL_RESOURCE_PROFILES } from '@kingsoftcloud/agentkit-harness-
2
2
  import { localControlSettings } from './local-process.mjs';
3
3
 
4
4
  export const LOCAL_RESOURCE_PROFILE = 'agentkit.local-resource-profile/v1';
5
+ const UNBOUNDED = Number.MAX_SAFE_INTEGER;
5
6
  const profiles = Object.freeze({
6
7
  'bounded/v1': Object.freeze({}),
7
8
  // Repository packs and build artifacts routinely exceed the restricted
@@ -11,6 +12,14 @@ const profiles = Object.freeze({
11
12
  // Versioned development budget: allow long builds without changing old Runs
12
13
  // or the restricted profile. A Host's explicit lower limit still wins.
13
14
  'local-development/v2': Object.freeze({ cpuSeconds: 900, maxFileBytes: 1024 ** 3 }),
15
+ // No per-command rlimits. A virtual address-space cap kills ordinary runtimes
16
+ // (Node/V8, Go, JVM and Chromium reserve far more address space than they use),
17
+ // and isolation belongs to the Host container, cgroup or sandbox. UNBOUNDED asks
18
+ // the launcher for no extra limit; it clamps to the existing hard limit. The
19
+ // wall-clock timeout, output cap, owner watchdog, process-group cleanup and the
20
+ // governed command pre-check still apply. Explicit Host settings still win.
21
+ 'local-development/v3': Object.freeze({ cpuSeconds: UNBOUNDED, addressSpaceBytes: UNBOUNDED, maxProcesses: UNBOUNDED,
22
+ maxOpenFiles: UNBOUNDED, maxFileBytes: UNBOUNDED }),
14
23
  });
15
24
  export function validLocalResourceProfile(profile) {
16
25
  return typeof profile === 'string' && NATIVE_LOCAL_RESOURCE_PROFILES.includes(profile) && Object.hasOwn(profiles, profile);