@kingsoftcloud/agentkit-harness-node 0.0.31 → 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.31",
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.31",
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",
@@ -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.
@@ -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);
@@ -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,
@@ -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);
@@ -12,6 +12,7 @@
12
12
  // the sealed providerReplay but never emitted in a public stream event's
13
13
  // metadata, and never concatenated to visible text.
14
14
 
15
+ import { modelToolView } from './model-tool-view.mjs';
15
16
  import {
16
17
  normalizeResponse, parseAnthropicUsageFragment, parseRetryAfterMs,
17
18
  ProtocolError, resolveUrl, boundOutputTokens,
@@ -159,10 +160,9 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
159
160
  const native = isNativeToolSearch(profile) && !['compaction', 'delivery_review'].includes(request.purpose);
160
161
  const systemParts = [];
161
162
  const items = [];
162
- const pending = new Set();
163
- // Pending call name per receipt callId, so native tool_reference metadata
163
+ // Track the canonical call by ID so native tool_reference metadata
164
164
  // pairs only with a ToolSearch call. The wire id still keys the receipt.
165
- const pendingNames = new Map();
165
+ const pending = new Map();
166
166
  const wireIds = new Map();
167
167
  const midSystem = profile.anthropicPolicy?.midSystem === true;
168
168
  for (const message of request.messages || []) {
@@ -172,16 +172,12 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
172
172
  if (role !== 'tool' && pending.size) throw new ProtocolError('incomplete assistant tool batch before next message');
173
173
  if (role === 'assistant' && message.toolCalls?.length) {
174
174
  validateAssistantToolIds(message.toolCalls);
175
- for (const call of message.toolCalls) {
176
- pending.add(call.callId);
177
- pendingNames.set(call.callId, modelWireToolCall(call).name);
178
- }
175
+ for (const call of message.toolCalls) pending.set(call.callId, call);
179
176
  }
180
- let pairedName;
177
+ let pairedCall;
181
178
  if (role === 'tool') {
179
+ pairedCall = pending.get(message.callId);
182
180
  if (!pending.delete(message.callId)) throw new ProtocolError('tool receipt does not match the pending assistant batch');
183
- pairedName = pendingNames.get(message.callId);
184
- pendingNames.delete(message.callId);
185
181
  }
186
182
  if (role === 'system' || role === 'developer') {
187
183
  if (midSystem && items.length) items.push({ role: 'system', content: message.content || '' });
@@ -195,12 +191,12 @@ function projectAnthropicMessages(request, maxInlineImageBytes) {
195
191
  // (no metadata) or empty names keep the ordinary text/media projection;
196
192
  // malformed or unpaired metadata fails preflight rather than widening
197
193
  // authority. Non-native policy ignores the metadata entirely.
198
- const references = native ? nativeToolReferenceContent(message, pairedName, request.tools) : undefined;
194
+ const references = native ? nativeToolReferenceContent(message, modelWireToolCall(pairedCall).name, request.tools) : undefined;
199
195
  const media = message.media ? message.media.map((b) => validateMediaBlock(b, maxInlineImageBytes)) : null;
200
196
  let content;
201
197
  if (references) content = [...references, ...(media?.length ? projectMediaAnthropic(media) : [])];
202
198
  else if (media && media.length) content = [{ type: 'text', text: message.content || '' }, ...projectMediaAnthropic(media)];
203
- else content = (message.content || '');
199
+ else content = modelToolView(message.content || '', pairedCall.name, request.tools);
204
200
  item = {
205
201
  role: 'user',
206
202
  content: [{
@@ -8,6 +8,7 @@
8
8
  //
9
9
  // Profiled inline reasoning is projected under the Run's frozen policy.
10
10
 
11
+ import { modelToolView } from './model-tool-view.mjs';
11
12
  import { ModelStreamLimitError } from './model-stream-budget.mjs';
12
13
  import {
13
14
  normalizeResponse, parseOpenAIUsage, sealUsage, ProtocolError, resolveUrl, boundOutputTokens,
@@ -128,7 +129,7 @@ export function buildOpenAIRequest(binding, request) {
128
129
  export function projectMessagesOpenAI(request, maxInlineImageBytes) {
129
130
  const profile = request.profile;
130
131
  const projected = [];
131
- const pending = new Set();
132
+ const pending = new Map();
132
133
  let images = [];
133
134
  for (const message of request.messages || []) {
134
135
  const role = message.role;
@@ -137,12 +138,14 @@ export function projectMessagesOpenAI(request, maxInlineImageBytes) {
137
138
  }
138
139
  if (role === 'assistant' && message.toolCalls && message.toolCalls.length) {
139
140
  validateAssistantToolIds(message.toolCalls);
140
- for (const call of message.toolCalls) pending.add(call.callId);
141
+ for (const call of message.toolCalls) pending.set(call.callId, call.name);
141
142
  }
143
+ let toolName;
142
144
  if (role === 'tool') {
143
145
  if (!pending.has(message.callId)) {
144
146
  throw new ProtocolError('tool receipt does not match the pending assistant batch');
145
147
  }
148
+ toolName = pending.get(message.callId);
146
149
  pending.delete(message.callId);
147
150
  }
148
151
  const media = message.media ? message.media.map((b) => validateMediaBlock(b, maxInlineImageBytes)) : null;
@@ -173,7 +176,7 @@ export function projectMessagesOpenAI(request, maxInlineImageBytes) {
173
176
  Object.assign(msg, openAIReplayFields(message, profile));
174
177
  projected.push(msg);
175
178
  } else if (role === 'tool') {
176
- projected.push({ role: 'tool', tool_call_id: message.callId, content: message.content || '' });
179
+ projected.push({ role: 'tool', tool_call_id: message.callId, content: modelToolView(message.content || '', toolName, request.tools) });
177
180
  } else {
178
181
  projected.push({ role, content: message.content || '' });
179
182
  }
@@ -7,6 +7,7 @@ import { ProtocolError } from './model-normalize.mjs';
7
7
  const strict = new Set(['openai', 'strict-openai', 'cerebras', 'groq']);
8
8
  const requiredAuto = new Set(['claude-opus-5-5', 'claude-sonnet-5-5', 'claude-fable-5-1', 'claude-mythos-5-1']);
9
9
  const mandatory = new Set(['claude-fable-5-1', 'claude-opus-5-5', 'claude-sonnet-5-5']);
10
+ const gatewayMandatoryGlm = new Set(['glm-5.3', 'glm-5.3-flash', 'glm-5.3-flashx']);
10
11
  const ranks = { none: 0, minimal: 1, low: 2, medium: 3, high: 4, xhigh: 5, max: 5 };
11
12
  const normalized = model => String(model ?? '').trim().toLowerCase().replaceAll('_', '-');
12
13
  const object = value => value && typeof value === 'object' && !Array.isArray(value);
@@ -44,25 +45,32 @@ export function applyAnthropicThinking(payload, profile, binding) {
44
45
  return { ...payload, thinking };
45
46
  }
46
47
 
47
- export function admitProviderCompatibilityPolicy(override) {
48
- return { contract: 'provider-compat/v5', rule: admitInlineReasoningPolicy(override).rule };
48
+ export function admitProviderCompatibilityPolicy(override, binding) {
49
+ const { rule } = admitInlineReasoningPolicy(override);
50
+ const needsThinkingGuard = binding?.protocol === 'openai-chat'
51
+ && gatewayMandatoryGlm.has(String(binding.model ?? '').trim().toLowerCase())
52
+ && resolveCompatibilityRule(rule, binding) === 'kspmas-gateway';
53
+ return { contract: needsThinkingGuard ? 'provider-compat/v6' : 'provider-compat/v5', rule };
49
54
  }
50
55
 
51
56
  export function resolveProviderCompatibility(policy, binding) {
52
57
  if (!policy) return null;
53
- const version = ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4', 'provider-compat/v5'].indexOf(policy.contract) + 1;
58
+ const version = ['provider-compat/v1', 'provider-compat/v2', 'provider-compat/v3', 'provider-compat/v4', 'provider-compat/v5', 'provider-compat/v6'].indexOf(policy.contract) + 1;
54
59
  if (!version) throw new ProtocolError('invalid_provider_compatibility_policy');
55
60
  const rule = resolveCompatibilityRule(policy.rule, binding);
56
61
  const name = String(binding.model ?? '').trim().toLowerCase();
57
62
  const kimi = ['kspmas-gateway', 'moonshot'].includes(rule)
58
63
  && ['kimi-k2.7-code', 'kimi-k2.7-code-highspeed'].includes(name);
59
64
  const modern = version >= 3;
60
- const reasoningRequired = modern && rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
65
+ const gatewayFlash = rule === 'kspmas-gateway' && name === 'glm-5.3-flash';
66
+ const gatewayMandatoryThinking = version >= 6 && rule === 'kspmas-gateway' && gatewayMandatoryGlm.has(name);
67
+ const reasoningRequired = gatewayMandatoryThinking || modern && gatewayFlash;
61
68
  const disabledEfforts = mandatory.has(name) || reasoningRequired ? [] : name === 'claude-haiku-5-5' ? ['low', 'medium', 'high'] : null;
62
69
  return { rule, supportsUsage: !strict.has(rule), supportsThinking: !strict.has(rule) && !kimi,
63
70
  supportsToolArgumentStreaming: version >= 2
64
71
  && ['zai', 'kspmas-gateway'].includes(rule) && incrementalToolModels.has(normalized(binding.model)),
65
- reasoningRequired, modern, firstToolLowEffort: version >= 5 && reasoningRequired,
72
+ reasoningRequired, modern, firstToolLowEffort: version >= 5 && gatewayFlash,
73
+ minimumReasoningEffort: gatewayMandatoryThinking ? 'low' : null,
66
74
  // This route already uses the supported non-thinking mode for tool work.
67
75
  // A bounded summary has no tools: omitting the switch can instead select
68
76
  // the provider's default high reasoning and consume its whole output cap.
@@ -118,6 +126,7 @@ export function applyProviderChatCompatibility(payload, request, binding) {
118
126
  if (requested === null && request.purpose === 'compaction' && compat.rule === 'kspmas-gateway'
119
127
  && ['glm-5.2', 'deepseek-v4-flash'].includes(name)) effort = 'none';
120
128
  if (requested === null && request.purpose === 'compaction' && compat.reasoningRequired) effort = 'low';
129
+ if (compat.minimumReasoningEffort && (effort === 'none' || effort === 'minimal')) effort = compat.minimumReasoningEffort;
121
130
  effort = compat.supportsEffort ? clampReasoningEffort(model, effort) : null;
122
131
  if (effort !== null) result.reasoning_effort = effort;
123
132
  if (result.stream) result.stream_options = { ...(object(result.stream_options) ? result.stream_options : {}), include_usage: true };
@@ -23,6 +23,7 @@
23
23
  // no reasoning items in its input array. See delivery evidence for the
24
24
  // audited gap.
25
25
 
26
+ import { modelToolView } from './model-tool-view.mjs';
26
27
  import {
27
28
  normalizeResponse, sealUsage, ProtocolError, resolveUrl, boundOutputTokens,
28
29
  emptyUsage,
@@ -199,7 +200,7 @@ export function projectMessagesResponses(request, maxInlineImageBytes) {
199
200
  const profile = request.profile;
200
201
  const instructions = [];
201
202
  const items = [];
202
- const pending = new Set();
203
+ const pending = new Map();
203
204
  for (const message of request.messages || []) {
204
205
  const role = message.role;
205
206
  if (role !== 'tool' && pending.size) {
@@ -207,12 +208,14 @@ export function projectMessagesResponses(request, maxInlineImageBytes) {
207
208
  }
208
209
  if (role === 'assistant' && message.toolCalls && message.toolCalls.length) {
209
210
  validateAssistantToolIds(message.toolCalls);
210
- for (const call of message.toolCalls) pending.add(call.callId);
211
+ for (const call of message.toolCalls) pending.set(call.callId, call.name);
211
212
  }
213
+ let toolName;
212
214
  if (role === 'tool') {
213
215
  if (!pending.has(message.callId)) {
214
216
  throw new ProtocolError('tool receipt does not match the pending assistant batch');
215
217
  }
218
+ toolName = pending.get(message.callId);
216
219
  pending.delete(message.callId);
217
220
  }
218
221
  // The Responses wire carries no Anthropic content; a cross-wire replay is
@@ -228,7 +231,7 @@ export function projectMessagesResponses(request, maxInlineImageBytes) {
228
231
  const media = message.media ? message.media.map((b) => validateMediaBlock(b, maxInlineImageBytes)) : null;
229
232
  const output = media && media.length
230
233
  ? [{ type: 'input_text', text: message.content || '' }, ...projectMediaResponses(media)]
231
- : (message.content || '');
234
+ : modelToolView(message.content || '', toolName, request.tools);
232
235
  items.push({ type: 'function_call_output', call_id: message.callId, output });
233
236
  continue;
234
237
  }
@@ -0,0 +1,24 @@
1
+ /** Compact receipts from the admitted local command tool. All other payloads
2
+ * keep their original framing and fields, including workspace and MCP data. */
3
+ export function modelToolView(text, toolName, tools) {
4
+ if (typeof text !== 'string' || !text) return text;
5
+ if (toolName !== 'run_command' || !tools?.some(tool => tool.name === toolName
6
+ && tool.backgroundCommandPolicy === 'owned-command-launch/v1'
7
+ && tool.workspaceChangePolicy === 'observed-command/v1'
8
+ && tool.permissions?.includes('sandbox:execute'))) return text;
9
+ // Re-serializing must not change an integer's digits (e.g. 9007199254740993
10
+ // would become ...992). Such receipts pass through verbatim.
11
+ let receipt, inexact = false;
12
+ try {
13
+ receipt = JSON.parse(text, (key, value, context) => {
14
+ const source = context?.source;
15
+ if (typeof value === 'number' && typeof source === 'string' && /^-?\d+$/.test(source) && JSON.stringify(value) !== source) inexact = true;
16
+ return value;
17
+ });
18
+ } catch { return text; }
19
+ if (inexact || receipt?.backend !== 'sandbox/local_process') return text;
20
+ // Output stays cursor-readable after the process exits. Preserve the task ID,
21
+ // cursors and paging instruction along with status and truncation evidence.
22
+ const { command, controls, sandbox_id, ...view } = receipt;
23
+ return JSON.stringify(view);
24
+ }