@ai-workbench/remote-agent 0.9.0-toolbridge.7 → 0.9.0-toolbridge.9
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/README.md +2 -11
- package/dist/acp.d.ts +0 -4
- package/dist/acp.js +6 -42
- package/dist/agents.d.ts +0 -2
- package/dist/agents.js +3 -4
- package/dist/claude-local.d.ts +0 -1
- package/dist/claude-local.js +2 -2
- package/dist/client.js +1 -1
- package/dist/employee-mcp.d.ts +24 -8
- package/dist/employee-mcp.js +188 -24
- package/dist/employee-tools.d.ts +22 -5
- package/dist/employee-tools.js +292 -4
- package/dist/index.d.ts +0 -4
- package/dist/index.js +19 -34
- package/dist/model-catalog.d.ts +3 -1
- package/dist/model-catalog.js +5 -5
- package/dist/presentation.js +1 -1
- package/dist/provider.js +2 -4
- package/dist/toolbridge-loop.js +0 -3
- package/dist/toolbridge-table.js +1 -4
- package/dist/toolbridge.d.ts +0 -1
- package/dist/toolbridge.js +0 -1
- package/helpers/ripgrep/LICENSE-vscode +13 -0
- package/helpers/ripgrep/PROVENANCE.md +9 -0
- package/helpers/ripgrep/darwin-arm64/rg +0 -0
- package/helpers/ripgrep/darwin-x64/rg +0 -0
- package/helpers/ripgrep/manifest.json +56 -0
- package/helpers/ripgrep/notices/COPYING-ripgrep +3 -0
- package/helpers/ripgrep/notices/DEPENDENCIES.json +946 -0
- package/helpers/ripgrep/notices/LICENCE-PCRE2.md +103 -0
- package/helpers/ripgrep/notices/LICENSE-MIT-ripgrep +21 -0
- package/helpers/ripgrep/notices/UNLICENSE-ripgrep +24 -0
- package/helpers/ripgrep/notices/aho-corasick-1.1.3/COPYING +3 -0
- package/helpers/ripgrep/notices/aho-corasick-1.1.3/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/aho-corasick-1.1.3/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/anyhow-1.0.100/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/anyhow-1.0.100/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/arbitrary-1.4.2/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/arbitrary-1.4.2/LICENSE-MIT +27 -0
- package/helpers/ripgrep/notices/bstr-1.12.0/COPYING +8 -0
- package/helpers/ripgrep/notices/bstr-1.12.0/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/bstr-1.12.0/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/cc-1.2.41/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/cc-1.2.41/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/cfg-if-1.0.4/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/cfg-if-1.0.4/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/crossbeam-channel-0.5.15/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/crossbeam-channel-0.5.15/LICENSE-MIT +27 -0
- package/helpers/ripgrep/notices/crossbeam-channel-0.5.15/LICENSE-THIRD-PARTY +593 -0
- package/helpers/ripgrep/notices/crossbeam-deque-0.8.6/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/crossbeam-deque-0.8.6/LICENSE-MIT +27 -0
- package/helpers/ripgrep/notices/crossbeam-epoch-0.9.18/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/crossbeam-epoch-0.9.18/LICENSE-MIT +27 -0
- package/helpers/ripgrep/notices/crossbeam-utils-0.8.21/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/crossbeam-utils-0.8.21/LICENSE-MIT +27 -0
- package/helpers/ripgrep/notices/derive_arbitrary-1.4.2/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/derive_arbitrary-1.4.2/LICENSE-MIT +27 -0
- package/helpers/ripgrep/notices/encoding_rs-0.8.35/COPYRIGHT +17 -0
- package/helpers/ripgrep/notices/encoding_rs-0.8.35/LICENSE-APACHE +202 -0
- package/helpers/ripgrep/notices/encoding_rs-0.8.35/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/encoding_rs-0.8.35/LICENSE-WHATWG +26 -0
- package/helpers/ripgrep/notices/encoding_rs_io-0.1.7/COPYING +8 -0
- package/helpers/ripgrep/notices/encoding_rs_io-0.1.7/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/encoding_rs_io-0.1.7/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/find-msvc-tools-0.1.4/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/find-msvc-tools-0.1.4/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/getrandom-0.3.4/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/getrandom-0.3.4/LICENSE-MIT +26 -0
- package/helpers/ripgrep/notices/glob-0.3.3/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/glob-0.3.3/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/itoa-1.0.15/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/itoa-1.0.15/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/jobserver-0.1.34/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/jobserver-0.1.34/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/lexopt-0.3.1/LICENSE +19 -0
- package/helpers/ripgrep/notices/libc-0.2.177/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/libc-0.2.177/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/log-0.4.28/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/log-0.4.28/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/memchr-2.7.6/COPYING +3 -0
- package/helpers/ripgrep/notices/memchr-2.7.6/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/memchr-2.7.6/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/memmap2-0.9.8/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/memmap2-0.9.8/LICENSE-MIT +26 -0
- package/helpers/ripgrep/notices/msvc_spectre_libs-0.1.3/LICENSE +21 -0
- package/helpers/ripgrep/notices/pcre2-0.2.11/COPYING +3 -0
- package/helpers/ripgrep/notices/pcre2-0.2.11/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/pcre2-0.2.11/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/pcre2-sys-0.2.10/COPYING +3 -0
- package/helpers/ripgrep/notices/pcre2-sys-0.2.10/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/pcre2-sys-0.2.10/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/pkg-config-0.3.32/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/pkg-config-0.3.32/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/proc-macro2-1.0.101/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/proc-macro2-1.0.101/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/quote-1.0.41/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/quote-1.0.41/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/r-efi-5.3.0/AUTHORS +74 -0
- package/helpers/ripgrep/notices/regex-1.12.2/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/regex-1.12.2/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/regex-automata-0.4.13/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/regex-automata-0.4.13/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/regex-syntax-0.8.8/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/regex-syntax-0.8.8/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/regex-syntax-0.8.8/src/unicode_tables/LICENSE-UNICODE +57 -0
- package/helpers/ripgrep/notices/ryu-1.0.20/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/ryu-1.0.20/LICENSE-BOOST +23 -0
- package/helpers/ripgrep/notices/same-file-1.0.6/COPYING +3 -0
- package/helpers/ripgrep/notices/same-file-1.0.6/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/same-file-1.0.6/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/serde-1.0.228/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/serde-1.0.228/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/serde_core-1.0.228/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/serde_core-1.0.228/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/serde_derive-1.0.228/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/serde_derive-1.0.228/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/serde_json-1.0.145/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/serde_json-1.0.145/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/shlex-1.3.0/LICENSE-APACHE +13 -0
- package/helpers/ripgrep/notices/shlex-1.3.0/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/syn-2.0.106/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/syn-2.0.106/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/termcolor-1.4.1/COPYING +3 -0
- package/helpers/ripgrep/notices/termcolor-1.4.1/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/termcolor-1.4.1/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/textwrap-0.16.2/LICENSE +21 -0
- package/helpers/ripgrep/notices/tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/jemalloc/COPYING +27 -0
- package/helpers/ripgrep/notices/tikv-jemallocator-0.6.0/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/tikv-jemallocator-0.6.0/LICENSE-MIT +25 -0
- package/helpers/ripgrep/notices/unicode-ident-1.0.19/LICENSE-APACHE +176 -0
- package/helpers/ripgrep/notices/unicode-ident-1.0.19/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/unicode-ident-1.0.19/LICENSE-UNICODE +39 -0
- package/helpers/ripgrep/notices/walkdir-2.5.0/COPYING +3 -0
- package/helpers/ripgrep/notices/walkdir-2.5.0/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/walkdir-2.5.0/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/wasip2-1.0.1+wasi-0.2.4/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/wasip2-1.0.1+wasi-0.2.4/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/helpers/ripgrep/notices/wasip2-1.0.1+wasi-0.2.4/LICENSE-MIT +23 -0
- package/helpers/ripgrep/notices/winapi-util-0.1.11/COPYING +3 -0
- package/helpers/ripgrep/notices/winapi-util-0.1.11/LICENSE-MIT +21 -0
- package/helpers/ripgrep/notices/winapi-util-0.1.11/UNLICENSE +24 -0
- package/helpers/ripgrep/notices/windows-link-0.2.1/license-apache-2.0 +201 -0
- package/helpers/ripgrep/notices/windows-link-0.2.1/license-mit +21 -0
- package/helpers/ripgrep/notices/windows-sys-0.61.2/license-apache-2.0 +201 -0
- package/helpers/ripgrep/notices/windows-sys-0.61.2/license-mit +21 -0
- package/helpers/ripgrep/notices/wit-bindgen-0.46.0/LICENSE-APACHE +201 -0
- package/helpers/ripgrep/notices/wit-bindgen-0.46.0/LICENSE-Apache-2.0_WITH_LLVM-exception +220 -0
- package/helpers/ripgrep/notices/wit-bindgen-0.46.0/LICENSE-MIT +23 -0
- package/package.json +20 -21
- package/dist/cloud-failure.d.ts +0 -11
- package/dist/cloud-failure.js +0 -54
package/dist/employee-tools.js
CHANGED
|
@@ -1,5 +1,293 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomUUID, createHash } from 'node:crypto';
|
|
3
|
+
import { readFile, writeFile, mkdir, glob, lstat, access, realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { resolve, dirname, isAbsolute, basename, join } from 'node:path';
|
|
6
|
+
import { fileURLToPath } from 'node:url';
|
|
2
7
|
import { NeedError } from "./remote.js";
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
8
|
+
export const EMPLOYEE_TOOL_NAMES = ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'];
|
|
9
|
+
const failure = (code) => new NeedError(code, '本机工具未完成(' + code + '),没有改到主机执行。', '本机实际执行能力;技术详情保留当前结果');
|
|
10
|
+
function object(value) { if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
11
|
+
throw failure('EMPLOYEE_ARGUMENT_INVALID'); return value; }
|
|
12
|
+
function string(args, key, required = true) {
|
|
13
|
+
const v = args[key];
|
|
14
|
+
if (v === undefined && !required)
|
|
15
|
+
return;
|
|
16
|
+
if (typeof v !== 'string' || v.includes('\0') || (required && !v))
|
|
17
|
+
throw failure('EMPLOYEE_ARGUMENT_INVALID');
|
|
18
|
+
return v;
|
|
19
|
+
}
|
|
20
|
+
function integer(args, key, min) { const v = args[key]; if (v === undefined)
|
|
21
|
+
return; if (!Number.isSafeInteger(v) || v < min)
|
|
22
|
+
throw failure('EMPLOYEE_ARGUMENT_INVALID'); return v; }
|
|
23
|
+
function boolean(args, key) { const v = args[key]; if (v === undefined)
|
|
24
|
+
return; if (typeof v !== 'boolean')
|
|
25
|
+
throw failure('EMPLOYEE_ARGUMENT_INVALID'); return v; }
|
|
26
|
+
function fields(args, allowed) { if (Object.keys(args).some(k => !allowed.includes(k)))
|
|
27
|
+
throw failure('EMPLOYEE_ARGUMENT_UNSUPPORTED'); }
|
|
28
|
+
function text(value) { return { content: [{ type: 'text', text: value }] }; }
|
|
29
|
+
// Shared across this plugin's sessions: protect the entire read/modify/write, not just writeFile.
|
|
30
|
+
const fileQueues = new Map();
|
|
31
|
+
async function serialized(key, work) {
|
|
32
|
+
const previous = fileQueues.get(key) ?? Promise.resolve();
|
|
33
|
+
let release = () => { };
|
|
34
|
+
const next = new Promise(yes => { release = yes; });
|
|
35
|
+
fileQueues.set(key, next);
|
|
36
|
+
await previous;
|
|
37
|
+
try {
|
|
38
|
+
return await work();
|
|
39
|
+
}
|
|
40
|
+
finally {
|
|
41
|
+
release();
|
|
42
|
+
if (fileQueues.get(key) === next)
|
|
43
|
+
fileQueues.delete(key);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function canonicalFile(path) {
|
|
47
|
+
try {
|
|
48
|
+
return await realpath(path);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
if (error.code !== 'ENOENT')
|
|
52
|
+
throw error;
|
|
53
|
+
const parent = dirname(path);
|
|
54
|
+
if (parent === path)
|
|
55
|
+
throw error;
|
|
56
|
+
return join(await canonicalFile(parent), basename(path));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
async function mutate(path, signal, work) {
|
|
60
|
+
return serialized('path:' + await canonicalFile(path), async () => {
|
|
61
|
+
signal.throwIfAborted();
|
|
62
|
+
let inode;
|
|
63
|
+
try {
|
|
64
|
+
const info = await stat(path);
|
|
65
|
+
inode = `inode:${info.dev}:${info.ino}`;
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
if (error.code !== 'ENOENT')
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
const perform = () => { signal.throwIfAborted(); return work(); };
|
|
72
|
+
return inode ? serialized(inode, perform) : perform();
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
async function bundledRipgrep() {
|
|
76
|
+
if (process.platform !== 'darwin' || !['arm64', 'x64'].includes(process.arch))
|
|
77
|
+
throw failure('EMPLOYEE_PLATFORM_UNSUPPORTED');
|
|
78
|
+
const root = new URL('./helpers/ripgrep/', import.meta.resolve('@ai-workbench/remote-agent/package.json'));
|
|
79
|
+
const manifest = JSON.parse(await readFile(new URL('manifest.json', root), 'utf8'));
|
|
80
|
+
const arch = 'darwin-' + process.arch, path = fileURLToPath(new URL(arch + '/rg', root)), entry = manifest.files[arch];
|
|
81
|
+
const info = await lstat(path);
|
|
82
|
+
if (!entry || !info.isFile() || info.isSymbolicLink() || info.size !== entry.bytes || createHash('sha256').update(await readFile(path)).digest('hex') !== entry.sha256)
|
|
83
|
+
throw failure('EMPLOYEE_SEARCH_COMPONENT_INVALID');
|
|
84
|
+
await access(path, constants.X_OK);
|
|
85
|
+
return path;
|
|
86
|
+
}
|
|
87
|
+
/** Executed only in the employee DSH process; never creates a host fallback. */
|
|
88
|
+
export function createEmployeeTools(options) {
|
|
89
|
+
if (!isAbsolute(options.cwd) || !isAbsolute(options.shell) || !Number.isSafeInteger(options.uid) || options.uid !== process.getuid?.() || !Number.isSafeInteger(options.maxBytes) || options.maxBytes < 1 || !Number.isSafeInteger(options.killGraceMs) || options.killGraceMs < 0)
|
|
90
|
+
throw failure('EMPLOYEE_CONTEXT_INVALID');
|
|
91
|
+
const lifetime = new AbortController(), children = new Set(), calls = new Set();
|
|
92
|
+
const path = (value) => resolve(options.cwd, value);
|
|
93
|
+
const capacity = (value) => { if (Buffer.byteLength(value) > options.maxBytes)
|
|
94
|
+
throw failure('EMPLOYEE_OUTPUT_TOO_LARGE'); };
|
|
95
|
+
async function run(command, args, signal, detail, timeout) {
|
|
96
|
+
signal.throwIfAborted();
|
|
97
|
+
const diagnostics = options.closeDiagnostics?.child(detail);
|
|
98
|
+
const operation = new Promise((yes, no) => {
|
|
99
|
+
const child = spawn(command, args, { cwd: options.cwd, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
100
|
+
child.stdin.end();
|
|
101
|
+
let bytes = 0, stdout = [], stderr = [], failed, killTimer, timeoutTimer;
|
|
102
|
+
const kill = (which) => { diagnostics?.record({ layer: 'executor', initiator: 'tools.process-kill', reason: failed?.code ?? 'PROCESS_CLEANUP', action: 'terminate', signal: which }); if (child.exitCode === null && child.signalCode === null)
|
|
103
|
+
child.kill(which); };
|
|
104
|
+
const stop = (code) => { diagnostics?.record({ layer: 'executor', initiator: 'tools.process-stop', reason: code, action: 'terminate', changes: [{ field: 'tools.stop-code', before: failed?.code ?? null, after: failed?.code ?? code }] }); if (failed)
|
|
105
|
+
return; failed = failure(code); kill('SIGTERM'); killTimer = setTimeout(() => kill('SIGKILL'), options.killGraceMs); killTimer.unref(); };
|
|
106
|
+
const aborted = () => stop('EMPLOYEE_CANCELLED_UNKNOWN');
|
|
107
|
+
const collect = (dest, chunk) => { bytes += chunk.length; if (bytes > options.maxBytes) {
|
|
108
|
+
stop('EMPLOYEE_OUTPUT_TOO_LARGE_UNKNOWN');
|
|
109
|
+
return;
|
|
110
|
+
} dest.push(chunk); };
|
|
111
|
+
child.stdout.on('data', (b) => collect(stdout, b));
|
|
112
|
+
child.stderr.on('data', (b) => collect(stderr, b));
|
|
113
|
+
child.on('spawn', () => { try {
|
|
114
|
+
detail({ kind: 'session', severity: 'info', code: 'CLAUDE_EMPLOYEE_PROCESS', summary: '本机工具子进程', payload: { childPid: child.pid ?? null, uid: options.uid, cwd: options.cwd } });
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
stop('CONVERSATION_DETAILS_FAILED');
|
|
118
|
+
} if (signal.aborted)
|
|
119
|
+
aborted(); });
|
|
120
|
+
child.on('error', e => { diagnostics?.record({ layer: 'executor', initiator: 'tools.process-error', reason: e.code === 'ENOENT' ? 'EMPLOYEE_COMMAND_UNAVAILABLE' : 'EMPLOYEE_PROCESS_FAILED', action: 'failure' }); failed ??= failure(e.code === 'ENOENT' ? 'EMPLOYEE_COMMAND_UNAVAILABLE' : 'EMPLOYEE_PROCESS_FAILED'); });
|
|
121
|
+
child.on('close', (exitCode, exitSignal) => { diagnostics?.record({ layer: 'executor', initiator: 'tools.process-close', reason: failed?.code ?? 'PROCESS_EXIT', action: 'exit', exitCode, signal: exitSignal }); signal.removeEventListener('abort', aborted); if (killTimer)
|
|
122
|
+
clearTimeout(killTimer); if (timeoutTimer)
|
|
123
|
+
clearTimeout(timeoutTimer); failed ? no(failed) : yes({ stdout: Buffer.concat(stdout).toString('utf8'), stderr: Buffer.concat(stderr).toString('utf8'), exitCode, signal: exitSignal }); });
|
|
124
|
+
signal.addEventListener('abort', aborted, { once: true });
|
|
125
|
+
if (signal.aborted)
|
|
126
|
+
aborted();
|
|
127
|
+
if (timeout !== undefined) {
|
|
128
|
+
timeoutTimer = setTimeout(() => stop('EMPLOYEE_TIMEOUT_UNKNOWN'), timeout);
|
|
129
|
+
timeoutTimer.unref();
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
children.add(operation);
|
|
133
|
+
try {
|
|
134
|
+
return await operation;
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
children.delete(operation);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
async function execute(name, args, signal, detail) {
|
|
141
|
+
const check = () => signal.throwIfAborted();
|
|
142
|
+
if (name === 'Read') {
|
|
143
|
+
fields(args, ['file_path', 'offset', 'limit', 'pages']);
|
|
144
|
+
if (args.pages !== undefined)
|
|
145
|
+
throw failure('EMPLOYEE_READ_PDF_UNSUPPORTED');
|
|
146
|
+
const target = path(string(args, 'file_path')), offset = integer(args, 'offset', 1) ?? 1, limit = integer(args, 'limit', 1);
|
|
147
|
+
const info = await lstat(target);
|
|
148
|
+
if (info.size > options.maxBytes)
|
|
149
|
+
throw failure('EMPLOYEE_OUTPUT_TOO_LARGE');
|
|
150
|
+
const bytes = await readFile(target, { signal });
|
|
151
|
+
check();
|
|
152
|
+
capacity(bytes);
|
|
153
|
+
const magic = bytes.subarray(0, 16), mime = magic[0] === 137 && magic.subarray(1, 4).toString() === 'PNG' ? 'image/png' : magic[0] === 255 && magic[1] === 216 ? 'image/jpeg' : magic.subarray(0, 4).toString() === 'RIFF' && magic.subarray(8, 12).toString() === 'WEBP' ? 'image/webp' : magic.subarray(0, 3).toString() === 'GIF' ? 'image/gif' : undefined;
|
|
154
|
+
if (mime) {
|
|
155
|
+
if (args.offset !== undefined || args.limit !== undefined)
|
|
156
|
+
throw failure('EMPLOYEE_IMAGE_RANGE_UNSUPPORTED');
|
|
157
|
+
return { content: [{ type: 'image', mimeType: mime, data: bytes.toString('base64') }] };
|
|
158
|
+
}
|
|
159
|
+
let contents;
|
|
160
|
+
try {
|
|
161
|
+
contents = new TextDecoder('utf8', { fatal: true }).decode(bytes);
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
throw failure('EMPLOYEE_READ_BINARY_UNSUPPORTED');
|
|
165
|
+
}
|
|
166
|
+
if (contents.includes('\0') || contents.startsWith('%PDF-'))
|
|
167
|
+
throw failure('EMPLOYEE_READ_BINARY_UNSUPPORTED');
|
|
168
|
+
const lines = contents.split('\n'), selected = lines.slice(offset - 1, limit === undefined ? undefined : offset - 1 + limit);
|
|
169
|
+
return text(selected.map((line, i) => String(offset + i) + '\t' + line).join('\n'));
|
|
170
|
+
}
|
|
171
|
+
if (name === 'Write') {
|
|
172
|
+
fields(args, ['file_path', 'content']);
|
|
173
|
+
const target = path(string(args, 'file_path')), content = string(args, 'content', false);
|
|
174
|
+
if (content === undefined)
|
|
175
|
+
throw failure('EMPLOYEE_ARGUMENT_INVALID');
|
|
176
|
+
capacity(content);
|
|
177
|
+
await mutate(target, signal, async () => { check(); await mkdir(dirname(target), { recursive: true }); check(); await writeFile(target, content, { signal }); });
|
|
178
|
+
return text('文件已写入:' + target);
|
|
179
|
+
}
|
|
180
|
+
if (name === 'Edit') {
|
|
181
|
+
fields(args, ['file_path', 'old_string', 'new_string', 'replace_all']);
|
|
182
|
+
const target = path(string(args, 'file_path')), old = string(args, 'old_string', false), replacement = string(args, 'new_string', false), all = boolean(args, 'replace_all') ?? false;
|
|
183
|
+
if (old === undefined || replacement === undefined || !old)
|
|
184
|
+
throw failure('EMPLOYEE_EDIT_EMPTY_MATCH_UNSUPPORTED');
|
|
185
|
+
return mutate(target, signal, async () => {
|
|
186
|
+
const bytes = await readFile(target, { signal });
|
|
187
|
+
capacity(bytes);
|
|
188
|
+
let content;
|
|
189
|
+
try {
|
|
190
|
+
content = new TextDecoder('utf8', { fatal: true, ignoreBOM: true }).decode(bytes);
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
throw failure('EMPLOYEE_READ_BINARY_UNSUPPORTED');
|
|
194
|
+
}
|
|
195
|
+
const matches = content.split(old).length - 1;
|
|
196
|
+
if (!matches)
|
|
197
|
+
throw failure('EMPLOYEE_EDIT_NOT_FOUND');
|
|
198
|
+
if (matches > 1 && !all)
|
|
199
|
+
throw failure('EMPLOYEE_EDIT_AMBIGUOUS');
|
|
200
|
+
const next = all ? content.replaceAll(old, () => replacement) : content.replace(old, () => replacement);
|
|
201
|
+
capacity(next);
|
|
202
|
+
check();
|
|
203
|
+
await writeFile(target, next, { signal });
|
|
204
|
+
return text('文件已修改:' + target);
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
if (name === 'Glob') {
|
|
208
|
+
fields(args, ['pattern', 'path']);
|
|
209
|
+
const pattern = string(args, 'pattern'), cwd = path(string(args, 'path', false) ?? '.'), found = [];
|
|
210
|
+
for await (const item of glob(pattern, { cwd })) {
|
|
211
|
+
check();
|
|
212
|
+
found.push(resolve(cwd, item));
|
|
213
|
+
capacity(JSON.stringify(found));
|
|
214
|
+
}
|
|
215
|
+
return text(JSON.stringify(found));
|
|
216
|
+
}
|
|
217
|
+
if (name === 'Grep') {
|
|
218
|
+
fields(args, ['pattern', 'path', 'glob', 'output_mode', '-B', '-A', '-C', '-n', '-i', 'type', 'head_limit', 'offset', 'multiline']);
|
|
219
|
+
const pattern = string(args, 'pattern'), mode = string(args, 'output_mode', false) ?? 'files_with_matches', argv = ['--hidden', '--pcre2', '--color', 'never'];
|
|
220
|
+
if (mode === 'files_with_matches')
|
|
221
|
+
argv.push('--files-with-matches');
|
|
222
|
+
else if (mode === 'count')
|
|
223
|
+
argv.push('--count');
|
|
224
|
+
else if (mode !== 'content')
|
|
225
|
+
throw failure('EMPLOYEE_ARGUMENT_UNSUPPORTED');
|
|
226
|
+
for (const flag of ['-B', '-A', '-C']) {
|
|
227
|
+
const value = integer(args, flag, 0);
|
|
228
|
+
if (value !== undefined)
|
|
229
|
+
argv.push(flag, String(value));
|
|
230
|
+
}
|
|
231
|
+
if (boolean(args, '-n'))
|
|
232
|
+
argv.push('--line-number');
|
|
233
|
+
if (boolean(args, '-i'))
|
|
234
|
+
argv.push('--ignore-case');
|
|
235
|
+
if (boolean(args, 'multiline'))
|
|
236
|
+
argv.push('--multiline', '--multiline-dotall');
|
|
237
|
+
for (const [key, flag] of [['glob', '--glob'], ['type', '--type']]) {
|
|
238
|
+
const v = string(args, key, false);
|
|
239
|
+
if (v !== undefined)
|
|
240
|
+
argv.push(flag, v);
|
|
241
|
+
}
|
|
242
|
+
argv.push('--', pattern, path(string(args, 'path', false) ?? '.'));
|
|
243
|
+
const result = await run(options.rgPath ?? await bundledRipgrep(), argv, signal, detail);
|
|
244
|
+
if (result.exitCode !== 0 && result.exitCode !== 1)
|
|
245
|
+
return { isError: true, content: [{ type: 'text', text: JSON.stringify(result) }] };
|
|
246
|
+
const offset = integer(args, 'offset', 0) ?? 0, limit = integer(args, 'head_limit', 0), lines = result.stdout.split('\n');
|
|
247
|
+
return text(lines.slice(offset, limit === undefined || limit === 0 ? undefined : offset + limit).join('\n'));
|
|
248
|
+
}
|
|
249
|
+
fields(args, ['command', 'timeout', 'description', 'run_in_background', 'dangerouslyDisableSandbox']);
|
|
250
|
+
if (boolean(args, 'run_in_background'))
|
|
251
|
+
throw failure('EMPLOYEE_BACKGROUND_UNSUPPORTED');
|
|
252
|
+
boolean(args, 'dangerouslyDisableSandbox');
|
|
253
|
+
string(args, 'description', false);
|
|
254
|
+
const timeout = integer(args, 'timeout', 1);
|
|
255
|
+
if (timeout !== undefined && timeout > 2147483647)
|
|
256
|
+
throw failure('EMPLOYEE_ARGUMENT_INVALID');
|
|
257
|
+
const command = string(args, 'command');
|
|
258
|
+
if (!options.runShell)
|
|
259
|
+
throw failure('EMPLOYEE_SHELL_ENDPOINT_UNAVAILABLE');
|
|
260
|
+
const result = await options.runShell({ command, signal, ...timeout === undefined ? {} : { timeout } });
|
|
261
|
+
return { ...text(JSON.stringify(result)), ...(result.exitCode !== 0 || result.signal ? { isError: true } : {}) };
|
|
262
|
+
}
|
|
263
|
+
async function call(name, input, requestSignal, observer = options.detail) {
|
|
264
|
+
const signal = AbortSignal.any([lifetime.signal, ...requestSignal ? [requestSignal] : []]);
|
|
265
|
+
signal.throwIfAborted();
|
|
266
|
+
const executionId = randomUUID();
|
|
267
|
+
let submitted = false;
|
|
268
|
+
const detail = (status, code) => observer({ kind: 'session', severity: status === 'completed' ? 'info' : 'warning', code: 'CLAUDE_EMPLOYEE_OPERATION', summary: 'Claude本机工具执行位置与结果', payload: { executionId, operation: name, status, ...code ? { reason: code } : {}, cwd: options.cwd, uid: options.uid, pid: process.pid } });
|
|
269
|
+
try {
|
|
270
|
+
if (!EMPLOYEE_TOOL_NAMES.includes(name))
|
|
271
|
+
throw failure('EMPLOYEE_TOOL_UNSUPPORTED');
|
|
272
|
+
await options.validate(signal);
|
|
273
|
+
signal.throwIfAborted();
|
|
274
|
+
submitted = true;
|
|
275
|
+
detail('started');
|
|
276
|
+
const result = await execute(name, object(input), signal, observer);
|
|
277
|
+
detail(result.isError ? 'failed' : 'completed');
|
|
278
|
+
await options.validate(signal);
|
|
279
|
+
signal.throwIfAborted();
|
|
280
|
+
capacity(JSON.stringify(result));
|
|
281
|
+
return result;
|
|
282
|
+
}
|
|
283
|
+
catch (error) {
|
|
284
|
+
const code = error instanceof NeedError ? error.code : signal.aborted ? 'EMPLOYEE_CANCELLED_UNKNOWN' : typeof error?.code === 'string' ? 'EMPLOYEE_IO_' + error.code : 'EMPLOYEE_OPERATION_FAILED';
|
|
285
|
+
detail(submitted && signal.aborted ? 'unknown' : 'failed', code);
|
|
286
|
+
return { isError: true, content: [{ type: 'text', text: code + ':本机操作未完成;没有在主机代跑。' }] };
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
return {
|
|
290
|
+
call(name, input, requestSignal, observer) { const operation = call(name, input, requestSignal, observer); calls.add(operation); void operation.then(() => calls.delete(operation), () => calls.delete(operation)); return operation; },
|
|
291
|
+
async close(cause = { layer: 'executor', initiator: 'tools.close', reason: 'EMPLOYEE_TOOLS_CLOSED', action: 'close' }) { options.closeDiagnostics?.record({ ...cause, changes: cause.changes ?? [{ field: 'tools.aborted', before: lifetime.signal.aborted, after: true }] }); lifetime.abort(); await Promise.allSettled([...calls, ...children]); },
|
|
292
|
+
};
|
|
293
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -19,16 +19,13 @@ export declare const DEFAULT_CONFIG: Readonly<{
|
|
|
19
19
|
readonly brokerMaxFrameBytes: 2097152;
|
|
20
20
|
readonly brokerControlMaxBytes: 1048576;
|
|
21
21
|
readonly employeeShellKillGraceMs: 1000;
|
|
22
|
-
readonly cloudCancelReceiptWaitMs: 10000;
|
|
23
22
|
}>;
|
|
24
23
|
export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
|
|
25
|
-
cloudCancelReceiptWaitMs: Schema<number, number, "volatile-defined">;
|
|
26
24
|
acpMaxMessageBytes: Schema<number, number, "volatile-defined">;
|
|
27
25
|
brokerMaxFrameBytes: Schema<number, number, "volatile-defined">;
|
|
28
26
|
brokerControlMaxBytes: Schema<number, number, "volatile-defined">;
|
|
29
27
|
employeeShellKillGraceMs: Schema<number, number, "volatile-defined">;
|
|
30
28
|
}>>, Schemastery.ObjectT<NoInfer<{
|
|
31
|
-
cloudCancelReceiptWaitMs: Schema<number, number, "volatile-defined">;
|
|
32
29
|
acpMaxMessageBytes: Schema<number, number, "volatile-defined">;
|
|
33
30
|
brokerMaxFrameBytes: Schema<number, number, "volatile-defined">;
|
|
34
31
|
brokerControlMaxBytes: Schema<number, number, "volatile-defined">;
|
|
@@ -39,7 +36,6 @@ export interface PluginConfig {
|
|
|
39
36
|
brokerMaxFrameBytes?: number;
|
|
40
37
|
brokerControlMaxBytes?: number;
|
|
41
38
|
employeeShellKillGraceMs?: number;
|
|
42
|
-
cloudCancelReceiptWaitMs?: number;
|
|
43
39
|
}
|
|
44
40
|
type LiveConfig = {
|
|
45
41
|
[K in keyof PluginConfig]: PluginConfig[K] | {
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { CloudTurnFailure, cloudTurnFailure, DEFAULT_CLOUD_CANCEL_RECEIPT_WAIT_MS } from "./cloud-failure.js";
|
|
2
1
|
import { ToolBridgeLoop } from "./toolbridge-loop.js";
|
|
3
2
|
import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
|
|
4
3
|
import { connectNeedMessage } from "./connect-need.js";
|
|
@@ -15,7 +14,7 @@ import { AcpSession } from "./acp.js";
|
|
|
15
14
|
import { StreamMapper } from "./mapping.js";
|
|
16
15
|
import { connectProvider } from "./provider.js";
|
|
17
16
|
import { brokerFactory } from "./broker.js";
|
|
18
|
-
import { AGENTS, CODEX_AGENT
|
|
17
|
+
import { AGENTS, CODEX_AGENT } from "./agents.js";
|
|
19
18
|
import { prepareInput, prepareContinuation } from "./input.js";
|
|
20
19
|
import { NeedError } from "./remote.js";
|
|
21
20
|
import { employeeFailure } from "./presentation.js";
|
|
@@ -40,9 +39,8 @@ export const settingsNamespace = 'ai-workbench-codex';
|
|
|
40
39
|
// L can be installed/enabled after X; keeping X mounted lets it explain the prerequisite.
|
|
41
40
|
export const inject = ['llm'];
|
|
42
41
|
/** Owner-approved defaults; administrators may override through the existing settings. */
|
|
43
|
-
export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes: 4194304, brokerMaxFrameBytes: 2097152, brokerControlMaxBytes: 1048576, employeeShellKillGraceMs: 1000
|
|
42
|
+
export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes: 4194304, brokerMaxFrameBytes: 2097152, brokerControlMaxBytes: 1048576, employeeShellKillGraceMs: 1000 });
|
|
44
43
|
export const Config = Schema.object({
|
|
45
|
-
cloudCancelReceiptWaitMs: Schema.number().min(1).max(2147483647).step(1).i18n({ en: 'Cloud cancellation receipt wait in milliseconds; default 10000, then end with unknown task status', zh: '云取消回执最长等待毫秒;默认10000,超时按云任务状态未知结束本轮' }).default(DEFAULT_CONFIG.cloudCancelReceiptWaitMs).volatile(),
|
|
46
44
|
acpMaxMessageBytes: Schema.number().min(1).step(1).i18n({ en: 'Session message limit; default 4 MiB, adjustable by administrators', zh: '会话消息容量;默认4 MiB,管理员可调整' }).default(DEFAULT_CONFIG.acpMaxMessageBytes).volatile(),
|
|
47
45
|
brokerMaxFrameBytes: Schema.number().min(1).step(1).i18n({ en: 'Host output chunk limit; default 2 MiB, adjustable by administrators', zh: '主机回传单段容量;默认2 MiB,管理员可调整' }).default(DEFAULT_CONFIG.brokerMaxFrameBytes).volatile(),
|
|
48
46
|
brokerControlMaxBytes: Schema.number().min(1).step(1).i18n({ en: 'Host session control reply limit; default 1 MiB, adjustable by administrators', zh: '主机会话管理回复容量;默认1 MiB,管理员可调整' }).default(DEFAULT_CONFIG.brokerControlMaxBytes).volatile(),
|
|
@@ -211,6 +209,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
211
209
|
throw failure.reason;
|
|
212
210
|
}
|
|
213
211
|
async *stream(options) {
|
|
212
|
+
// Before the tool bridge: a parked turn must not take a background request for its own continuation.
|
|
213
|
+
if (options.purpose)
|
|
214
|
+
throw new LlmError(employeeFailure('PURPOSE_UNSUPPORTED', this.agent.loginProvider, false), 'PURPOSE_UNSUPPORTED');
|
|
214
215
|
let promptDispatched = !!options.sessionId && (this.sessions.get(options.sessionId)?.session.promptDispatchCount ?? 0) > 0;
|
|
215
216
|
try {
|
|
216
217
|
for await (const chunk of this.bridgeLoop.stream(options, (o, b) => this.generate(o, () => { promptDispatched = true; }, b))) {
|
|
@@ -222,15 +223,12 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
222
223
|
}
|
|
223
224
|
}
|
|
224
225
|
catch (error) {
|
|
225
|
-
if (error instanceof CloudTurnFailure)
|
|
226
|
-
throw new LlmError(error.message, error.code, { cause: new Error(error.requires) });
|
|
227
|
-
const cloudNotice = this.agent.id === CODEX_CLOUD_AGENT.id && promptDispatched ? ' 云任务可能继续运行至结束;未回落到主机 Codex。' : '';
|
|
228
226
|
if (error instanceof ModelConfigurationError)
|
|
229
|
-
throw new LlmError(employeeFailure(error.code, this.agent.loginProvider, promptDispatched)
|
|
227
|
+
throw new LlmError(employeeFailure(error.code, this.agent.loginProvider, promptDispatched), error.code, { cause: error });
|
|
230
228
|
if (error instanceof NeedError) {
|
|
231
229
|
const rpc = /RPC 错误码 (-?\d+)/u.exec(error.requires)?.[1];
|
|
232
230
|
const evidence = failureEvidenceSummary(error);
|
|
233
|
-
const message =
|
|
231
|
+
const message = connectNeedMessage(error) ?? employeeFailure(error.code, this.agent.loginProvider, promptDispatched);
|
|
234
232
|
const login = originalLoginFailure(error);
|
|
235
233
|
let diagnostic = login?.technical ? JSON.stringify(login.technical) : '';
|
|
236
234
|
if (login?.technical && this.reportLoginFailure) {
|
|
@@ -244,7 +242,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
244
242
|
}
|
|
245
243
|
throw new LlmError(message, error.code, { cause: new Error(`诊断代码:${error.code};${error.requires}` + (evidence ? ';' + evidence : '') + (diagnostic ? ';' + diagnostic : '')) });
|
|
246
244
|
}
|
|
247
|
-
throw new LlmError(employeeFailure('TURN_FAILED', this.agent.loginProvider, promptDispatched)
|
|
245
|
+
throw new LlmError(employeeFailure('TURN_FAILED', this.agent.loginProvider, promptDispatched), 'TURN_FAILED', { cause: error });
|
|
248
246
|
}
|
|
249
247
|
finally {
|
|
250
248
|
if (options.sessionId)
|
|
@@ -252,8 +250,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
252
250
|
}
|
|
253
251
|
}
|
|
254
252
|
async *generate(original, onPromptDispatched, bridge) {
|
|
255
|
-
if (original.purpose)
|
|
256
|
-
throw new NeedError('PURPOSE_UNSUPPORTED', '此远程模型不处理后台标题或上下文整理请求,未发送模型请求', '独立的后台请求能力');
|
|
257
253
|
if (this.lifetime.signal.aborted)
|
|
258
254
|
throw new NeedError('DISPOSED', '远程模型插件已关闭', '启用远程模型插件');
|
|
259
255
|
const key = original.sessionId;
|
|
@@ -307,7 +303,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
307
303
|
this.employeeNoticeSessions.add(key);
|
|
308
304
|
live = undefined;
|
|
309
305
|
const configuration = JSON.stringify([config.acpMaxMessageBytes, config.brokerMaxFrameBytes, config.brokerControlMaxBytes, config.employeeShellKillGraceMs]);
|
|
310
|
-
Object.assign(request, { acpMaxMessageBytes: config.acpMaxMessageBytes, resumeSessionId:
|
|
306
|
+
Object.assign(request, { acpMaxMessageBytes: config.acpMaxMessageBytes, resumeSessionId: previous?.sessionId, sessionId: options.sessionId, mode, hostSource: previous?.hostSource, cwd: previous?.cwd, identity: previous?.identity, bindingId: previous?.bindingId, workspaceId: previous?.workspaceId, agent: this.agent, signal, brokerSettings: Object.freeze({ brokerMaxFrameBytes: config.brokerMaxFrameBytes, brokerControlMaxBytes: config.brokerControlMaxBytes }) });
|
|
311
307
|
request.previousContextSha256 = previous?.contextSha256;
|
|
312
308
|
const after = options.messages.findLastIndex(message => message.role === 'assistant');
|
|
313
309
|
const tail = options.messages.slice(after + 1);
|
|
@@ -328,7 +324,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
328
324
|
let input = await prepareInput(options, this.readImage);
|
|
329
325
|
const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
|
|
330
326
|
request.contextSha256 = contextSha256;
|
|
331
|
-
const codex = this.agent.
|
|
327
|
+
const codex = this.agent.loginProvider === 'codex';
|
|
332
328
|
const contextChanged = !!previous && codex && (previous.contextSha256 ?? '').toLowerCase() !== contextSha256;
|
|
333
329
|
// Only identical durable context can prove a legacy context-bound journal.
|
|
334
330
|
// New Codex transport scopes are independent of the native context digest.
|
|
@@ -353,7 +349,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
353
349
|
}
|
|
354
350
|
if (previous && !runtime.hostSource && (previous.identity !== runtime.identity || previous.cwd !== runtime.cwd || previous.bindingId && previous.bindingId !== runtime.binding?.bindingId || previous.workspaceId && previous.workspaceId !== runtime.binding?.workspaceId))
|
|
355
351
|
throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
|
|
356
|
-
input = await prepareContinuation({ ...options, messages: options.messages.slice(
|
|
352
|
+
input = await prepareContinuation({ ...options, messages: options.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
|
|
357
353
|
if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
|
|
358
354
|
throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
|
|
359
355
|
const details = runtime.details ?? await createRemoteDetails({ warn: line => console.warn(line) }).open({ sessionId: options.sessionId ?? 'unscoped', provider: this.agent.loginProvider, identity: runtime.identity, connection: runtime.connection });
|
|
@@ -402,7 +398,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
402
398
|
const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
|
|
403
399
|
let promptPermit;
|
|
404
400
|
let confirmedNativeMode;
|
|
405
|
-
const hooks = {
|
|
401
|
+
const hooks = { closeDiagnostics: runtime.closeDiagnostics, broker: runtime.broker, sessionOwnership: runtime.sessionOwnership, employeeExecution: runtime.employeeExecution, ...this.permissions ? { promptGuard: () => {
|
|
406
402
|
if (!promptPermit)
|
|
407
403
|
throw new NeedError('PERMISSION_POLICY_CHANGED', '当前权限没有保持确认,本次没有继续派发。', '当前权限代次和同值回执');
|
|
408
404
|
return promptPermit;
|
|
@@ -412,18 +408,13 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
412
408
|
} } : {}, approve: async (permission, approvalSignal) => {
|
|
413
409
|
const execution = runtime.execution;
|
|
414
410
|
const toolName = permission.toolCall.name ?? permission.toolCall._meta?.claudeCode?.toolName;
|
|
415
|
-
if (this.agent.id === CODEX_CLOUD_AGENT.id && this.permissions?.read(options.sessionId).sandbox === 'read-only' && ['mcp__employee__Write', 'mcp__employee__Edit', 'mcp__employee__Bash'].includes(toolName ?? '')) {
|
|
416
|
-
details.record({ kind: 'tool', severity: 'info', code: 'EMPLOYEE_READ_ONLY', summary: '只读档员工写请求已拒绝,未创建审批卡。', payload: { tool: toolName } });
|
|
417
|
-
return 'rejected';
|
|
418
|
-
}
|
|
419
411
|
if (execution && bridge?.enabled && bridge.isBridge(toolName)) {
|
|
420
412
|
const current = this.permissions ? permissionMode('claude', this.permissions.read(options.sessionId)) : undefined;
|
|
421
|
-
|
|
422
|
-
if (current === 'plan' && !cloudReadOnly) {
|
|
413
|
+
if (current === 'plan') {
|
|
423
414
|
details.record({ kind: 'tool', severity: 'info', code: 'TOOLBRIDGE_PLAN_PERMISSION_REJECTED', summary: '本轮为plan档,桥接原生权限请求未放行。' });
|
|
424
415
|
return 'rejected';
|
|
425
416
|
}
|
|
426
|
-
if (
|
|
417
|
+
if (current === 'default' && confirmedNativeMode === 'default') {
|
|
427
418
|
details.record({ kind: 'tool', severity: 'info', code: 'TOOLBRIDGE_NATIVE_PERMISSION_ANSWERED', summary: '已确认桥接工具仅在DSH审批,原生请求自动答复一次。', payload: { tool: toolName } });
|
|
428
419
|
return 'allowed-once';
|
|
429
420
|
}
|
|
@@ -444,13 +435,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
444
435
|
catch (error) {
|
|
445
436
|
failure = error;
|
|
446
437
|
session?.close({ layer: 'adapter', initiator: 'adapter.mapper-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' });
|
|
447
|
-
} }, onResponse: response =>
|
|
448
|
-
const failed = cloudTurnFailure(response);
|
|
449
|
-
if (failed) {
|
|
450
|
-
details.record({ kind: 'need', severity: 'action-required', code: failed.code, summary: failed.message, method: 'session/prompt', payload: failed.info });
|
|
451
|
-
throw failed;
|
|
452
|
-
}
|
|
453
|
-
} push(mapper.acpResponse(response)); }, onDetail: detail => details.record(detail) };
|
|
438
|
+
} }, onResponse: response => push(mapper.acpResponse(response)), onDetail: detail => details.record(detail) };
|
|
454
439
|
const transport = runtime.acpTransport instanceof acp.AgentApp || runtime.acpTransport instanceof unstable.AgentApp ? runtime.acpTransport : acp.ndJsonStream(runtime.acpTransport.writable, runtime.acpTransport.readable, { maxMessageBytes: config.acpMaxMessageBytes });
|
|
455
440
|
session = new AcpSession(transport, hooks);
|
|
456
441
|
live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot };
|
|
@@ -500,7 +485,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
|
|
|
500
485
|
const task = (async () => {
|
|
501
486
|
remoteAttempted = true;
|
|
502
487
|
try {
|
|
503
|
-
await session.start(runtime.execution?.hostCwd ?? runtime.cwd,
|
|
488
|
+
await session.start(runtime.execution?.hostCwd ?? runtime.cwd, previous?.sessionId, modelSignal, { systemPrompt: input.systemPrompt, ...(bridgeMcp ? { toolBridgeServers: bridgeMcp.mcpServers } : {}), ...(runtime.execution ? { employeeRouting: runtime.execution.routing } : {}), ...(codex ? { codexNewSessionOnly: true } : {}), ...(runtime.employeeExecutionMeta ? { employeeExecution: runtime.employeeExecutionMeta } : {}) }, input.prompt);
|
|
504
489
|
}
|
|
505
490
|
catch (error) {
|
|
506
491
|
details.record({ kind: 'session', severity: 'action-required', code: 'SESSION_START_FAILED', summary: '远端会话建立或恢复失败,本轮用户输入未发送。', payload: { operation: previous ? 'resume-or-load' : 'new', reason: closeCode(error, 'ACP_FAILED'), promptDispatched: false } });
|
|
@@ -658,7 +643,7 @@ export class RemoteAgentsAdapter extends LlmAdapter {
|
|
|
658
643
|
async prepareCall(provider, model, signal) { const prepared = await this.adapter(provider).prepareCall(provider, model, signal); return { ...prepared, stream: (options) => this.stream(options) }; }
|
|
659
644
|
providerRetryPolicy() { return { mode: 'normal', maxRetries: 0, retryableCodes: [], initialDelayMs: 0, maxDelayMs: 0, jitterRatio: 0 }; }
|
|
660
645
|
stream(options) {
|
|
661
|
-
if (options.sessionId)
|
|
646
|
+
if (options.sessionId && !options.purpose)
|
|
662
647
|
for (const [provider, adapter] of this.adapters)
|
|
663
648
|
if (provider !== options.provider && adapter.hasBridgeSession(options.sessionId)) {
|
|
664
649
|
void adapter.disposeSession(options.sessionId);
|
|
@@ -740,14 +725,14 @@ export function apply(ctx, live) {
|
|
|
740
725
|
};
|
|
741
726
|
return runtime;
|
|
742
727
|
};
|
|
743
|
-
const local = agent.
|
|
728
|
+
const local = agent.loginProvider === 'claude' ? createClaudeLocalProvider({ getConnect: get, getNetwork: () => ctx.get('aiWorkbenchNetwork'), readWorkspace: id => readEmployeeWorkspace(ctx, id), readUserTurn: request => readLocalUserTurn(ctx, { sessionId: request.sessionId, route: agent.id, userMessageIds: request.userMessageIds ?? [] }), reportAdmissionFailure: (request, code) => preflightDiagnostics.failure(request, 'claude', code, 'local-admission'), recordUnscoped: (request, observation) => managerForProfile().recordLocalFailure({ sessionId: request.sessionId, provider: 'claude', code: observation.code, observation }), configuration: config, details, open }) : undefined;
|
|
744
729
|
const workspace = async (request) => {
|
|
745
730
|
const services = ctx;
|
|
746
731
|
const registry = services.get('workspaceRegistry');
|
|
747
732
|
const sessions = services.get('sessions');
|
|
748
733
|
return officialEmployeeWorkspace(request.sessionId, registry, sessions?.get(request.sessionId)?.header);
|
|
749
734
|
};
|
|
750
|
-
const provider = connectProvider(get, { agent, workspace, source: sessionSources, ...(agent.
|
|
735
|
+
const provider = connectProvider(get, { agent, workspace, source: sessionSources, ...(agent.loginProvider === 'codex' ? { employee: {
|
|
751
736
|
getNetwork: () => ctx.get('aiWorkbenchNetwork'),
|
|
752
737
|
workspace, native: () => resolveEmployeeNative(),
|
|
753
738
|
} } : {}), details, open, local });
|
package/dist/model-catalog.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { type LlmResolvedModelInfo } from '@deepseek-ai/dsh-llm';
|
|
2
2
|
import type { ModelCatalogTarget } from '@ai-workbench/connect/api';
|
|
3
|
-
import {
|
|
3
|
+
import type { AgentDefinition } from './agents.ts';
|
|
4
4
|
import { type ConnectApi, type ConnectTarget } from './provider.ts';
|
|
5
5
|
export { runCatalog } from './catalog-ssh.ts';
|
|
6
6
|
export interface HostModel {
|
|
@@ -17,6 +17,8 @@ export interface HostModel {
|
|
|
17
17
|
defaultKnown: boolean;
|
|
18
18
|
};
|
|
19
19
|
source: unknown;
|
|
20
|
+
/** Host-sourced token capacity. Absent means unknown: X declares nothing and DSH reports it. */
|
|
21
|
+
contextWindow?: number;
|
|
20
22
|
}
|
|
21
23
|
export interface CatalogLease {
|
|
22
24
|
readonly target: ModelCatalogTarget;
|
package/dist/model-catalog.js
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { LlmError, ReasoningEffortId } from '@deepseek-ai/dsh-llm';
|
|
2
|
-
import { CODEX_CLOUD_AGENT } from "./agents.js";
|
|
3
2
|
import { validateTarget } from "./provider.js";
|
|
4
3
|
import { ModelConfigurationError } from "./model-configuration.js";
|
|
5
4
|
import { runCatalog, catalogSafeText } from "./catalog-ssh.js";
|
|
@@ -62,6 +61,10 @@ export function parseHostCatalog(input, provider, username) {
|
|
|
62
61
|
reject('具体型号与发送模型值不一致');
|
|
63
62
|
continue;
|
|
64
63
|
}
|
|
64
|
+
if (model.contextWindow !== undefined && (!Number.isSafeInteger(model.contextWindow) || model.contextWindow < 1)) {
|
|
65
|
+
reject('上下文窗口不是正整数', 'MODEL_CONTEXT_WINDOW_INVALID');
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
65
68
|
const r = model.reasoning;
|
|
66
69
|
if (!Array.isArray(r.options) || typeof r.defaultKnown !== 'boolean' || (r.defaultValue !== null && !text(r.defaultValue)) || (!r.defaultKnown && r.defaultValue !== null)) {
|
|
67
70
|
reject('推理档位或默认档位资料无效', 'MODEL_REASONING_INVALID');
|
|
@@ -125,9 +128,6 @@ export class ModelCatalog {
|
|
|
125
128
|
if (state.phase !== 'connected' || state.instanceId !== target.instanceId || state.epoch !== target.epoch)
|
|
126
129
|
controller.abort(new CatalogError('连接已变化,本次模型列表读取已停止;连接恢复后请重新打开模型菜单。', 'MODEL_CATALOG_CONNECTION_CHANGED'));
|
|
127
130
|
});
|
|
128
|
-
// The cloud ACP contract has one selector, independent of the host CLI catalog.
|
|
129
|
-
if (agent.id === CODEX_CLOUD_AGENT.id)
|
|
130
|
-
return { target, models: freeze([{ id: 'codex-cloud', value: 'codex-cloud', name: agent.name.zh, resolvedModel: 'codex-cloud', reasoning: { options: [], defaultValue: null, defaultKnown: false }, source: { agent: 'aw-cloud-acp', version: '0.1.2' } }]), signal: combined, release() { } };
|
|
131
131
|
const max = this.maxBytes();
|
|
132
132
|
if (!Number.isSafeInteger(max) || max < 1)
|
|
133
133
|
fail('模型目录容量设置无效,请联系管理员检查插件配置。');
|
|
@@ -165,5 +165,5 @@ export class ModelCatalog {
|
|
|
165
165
|
}
|
|
166
166
|
export function modelInfo(provider, model) {
|
|
167
167
|
// Official rc.2 represents no reasoning levels by absence, and rejects an empty efforts array.
|
|
168
|
-
return { provider, id: model.id, name: model.name, inputModalities: ['text', 'image'], ...(model.reasoning.options.length ? { reasoning: { efforts: model.reasoning.options.map(option => ({ id: ReasoningEffortId(option.value), name: option.name })), ...(model.reasoning.defaultKnown && model.reasoning.defaultValue !== null ? { defaultEffort: ReasoningEffortId(model.reasoning.defaultValue) } : {}) } } : {}), catalog: model };
|
|
168
|
+
return { provider, id: model.id, name: model.name, inputModalities: ['text', 'image'], ...(model.contextWindow === undefined ? {} : { context: { contextWindow: model.contextWindow } }), ...(model.reasoning.options.length ? { reasoning: { efforts: model.reasoning.options.map(option => ({ id: ReasoningEffortId(option.value), name: option.name })), ...(model.reasoning.defaultKnown && model.reasoning.defaultValue !== null ? { defaultEffort: ReasoningEffortId(model.reasoning.defaultValue) } : {}) } } : {}), catalog: model };
|
|
169
169
|
}
|
package/dist/presentation.js
CHANGED
|
@@ -4,7 +4,6 @@ export const CONNECTION_REQUIRED = '远程主机连接组件没有装好,请
|
|
|
4
4
|
/** Employee failures use business language; diagnostic codes remain separately available. */
|
|
5
5
|
export function employeeFailure(code, brand = 'codex', promptDispatched = true) {
|
|
6
6
|
const messages = {
|
|
7
|
-
CLOUD_LOCAL_WORKSPACE_REQUIRED: 'Codex(云)目前只支持本机文件夹;请选择本机文件夹并新建会话。',
|
|
8
7
|
PERMISSION_POLICY_REQUIRED: '我需要读取这条对话的权限设置,目前没有读到;本轮未执行,你的原话仍保留。',
|
|
9
8
|
PERMISSION_MODE_UNSUPPORTED: '这个权限档位还没有对应的远程执行能力;我需要主机连接组件支持该档位,本轮未执行,你的原话仍保留。',
|
|
10
9
|
PERMISSION_MODE_UNCONFIRMED: '远端没有确认按当前权限执行,本轮未继续;你的原话仍保留,具体原因见技术详情。',
|
|
@@ -55,6 +54,7 @@ export function employeeFailure(code, brand = 'codex', promptDispatched = true)
|
|
|
55
54
|
PROMPT_CONTENT_UNSUPPORTED: '远端没有声明这类输入能力,本轮未发送;请使用受支持的内容或联系管理员。',
|
|
56
55
|
ATTACHMENT_REQUIRED: '我需要官方附件组件读取这张图片,请联系管理员检查组件。',
|
|
57
56
|
ATTACHMENT_INVALID: '图片附件没有返回匹配的已核验内容,本轮未发送;请重新添加图片或联系管理员。',
|
|
57
|
+
PURPOSE_UNSUPPORTED: '这段对话太长,需要先整理上下文,但远程模型不支持整理;这句话未发送,需要重新输入。请新建会话继续,或换回原来的模型',
|
|
58
58
|
ACP_MESSAGE_TOO_LARGE: '本轮输入超过会话消息容量,未截断或发送;请联系管理员调整acpMaxMessageBytes。',
|
|
59
59
|
};
|
|
60
60
|
if (messages[code])
|
package/dist/provider.js
CHANGED
|
@@ -3,7 +3,7 @@ import { connectNeedError } from "./connect-need.js";
|
|
|
3
3
|
import { loginDiagnostic, loginReason } from "./login-diagnostic.js";
|
|
4
4
|
import { NeedError } from "./remote.js";
|
|
5
5
|
import { CONNECTION_REQUIRED } from "./presentation.js";
|
|
6
|
-
import { CODEX_AGENT
|
|
6
|
+
import { CODEX_AGENT } from "./agents.js";
|
|
7
7
|
export function requireLoginCoordinator(api) {
|
|
8
8
|
if (!['getConnectionState', 'getLoginPromptState', 'requestLoginPrompt', 'refreshLoginPrompts'].every(key => typeof api[key] === 'function'))
|
|
9
9
|
throw new NeedError('CONNECT_API_MISMATCH', '我需要 connect-api 0.6.1 的统一登录询问与连接状态能力', 'L >=0.6.1');
|
|
@@ -164,8 +164,6 @@ export function connectProvider(get, options = {}) {
|
|
|
164
164
|
request.workspaceSource = workspaceSessionSource(api, workspace.id, request);
|
|
165
165
|
}
|
|
166
166
|
const host = request.workspaceSource?.source === 'host';
|
|
167
|
-
if (host && agent.id === CODEX_CLOUD_AGENT.id)
|
|
168
|
-
throw new NeedError('CLOUD_LOCAL_WORKSPACE_REQUIRED', 'Codex(云)目前只支持本机文件夹;请选择本机文件夹并新建会话。', 'L确认的本机工作区与员工工具通道');
|
|
169
167
|
if (options.employee && !host) {
|
|
170
168
|
const module = await import("./employee-provider.js");
|
|
171
169
|
request.localContext = await module.inspectEmployeeWorkspace(get, options.employee, agent, api, request);
|
|
@@ -219,7 +217,7 @@ export function connectProvider(get, options = {}) {
|
|
|
219
217
|
return local;
|
|
220
218
|
}
|
|
221
219
|
}
|
|
222
|
-
if (!host && agent.
|
|
220
|
+
if (!host && agent.loginProvider === 'claude' && options.local) {
|
|
223
221
|
const runtime = await options.local(request, api, connection, target);
|
|
224
222
|
if (runtime)
|
|
225
223
|
return runtime;
|
package/dist/toolbridge-loop.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { CloudTurnFailure } from "./cloud-failure.js";
|
|
2
1
|
import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
|
|
3
2
|
import { ToolBridge } from "./toolbridge.js";
|
|
4
3
|
import { NeedError } from "./remote.js";
|
|
@@ -246,8 +245,6 @@ export class ToolBridgeLoop {
|
|
|
246
245
|
if (key && this.runs.get(key) === run)
|
|
247
246
|
this.runs.delete(key);
|
|
248
247
|
await run.task;
|
|
249
|
-
if (run.error instanceof CloudTurnFailure)
|
|
250
|
-
throw run.error;
|
|
251
248
|
}
|
|
252
249
|
}
|
|
253
250
|
}
|