@kingsoftcloud/agentkit-harness-node 0.0.27 → 0.0.29
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 +1 -1
- package/dist/index.mjs +155 -52
- package/dist/rpc-entry.mjs +155 -52
- package/package.json +2 -2
- package/src/native/e2b-command-tools.mjs +27 -10
- package/src/native/engine-runtime.mjs +10 -7
- package/src/native/engine-service.mjs +4 -1
- package/src/native/local-command-state.mjs +10 -2
- package/src/native/model-anthropic.mjs +10 -1
- package/src/native/model-openai-chat.mjs +14 -4
- package/src/native/model-port.mjs +42 -11
- package/src/native/model-responses.mjs +26 -9
- package/src/native/model-sse.mjs +44 -24
- package/src/native/model-stream-budget.mjs +31 -0
- package/src/native/native-terminal-failure.mjs +5 -0
- package/src/native/windows-private-state.mjs +41 -0
- package/src/native/workspace-state.mjs +3 -3
- package/src/native/workspace-tools.mjs +3 -3
package/src/native/model-sse.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Strict SSE byte framing for the native model transport.
|
|
2
2
|
//
|
|
3
3
|
// Ports ksadk._model_sse: UTF-8 is deliberately strict (replacing corrupt bytes
|
|
4
|
-
// inside JSON changes model facts),
|
|
4
|
+
// inside JSON changes model facts), byte budgets bound partial lines and frames, and a
|
|
5
5
|
// blank line is the only frame dispatch. A discarded terminal fragment at EOF
|
|
6
6
|
// is an unfinished frame, never a complete response. Idle silence is bounded.
|
|
7
7
|
//
|
|
@@ -38,14 +38,17 @@ function toAsyncIterator(body) {
|
|
|
38
38
|
// Stateful line framer mirroring ksadk._model_sse._Framer. CRLF/CR/LF all
|
|
39
39
|
// terminate lines; a blank line dispatches a frame from accumulated data lines.
|
|
40
40
|
class SseFramer {
|
|
41
|
-
constructor() {
|
|
41
|
+
constructor(maxFrameBytes) {
|
|
42
|
+
this.maxFrameBytes = maxFrameBytes;
|
|
43
|
+
this.lineBytes = 0;
|
|
44
|
+
this.dataBytes = 0;
|
|
42
45
|
this.lineParts = [];
|
|
43
46
|
this.dataLines = [];
|
|
44
47
|
this.eventName = '';
|
|
45
48
|
this.afterCr = false;
|
|
46
49
|
}
|
|
47
50
|
|
|
48
|
-
feed(text
|
|
51
|
+
*feed(text) {
|
|
49
52
|
if (!text) return;
|
|
50
53
|
if (this.afterCr) {
|
|
51
54
|
if (text.startsWith('\n')) text = text.slice(1);
|
|
@@ -53,15 +56,28 @@ class SseFramer {
|
|
|
53
56
|
}
|
|
54
57
|
let start = 0;
|
|
55
58
|
for (const m of text.matchAll(/\r\n|\r|\n/g)) {
|
|
56
|
-
this.
|
|
59
|
+
this.appendLine(text.slice(start, m.index));
|
|
57
60
|
const line = this.lineParts.join('');
|
|
58
61
|
this.lineParts = [];
|
|
62
|
+
this.lineBytes = 0;
|
|
59
63
|
start = m.index + m[0].length;
|
|
60
64
|
this.afterCr = m[0] === '\r' && start === text.length;
|
|
61
65
|
const frame = this.handleLine(line);
|
|
62
|
-
if (frame)
|
|
66
|
+
if (frame) yield frame;
|
|
67
|
+
}
|
|
68
|
+
if (start < text.length) this.appendLine(text.slice(start));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
appendLine(part) {
|
|
72
|
+
this.lineBytes += Buffer.byteLength(part);
|
|
73
|
+
this.checkFrameBytes(this.lineBytes);
|
|
74
|
+
this.lineParts.push(part);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
checkFrameBytes(bytes) {
|
|
78
|
+
if (bytes > this.maxFrameBytes) {
|
|
79
|
+
throw new SseFramingError('model SSE line or event exceeded the byte limit', 'stream_frame_limit');
|
|
63
80
|
}
|
|
64
|
-
if (start < text.length) this.lineParts.push(text.slice(start));
|
|
65
81
|
}
|
|
66
82
|
|
|
67
83
|
handleLine(line) {
|
|
@@ -69,6 +85,7 @@ class SseFramer {
|
|
|
69
85
|
if (this.dataLines.length === 0) { this.eventName = ''; return null; }
|
|
70
86
|
const frame = { data: this.dataLines.join('\n'), event: this.eventName || '' };
|
|
71
87
|
this.dataLines = [];
|
|
88
|
+
this.dataBytes = 0;
|
|
72
89
|
this.eventName = '';
|
|
73
90
|
return frame;
|
|
74
91
|
}
|
|
@@ -77,8 +94,14 @@ class SseFramer {
|
|
|
77
94
|
const name = sep === -1 ? line : line.slice(0, sep);
|
|
78
95
|
let value = sep === -1 ? '' : line.slice(sep + 1);
|
|
79
96
|
if (value.startsWith(' ')) value = value.slice(1);
|
|
80
|
-
if (name === 'data')
|
|
81
|
-
|
|
97
|
+
if (name === 'data') {
|
|
98
|
+
this.dataBytes += Buffer.byteLength(value) + Number(this.dataLines.length > 0);
|
|
99
|
+
this.checkFrameBytes(this.dataBytes + Buffer.byteLength(this.eventName));
|
|
100
|
+
this.dataLines.push(value);
|
|
101
|
+
} else if (name === 'event') {
|
|
102
|
+
this.checkFrameBytes(this.dataBytes + Buffer.byteLength(value));
|
|
103
|
+
this.eventName = value;
|
|
104
|
+
}
|
|
82
105
|
// `id` and `retry` are transport controls, not model payloads; ignore them.
|
|
83
106
|
return null;
|
|
84
107
|
}
|
|
@@ -96,20 +119,22 @@ class SseFramer {
|
|
|
96
119
|
* Yield { data, event } SSE frames from a byte stream with strict framing.
|
|
97
120
|
*
|
|
98
121
|
* @param body fetch response body (ReadableStream or async iterable of bytes)
|
|
99
|
-
* @param {maxBytes, idleTimeoutMs, abort} bounds.
|
|
122
|
+
* @param {maxFrameBytes, maxBytes, idleTimeoutMs, abort} bounds. maxFrameBytes bounds a line or event;
|
|
123
|
+
* maxBytes is an optional explicit whole-response ceiling for callers.
|
|
100
124
|
* idleTimeoutMs bounds silence between nonempty frames: when it fires, abort
|
|
101
125
|
* is called with an IdleTimeout so the underlying fetch aborts and the
|
|
102
126
|
* pending read rejects cleanly (no orphaned read to cancel). Throws
|
|
103
127
|
* SseFramingError (terminal) or propagates transport/abort errors.
|
|
104
128
|
*/
|
|
105
|
-
export async function* readModelSse(body, {
|
|
106
|
-
if (!Number.isSafeInteger(
|
|
129
|
+
export async function* readModelSse(body, { maxFrameBytes = 8 * 1024 * 1024, maxBytes, idleTimeoutMs, abort, observeBytes } = {}) {
|
|
130
|
+
if (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0
|
|
131
|
+
|| maxBytes !== undefined && (!Number.isSafeInteger(maxBytes) || maxBytes <= 0)) {
|
|
107
132
|
throw new SseFramingError('model SSE needs a positive byte budget');
|
|
108
133
|
}
|
|
109
134
|
const iter = toAsyncIterator(body);
|
|
110
135
|
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
111
|
-
const framer = new SseFramer();
|
|
112
|
-
let
|
|
136
|
+
const framer = new SseFramer(maxFrameBytes);
|
|
137
|
+
let wireBytes = 0;
|
|
113
138
|
const idleEnabled = typeof idleTimeoutMs === 'number' && idleTimeoutMs > 0 && typeof abort === 'function';
|
|
114
139
|
let idleTimer = null;
|
|
115
140
|
const armIdle = () => {
|
|
@@ -120,7 +145,6 @@ export async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTime
|
|
|
120
145
|
};
|
|
121
146
|
const disarmIdle = () => { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } };
|
|
122
147
|
armIdle();
|
|
123
|
-
const frames = [];
|
|
124
148
|
try {
|
|
125
149
|
while (true) {
|
|
126
150
|
let result;
|
|
@@ -130,18 +154,18 @@ export async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTime
|
|
|
130
154
|
if (!(chunk instanceof Uint8Array) && !(chunk instanceof ArrayBuffer)) {
|
|
131
155
|
throw new SseFramingError('model SSE requires byte chunks');
|
|
132
156
|
}
|
|
133
|
-
total += chunk.byteLength;
|
|
134
157
|
observeBytes?.(chunk.byteLength);
|
|
135
|
-
if (
|
|
158
|
+
if (maxBytes !== undefined) {
|
|
159
|
+
wireBytes += chunk.byteLength;
|
|
160
|
+
if (wireBytes > maxBytes) throw new SseFramingError('model SSE byte budget exceeded', 'body_limit');
|
|
161
|
+
}
|
|
136
162
|
let text;
|
|
137
163
|
try {
|
|
138
164
|
text = decoder.decode(chunk, { stream: true });
|
|
139
165
|
} catch {
|
|
140
166
|
throw new SseFramingError('invalid utf-8 in model stream', 'body_encoding');
|
|
141
167
|
}
|
|
142
|
-
|
|
143
|
-
framer.feed(text, frames);
|
|
144
|
-
for (const frame of frames) {
|
|
168
|
+
for (const frame of framer.feed(text)) {
|
|
145
169
|
yield frame;
|
|
146
170
|
// Time spent by the consumer is not provider idle time. Comments and
|
|
147
171
|
// blank data do not reset the deadline; only nonempty data does.
|
|
@@ -154,11 +178,7 @@ export async function* readModelSse(body, { maxBytes = 8 * 1024 * 1024, idleTime
|
|
|
154
178
|
} catch {
|
|
155
179
|
throw new SseFramingError('invalid utf-8 in model stream', 'body_encoding');
|
|
156
180
|
}
|
|
157
|
-
|
|
158
|
-
frames.length = 0;
|
|
159
|
-
framer.feed(tail, frames);
|
|
160
|
-
for (const frame of frames) yield frame;
|
|
161
|
-
}
|
|
181
|
+
yield* framer.feed(tail);
|
|
162
182
|
framer.finish();
|
|
163
183
|
} finally {
|
|
164
184
|
disarmIdle();
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { ProtocolError } from './model-normalize.mjs';
|
|
2
|
+
|
|
3
|
+
export class ModelStreamLimitError extends ProtocolError {}
|
|
4
|
+
|
|
5
|
+
// Count assembled payload bytes only. Provider envelopes, keepalives and
|
|
6
|
+
// repeated terminal snapshots do not add to the retained content.
|
|
7
|
+
export function createModelStreamBudget(maxOutputBytes, maxToolBytes) {
|
|
8
|
+
let outputBytes = 0;
|
|
9
|
+
const toolBytes = new WeakMap();
|
|
10
|
+
const retain = (bytes, code = 'stream_output_limit') => {
|
|
11
|
+
if (outputBytes + bytes > maxOutputBytes) {
|
|
12
|
+
throw new ModelStreamLimitError('assembled model output exceeded the byte limit', code);
|
|
13
|
+
}
|
|
14
|
+
outputBytes += bytes;
|
|
15
|
+
};
|
|
16
|
+
return {
|
|
17
|
+
output(text) { retain(Buffer.byteLength(text)); },
|
|
18
|
+
// Indexed items also retain state when their payload is empty.
|
|
19
|
+
slot() { retain(128); },
|
|
20
|
+
tool(call, fragment) {
|
|
21
|
+
const bytes = Buffer.byteLength(fragment);
|
|
22
|
+
const total = (toolBytes.get(call) ?? 0) + bytes;
|
|
23
|
+
if (total > maxToolBytes) {
|
|
24
|
+
throw new ModelStreamLimitError('assembled tool input exceeded the byte limit', 'tool_argument_limit');
|
|
25
|
+
}
|
|
26
|
+
// A tool fragment exhausting the shared budget also needs smaller calls.
|
|
27
|
+
retain(bytes, 'tool_argument_limit');
|
|
28
|
+
toolBytes.set(call, total);
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -39,6 +39,11 @@ function modelFailureMessage(value, retriesExhausted = false) {
|
|
|
39
39
|
if (value.code === 'host_binding') return '模型连接配置未能加载,请检查运行配置。';
|
|
40
40
|
if (value.phase === 'request') return '模型请求在发送前未通过校验,请查看运行诊断。';
|
|
41
41
|
if (value.code === 'stream_timeout' || value.code === 'http_timeout') return '等待模型服务响应超时,本次运行未能完成。';
|
|
42
|
+
if (value.code === 'body_limit') return '模型响应超过大小上限,本次运行已停止。';
|
|
43
|
+
if (value.code === 'stream_frame_limit') return '模型响应中的单个流式事件超过大小上限。';
|
|
44
|
+
if (value.code === 'stream_output_limit') return '模型本次输出的内容超过大小上限。';
|
|
45
|
+
if (value.code === 'tool_argument_limit') return '模型生成的工具参数超过大小上限,本批工具未执行。';
|
|
46
|
+
if (value.code === 'stream_incomplete') return '模型响应中途结束,未收到完整结果。';
|
|
42
47
|
if (value.code === 'transport_error') return '与模型服务的连接中断,本次运行未能完成。';
|
|
43
48
|
if (value.code === 'provider_error' || value.code === 'http_server') return '模型服务返回执行错误,本次运行未能完成。';
|
|
44
49
|
if (value.phase === 'stream' || value.phase === 'buffered') return '模型响应未通过协议校验,本次运行已停止,请查看运行诊断。';
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
|
|
4
|
+
// Windows mode bits and uid do not describe NTFS access. Resolve security
|
|
5
|
+
// identifiers directly so the check does not depend on localized account names.
|
|
6
|
+
const checkAcl = Buffer.from(String.raw`
|
|
7
|
+
$ErrorActionPreference = 'Stop'
|
|
8
|
+
$sidType = [System.Security.Principal.SecurityIdentifier]
|
|
9
|
+
$user = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
|
10
|
+
$trusted = @($user, 'S-1-5-18', 'S-1-5-32-544')
|
|
11
|
+
$acl = Microsoft.PowerShell.Security\Get-Acl -LiteralPath $env:AGENTKIT_WINDOWS_PRIVATE_STATE_PATH
|
|
12
|
+
if ($acl.GetOwner($sidType).Value -notin $trusted) { exit 2 }
|
|
13
|
+
foreach ($entry in $acl.GetAccessRules($true, $true, $sidType)) {
|
|
14
|
+
if ($entry.AccessControlType -ne 'Allow') { continue }
|
|
15
|
+
$principal = $entry.IdentityReference.Value
|
|
16
|
+
if ($principal -in $trusted) { continue }
|
|
17
|
+
$inheritOnly = $entry.PropagationFlags -band [System.Security.AccessControl.PropagationFlags]::InheritOnly
|
|
18
|
+
if ($principal -eq 'S-1-3-0' -and $inheritOnly) { continue }
|
|
19
|
+
exit 2
|
|
20
|
+
}
|
|
21
|
+
`, 'utf16le').toString('base64');
|
|
22
|
+
|
|
23
|
+
const verified = new Map();
|
|
24
|
+
|
|
25
|
+
export function verifyWindowsPrivateState(path, stat) {
|
|
26
|
+
const identity = [stat.dev, stat.ino, stat.birthtimeMs, stat.ctimeMs].join(':');
|
|
27
|
+
if (verified.get(path) === identity) return true;
|
|
28
|
+
const root = process.env.SystemRoot;
|
|
29
|
+
if (!root) return false;
|
|
30
|
+
const executable = join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
31
|
+
const result = spawnSync(executable, ['-NoLogo', '-NoProfile', '-NonInteractive', '-EncodedCommand', checkAcl], {
|
|
32
|
+
env: { SystemRoot: root, AGENTKIT_WINDOWS_PRIVATE_STATE_PATH: path },
|
|
33
|
+
stdio: 'ignore', windowsHide: true, timeout: 5000,
|
|
34
|
+
});
|
|
35
|
+
if (result.status !== 0 || result.error) return false;
|
|
36
|
+
// Only the accepted principals can change an accepted ACL. File replacement
|
|
37
|
+
// or metadata changes require a fresh check.
|
|
38
|
+
if (verified.size >= 1024) verified.clear();
|
|
39
|
+
verified.set(path, identity);
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* JSON files for audit/inspection only.
|
|
22
22
|
*/
|
|
23
23
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
24
|
-
import { isAbsolute, join } from 'node:path';
|
|
24
|
+
import { basename, dirname, isAbsolute, join } from 'node:path';
|
|
25
25
|
import { createHash, randomUUID } from 'node:crypto';
|
|
26
26
|
|
|
27
27
|
const READ_STATE_VERSION = 'native-workspace-read-state/v1';
|
|
@@ -244,9 +244,9 @@ export class WorkspaceStateStore {
|
|
|
244
244
|
|
|
245
245
|
/** Write JSON atomically (temp sibling + rename) to avoid torn reads on restart. */
|
|
246
246
|
export function atomicWriteJson(dest, value) {
|
|
247
|
-
const dir =
|
|
247
|
+
const dir = dirname(dest);
|
|
248
248
|
mkdirSync(dir, { recursive: true });
|
|
249
|
-
const tmp = join(dir, `.${dest
|
|
249
|
+
const tmp = join(dir, `.${basename(dest)}.tmp-${process.pid}-${Math.random().toString(36).slice(2)}`);
|
|
250
250
|
writeFileSync(tmp, JSON.stringify(value), 'utf-8');
|
|
251
251
|
renameSync(tmp, dest);
|
|
252
252
|
}
|
|
@@ -22,7 +22,7 @@ import {
|
|
|
22
22
|
readFileSync, readlinkSync, readSync, realpathSync, rmdirSync, statSync,
|
|
23
23
|
unlinkSync,
|
|
24
24
|
} from 'node:fs';
|
|
25
|
-
import { join } from 'node:path';
|
|
25
|
+
import { basename, join } from 'node:path';
|
|
26
26
|
import { checkPythonSyntax, NATIVE_PYTHON_SYNTAX } from './python-syntax.mjs';
|
|
27
27
|
import { acquireWorkspaceMutationLock, workspaceMutationGuard } from './workspace-mutation-lock.mjs';
|
|
28
28
|
import { budgetWorkspaceSourcePage, validateSourcePageBudget } from './source-page.mjs';
|
|
@@ -247,7 +247,7 @@ export function createNativeWorkspaceTools({
|
|
|
247
247
|
const items = []; // {abs, name}
|
|
248
248
|
const targetInfo = lstatSync(target, { bigint: true });
|
|
249
249
|
if (targetInfo.isFile()) {
|
|
250
|
-
items.push({ abs: target, name: target
|
|
250
|
+
items.push({ abs: target, name: basename(target) });
|
|
251
251
|
} else if (targetInfo.isDirectory()) {
|
|
252
252
|
const stack = [target];
|
|
253
253
|
while (stack.length) {
|
|
@@ -918,7 +918,7 @@ export function createNativeWorkspaceTools({
|
|
|
918
918
|
if (glob) {
|
|
919
919
|
filtered = candidates.filter((c) => {
|
|
920
920
|
const rel = relativeOf(c);
|
|
921
|
-
return fnmatch(rel, glob) || fnmatch(c
|
|
921
|
+
return fnmatch(rel, glob) || fnmatch(basename(c), glob);
|
|
922
922
|
});
|
|
923
923
|
}
|
|
924
924
|
let pattern;
|