@kingsoftcloud/agentkit-harness-node 0.0.19 → 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.
- package/dist/engine-view.html +31 -23
- package/dist/index.mjs +77 -26
- package/dist/rpc-entry.mjs +77 -26
- package/package.json +2 -2
- package/src/native/engine-client.mjs +15 -4
- package/src/native/engine-delivery-evidence.mjs +72 -4
- package/src/native/engine-host-effects.mjs +26 -16
- package/src/native/engine-managed-service.mjs +12 -5
- package/src/native/engine-runtime.mjs +67 -14
- package/src/native/engine-server.mjs +148 -33
- package/src/native/engine-service.mjs +99 -19
- package/src/native/engine-verification.mjs +31 -5
- package/src/native/local-command-policy-worker.mjs +2 -2
- package/src/native/local-command-tools.mjs +19 -12
- package/src/native/model-inline-reasoning.mjs +2 -0
- package/src/native/model-port.mjs +72 -31
- package/src/native/native-terminal-failure.mjs +15 -4
- package/src/native/workspace-tools.mjs +32 -8
|
@@ -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
|
-
|
|
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 });
|
|
@@ -78,27 +104,45 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
|
|
|
78
104
|
resolve(frame);
|
|
79
105
|
}
|
|
80
106
|
});
|
|
81
|
-
const takeHostRequests = runId => {
|
|
82
|
-
|
|
107
|
+
const takeHostRequests = (runId, receiver) => {
|
|
108
|
+
const now = Date.now();
|
|
109
|
+
pruneHostRequests(now);
|
|
83
110
|
const ready = [];
|
|
84
111
|
for (const request of hostRequests.values()) {
|
|
85
|
-
if (
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
112
|
+
if (runId !== undefined && request.frame.params?.runId !== runId) continue;
|
|
113
|
+
if (request.claimed && (!receiver || request.receiver !== receiver || now < request.redeliverAt)) continue;
|
|
114
|
+
request.claimed = true;
|
|
115
|
+
request.receiver = receiver;
|
|
116
|
+
request.redeliverAt = now + 500;
|
|
117
|
+
ready.push(request.frame);
|
|
89
118
|
}
|
|
90
119
|
return ready;
|
|
91
120
|
};
|
|
92
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
|
+
},
|
|
93
128
|
request(frame) {
|
|
94
|
-
if (pending.has(frame.id)) return null;
|
|
129
|
+
if (stopped || pending.has(frame.id)) return null;
|
|
130
|
+
lastUsed = Date.now();
|
|
95
131
|
return new Promise(resolve => {
|
|
96
|
-
|
|
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);
|
|
97
139
|
input.write(JSON.stringify(frame) + '\n');
|
|
98
140
|
});
|
|
99
141
|
},
|
|
100
|
-
async takeHostRequests(runId, waitMs, response) {
|
|
101
|
-
|
|
142
|
+
async takeHostRequests(runId, waitMs, response, receiver) {
|
|
143
|
+
if (stopped) return [];
|
|
144
|
+
lastUsed = Date.now();
|
|
145
|
+
const available = takeHostRequests(runId, receiver);
|
|
102
146
|
if (available.length || !waitMs || response.destroyed) return available;
|
|
103
147
|
return new Promise(resolve => {
|
|
104
148
|
const finish = frames => {
|
|
@@ -110,7 +154,7 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
|
|
|
110
154
|
const cancel = () => finish([]);
|
|
111
155
|
const notify = stopped => {
|
|
112
156
|
if (stopped || response.destroyed) return cancel();
|
|
113
|
-
const ready = takeHostRequests(runId);
|
|
157
|
+
const ready = takeHostRequests(runId, receiver);
|
|
114
158
|
if (ready.length) finish(ready);
|
|
115
159
|
};
|
|
116
160
|
const timer = setTimeout(cancel, waitMs);
|
|
@@ -119,13 +163,15 @@ function openSession(sessionId, startup, env, fetchImpl, log, viewStore) {
|
|
|
119
163
|
});
|
|
120
164
|
},
|
|
121
165
|
reply(frame) {
|
|
166
|
+
if (stopped) return false;
|
|
167
|
+
lastUsed = Date.now();
|
|
122
168
|
const request = hostRequests.get(frame.id);
|
|
123
169
|
if (!request?.claimed || !hostRequests.delete(frame.id) || request.frame.expiresAt <= Date.now()) return false;
|
|
124
170
|
input.write(JSON.stringify(frame) + '\n');
|
|
125
171
|
return true;
|
|
126
172
|
},
|
|
127
173
|
async close() {
|
|
128
|
-
|
|
174
|
+
stop();
|
|
129
175
|
await done;
|
|
130
176
|
},
|
|
131
177
|
};
|
|
@@ -154,6 +200,26 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
|
|
|
154
200
|
const managedRuntime = managed && createEngineManagedService({ startup, stateDir, workspace,
|
|
155
201
|
config: managed, env, fetchImpl, log, serviceToken: token, viewStore, viewRef });
|
|
156
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();
|
|
157
223
|
const handleRequest = async (request, response) => {
|
|
158
224
|
if (request.method === 'GET' && request.url === '/healthz') {
|
|
159
225
|
return respond(response, closing ? 503 : 200, {
|
|
@@ -198,11 +264,15 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
|
|
|
198
264
|
try {
|
|
199
265
|
if (request.method === 'GET' && action === 'host-requests') {
|
|
200
266
|
const session = sessions.get(id);
|
|
201
|
-
if (!session) return respond(response, 404, { error: 'session_not_found' });
|
|
267
|
+
if (!session || session.stopped) return respond(response, 404, { error: 'session_not_found' });
|
|
202
268
|
const search = new URLSearchParams(query);
|
|
203
269
|
const runId = search.get('runId') ?? undefined;
|
|
204
270
|
const waitMs = Math.min(Math.max(Number(search.get('waitMs')) || 0, 0), 5000);
|
|
205
|
-
|
|
271
|
+
// Existing hosts use one-shot delivery. Only a Run-scoped client
|
|
272
|
+
// that deduplicates execution by frame ID can request redelivery.
|
|
273
|
+
const requestedReceiver = search.get('receiver');
|
|
274
|
+
const receiver = runId !== undefined && /^[a-f0-9-]{36}$/.test(requestedReceiver ?? '') ? requestedReceiver : null;
|
|
275
|
+
const requests = await session.takeHostRequests(runId, waitMs, response, receiver);
|
|
206
276
|
return respond(response, 200, { requests });
|
|
207
277
|
}
|
|
208
278
|
if (query !== undefined) return respond(response, 400, { error: 'invalid_query' });
|
|
@@ -218,11 +288,20 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
|
|
|
218
288
|
}
|
|
219
289
|
if (typeof frame.method !== 'string' || frame.method === 'shutdown')
|
|
220
290
|
return respond(response, 400, { error: 'invalid_method' });
|
|
221
|
-
|
|
291
|
+
while (!session || session.stopped) {
|
|
222
292
|
if (frame.method !== 'initialize') return respond(response, 404, { error: 'session_not_found' });
|
|
223
|
-
if (
|
|
224
|
-
|
|
225
|
-
|
|
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);
|
|
226
305
|
}
|
|
227
306
|
const result = await session.request(frame);
|
|
228
307
|
if (closing) return respond(response, 503, { error: 'service_stopping' });
|
|
@@ -237,6 +316,7 @@ export function createEngineService({ startup, token, env = process.env, fetchIm
|
|
|
237
316
|
server,
|
|
238
317
|
async close() {
|
|
239
318
|
closing = true;
|
|
319
|
+
clearInterval(cleanup);
|
|
240
320
|
const stopped = new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve()));
|
|
241
321
|
await Promise.allSettled([...sessions.values()].map(session => session.close()).concat(managedRuntime?.close() ?? []));
|
|
242
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
|
|
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,
|
|
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))
|
|
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
|
|
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
|
|
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
|
-
|
|
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() : '';
|
|
@@ -33,7 +33,8 @@ import { buildNativeModelRequest } from './model-request.mjs';
|
|
|
33
33
|
// parseModelJson is the kernel's strict finite JSON parser; used here for the
|
|
34
34
|
// 400 context-length error heuristic so a malformed error body is never parsed
|
|
35
35
|
// as a lenient ambiguity.
|
|
36
|
-
import { parseModelJson, MODEL_FAILURE_CODES
|
|
36
|
+
import { parseModelJson, MODEL_FAILURE_CODES, MODEL_GATEWAY_ERROR_CODES, MODEL_GATEWAY_ERROR_TYPES,
|
|
37
|
+
isModelGatewayRequestId } from '@kingsoftcloud/agentkit-harness-core';
|
|
37
38
|
import { observeModelTransportPort } from './model-transport-observation.mjs';
|
|
38
39
|
|
|
39
40
|
const DEFAULT_MAX_BYTES = 8 * 1024 * 1024;
|
|
@@ -136,12 +137,14 @@ export function createNativeModelPort({
|
|
|
136
137
|
try {
|
|
137
138
|
if (!response.ok) {
|
|
138
139
|
observation.phase('http-error');
|
|
139
|
-
const
|
|
140
|
+
const body = await readHttpError(response, maxBytes);
|
|
141
|
+
const result = classifyHttpError(response, body);
|
|
142
|
+
const gateway = httpGatewayDiagnostic(response, body);
|
|
140
143
|
request.signal?.throwIfAborted();
|
|
141
144
|
const code = response.status === 401 ? 'http_authentication' : response.status === 403 ? 'http_permission'
|
|
142
145
|
: response.status === 429 ? 'http_rate_limit' : response.status === 408 ? 'http_timeout'
|
|
143
146
|
: response.status >= 500 ? 'http_server' : 'http_client';
|
|
144
|
-
return withFailure(result, binding, 'http-error', code, { httpStatus: response.status });
|
|
147
|
+
return withFailure(result, binding, 'http-error', code, { httpStatus: response.status, ...(gateway ? { gateway } : {}) });
|
|
145
148
|
}
|
|
146
149
|
const contentType = response.headers.get('content-type') || '';
|
|
147
150
|
if (contentType.includes('text/event-stream')) {
|
|
@@ -182,6 +185,27 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
182
185
|
// body read rejects cleanly instead of leaving an orphaned read to cancel.
|
|
183
186
|
const abort = (reason) => internal.abort(reason);
|
|
184
187
|
let frameIndex = -1;
|
|
188
|
+
// Bound only a sustained, exact cycle before the response produces text or
|
|
189
|
+
// tool arguments. Inspect a small suffix independent of SSE chunk boundaries.
|
|
190
|
+
let reasoning = request.purpose == null || request.purpose === 'task' ? '' : null;
|
|
191
|
+
let sinceCheck = 0;
|
|
192
|
+
let repetition = false;
|
|
193
|
+
const observe = event => {
|
|
194
|
+
if ((event.kind === 'text' && event.text.trim()) || event.kind === 'tool_delta') reasoning = null;
|
|
195
|
+
if (reasoning !== null && event.kind === 'thinking' && event.text) {
|
|
196
|
+
reasoning = (reasoning + event.text).slice(-1024);
|
|
197
|
+
sinceCheck += event.text.length;
|
|
198
|
+
if (reasoning.length === 1024 && sinceCheck >= 128) {
|
|
199
|
+
sinceCheck = 0;
|
|
200
|
+
for (let size = 1; size <= 64; size++) {
|
|
201
|
+
if (reasoning.slice(size) !== reasoning.slice(0, -size)) continue;
|
|
202
|
+
repetition = true;
|
|
203
|
+
break;
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
emit(event);
|
|
208
|
+
};
|
|
185
209
|
const failed = (result, code, fields = {}) => withFailure(result, binding, 'stream', code,
|
|
186
210
|
{ ...(frameIndex < 0 ? {} : { frameIndex }),
|
|
187
211
|
...(code === 'usage_conflict' && state.usageConflict ? { usageConflict: state.usageConflict } : {}), ...fields });
|
|
@@ -190,7 +214,12 @@ async function streamResponse(response, request, binding, emit, internal, maxByt
|
|
|
190
214
|
if (idlePolicy && !frame.data.trim()) continue;
|
|
191
215
|
frameIndex++;
|
|
192
216
|
observation.frame();
|
|
193
|
-
state.consume(frame,
|
|
217
|
+
state.consume(frame, observe);
|
|
218
|
+
if (repetition && reasoning !== null && !state.done) {
|
|
219
|
+
abort(new Error('reasoning_repetition'));
|
|
220
|
+
return failed({ kind: 'output_limit', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false,
|
|
221
|
+
textCommitVersion: 'provider-finished-text/v1', outputBoundary: 'no-visible-output/v1' }, 'reasoning_repetition');
|
|
222
|
+
}
|
|
194
223
|
if (idlePolicy) emit({ kind: 'activity', text: '' });
|
|
195
224
|
if (state.done) break;
|
|
196
225
|
}
|
|
@@ -248,41 +277,45 @@ async function bufferedResponse(response, request, binding, maxBytes, emit, obse
|
|
|
248
277
|
}
|
|
249
278
|
}
|
|
250
279
|
|
|
251
|
-
//
|
|
252
|
-
//
|
|
253
|
-
|
|
254
|
-
// body that cannot be read (timeout/overflow/bad utf-8) cannot erase the HTTP
|
|
255
|
-
// failure fact — the status-based classification still stands.
|
|
256
|
-
async function classifyHttpError(response, { maxBytes }) {
|
|
280
|
+
// Diagnostics are observational. Neither body identifiers nor correlation
|
|
281
|
+
// headers change retry behavior, except for the existing context-overflow rule.
|
|
282
|
+
function classifyHttpError(response, body) {
|
|
257
283
|
const status = response.status;
|
|
258
284
|
const retryAfterMs = parseRetryAfterMs(response.headers.get('retry-after'));
|
|
259
285
|
if (status === 408) return retryableResult('request_timeout', retryAfterMs);
|
|
260
286
|
if (status === 429) return retryableResult('rate_limit', retryAfterMs);
|
|
261
287
|
if (status >= 500 && status <= 599) return retryableResult('server_error', retryAfterMs);
|
|
262
288
|
if (status === 403) return { kind: 'policy_abort', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
263
|
-
if (status === 400) {
|
|
264
|
-
|
|
265
|
-
const bodyText = await readBoundedText(response, maxBytes);
|
|
266
|
-
if (hasContextLengthExceeded(bodyText)) {
|
|
267
|
-
return { kind: 'context_overflow', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
268
|
-
}
|
|
269
|
-
} catch { /* an unreadable 400 body cannot erase the 400 failure fact */ }
|
|
270
|
-
return terminalResult('client_error');
|
|
289
|
+
if (status === 400 && (body?.error?.code === 'context_length_exceeded' || body?.error?.type === 'context_length_exceeded')) {
|
|
290
|
+
return { kind: 'context_overflow', text: '', toolCalls: [], usage: emptyUsage(), usageReported: false };
|
|
271
291
|
}
|
|
272
292
|
return terminalResult('client_error');
|
|
273
293
|
}
|
|
274
294
|
|
|
275
|
-
function
|
|
295
|
+
async function readHttpError(response, maxBytes) {
|
|
296
|
+
// Rate limiting is fully determined by status and Retry-After. Only the
|
|
297
|
+
// allowlisted correlation header is needed; never wait on a 429 body.
|
|
298
|
+
if (response.status === 429) return null;
|
|
299
|
+
const contextCheck = response.status === 400;
|
|
300
|
+
// Keep the original 400 compatibility check. For other statuses this is
|
|
301
|
+
// optional evidence; a stalled error body must not delay retries.
|
|
302
|
+
if (!contextCheck && !response.body?.getReader) return null;
|
|
276
303
|
try {
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
304
|
+
return parseModelJson(await readBoundedText(response, contextCheck ? maxBytes : Math.min(maxBytes, 8192),
|
|
305
|
+
undefined, contextCheck ? undefined : AbortSignal.timeout(200)));
|
|
306
|
+
} catch { return null; }
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function httpGatewayDiagnostic(response, body) {
|
|
310
|
+
const diagnostic = {};
|
|
311
|
+
const error = body?.error && typeof body.error === 'object' ? body.error : body;
|
|
312
|
+
if (MODEL_GATEWAY_ERROR_CODES.includes(error?.code)
|
|
313
|
+
|| Number.isInteger(error?.code) && error.code >= 400 && error.code <= 599) diagnostic.code = error.code;
|
|
314
|
+
if (MODEL_GATEWAY_ERROR_TYPES.includes(error?.type)) diagnostic.type = error.type;
|
|
315
|
+
const requestId = ['x-request-id', 'request-id', 'x-ksc-request-id']
|
|
316
|
+
.map(header => response.headers.get(header)).find(isModelGatewayRequestId);
|
|
317
|
+
if (requestId) diagnostic.requestId = requestId;
|
|
318
|
+
return Object.keys(diagnostic).length ? diagnostic : null;
|
|
286
319
|
}
|
|
287
320
|
|
|
288
321
|
function terminalResult(failureKind) {
|
|
@@ -296,9 +329,12 @@ function protocolCode(error) {
|
|
|
296
329
|
? error.code : 'protocol_invalid';
|
|
297
330
|
}
|
|
298
331
|
function withFailure(result, binding, phase, code, fields = {}) {
|
|
299
|
-
if (!['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)
|
|
332
|
+
if (!['provider_terminal_error', 'provider_retryable_error', 'policy_abort', 'malformed_tool_call'].includes(result.kind)
|
|
333
|
+
&& !(result.kind === 'output_limit' && code === 'reasoning_repetition')
|
|
334
|
+
&& !(result.kind === 'context_overflow' && fields.gateway)) return result;
|
|
300
335
|
const protocol = ['openai-chat', 'openai-responses', 'anthropic-messages'].includes(binding?.protocol) ? binding.protocol : 'unknown';
|
|
301
|
-
return { ...result, failureDiagnostic: { contract: fields.
|
|
336
|
+
return { ...result, failureDiagnostic: { contract: fields.gateway ? 'model-failure-diagnostic/v4'
|
|
337
|
+
: fields.providerError ? 'model-failure-diagnostic/v3' : fields.usageConflict
|
|
302
338
|
? 'model-failure-diagnostic/v2' : 'model-failure-diagnostic/v1', protocol, phase, code, ...fields } };
|
|
303
339
|
}
|
|
304
340
|
|
|
@@ -329,7 +365,7 @@ function cancelBody(response) {
|
|
|
329
365
|
// truncating a prefix (a JSON prefix + overflow suffix must not masquerade as a
|
|
330
366
|
// complete response). Reads to EOF before sealing. Throws OverflowError on
|
|
331
367
|
// overflow; propagates abort and bad-UTF-8 errors for the caller to classify.
|
|
332
|
-
async function readBoundedText(response, maxBytes, observeBytes) {
|
|
368
|
+
async function readBoundedText(response, maxBytes, observeBytes, signal) {
|
|
333
369
|
const body = response.body;
|
|
334
370
|
if (body == null) return '';
|
|
335
371
|
const reader = body.getReader ? body.getReader() : null;
|
|
@@ -337,9 +373,13 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
337
373
|
let total = 0;
|
|
338
374
|
const chunks = [];
|
|
339
375
|
if (reader) {
|
|
376
|
+
const abort = () => { void reader.cancel().catch(() => {}); };
|
|
340
377
|
try {
|
|
378
|
+
signal?.throwIfAborted();
|
|
379
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
341
380
|
while (true) {
|
|
342
381
|
const { value, done } = await reader.read();
|
|
382
|
+
signal?.throwIfAborted();
|
|
343
383
|
if (done) break;
|
|
344
384
|
if (!value) continue;
|
|
345
385
|
if (!(value instanceof Uint8Array) && !(value instanceof ArrayBuffer)) throw new ProtocolError('body requires bytes');
|
|
@@ -351,6 +391,7 @@ async function readBoundedText(response, maxBytes, observeBytes) {
|
|
|
351
391
|
chunks.push(decoder.decode());
|
|
352
392
|
return chunks.join('');
|
|
353
393
|
} finally {
|
|
394
|
+
signal?.removeEventListener('abort', abort);
|
|
354
395
|
reader.releaseLock?.();
|
|
355
396
|
}
|
|
356
397
|
}
|
|
@@ -27,13 +27,15 @@ const messages = Object.freeze({
|
|
|
27
27
|
});
|
|
28
28
|
|
|
29
29
|
const modelReasons = new Set(['provider_terminal_error', 'provider_retryable_error_retry_exhausted',
|
|
30
|
-
'malformed_tool_call_retry_exhausted', 'model_policy_abort'
|
|
31
|
-
|
|
30
|
+
'malformed_tool_call_retry_exhausted', 'model_policy_abort', 'context_summary_provider_terminal_error',
|
|
31
|
+
'context_summary_retry_exhausted']);
|
|
32
|
+
function modelFailureMessage(value, retriesExhausted = false) {
|
|
32
33
|
if (!value) return null;
|
|
33
34
|
try { validateModelFailure(value); } catch { return null; }
|
|
34
35
|
if (value.code === 'http_authentication') return '模型服务拒绝身份认证,请检查模型凭据。';
|
|
35
36
|
if (value.code === 'http_permission') return '模型请求被服务端权限或策略拒绝。';
|
|
36
|
-
if (value.code === '
|
|
37
|
+
if (value.code === 'http_client') return `模型网关拒绝了请求(HTTP ${value.httpStatus})${retriesExhausted ? '。' : ',未自动重试。'}`;
|
|
38
|
+
if (value.code === 'http_rate_limit') return '模型服务返回限流错误(HTTP 429)。';
|
|
37
39
|
if (value.code === 'host_binding') return '模型连接配置未能加载,请检查运行配置。';
|
|
38
40
|
if (value.phase === 'request') return '模型请求在发送前未通过校验,请查看运行诊断。';
|
|
39
41
|
if (value.code === 'stream_timeout' || value.code === 'http_timeout') return '等待模型服务响应超时,本次运行未能完成。';
|
|
@@ -42,11 +44,20 @@ function modelFailureMessage(value) {
|
|
|
42
44
|
if (value.phase === 'stream' || value.phase === 'buffered') return '模型响应未通过协议校验,本次运行已停止,请查看运行诊断。';
|
|
43
45
|
return null;
|
|
44
46
|
}
|
|
47
|
+
export function nativeModelStopMessage(reason, modelFailure) {
|
|
48
|
+
if (reason === 'provider_unavailable') return '模型服务暂不可用,自动重试次数已用完。任务已暂停,可稍后继续。';
|
|
49
|
+
if (!modelReasons.has(reason)) return null;
|
|
50
|
+
if (reason.endsWith('_retry_exhausted')) {
|
|
51
|
+
const detail = modelFailureMessage(modelFailure, true);
|
|
52
|
+
return detail ? `${detail}自动重试次数已用完。` : '模型请求未能完成,自动重试次数已用完。';
|
|
53
|
+
}
|
|
54
|
+
return modelFailureMessage(modelFailure) ?? (Object.hasOwn(messages, reason) ? messages[reason] : '模型请求未能完成,任务已停止。');
|
|
55
|
+
}
|
|
45
56
|
export function nativePublicTerminalError(phase, reason, modelFailure) {
|
|
46
57
|
if (phase !== 'failed' && phase !== 'interrupted') return null;
|
|
47
58
|
return {
|
|
48
59
|
code: phase === 'interrupted' ? 'NATIVE_EXECUTION_INTERRUPTED' : 'NATIVE_EXECUTION_NOT_COMPLETED',
|
|
49
|
-
message: (
|
|
60
|
+
message: nativeModelStopMessage(reason, modelFailure) ?? (Object.hasOwn(messages, reason) ? messages[reason] : (phase === 'interrupted'
|
|
50
61
|
? '原运行需要核对后才能继续,不会自动重复可能产生副作用的操作。'
|
|
51
62
|
: 'Native 运行未完成,请检查运行记录和配置。')),
|
|
52
63
|
};
|