@ai-workbench/remote-agent 0.9.0-toolbridge.3 → 0.9.0-toolbridge.7

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.
Files changed (153) hide show
  1. package/README.md +11 -2
  2. package/dist/acp.d.ts +4 -0
  3. package/dist/acp.js +42 -6
  4. package/dist/agents.d.ts +2 -0
  5. package/dist/agents.js +4 -3
  6. package/dist/claude-local.d.ts +1 -0
  7. package/dist/claude-local.js +2 -2
  8. package/dist/client.js +1 -1
  9. package/dist/cloud-failure.d.ts +11 -0
  10. package/dist/cloud-failure.js +54 -0
  11. package/dist/employee-mcp.d.ts +8 -24
  12. package/dist/employee-mcp.js +24 -188
  13. package/dist/employee-tools.d.ts +5 -22
  14. package/dist/employee-tools.js +4 -292
  15. package/dist/index.d.ts +4 -0
  16. package/dist/index.js +31 -15
  17. package/dist/model-catalog.d.ts +1 -1
  18. package/dist/model-catalog.js +4 -0
  19. package/dist/presentation.js +1 -0
  20. package/dist/provider.js +4 -2
  21. package/dist/toolbridge-loop.js +3 -0
  22. package/dist/toolbridge-table.js +4 -1
  23. package/dist/toolbridge.d.ts +1 -0
  24. package/dist/toolbridge.js +1 -0
  25. package/package.json +10 -6
  26. package/helpers/ripgrep/LICENSE-vscode +0 -13
  27. package/helpers/ripgrep/PROVENANCE.md +0 -9
  28. package/helpers/ripgrep/darwin-arm64/rg +0 -0
  29. package/helpers/ripgrep/darwin-x64/rg +0 -0
  30. package/helpers/ripgrep/manifest.json +0 -56
  31. package/helpers/ripgrep/notices/COPYING-ripgrep +0 -3
  32. package/helpers/ripgrep/notices/DEPENDENCIES.json +0 -946
  33. package/helpers/ripgrep/notices/LICENCE-PCRE2.md +0 -103
  34. package/helpers/ripgrep/notices/LICENSE-MIT-ripgrep +0 -21
  35. package/helpers/ripgrep/notices/UNLICENSE-ripgrep +0 -24
  36. package/helpers/ripgrep/notices/aho-corasick-1.1.3/COPYING +0 -3
  37. package/helpers/ripgrep/notices/aho-corasick-1.1.3/LICENSE-MIT +0 -21
  38. package/helpers/ripgrep/notices/aho-corasick-1.1.3/UNLICENSE +0 -24
  39. package/helpers/ripgrep/notices/anyhow-1.0.100/LICENSE-APACHE +0 -176
  40. package/helpers/ripgrep/notices/anyhow-1.0.100/LICENSE-MIT +0 -23
  41. package/helpers/ripgrep/notices/arbitrary-1.4.2/LICENSE-APACHE +0 -201
  42. package/helpers/ripgrep/notices/arbitrary-1.4.2/LICENSE-MIT +0 -27
  43. package/helpers/ripgrep/notices/bstr-1.12.0/COPYING +0 -8
  44. package/helpers/ripgrep/notices/bstr-1.12.0/LICENSE-APACHE +0 -201
  45. package/helpers/ripgrep/notices/bstr-1.12.0/LICENSE-MIT +0 -21
  46. package/helpers/ripgrep/notices/cc-1.2.41/LICENSE-APACHE +0 -201
  47. package/helpers/ripgrep/notices/cc-1.2.41/LICENSE-MIT +0 -25
  48. package/helpers/ripgrep/notices/cfg-if-1.0.4/LICENSE-APACHE +0 -201
  49. package/helpers/ripgrep/notices/cfg-if-1.0.4/LICENSE-MIT +0 -25
  50. package/helpers/ripgrep/notices/crossbeam-channel-0.5.15/LICENSE-APACHE +0 -201
  51. package/helpers/ripgrep/notices/crossbeam-channel-0.5.15/LICENSE-MIT +0 -27
  52. package/helpers/ripgrep/notices/crossbeam-channel-0.5.15/LICENSE-THIRD-PARTY +0 -593
  53. package/helpers/ripgrep/notices/crossbeam-deque-0.8.6/LICENSE-APACHE +0 -201
  54. package/helpers/ripgrep/notices/crossbeam-deque-0.8.6/LICENSE-MIT +0 -27
  55. package/helpers/ripgrep/notices/crossbeam-epoch-0.9.18/LICENSE-APACHE +0 -201
  56. package/helpers/ripgrep/notices/crossbeam-epoch-0.9.18/LICENSE-MIT +0 -27
  57. package/helpers/ripgrep/notices/crossbeam-utils-0.8.21/LICENSE-APACHE +0 -201
  58. package/helpers/ripgrep/notices/crossbeam-utils-0.8.21/LICENSE-MIT +0 -27
  59. package/helpers/ripgrep/notices/derive_arbitrary-1.4.2/LICENSE-APACHE +0 -201
  60. package/helpers/ripgrep/notices/derive_arbitrary-1.4.2/LICENSE-MIT +0 -27
  61. package/helpers/ripgrep/notices/encoding_rs-0.8.35/COPYRIGHT +0 -17
  62. package/helpers/ripgrep/notices/encoding_rs-0.8.35/LICENSE-APACHE +0 -202
  63. package/helpers/ripgrep/notices/encoding_rs-0.8.35/LICENSE-MIT +0 -25
  64. package/helpers/ripgrep/notices/encoding_rs-0.8.35/LICENSE-WHATWG +0 -26
  65. package/helpers/ripgrep/notices/encoding_rs_io-0.1.7/COPYING +0 -8
  66. package/helpers/ripgrep/notices/encoding_rs_io-0.1.7/LICENSE-APACHE +0 -201
  67. package/helpers/ripgrep/notices/encoding_rs_io-0.1.7/LICENSE-MIT +0 -21
  68. package/helpers/ripgrep/notices/find-msvc-tools-0.1.4/LICENSE-APACHE +0 -201
  69. package/helpers/ripgrep/notices/find-msvc-tools-0.1.4/LICENSE-MIT +0 -25
  70. package/helpers/ripgrep/notices/getrandom-0.3.4/LICENSE-APACHE +0 -201
  71. package/helpers/ripgrep/notices/getrandom-0.3.4/LICENSE-MIT +0 -26
  72. package/helpers/ripgrep/notices/glob-0.3.3/LICENSE-APACHE +0 -201
  73. package/helpers/ripgrep/notices/glob-0.3.3/LICENSE-MIT +0 -25
  74. package/helpers/ripgrep/notices/itoa-1.0.15/LICENSE-APACHE +0 -176
  75. package/helpers/ripgrep/notices/itoa-1.0.15/LICENSE-MIT +0 -23
  76. package/helpers/ripgrep/notices/jobserver-0.1.34/LICENSE-APACHE +0 -201
  77. package/helpers/ripgrep/notices/jobserver-0.1.34/LICENSE-MIT +0 -25
  78. package/helpers/ripgrep/notices/lexopt-0.3.1/LICENSE +0 -19
  79. package/helpers/ripgrep/notices/libc-0.2.177/LICENSE-APACHE +0 -176
  80. package/helpers/ripgrep/notices/libc-0.2.177/LICENSE-MIT +0 -25
  81. package/helpers/ripgrep/notices/log-0.4.28/LICENSE-APACHE +0 -201
  82. package/helpers/ripgrep/notices/log-0.4.28/LICENSE-MIT +0 -25
  83. package/helpers/ripgrep/notices/memchr-2.7.6/COPYING +0 -3
  84. package/helpers/ripgrep/notices/memchr-2.7.6/LICENSE-MIT +0 -21
  85. package/helpers/ripgrep/notices/memchr-2.7.6/UNLICENSE +0 -24
  86. package/helpers/ripgrep/notices/memmap2-0.9.8/LICENSE-APACHE +0 -201
  87. package/helpers/ripgrep/notices/memmap2-0.9.8/LICENSE-MIT +0 -26
  88. package/helpers/ripgrep/notices/msvc_spectre_libs-0.1.3/LICENSE +0 -21
  89. package/helpers/ripgrep/notices/pcre2-0.2.11/COPYING +0 -3
  90. package/helpers/ripgrep/notices/pcre2-0.2.11/LICENSE-MIT +0 -21
  91. package/helpers/ripgrep/notices/pcre2-0.2.11/UNLICENSE +0 -24
  92. package/helpers/ripgrep/notices/pcre2-sys-0.2.10/COPYING +0 -3
  93. package/helpers/ripgrep/notices/pcre2-sys-0.2.10/LICENSE-MIT +0 -21
  94. package/helpers/ripgrep/notices/pcre2-sys-0.2.10/UNLICENSE +0 -24
  95. package/helpers/ripgrep/notices/pkg-config-0.3.32/LICENSE-APACHE +0 -201
  96. package/helpers/ripgrep/notices/pkg-config-0.3.32/LICENSE-MIT +0 -25
  97. package/helpers/ripgrep/notices/proc-macro2-1.0.101/LICENSE-APACHE +0 -176
  98. package/helpers/ripgrep/notices/proc-macro2-1.0.101/LICENSE-MIT +0 -23
  99. package/helpers/ripgrep/notices/quote-1.0.41/LICENSE-APACHE +0 -176
  100. package/helpers/ripgrep/notices/quote-1.0.41/LICENSE-MIT +0 -23
  101. package/helpers/ripgrep/notices/r-efi-5.3.0/AUTHORS +0 -74
  102. package/helpers/ripgrep/notices/regex-1.12.2/LICENSE-APACHE +0 -201
  103. package/helpers/ripgrep/notices/regex-1.12.2/LICENSE-MIT +0 -25
  104. package/helpers/ripgrep/notices/regex-automata-0.4.13/LICENSE-APACHE +0 -201
  105. package/helpers/ripgrep/notices/regex-automata-0.4.13/LICENSE-MIT +0 -25
  106. package/helpers/ripgrep/notices/regex-syntax-0.8.8/LICENSE-APACHE +0 -201
  107. package/helpers/ripgrep/notices/regex-syntax-0.8.8/LICENSE-MIT +0 -25
  108. package/helpers/ripgrep/notices/regex-syntax-0.8.8/src/unicode_tables/LICENSE-UNICODE +0 -57
  109. package/helpers/ripgrep/notices/ryu-1.0.20/LICENSE-APACHE +0 -176
  110. package/helpers/ripgrep/notices/ryu-1.0.20/LICENSE-BOOST +0 -23
  111. package/helpers/ripgrep/notices/same-file-1.0.6/COPYING +0 -3
  112. package/helpers/ripgrep/notices/same-file-1.0.6/LICENSE-MIT +0 -21
  113. package/helpers/ripgrep/notices/same-file-1.0.6/UNLICENSE +0 -24
  114. package/helpers/ripgrep/notices/serde-1.0.228/LICENSE-APACHE +0 -176
  115. package/helpers/ripgrep/notices/serde-1.0.228/LICENSE-MIT +0 -23
  116. package/helpers/ripgrep/notices/serde_core-1.0.228/LICENSE-APACHE +0 -176
  117. package/helpers/ripgrep/notices/serde_core-1.0.228/LICENSE-MIT +0 -23
  118. package/helpers/ripgrep/notices/serde_derive-1.0.228/LICENSE-APACHE +0 -176
  119. package/helpers/ripgrep/notices/serde_derive-1.0.228/LICENSE-MIT +0 -23
  120. package/helpers/ripgrep/notices/serde_json-1.0.145/LICENSE-APACHE +0 -176
  121. package/helpers/ripgrep/notices/serde_json-1.0.145/LICENSE-MIT +0 -23
  122. package/helpers/ripgrep/notices/shlex-1.3.0/LICENSE-APACHE +0 -13
  123. package/helpers/ripgrep/notices/shlex-1.3.0/LICENSE-MIT +0 -21
  124. package/helpers/ripgrep/notices/syn-2.0.106/LICENSE-APACHE +0 -176
  125. package/helpers/ripgrep/notices/syn-2.0.106/LICENSE-MIT +0 -23
  126. package/helpers/ripgrep/notices/termcolor-1.4.1/COPYING +0 -3
  127. package/helpers/ripgrep/notices/termcolor-1.4.1/LICENSE-MIT +0 -21
  128. package/helpers/ripgrep/notices/termcolor-1.4.1/UNLICENSE +0 -24
  129. package/helpers/ripgrep/notices/textwrap-0.16.2/LICENSE +0 -21
  130. package/helpers/ripgrep/notices/tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/LICENSE-APACHE +0 -201
  131. package/helpers/ripgrep/notices/tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/LICENSE-MIT +0 -25
  132. package/helpers/ripgrep/notices/tikv-jemalloc-sys-0.6.0+5.3.0-1-ge13ca993e8ccb9ba9847cc330696e02839f328f7/jemalloc/COPYING +0 -27
  133. package/helpers/ripgrep/notices/tikv-jemallocator-0.6.0/LICENSE-APACHE +0 -201
  134. package/helpers/ripgrep/notices/tikv-jemallocator-0.6.0/LICENSE-MIT +0 -25
  135. package/helpers/ripgrep/notices/unicode-ident-1.0.19/LICENSE-APACHE +0 -176
  136. package/helpers/ripgrep/notices/unicode-ident-1.0.19/LICENSE-MIT +0 -23
  137. package/helpers/ripgrep/notices/unicode-ident-1.0.19/LICENSE-UNICODE +0 -39
  138. package/helpers/ripgrep/notices/walkdir-2.5.0/COPYING +0 -3
  139. package/helpers/ripgrep/notices/walkdir-2.5.0/LICENSE-MIT +0 -21
  140. package/helpers/ripgrep/notices/walkdir-2.5.0/UNLICENSE +0 -24
  141. package/helpers/ripgrep/notices/wasip2-1.0.1+wasi-0.2.4/LICENSE-APACHE +0 -201
  142. package/helpers/ripgrep/notices/wasip2-1.0.1+wasi-0.2.4/LICENSE-Apache-2.0_WITH_LLVM-exception +0 -220
  143. package/helpers/ripgrep/notices/wasip2-1.0.1+wasi-0.2.4/LICENSE-MIT +0 -23
  144. package/helpers/ripgrep/notices/winapi-util-0.1.11/COPYING +0 -3
  145. package/helpers/ripgrep/notices/winapi-util-0.1.11/LICENSE-MIT +0 -21
  146. package/helpers/ripgrep/notices/winapi-util-0.1.11/UNLICENSE +0 -24
  147. package/helpers/ripgrep/notices/windows-link-0.2.1/license-apache-2.0 +0 -201
  148. package/helpers/ripgrep/notices/windows-link-0.2.1/license-mit +0 -21
  149. package/helpers/ripgrep/notices/windows-sys-0.61.2/license-apache-2.0 +0 -201
  150. package/helpers/ripgrep/notices/windows-sys-0.61.2/license-mit +0 -21
  151. package/helpers/ripgrep/notices/wit-bindgen-0.46.0/LICENSE-APACHE +0 -201
  152. package/helpers/ripgrep/notices/wit-bindgen-0.46.0/LICENSE-Apache-2.0_WITH_LLVM-exception +0 -220
  153. package/helpers/ripgrep/notices/wit-bindgen-0.46.0/LICENSE-MIT +0 -23
@@ -1,23 +1,7 @@
1
- import { type CloseCause, type CloseDiagnostics } from './close-diagnostics.ts';
2
- import type { DetailObservation } from './conversation-details.ts';
3
- import type { EmployeeShell } from './employee-shell.ts';
4
- export declare const EMPLOYEE_TOOL_NAMES: readonly ["Read", "Write", "Edit", "Glob", "Grep", "Bash"];
5
- export type EmployeeToolName = typeof EMPLOYEE_TOOL_NAMES[number];
6
- interface Options {
7
- closeDiagnostics?: CloseDiagnostics;
8
- cwd: string;
9
- shell: string;
10
- uid: number;
11
- maxBytes: number;
12
- killGraceMs: number;
13
- validate: (signal?: AbortSignal) => Promise<void>;
14
- detail: (event: DetailObservation) => void;
15
- rgPath?: string;
16
- runShell?: EmployeeShell;
17
- }
18
- /** Executed only in the employee DSH process; never creates a host fallback. */
19
- export declare function createEmployeeTools(options: Options): {
20
- call(name: string, input: unknown, requestSignal?: AbortSignal, observer?: Options["detail"]): Promise<{
1
+ import { type EmployeeToolsOptions } from '@ai-workbench/employee-tools';
2
+ export { EMPLOYEE_TOOL_NAMES, type EmployeeToolName } from '@ai-workbench/employee-tools';
3
+ export declare function createEmployeeTools(options: EmployeeToolsOptions): {
4
+ call(name: string, input: unknown, requestSignal?: AbortSignal, observer?: EmployeeToolsOptions["detail"]): Promise<{
21
5
  [x: string]: unknown;
22
6
  content: ({
23
7
  type: "text";
@@ -114,6 +98,5 @@ export declare function createEmployeeTools(options: Options): {
114
98
  } | undefined;
115
99
  isError?: boolean | undefined;
116
100
  }>;
117
- close(cause?: CloseCause): Promise<void>;
101
+ close(cause?: import("@ai-workbench/employee-tools").CloseCause): Promise<void>;
118
102
  };
119
- export {};
@@ -1,293 +1,5 @@
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';
1
+ import { createEmployeeTools as create } from '@ai-workbench/employee-tools';
7
2
  import { NeedError } from "./remote.js";
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
- }
3
+ import { closeCode } from "./close-diagnostics.js";
4
+ export { EMPLOYEE_TOOL_NAMES } from '@ai-workbench/employee-tools';
5
+ export function createEmployeeTools(options) { return create(options, { NeedError, closeCode }); }
package/dist/index.d.ts CHANGED
@@ -19,13 +19,16 @@ 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;
22
23
  }>;
23
24
  export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
25
+ cloudCancelReceiptWaitMs: Schema<number, number, "volatile-defined">;
24
26
  acpMaxMessageBytes: Schema<number, number, "volatile-defined">;
25
27
  brokerMaxFrameBytes: Schema<number, number, "volatile-defined">;
26
28
  brokerControlMaxBytes: Schema<number, number, "volatile-defined">;
27
29
  employeeShellKillGraceMs: Schema<number, number, "volatile-defined">;
28
30
  }>>, Schemastery.ObjectT<NoInfer<{
31
+ cloudCancelReceiptWaitMs: Schema<number, number, "volatile-defined">;
29
32
  acpMaxMessageBytes: Schema<number, number, "volatile-defined">;
30
33
  brokerMaxFrameBytes: Schema<number, number, "volatile-defined">;
31
34
  brokerControlMaxBytes: Schema<number, number, "volatile-defined">;
@@ -36,6 +39,7 @@ export interface PluginConfig {
36
39
  brokerMaxFrameBytes?: number;
37
40
  brokerControlMaxBytes?: number;
38
41
  employeeShellKillGraceMs?: number;
42
+ cloudCancelReceiptWaitMs?: number;
39
43
  }
40
44
  type LiveConfig = {
41
45
  [K in keyof PluginConfig]: PluginConfig[K] | {
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { CloudTurnFailure, cloudTurnFailure, DEFAULT_CLOUD_CANCEL_RECEIPT_WAIT_MS } from "./cloud-failure.js";
1
2
  import { ToolBridgeLoop } from "./toolbridge-loop.js";
2
3
  import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
3
4
  import { connectNeedMessage } from "./connect-need.js";
@@ -14,7 +15,7 @@ import { AcpSession } from "./acp.js";
14
15
  import { StreamMapper } from "./mapping.js";
15
16
  import { connectProvider } from "./provider.js";
16
17
  import { brokerFactory } from "./broker.js";
17
- import { AGENTS, CODEX_AGENT } from "./agents.js";
18
+ import { AGENTS, CODEX_AGENT, CODEX_CLOUD_AGENT } from "./agents.js";
18
19
  import { prepareInput, prepareContinuation } from "./input.js";
19
20
  import { NeedError } from "./remote.js";
20
21
  import { employeeFailure } from "./presentation.js";
@@ -39,8 +40,9 @@ export const settingsNamespace = 'ai-workbench-codex';
39
40
  // L can be installed/enabled after X; keeping X mounted lets it explain the prerequisite.
40
41
  export const inject = ['llm'];
41
42
  /** Owner-approved defaults; administrators may override through the existing settings. */
42
- export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes: 4194304, brokerMaxFrameBytes: 2097152, brokerControlMaxBytes: 1048576, employeeShellKillGraceMs: 1000 });
43
+ export const DEFAULT_CONFIG = Object.freeze({ acpMaxMessageBytes: 4194304, brokerMaxFrameBytes: 2097152, brokerControlMaxBytes: 1048576, employeeShellKillGraceMs: 1000, cloudCancelReceiptWaitMs: DEFAULT_CLOUD_CANCEL_RECEIPT_WAIT_MS });
43
44
  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(),
44
46
  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(),
45
47
  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(),
46
48
  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(),
@@ -220,12 +222,15 @@ export class CodexRemoteAdapter extends LlmAdapter {
220
222
  }
221
223
  }
222
224
  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。' : '';
223
228
  if (error instanceof ModelConfigurationError)
224
- throw new LlmError(employeeFailure(error.code, this.agent.loginProvider, promptDispatched), error.code, { cause: error });
229
+ throw new LlmError(employeeFailure(error.code, this.agent.loginProvider, promptDispatched) + cloudNotice, error.code, { cause: error });
225
230
  if (error instanceof NeedError) {
226
231
  const rpc = /RPC 错误码 (-?\d+)/u.exec(error.requires)?.[1];
227
232
  const evidence = failureEvidenceSummary(error);
228
- const message = connectNeedMessage(error) ?? employeeFailure(error.code, this.agent.loginProvider, promptDispatched);
233
+ const message = (connectNeedMessage(error) ?? employeeFailure(error.code, this.agent.loginProvider, promptDispatched)) + cloudNotice;
229
234
  const login = originalLoginFailure(error);
230
235
  let diagnostic = login?.technical ? JSON.stringify(login.technical) : '';
231
236
  if (login?.technical && this.reportLoginFailure) {
@@ -239,7 +244,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
239
244
  }
240
245
  throw new LlmError(message, error.code, { cause: new Error(`诊断代码:${error.code};${error.requires}` + (evidence ? ';' + evidence : '') + (diagnostic ? ';' + diagnostic : '')) });
241
246
  }
242
- throw new LlmError(employeeFailure('TURN_FAILED', this.agent.loginProvider, promptDispatched), 'TURN_FAILED', { cause: error });
247
+ throw new LlmError(employeeFailure('TURN_FAILED', this.agent.loginProvider, promptDispatched) + cloudNotice, 'TURN_FAILED', { cause: error });
243
248
  }
244
249
  finally {
245
250
  if (options.sessionId)
@@ -302,7 +307,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
302
307
  this.employeeNoticeSessions.add(key);
303
308
  live = undefined;
304
309
  const configuration = JSON.stringify([config.acpMaxMessageBytes, config.brokerMaxFrameBytes, config.brokerControlMaxBytes, config.employeeShellKillGraceMs]);
305
- 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 }) });
310
+ Object.assign(request, { acpMaxMessageBytes: config.acpMaxMessageBytes, resumeSessionId: this.agent.id === CODEX_CLOUD_AGENT.id ? undefined : 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 }) });
306
311
  request.previousContextSha256 = previous?.contextSha256;
307
312
  const after = options.messages.findLastIndex(message => message.role === 'assistant');
308
313
  const tail = options.messages.slice(after + 1);
@@ -323,7 +328,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
323
328
  let input = await prepareInput(options, this.readImage);
324
329
  const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
325
330
  request.contextSha256 = contextSha256;
326
- const codex = this.agent.loginProvider === 'codex';
331
+ const codex = this.agent.routing === 'native-exec';
327
332
  const contextChanged = !!previous && codex && (previous.contextSha256 ?? '').toLowerCase() !== contextSha256;
328
333
  // Only identical durable context can prove a legacy context-bound journal.
329
334
  // New Codex transport scopes are independent of the native context digest.
@@ -348,7 +353,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
348
353
  }
349
354
  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))
350
355
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
351
- input = await prepareContinuation({ ...options, messages: options.messages.slice((checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
356
+ input = await prepareContinuation({ ...options, messages: options.messages.slice(this.agent.id === CODEX_CLOUD_AGENT.id ? 0 : (checkpoint?.index ?? -1) + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
352
357
  if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
353
358
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
354
359
  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 });
@@ -397,7 +402,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
397
402
  const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
398
403
  let promptPermit;
399
404
  let confirmedNativeMode;
400
- const hooks = { closeDiagnostics: runtime.closeDiagnostics, broker: runtime.broker, sessionOwnership: runtime.sessionOwnership, employeeExecution: runtime.employeeExecution, ...this.permissions ? { promptGuard: () => {
405
+ const hooks = { cloudCancelReceiptWaitMs: config.cloudCancelReceiptWaitMs ?? DEFAULT_CONFIG.cloudCancelReceiptWaitMs, closeDiagnostics: runtime.closeDiagnostics, broker: runtime.broker, sessionOwnership: runtime.sessionOwnership, employeeExecution: runtime.employeeExecution, ...this.permissions ? { promptGuard: () => {
401
406
  if (!promptPermit)
402
407
  throw new NeedError('PERMISSION_POLICY_CHANGED', '当前权限没有保持确认,本次没有继续派发。', '当前权限代次和同值回执');
403
408
  return promptPermit;
@@ -407,13 +412,18 @@ export class CodexRemoteAdapter extends LlmAdapter {
407
412
  } } : {}, approve: async (permission, approvalSignal) => {
408
413
  const execution = runtime.execution;
409
414
  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
+ }
410
419
  if (execution && bridge?.enabled && bridge.isBridge(toolName)) {
411
420
  const current = this.permissions ? permissionMode('claude', this.permissions.read(options.sessionId)) : undefined;
412
- if (current === 'plan') {
421
+ const cloudReadOnly = this.agent.id === CODEX_CLOUD_AGENT.id && current === 'plan' && confirmedNativeMode === 'read-only' && bridge.isReadOnly(toolName);
422
+ if (current === 'plan' && !cloudReadOnly) {
413
423
  details.record({ kind: 'tool', severity: 'info', code: 'TOOLBRIDGE_PLAN_PERMISSION_REJECTED', summary: '本轮为plan档,桥接原生权限请求未放行。' });
414
424
  return 'rejected';
415
425
  }
416
- if (current === 'default' && confirmedNativeMode === 'default') {
426
+ if (cloudReadOnly || current === 'default' && confirmedNativeMode === (this.agent.loginProvider === 'claude' ? 'default' : 'workspace-write')) {
417
427
  details.record({ kind: 'tool', severity: 'info', code: 'TOOLBRIDGE_NATIVE_PERMISSION_ANSWERED', summary: '已确认桥接工具仅在DSH审批,原生请求自动答复一次。', payload: { tool: toolName } });
418
428
  return 'allowed-once';
419
429
  }
@@ -434,7 +444,13 @@ export class CodexRemoteAdapter extends LlmAdapter {
434
444
  catch (error) {
435
445
  failure = error;
436
446
  session?.close({ layer: 'adapter', initiator: 'adapter.mapper-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' });
437
- } }, onResponse: response => push(mapper.acpResponse(response)), onDetail: detail => details.record(detail) };
447
+ } }, onResponse: response => { if (this.agent.id === CODEX_CLOUD_AGENT.id) {
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
454
  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 });
439
455
  session = new AcpSession(transport, hooks);
440
456
  live = { session, runtime, configuration, contextSha256, usageSnapshot: mapper.usageSnapshot };
@@ -484,7 +500,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
484
500
  const task = (async () => {
485
501
  remoteAttempted = true;
486
502
  try {
487
- 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);
503
+ await session.start(runtime.execution?.hostCwd ?? runtime.cwd, this.agent.id === CODEX_CLOUD_AGENT.id ? undefined : previous?.sessionId, modelSignal, { systemPrompt: input.systemPrompt, routing: this.agent.routing, loginProvider: this.agent.loginProvider, ...(bridgeMcp ? { toolBridgeServers: bridgeMcp.mcpServers } : {}), ...(runtime.execution ? { employeeRouting: runtime.execution.routing } : {}), ...(codex ? { codexNewSessionOnly: true } : {}), ...(runtime.employeeExecutionMeta ? { employeeExecution: runtime.employeeExecutionMeta } : {}) }, input.prompt);
488
504
  }
489
505
  catch (error) {
490
506
  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 } });
@@ -724,14 +740,14 @@ export function apply(ctx, live) {
724
740
  };
725
741
  return runtime;
726
742
  };
727
- 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;
743
+ const local = agent.routing === 'mcp' ? 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, agent.loginProvider, code, 'local-admission'), recordUnscoped: (request, observation) => managerForProfile().recordLocalFailure({ sessionId: request.sessionId, provider: agent.loginProvider, code: observation.code, observation }), configuration: config, details, open, ...(agent.id === CODEX_CLOUD_AGENT.id ? { readOnly: (id) => dshPermissionSource(ctx).read(id).sandbox === 'read-only' } : {}) }) : undefined;
728
744
  const workspace = async (request) => {
729
745
  const services = ctx;
730
746
  const registry = services.get('workspaceRegistry');
731
747
  const sessions = services.get('sessions');
732
748
  return officialEmployeeWorkspace(request.sessionId, registry, sessions?.get(request.sessionId)?.header);
733
749
  };
734
- const provider = connectProvider(get, { agent, workspace, source: sessionSources, ...(agent.loginProvider === 'codex' ? { employee: {
750
+ const provider = connectProvider(get, { agent, workspace, source: sessionSources, ...(agent.routing === 'native-exec' ? { employee: {
735
751
  getNetwork: () => ctx.get('aiWorkbenchNetwork'),
736
752
  workspace, native: () => resolveEmployeeNative(),
737
753
  } } : {}), details, open, local });
@@ -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 type { AgentDefinition } from './agents.ts';
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 {
@@ -1,4 +1,5 @@
1
1
  import { LlmError, ReasoningEffortId } from '@deepseek-ai/dsh-llm';
2
+ import { CODEX_CLOUD_AGENT } from "./agents.js";
2
3
  import { validateTarget } from "./provider.js";
3
4
  import { ModelConfigurationError } from "./model-configuration.js";
4
5
  import { runCatalog, catalogSafeText } from "./catalog-ssh.js";
@@ -124,6 +125,9 @@ export class ModelCatalog {
124
125
  if (state.phase !== 'connected' || state.instanceId !== target.instanceId || state.epoch !== target.epoch)
125
126
  controller.abort(new CatalogError('连接已变化,本次模型列表读取已停止;连接恢复后请重新打开模型菜单。', 'MODEL_CATALOG_CONNECTION_CHANGED'));
126
127
  });
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() { } };
127
131
  const max = this.maxBytes();
128
132
  if (!Number.isSafeInteger(max) || max < 1)
129
133
  fail('模型目录容量设置无效,请联系管理员检查插件配置。');
@@ -4,6 +4,7 @@ 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(云)目前只支持本机文件夹;请选择本机文件夹并新建会话。',
7
8
  PERMISSION_POLICY_REQUIRED: '我需要读取这条对话的权限设置,目前没有读到;本轮未执行,你的原话仍保留。',
8
9
  PERMISSION_MODE_UNSUPPORTED: '这个权限档位还没有对应的远程执行能力;我需要主机连接组件支持该档位,本轮未执行,你的原话仍保留。',
9
10
  PERMISSION_MODE_UNCONFIRMED: '远端没有确认按当前权限执行,本轮未继续;你的原话仍保留,具体原因见技术详情。',
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 } from "./agents.js";
6
+ import { CODEX_AGENT, CODEX_CLOUD_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,6 +164,8 @@ 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确认的本机工作区与员工工具通道');
167
169
  if (options.employee && !host) {
168
170
  const module = await import("./employee-provider.js");
169
171
  request.localContext = await module.inspectEmployeeWorkspace(get, options.employee, agent, api, request);
@@ -217,7 +219,7 @@ export function connectProvider(get, options = {}) {
217
219
  return local;
218
220
  }
219
221
  }
220
- if (!host && agent.loginProvider === 'claude' && options.local) {
222
+ if (!host && agent.routing === 'mcp' && options.local) {
221
223
  const runtime = await options.local(request, api, connection, target);
222
224
  if (runtime)
223
225
  return runtime;
@@ -1,3 +1,4 @@
1
+ import { CloudTurnFailure } from "./cloud-failure.js";
1
2
  import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
2
3
  import { ToolBridge } from "./toolbridge.js";
3
4
  import { NeedError } from "./remote.js";
@@ -245,6 +246,8 @@ export class ToolBridgeLoop {
245
246
  if (key && this.runs.get(key) === run)
246
247
  this.runs.delete(key);
247
248
  await run.task;
249
+ if (run.error instanceof CloudTurnFailure)
250
+ throw run.error;
248
251
  }
249
252
  }
250
253
  }
@@ -21,7 +21,10 @@ export function bridgeTable(tools = []) {
21
21
  if (table.has(alias))
22
22
  throw new NeedError('TOOLBRIDGE_NAME_COLLISION', '工具桥名称冲突,未执行。', '唯一工具桥名称');
23
23
  const schema = structuredClone(tool);
24
- table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description, inputSchema: structuredClone(schema.parameters) } });
24
+ // Only an explicit boolean from the supplied tool declaration is authority.
25
+ // Pinned DSH ToolSchema has no read-only field; unmarked tools stay unmarked.
26
+ const hint = schema.annotations?.readOnlyHint;
27
+ table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description, inputSchema: structuredClone(schema.parameters), ...(typeof hint === 'boolean' ? { annotations: { readOnlyHint: hint } } : {}) } });
25
28
  }
26
29
  return table;
27
30
  }
@@ -86,6 +86,7 @@ export declare class ToolBridge {
86
86
  title?: string | undefined;
87
87
  }[];
88
88
  isBridge(name: unknown): boolean;
89
+ isReadOnly(name: unknown): boolean;
89
90
  call(alias: string, args: Record<string, unknown>, signal: AbortSignal): Promise<CallToolResult>;
90
91
  get pending(): Pending[];
91
92
  get unsettled(): boolean;
@@ -44,6 +44,7 @@ export class ToolBridge {
44
44
  return; this.enabled = true; this.record = record; record({ kind: 'session', severity: 'info', code: 'TOOLBRIDGE_SELECTED', summary: TOOLBRIDGE_NOTICE, payload: { toolCount: this.table.size, toolTimeoutSec: TOOLBRIDGE_TIMEOUT_SECONDS, timeoutSource: 'owner-2026-10-26', snapshot: 'native-session-open', excluded: 'official-file-command-subagent-team-run_code' } }); }
45
45
  get tools() { return [...this.table.values()].map(t => t.wire); }
46
46
  isBridge(name) { return typeof name === 'string' && this.table.has(name.replace(/^mcp__employee__/, '')); }
47
+ isReadOnly(name) { return typeof name === 'string' && this.table.get(name.replace(/^mcp__employee__/, ''))?.wire.annotations?.readOnlyHint === true; }
47
48
  async call(alias, args, signal) {
48
49
  const tool = this.table.get(alias);
49
50
  if (!this.enabled || this.ended || this.localTurnEnded || !this.active || this.active.aborted || !tool || signal.aborted)