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

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 (56) hide show
  1. package/README.md +36 -7
  2. package/dist/acp.d.ts +23 -3
  3. package/dist/acp.js +106 -21
  4. package/dist/broker-runtime.d.ts +2 -0
  5. package/dist/broker-runtime.js +60 -3
  6. package/dist/broker.d.ts +56 -1
  7. package/dist/broker.js +310 -11
  8. package/dist/claude-local.js +26 -5
  9. package/dist/client.js +1 -1
  10. package/dist/close-diagnostics.d.ts +1 -1
  11. package/dist/close-diagnostics.js +1 -1
  12. package/dist/cold-protocol.d.ts +17 -0
  13. package/dist/cold-protocol.js +399 -0
  14. package/dist/cold-recovery.d.ts +62 -0
  15. package/dist/cold-recovery.js +595 -0
  16. package/dist/cold-store.d.ts +99 -0
  17. package/dist/cold-store.js +29 -0
  18. package/dist/conversation-details.js +21 -8
  19. package/dist/employee-endpoint.js +15 -1
  20. package/dist/employee-mcp.js +1 -1
  21. package/dist/employee-native.js +7 -1
  22. package/dist/employee-provider.d.ts +2 -0
  23. package/dist/employee-provider.js +46 -11
  24. package/dist/employee-relay.js +148 -1
  25. package/dist/employee-shell.d.ts +2 -0
  26. package/dist/employee-shell.js +22 -19
  27. package/dist/employee-startup.d.ts +18 -0
  28. package/dist/employee-startup.js +95 -0
  29. package/dist/employee-tools.js +2 -2
  30. package/dist/employee-workspace.d.ts +20 -4
  31. package/dist/employee-workspace.js +26 -5
  32. package/dist/index.d.ts +12 -3
  33. package/dist/index.js +223 -51
  34. package/dist/input.js +4 -1
  35. package/dist/live-steering.d.ts +46 -0
  36. package/dist/live-steering.js +45 -0
  37. package/dist/mapping.d.ts +4 -24
  38. package/dist/mapping.js +11 -65
  39. package/dist/model-catalog.d.ts +2 -0
  40. package/dist/model-catalog.js +5 -1
  41. package/dist/preflight-diagnostic.js +1 -1
  42. package/dist/presentation.js +1 -0
  43. package/dist/provider.d.ts +16 -0
  44. package/dist/provider.js +66 -33
  45. package/dist/rpc-namespace.js +16 -2
  46. package/dist/session-source.d.ts +3 -1
  47. package/dist/session-source.js +2 -1
  48. package/dist/startup-timing.d.ts +14 -0
  49. package/dist/startup-timing.js +34 -0
  50. package/dist/toolbridge-loop.d.ts +3 -2
  51. package/dist/toolbridge-loop.js +4 -2
  52. package/dist/toolbridge-table.d.ts +4 -3
  53. package/dist/toolbridge-table.js +14 -5
  54. package/dist/toolbridge.d.ts +1 -1
  55. package/dist/toolbridge.js +23 -4
  56. package/package.json +23 -16
@@ -0,0 +1,99 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { NeedError } from './remote.ts';
3
+ import type { ConnectTarget } from './provider.ts';
4
+ export interface ColdWrite {
5
+ id: string;
6
+ sha256: string;
7
+ wire: string;
8
+ baseSequence: number;
9
+ chunkBytes: number;
10
+ chunks: number;
11
+ method?: string;
12
+ rpcId?: string | number | null;
13
+ }
14
+ export interface ColdRound {
15
+ version: 1;
16
+ id: string;
17
+ sessionId: string;
18
+ provider: string;
19
+ brand: 'codex' | 'claude';
20
+ phase: 'opening' | 'running' | 'terminal' | 'committed';
21
+ target: ConnectTarget;
22
+ brokerId: string;
23
+ instanceId: string;
24
+ controlMaxBytes: number;
25
+ heartbeatIntervalMs: number;
26
+ nativeId?: string;
27
+ promptId?: string;
28
+ promptSha256?: string;
29
+ promptBytes?: number;
30
+ originTurn?: number;
31
+ originStep?: number;
32
+ rpcIds: (string | number | null)[];
33
+ answered: (string | number | null)[];
34
+ inputSequence: number;
35
+ pending?: ColdWrite;
36
+ meta?: {
37
+ identity: string;
38
+ cwd: string;
39
+ binding?: {
40
+ bindingId: string;
41
+ workspaceId: string;
42
+ revision: number;
43
+ };
44
+ hostSource?: unknown;
45
+ contextSha256: string; /** 只读旧版字段;不再作为跨轮基线。 */
46
+ baseline?: unknown;
47
+ modelConfiguration?: unknown;
48
+ header: unknown;
49
+ model: string; /** 只读旧版字段;不再覆盖DSH已冻结的本步配置。 */
50
+ callConfig?: import('@deepseek-ai/dsh-llm').LlmCallConfig;
51
+ prelude?: string;
52
+ inputDigests?: Record<string, string>;
53
+ localDirectory?: {
54
+ path: string;
55
+ device: number;
56
+ inode: number;
57
+ };
58
+ };
59
+ localNotices?: {
60
+ beforeUpdate: number;
61
+ text: string;
62
+ kind?: 'text' | 'reasoning';
63
+ }[];
64
+ cancelIntent?: {
65
+ source: 'user-signal' | 'official-user' | 'wire';
66
+ delivered?: boolean;
67
+ };
68
+ cancelCheckpoint?: {
69
+ inputNotDelivered: true;
70
+ receipt: unknown;
71
+ };
72
+ /** 只读旧版字段;不再参与恢复结算。 */ finalUsage?: unknown;
73
+ errorDelivery?: {
74
+ markerId: string;
75
+ code: string;
76
+ promptId?: string;
77
+ token: string;
78
+ message: string;
79
+ };
80
+ terminalAfter?: number;
81
+ outputStart?: number;
82
+ outputAfter: number;
83
+ officialSeq?: number;
84
+ terminal?: {
85
+ kind: 'result' | 'error' | 'local-cancel';
86
+ value: unknown;
87
+ };
88
+ failure?: string;
89
+ }
90
+ export interface ColdStore {
91
+ read(sessionId: string, provider: string): Promise<ColdRound | undefined>;
92
+ put(round: ColdRound): Promise<void>;
93
+ update(sessionId: string, provider: string, id: string, change: (round: ColdRound) => void): Promise<ColdRound>;
94
+ }
95
+ export declare const coldKey: (sessionId: string, provider: string) => string;
96
+ export declare function coldNeed(code?: string): NeedError;
97
+ export declare function createColdStore(ctx: Context): ColdStore;
98
+ export declare const wireDigest: (bytes: Uint8Array) => string;
99
+ export declare function newColdId(): `${string}-${string}-${string}-${string}-${string}`;
@@ -0,0 +1,29 @@
1
+ import { randomUUID, createHash } from 'node:crypto';
2
+ import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
3
+ import { z } from 'zod';
4
+ import { NeedError } from "./remote.js";
5
+ const spec = defineDomain({ name: 'ai_workbench_cold_rounds', version: 1, tables: { rounds: domainTable(z.object({ sessionId: z.string(), provider: z.string(), payload: z.unknown() }).strict()) } });
6
+ export const coldKey = (sessionId, provider) => JSON.stringify([sessionId, provider]);
7
+ export function coldNeed(code = 'INPUT_DELIVERY_UNCONFIRMED') { return new NeedError(code, '原轮恢复状态未能确认,没有另开模型轮或重复发送输入。', '原会话持久归属、输入确认和官方日志落盘证据'); }
8
+ export function createColdStore(ctx) {
9
+ let domain;
10
+ let tail = Promise.resolve();
11
+ const open = () => { if (!domain) {
12
+ const service = ctx.get('storageDomain');
13
+ if (!service)
14
+ throw coldNeed();
15
+ domain = service.open(spec).catch(e => { domain = undefined; throw e; });
16
+ } return domain; };
17
+ ctx.effect(() => async () => { await tail; if (domain)
18
+ await (await domain).close(); });
19
+ const rawRead = async (sessionId, provider) => { const row = (await open()).table('rounds').get(coldKey(sessionId, provider)); if (!row)
20
+ return; const record = structuredClone(row.payload); if (record.version !== 1 || record.sessionId !== sessionId || record.provider !== provider || !record.id || !Array.isArray(record.rpcIds) || !Array.isArray(record.answered))
21
+ throw coldNeed(); return record; };
22
+ const rawPut = async (round) => { await (await open()).table('rounds').put(coldKey(round.sessionId, round.provider), { sessionId: round.sessionId, provider: round.provider, payload: structuredClone(round) }); };
23
+ const enqueue = (work) => { const result = tail.then(work); tail = result.then(() => { }, () => { }); return result; };
24
+ const store = { async read(sessionId, provider) { await tail; return rawRead(sessionId, provider); }, put(round) { const copy = structuredClone(round); return enqueue(() => rawPut(copy)); }, update(sessionId, provider, id, change) { return enqueue(async () => { const row = await rawRead(sessionId, provider); if (!row || row.id !== id)
25
+ throw coldNeed('SESSION_CONTEXT_MISMATCH'); change(row); await rawPut(row); return row; }); } };
26
+ return store;
27
+ }
28
+ export const wireDigest = (bytes) => createHash('sha256').update(bytes).digest('hex');
29
+ export function newColdId() { return randomUUID(); }
@@ -1,3 +1,4 @@
1
+ import { STARTUP_STAGES } from "./startup-timing.js";
1
2
  import { employeeExecutionInfo } from "./employee-info.js";
2
3
  const redactionMarkers = new WeakSet();
3
4
  function redaction(fields) {
@@ -349,6 +350,17 @@ function catalogScopeStructure(value, nested = false) {
349
350
  return [key, opaqueStructure(child)];
350
351
  }));
351
352
  }
353
+ function startupTimingStructure(value) {
354
+ if (!value || typeof value !== 'object' || Array.isArray(value))
355
+ return opaqueStructure(value);
356
+ return Object.fromEntries(Object.entries(value).map(([key, child]) => {
357
+ if (key === 'clock' && child === 'client-monotonic' || key === 'stage' && typeof child === 'string' && STARTUP_STAGES.includes(child) || key === 'outcome' && (child === 'completed' || child === 'failed'))
358
+ return [key, child];
359
+ if (['startMs', 'endMs', 'durationMs'].includes(key) && typeof child === 'number' && Number.isFinite(child) && child >= 0)
360
+ return [key, child];
361
+ return [key, opaqueStructure(child)];
362
+ }));
363
+ }
352
364
  export function sanitizeObservation(observation, protectModelMaterial = false) {
353
365
  const payload = snapshotPayload(observation.payload, new Set(), protectModelMaterial && observation.kind !== 'commands');
354
366
  return freezeDeep({
@@ -359,13 +371,14 @@ export function sanitizeObservation(observation, protectModelMaterial = false) {
359
371
  : observation.kind === 'session' && observation.code === 'CATALOG_SCOPE_INFORMATION' ? catalogScopeStructure(payload)
360
372
  : observation.kind === 'session' && observation.code === 'CODEX_CONTEXT_SESSION_REPLACED' ? contextTransitionStructure(payload)
361
373
  : observation.kind === 'session' && ['MODEL_CONFIGURATION_CONFIRMED', 'MODEL_CONFIGURATION_FAILED', 'MODEL_CONFIGURATION_INFORMATION', 'MODEL_CONFIGURATION_CHANGED_DURING_TURN', 'TURN_GATE_INFORMATION'].includes(observation.code) ? modelConfigurationStructure(payload)
362
- : observation.kind === 'session' && observation.code === 'REMOTE_CLOSE_REASON' ? closeStructure(payload)
363
- : observation.kind === 'commands' ? catalogStructure(payload)
364
- : observation.kind === 'usage' ? usageStructure(payload)
365
- : observation.kind === 'session' && observation.code === 'EMPLOYEE_MCP_INFORMATION' ? (employeeExecutionInfo(observation.payload) ?? { information: 'unconfirmed' })
366
- : observation.kind === 'session' && ['CLAUDE_EMPLOYEE_OPERATION', 'CLAUDE_EMPLOYEE_PROCESS', 'CLAUDE_EMPLOYEE_REVOKED', 'CLAUDE_EMPLOYEE_SCOPE'].includes(observation.code) ? employeeStructure(payload)
367
- : observation.kind === 'need' ? payload
368
- : observation.kind === 'tool' || ['SDK_ITEM', 'SDK_TOOL', 'ACP_SESSION_UPDATE', 'ACP_IDLE_UPDATE'].includes(observation.code) ? toolStructure(payload)
369
- : opaqueStructure(payload),
374
+ : observation.kind === 'session' && observation.code === 'STARTUP_TIMING' ? startupTimingStructure(payload)
375
+ : observation.kind === 'session' && observation.code === 'REMOTE_CLOSE_REASON' ? closeStructure(payload)
376
+ : observation.kind === 'commands' ? catalogStructure(payload)
377
+ : observation.kind === 'usage' ? usageStructure(payload)
378
+ : observation.kind === 'session' && observation.code === 'EMPLOYEE_MCP_INFORMATION' ? (employeeExecutionInfo(observation.payload) ?? { information: 'unconfirmed' })
379
+ : observation.kind === 'session' && ['CLAUDE_EMPLOYEE_OPERATION', 'CLAUDE_EMPLOYEE_PROCESS', 'CLAUDE_EMPLOYEE_REVOKED', 'CLAUDE_EMPLOYEE_SCOPE'].includes(observation.code) ? employeeStructure(payload)
380
+ : observation.kind === 'need' ? payload
381
+ : observation.kind === 'tool' || ['SDK_ITEM', 'SDK_TOOL', 'ACP_SESSION_UPDATE', 'ACP_IDLE_UPDATE'].includes(observation.code) ? toolStructure(payload)
382
+ : opaqueStructure(payload),
370
383
  });
371
384
  }
@@ -67,7 +67,21 @@ export async function openEmployeeLease(options, initialSignal) {
67
67
  catch {
68
68
  invalidate('EMPLOYEE_CONTEXT_CHANGED', initiator);
69
69
  } };
70
- offs.push(api.onConnectionState(() => changed('lease.connection-change')), api.onWorkspaceLocationState(() => changed('lease.workspace-change')), network.onState(event => { if (event?.kind === 'lost' || network.getState().phase !== 'online')
70
+ offs.push(api.onConnectionState(() => {
71
+ try {
72
+ current();
73
+ return;
74
+ }
75
+ catch { }
76
+ const currentState = api.getWorkspaceLocationState(), rows = currentState.items.filter(x => x.workspaceId === request.workspaceId);
77
+ if (options.getConnect() === api && options.getNetwork() === network && api.getConnectionState().instanceId === connection.instanceId && (currentState.phase !== 'ready' || rows.length === 1 && rows[0].bindingId === request.expectedBindingId && rows[0].source === 'local' && rows[0].status === 'selected'))
78
+ invalidate('CONNECTION_LOST', 'lease.connection-change');
79
+ else
80
+ changed('lease.connection-change');
81
+ }), api.onWorkspaceLocationState(() => { if (api.getWorkspaceLocationState().phase !== 'ready')
82
+ invalidate('CONNECTION_LOST', 'lease.workspace-offline');
83
+ else
84
+ changed('lease.workspace-change'); }), network.onState(event => { if (event?.kind === 'lost' || network.getState().phase !== 'online')
71
85
  invalidate('EMPLOYEE_ENDPOINT_UNAVAILABLE', 'lease.network-loss'); }));
72
86
  async function physicalDirectory(signal) {
73
87
  current();
@@ -8,7 +8,7 @@ import { createEmployeeTools } from "./employee-tools.js";
8
8
  import { employeeRouting } from "./employee-relay.js";
9
9
  import { NeedError } from "./remote.js";
10
10
  const string = { type: 'string' }, integer = { type: 'integer' }, boolean = { type: 'boolean' };
11
- function schema(name, properties, required) { return { name, description: '在员工电脑所选工作区执行' + name + ';不在主机回退。', inputSchema: { type: 'object', properties, required, additionalProperties: false } }; }
11
+ function schema(name, properties, required) { return { name, description: '在员工电脑所选工作区执行' + name + ';不在主机回退。' + (name === 'Bash' ? '输出原样保留:若stdoutEncoding或stderrEncoding为base64,对应字符串为原始字节的base64编码,按标明编码处理;退出状态独立保留。' : ''), inputSchema: { type: 'object', properties, required, additionalProperties: false } }; }
12
12
  export const EMPLOYEE_MCP_TOOLS = [
13
13
  schema('Read', { file_path: string, offset: integer, limit: integer, pages: string }, ['file_path']),
14
14
  schema('Write', { file_path: string, content: string }, ['file_path', 'content']),
@@ -2,14 +2,20 @@ import { createRequire } from 'node:module';
2
2
  import { dirname, join } from 'node:path';
3
3
  import { NeedError } from "./remote.js";
4
4
  const require = createRequire(import.meta.url);
5
+ let installedPath;
5
6
  export const EMPLOYEE_NATIVE = Object.freeze({ version: '0.160.1', platform: 'darwin', arch: 'arm64', package: '@openai/codex-darwin-arm64', packageVersion: '0.160.1-darwin-arm64', triple: 'aarch64-apple-darwin' });
6
7
  /** Resolve the installed executable; no per-turn hash or version probe. */
7
8
  export async function resolveEmployeeNative(ports = {}) {
8
9
  if ((ports.platform ?? process.platform) !== EMPLOYEE_NATIVE.platform || (ports.arch ?? process.arch) !== EMPLOYEE_NATIVE.arch)
9
10
  throw new NeedError('EMPLOYEE_PLATFORM_UNSUPPORTED', '当前设备尚未支持本机执行。', '对应平台执行器');
11
+ if (!ports.resolve && installedPath)
12
+ return { path: installedPath };
10
13
  try {
11
14
  const manifest = (ports.resolve ?? require.resolve)(EMPLOYEE_NATIVE.package + '/package.json');
12
- return { path: join(dirname(manifest), 'vendor', EMPLOYEE_NATIVE.triple, 'bin', 'codex') };
15
+ const path = join(dirname(manifest), 'vendor', EMPLOYEE_NATIVE.triple, 'bin', 'codex');
16
+ if (!ports.resolve)
17
+ installedPath = path;
18
+ return { path };
13
19
  }
14
20
  catch {
15
21
  throw new NeedError('AW_EMPLOYEE_BINARY_MISSING', '本机执行组件没有装齐,请重新安装插件。', '随插件安装的执行组件');
@@ -4,6 +4,7 @@ import type { ConnectApi, ConnectTarget, ConnectionState, Project, Runtime, Runt
4
4
  import { type BrokerIo, type SshArgv } from './broker.ts';
5
5
  import type { DetailChannel } from './remote-details.ts';
6
6
  import type { LocalWorkspaceContext } from '@ai-workbench/connect/api';
7
+ import type { EmployeeStartup } from './employee-startup.ts';
7
8
  export interface EmployeeProviderOptions {
8
9
  getNetwork(): NetworkApi | undefined;
9
10
  workspace(request: RuntimeRequest): Promise<{
@@ -26,6 +27,7 @@ interface Admission {
26
27
  target: ConnectTarget;
27
28
  connection: ConnectionState;
28
29
  request: RuntimeRequest;
30
+ preparation?: EmployeeStartup;
29
31
  }
30
32
  /** Inspect the current local workspace once at turn start, before host readiness. */
31
33
  export declare function inspectEmployeeWorkspace(get: () => ConnectApi | undefined, employee: EmployeeProviderOptions, agent: AgentDefinition, api: ConnectApi, request: RuntimeRequest): Promise<Readonly<LocalWorkspaceContext> | undefined>;
@@ -52,7 +52,8 @@ export async function inspectEmployeeWorkspace(get, employee, agent, api, reques
52
52
  const stable = () => { sourceStable(); const now = api.getConnectionState(), location = api.getWorkspaceLocationState(), matches = location.items.filter(x => x.workspaceId === workspace.id); if (get() !== api || now.phase !== 'connected' || now.instanceId !== connection.instanceId || now.epoch !== connection.epoch || location.phase !== 'ready' || location.instanceId !== connection.instanceId || location.epoch !== connection.epoch || matches.length !== 1 || matches[0].source !== 'local' || matches[0].status !== 'selected' || matches[0].bindingId !== row.bindingId)
53
53
  throw fail('EMPLOYEE_CONTEXT_CHANGED'); request.signal?.throwIfAborted(); };
54
54
  stable();
55
- const context = await api.getLocalWorkspaceContext({ instanceId: connection.instanceId, epoch: connection.epoch, workspaceId: workspace.id, expectedBindingId: row.bindingId });
55
+ const readContext = () => api.getLocalWorkspaceContext({ instanceId: connection.instanceId, epoch: connection.epoch, workspaceId: workspace.id, expectedBindingId: row.bindingId });
56
+ const context = await (request.startupTiming?.run('workspace-context', readContext) ?? readContext());
56
57
  if (!context.ok)
57
58
  throw connectNeedError(context.error);
58
59
  stable();
@@ -111,6 +112,10 @@ export function createEmployeeProvider(get, options, agent) {
111
112
  const revoke = (reason, initiator, changes) => { lifetime.abort(reason); if (candidate)
112
113
  void candidate.dispose(reason, { layer: 'endpoint', initiator, reason: reason.code, action: 'invalidate', changes }).catch(() => { }); };
113
114
  disposers.push(api.onWorkspaceLocationState(next => {
115
+ if (next.phase !== 'ready') {
116
+ revoke(fail('CONNECTION_LOST'), 'endpoint.workspace-offline');
117
+ return;
118
+ }
114
119
  const matches = next.items.filter(item => item.workspaceId === context.workspaceId);
115
120
  if (get() !== api || next.phase !== 'ready' || next.instanceId !== connection.instanceId || next.epoch !== connection.epoch || matches.length !== 1 || matches[0].bindingId !== context.bindingId || matches[0].source !== 'local' || matches[0].status !== 'selected')
116
121
  revoke(fail('EMPLOYEE_CONTEXT_CHANGED'), 'endpoint.workspace-change', [{ field: 'workspace.binding-id', before: context.bindingId, after: matches[0]?.bindingId ?? null }, { field: 'workspace.source', before: 'local', after: matches[0]?.source ?? null }, { field: 'workspace.status', before: 'selected', after: matches[0]?.status ?? null }, { field: 'workspace.match-count', before: 1, after: matches.length }]);
@@ -118,6 +123,8 @@ export function createEmployeeProvider(get, options, agent) {
118
123
  revoke(fail('CONNECTION_LOST'), 'endpoint.connection-change', [{ field: 'connection.instance-id', before: connection.instanceId, after: next.instanceId }, { field: 'connection.epoch', before: connection.epoch, after: next.epoch }, { field: 'connection.phase', before: 'connected', after: next.phase }]); }), network.onState(event => { if (event.kind === 'lost' || employee.getNetwork() !== network)
119
124
  revoke(fail('CONNECTION_LOST'), 'endpoint.network-loss', [{ field: 'network.phase', before: null, after: event.state.phase }]); }));
120
125
  details = await options.details?.(request, api, connection, target);
126
+ if (details)
127
+ request.startupTiming?.bind(event => details.record(event));
121
128
  const sink = details;
122
129
  closeDiagnostics = new CloseDiagnostics(event => sink?.record(event));
123
130
  closeDiagnostics.bind(event => sink?.record(event));
@@ -127,11 +134,22 @@ export function createEmployeeProvider(get, options, agent) {
127
134
  throw fail('EMPLOYEE_OPERATION_UNSUPPORTED');
128
135
  if (!Number.isSafeInteger(request.acpMaxMessageBytes) || request.acpMaxMessageBytes < 1)
129
136
  throw fail('SETTINGS_REQUIRED');
130
- const admitted = await admitEmployeeLocation({ api: api, network, workspace, connection, expectedLocal: { instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, bindingId: context.bindingId, directory: { ...context.directory } }, settingsPath: target.session.settingsPath, signal: roundSignal });
137
+ const prepareLocation = () => input.preparation ? input.preparation.location(network, context) : admitEmployeeLocation({ api: api, network, workspace, connection, expectedLocal: { instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, bindingId: context.bindingId, directory: { ...context.directory } }, settingsPath: target.session.settingsPath, signal: roundSignal });
138
+ const resolveNative = () => input.preparation ? input.preparation.native() : employee.native();
139
+ // 仅把无授权、无目标的静态包路径解析与本轮N准备重叠。两项都收敛后,
140
+ // 按原顺序处理错误;每轮N准备、事件撤销、执行目标绑定仍完整执行。
141
+ const [locationResult, nativeResult] = await Promise.allSettled([
142
+ input.preparation ? prepareLocation() : request.startupTiming?.run('endpoint-prepare', prepareLocation) ?? prepareLocation(),
143
+ input.preparation ? resolveNative() : request.startupTiming?.run('native-metadata', resolveNative) ?? resolveNative(),
144
+ ]);
145
+ if (locationResult.status === 'rejected')
146
+ throw locationResult.reason;
147
+ if (nativeResult.status === 'rejected')
148
+ throw nativeResult.reason;
149
+ const admitted = locationResult.value, native = nativeResult.value;
150
+ roundSignal.throwIfAborted();
131
151
  if (request.cwd && request.cwd !== admitted.cwd || request.bindingId && request.bindingId !== admitted.bindingId || request.workspaceId && request.workspaceId !== admitted.workspaceId)
132
152
  throw fail('SESSION_CONTEXT_MISMATCH');
133
- const native = await employee.native();
134
- roundSignal.throwIfAborted();
135
153
  if (!absolute(native.path))
136
154
  throw fail('EMPLOYEE_BINARY_REQUIRED');
137
155
  // Only executable identity belongs in this scope. Diagnostic metadata and object key
@@ -167,18 +185,33 @@ export function createEmployeeProvider(get, options, agent) {
167
185
  if (!options.open)
168
186
  throw fail('RUNTIME_REQUIRED');
169
187
  // Host cwd is only the protected agent bootstrap/config directory. Native tools use admitted.cwd.
170
- const host = opening = await options.open(target, { name: 'employee', path: target.projectRoot }, { ...request, signal: roundSignal, agent, employeeScope: scope, bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, bindingRevision: state.revision, closeDiagnostics, detailChannel: details, resumeSessionId: request.resumeSessionId });
188
+ const openHost = () => options.open(target, { name: 'employee', path: target.projectRoot }, { ...request, signal: roundSignal, agent, employeeScope: scope, bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, bindingRevision: state.revision, closeDiagnostics, detailChannel: details, resumeSessionId: request.resumeSessionId });
189
+ const host = opening = await (request.startupTiming?.run('broker-open', openHost) ?? openHost());
171
190
  roundSignal.throwIfAborted();
172
191
  // The old per-RPC identity check belongs once at the end of this round's opening.
173
192
  if (get() !== api || employee.getNetwork() !== network)
174
193
  throw fail('EMPLOYEE_CONTEXT_CHANGED');
175
194
  const execution = new EmployeeExecution({ closeDiagnostics, bindingId: admitted.bindingId, acpMaxMessageBytes: request.acpMaxMessageBytes, transport: signal => createEmployeeSshTransport(ssh, signal) });
176
- const runtime = { ...host, closeDiagnostics, cwd: admitted.cwd, details, connection: { ...connection }, binding: { bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, revision: state.revision }, employeeExecutionMeta: { version: 1, bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, cwd: admitted.cwd, acpMaxMessageBytes: request.acpMaxMessageBytes }, employeePresentation: EMPLOYEE_EXECUTION_NOTICE };
195
+ const runtime = { ...host, localDirectory: { ...context.directory }, closeDiagnostics, cwd: admitted.cwd, details, connection: { ...connection }, binding: { bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, revision: state.revision }, employeeExecutionMeta: { version: 1, bindingId: admitted.bindingId, workspaceId: admitted.workspaceId, cwd: admitted.cwd, acpMaxMessageBytes: request.acpMaxMessageBytes }, employeePresentation: EMPLOYEE_EXECUTION_NOTICE };
177
196
  runtime.employeeRemoteCloseReason = () => execution.remoteClose?.reason;
197
+ let hostFinalized = false;
198
+ const finishHost = (reason, cause) => {
199
+ if (hostFinalized)
200
+ return;
201
+ hostFinalized = true;
202
+ const detach = cause.action === 'detach' && host.broker?.supportsRecovery;
203
+ if (!detach)
204
+ host.broker?.fail(reason ?? fail('EMPLOYEE_EXEC_CLOSED'));
205
+ void Promise.resolve(detach ? host.detach?.(cause) : host.dispose?.(cause)).catch(() => console.warn('[remote-agent] 原主机资源暂未确认清理,将由主机生命周期回收'));
206
+ };
178
207
  entry = { scope, runtime, current: input, details, execution, network, ended: false, dispose: (reason, cause = { layer: 'runtime', initiator: 'provider.dispose', reason: reason?.code ?? 'EMPLOYEE_EXEC_CLOSED', action: 'dispose' }) => {
179
208
  closeDiagnostics.record({ ...cause, changes: cause.changes ?? [{ field: 'provider.ended', before: entry.ended, after: true }] });
180
- if (entry.ended)
209
+ const preserve = !!host.broker?.supportsRecovery && !!reason && ['CONNECTION_LOST', 'EMPLOYEE_EXEC_UNKNOWN'].includes(reason.code);
210
+ if (entry.ended) {
211
+ if (!preserve)
212
+ finishHost(reason, cause);
181
213
  return Promise.resolve();
214
+ }
182
215
  entry.ended = true;
183
216
  entry.reason = reason;
184
217
  if (live.get(sessionId) === entry)
@@ -186,9 +219,11 @@ export function createEmployeeProvider(get, options, agent) {
186
219
  execution.invalidate(reason ?? fail('EMPLOYEE_EXEC_CLOSED'), { layer: 'executor', initiator: 'provider.invalidate-executor', reason: reason?.code ?? 'EMPLOYEE_EXEC_CLOSED', action: 'invalidate' });
187
220
  for (const off of disposers)
188
221
  off();
189
- host.broker?.fail(reason ?? fail('EMPLOYEE_EXEC_CLOSED'));
190
- void Promise.allSettled([execution.dispose({ layer: 'executor', initiator: 'provider.cleanup-executor', reason: 'RUNTIME_CLEANUP', action: 'dispose' }), host.dispose?.({ layer: 'broker', initiator: 'provider.cleanup-host', reason: 'RUNTIME_CLEANUP', action: 'dispose' })]).then(results => { if (results.some(result => result.status === 'rejected'))
191
- console.warn('[remote-agent] 员工执行通道的旧资源将由主机回收'); });
222
+ // Keep the model's original prompt and SDK alive through transport loss.
223
+ // The old employee execution stays UNKNOWN, never swapped for a fresh process.
224
+ if (!preserve)
225
+ finishHost(reason, cause);
226
+ void execution.dispose({ layer: 'executor', initiator: 'provider.cleanup-executor', reason: 'RUNTIME_CLEANUP', action: 'dispose' }).catch(() => console.warn('[remote-agent] 员工执行端旧资源将由主机回收'));
192
227
  return Promise.resolve();
193
228
  } };
194
229
  candidate = entry;
@@ -209,7 +244,7 @@ export function createEmployeeProvider(get, options, agent) {
209
244
  runtime.dispose = cause => entry.dispose(undefined, cause ?? { layer: 'runtime', initiator: 'runtime.dispose', reason: 'RUNTIME_DISPOSE', action: 'dispose' });
210
245
  runtime.detach = cause => entry.dispose(undefined, cause ?? { layer: 'runtime', initiator: 'runtime.detach', reason: 'RUNTIME_DETACH', action: 'detach' });
211
246
  if (host.broker)
212
- disposers.push(host.broker.onChange(() => { if (!host.broker.online)
247
+ disposers.push(host.broker.onChange(() => { if (!host.broker.online && !host.broker.recovering)
213
248
  revoke(fail('EMPLOYEE_EXEC_UNKNOWN'), 'endpoint.broker-offline'); }));
214
249
  live.set(sessionId, entry);
215
250
  return runtime;
@@ -37,7 +37,154 @@ export const EMPLOYEE_RELAY_PYTHON = EMPLOYEE_TARGET_PYTHON + String.raw `
37
37
  socket=x["socketPath"]
38
38
  if not isinstance(socket,str) or not socket.startswith("/") or "\x00" in socket:fail("EMPLOYEE_RELAY_SOCKET_INVALID")
39
39
  command=shlex.join(["/usr/bin/nc","-U",socket])
40
- os.execv("/usr/bin/ssh",["/usr/bin/ssh","-T"]+args+[command])
40
+ import asyncio,signal
41
+ class Disconnected(Exception):pass
42
+ class Relay:
43
+ def __init__(self,output):
44
+ self.output=output;self.process=None;self.ready=False;self.initialize=None;self.initialized=None;self.serial=0
45
+ self.pending={};self.front_ids={};self.server_ids={};self.readers=set();self.tasks={}
46
+ self.connect_lock=asyncio.Lock();self.write_lock=asyncio.Lock();self.output_lock=asyncio.Lock()
47
+ def identity(self):
48
+ self.serial+=1
49
+ return "aw-relay-"+str(self.serial)
50
+ def encode(self,message):
51
+ data=(json.dumps(message,ensure_ascii=False,separators=(",",":"))+"\n").encode("utf-8",errors="backslashreplace")
52
+ if len(data)-1>maximum:raise Disconnected()
53
+ return data
54
+ async def emit(self,message):
55
+ async with self.output_lock:
56
+ self.output.write(self.encode(message));await self.output.drain()
57
+ async def write(self,process,message):
58
+ async with self.write_lock:
59
+ if process is not self.process:raise Disconnected()
60
+ process.stdin.write(self.encode(message));await process.stdin.drain()
61
+ async def disconnect(self,process,report=True):
62
+ if self.process is process:
63
+ if self.ready and report:sys.stderr.write("CLAUDE_EMPLOYEE_MCP_UNKNOWN\n");sys.stderr.flush()
64
+ self.process=None;self.ready=False
65
+ for key,(owner,future) in list(self.pending.items()):
66
+ if owner is process:
67
+ self.pending.pop(key,None)
68
+ if not future.done():future.set_exception(Disconnected())
69
+ self.server_ids={key:value for key,value in self.server_ids.items() if value[0] is not process}
70
+ if process.stdin:process.stdin.close()
71
+ if process.returncode is None:
72
+ try:process.kill()
73
+ except ProcessLookupError:pass
74
+ await process.wait()
75
+ async def read(self,process):
76
+ try:
77
+ while True:
78
+ line=await process.stdout.readline()
79
+ if not line:break
80
+ message=json.loads(line)
81
+ if process is not self.process:continue
82
+ key=message.get("id")
83
+ if "method" not in message and key in self.pending:
84
+ owner,future=self.pending.pop(key)
85
+ if owner is process and not future.done():future.set_result(message)
86
+ elif "method" in message and self.ready:
87
+ if message["method"]=="notifications/cancelled":
88
+ original=message.get("params",{}).get("requestId")
89
+ front=next((key for key,value in self.server_ids.items() if value==(process,original)),None)
90
+ if front is None:continue
91
+ message={**message,"params":{**message["params"],"requestId":front}}
92
+ if "id" in message:
93
+ front=self.identity();self.server_ids[front]=(process,key);message={**message,"id":front}
94
+ await self.emit(message)
95
+ except (OSError,ValueError,Disconnected):pass
96
+ finally:await self.disconnect(process)
97
+ async def request(self,process,message):
98
+ key=self.identity();future=asyncio.get_running_loop().create_future();self.pending[key]=(process,future)
99
+ front=message.get("id");self.front_ids[front]=(process,key)
100
+ try:
101
+ try:await self.write(process,{**message,"id":key})
102
+ except (OSError,Disconnected):await self.disconnect(process)
103
+ return await future
104
+ finally:
105
+ self.pending.pop(key,None)
106
+ if self.front_ids.get(front)==(process,key):self.front_ids.pop(front,None)
107
+ async def connect(self):
108
+ async with self.connect_lock:
109
+ if self.process is not None and self.ready:return self.process
110
+ if self.initialize is None:raise Disconnected()
111
+ process=await asyncio.create_subprocess_exec("/usr/bin/ssh","-T",*args,command,stdin=asyncio.subprocess.PIPE,stdout=asyncio.subprocess.PIPE,limit=maximum+1)
112
+ self.process=process;self.ready=False
113
+ reader=asyncio.create_task(self.read(process));self.readers.add(reader);reader.add_done_callback(self.readers.discard)
114
+ try:
115
+ reply=await self.request(process,{"jsonrpc":"2.0","method":"initialize","params":self.initialize})
116
+ if "error" in reply:raise Disconnected()
117
+ await self.write(process,{"jsonrpc":"2.0","method":"notifications/initialized"})
118
+ if process is not self.process:raise Disconnected()
119
+ self.initialized=reply["result"];self.ready=True
120
+ return process
121
+ except asyncio.CancelledError:
122
+ await self.disconnect(process);raise
123
+ except (OSError,KeyError,Disconnected):
124
+ await self.disconnect(process);raise Disconnected()
125
+ async def serve(self,message):
126
+ method=message.get("method");front=message.get("id")
127
+ if method is None:
128
+ owner=self.server_ids.pop(front,None)
129
+ if owner and owner[0] is self.process:
130
+ try:await self.write(owner[0],{**message,"id":owner[1]})
131
+ except (OSError,Disconnected):await self.disconnect(owner[0])
132
+ return
133
+ if "id" not in message:
134
+ if method=="notifications/initialized":return
135
+ if method=="notifications/cancelled":
136
+ request_id=message.get("params",{}).get("requestId");owner=self.front_ids.get(request_id)
137
+ if not owner:
138
+ task=self.tasks.get(request_id)
139
+ if task:task.cancel()
140
+ return
141
+ if owner[0] is not self.process:return
142
+ message={**message,"params":{**message["params"],"requestId":owner[1]}}
143
+ try:await self.write(owner[0],message)
144
+ except (OSError,Disconnected):await self.disconnect(owner[0])
145
+ task=self.tasks.get(request_id)
146
+ if task:task.cancel()
147
+ return
148
+ if self.process is not None and self.ready:
149
+ process=self.process
150
+ try:await self.write(process,message)
151
+ except (OSError,Disconnected):await self.disconnect(process)
152
+ return
153
+ try:
154
+ if method=="initialize":self.initialize=message.get("params",{})
155
+ process=await self.connect()
156
+ reply={"jsonrpc":"2.0","result":self.initialized} if method=="initialize" else await self.request(process,message)
157
+ await self.emit({**reply,"id":front})
158
+ except (OSError,Disconnected):
159
+ text="本机工具连接中断,在途结果未知,没有重放;下一次工具调用会重新建立通道。"
160
+ reply={"result":{"isError":True,"content":[{"type":"text","text":text}]}} if method=="tools/call" else {"error":{"code":-32603,"message":text}}
161
+ await self.emit({"jsonrpc":"2.0","id":front,**reply})
162
+ async def relay():
163
+ loop=asyncio.get_running_loop();current=asyncio.current_task()
164
+ for sig in [signal.SIGTERM,signal.SIGHUP,signal.SIGINT]:loop.add_signal_handler(sig,current.cancel)
165
+ input=asyncio.StreamReader(limit=maximum+1);protocol=asyncio.StreamReaderProtocol(input)
166
+ await loop.connect_read_pipe(lambda:protocol,sys.stdin.buffer)
167
+ transport,protocol=await loop.connect_write_pipe(asyncio.streams.FlowControlMixin,sys.stdout.buffer)
168
+ output=asyncio.StreamWriter(transport,protocol,None,loop);proxy=Relay(output);tasks=set()
169
+ try:
170
+ while True:
171
+ line=await input.readline()
172
+ if not line:break
173
+ message=json.loads(line);task=asyncio.create_task(proxy.serve(message));tasks.add(task)
174
+ if "method" in message and "id" in message:proxy.tasks[message["id"]]=task
175
+ def finished(done,front=message.get("id")):
176
+ tasks.discard(done)
177
+ if proxy.tasks.get(front) is done:proxy.tasks.pop(front,None)
178
+ if not done.cancelled() and done.exception() is not None:current.cancel()
179
+ task.add_done_callback(finished)
180
+ finally:
181
+ for task in tasks:task.cancel()
182
+ await asyncio.gather(*tasks,return_exceptions=True)
183
+ if proxy.process is not None:await proxy.disconnect(proxy.process,False)
184
+ await asyncio.gather(*proxy.readers,return_exceptions=True)
185
+ output.close()
186
+ try:asyncio.run(relay())
187
+ except asyncio.CancelledError:pass
41
188
  ` + EMPLOYEE_PYTHON_ERRORS;
42
189
  export function employeeRouting(target, socketPath, maxBytes) {
43
190
  const names = ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash'];
@@ -4,6 +4,8 @@ import type { EmployeeEndpointTarget } from './employee-endpoint.ts';
4
4
  export interface EmployeeShellResult {
5
5
  stdout: string;
6
6
  stderr: string;
7
+ stdoutEncoding?: 'base64';
8
+ stderrEncoding?: 'base64';
7
9
  stderrSource: 'combined-ssh-and-command';
8
10
  exitCode: number;
9
11
  signal: null;
@@ -32,11 +32,19 @@ try:
32
32
  sys.exit(code if code>=0 else 255)
33
33
  ` + EMPLOYEE_PYTHON_ERRORS;
34
34
  const unknown = (code) => new NeedError(code, '本机命令结果未知;没有重放,也未改在主机执行。', '员工端真实退出回执');
35
+ function output(bytes) {
36
+ try {
37
+ return { text: new TextDecoder('utf8', { fatal: true, ignoreBOM: true }).decode(bytes) };
38
+ }
39
+ catch {
40
+ return { text: bytes.toString('base64'), encoding: 'base64' };
41
+ }
42
+ }
35
43
  /** Use only the target verified at this round lease opening. Cancellation cannot prove remote exit. */
36
44
  export function createEmployeeShell(options) {
37
45
  return async ({ command, timeout, signal }) => {
38
46
  signal.throwIfAborted();
39
- const diagnostics = options.closeDiagnostics?.child();
47
+ const diagnostics = options.closeDiagnostics?.child(undefined, true);
40
48
  const executionId = randomUUID(), target = options.target;
41
49
  const child = await options.attach({ command: '/usr/bin/python3', args: ['-c', SHELL_PYTHON, JSON.stringify({ endpoint: target.endpoint, sshArgs: options.sshArgs, cwd: target.local.directory.path, executionId, maxBytes: options.maxBytes })] });
42
50
  return new Promise((yes, no) => {
@@ -58,51 +66,46 @@ export function createEmployeeShell(options) {
58
66
  no(error);
59
67
  return;
60
68
  }
61
- let out, err;
62
- try {
63
- out = new TextDecoder('utf8', { fatal: true, ignoreBOM: true }).decode(Buffer.concat(stdout));
64
- err = new TextDecoder('utf8', { fatal: true, ignoreBOM: true }).decode(Buffer.concat(stderr));
65
- }
66
- catch {
67
- no(unknown('EMPLOYEE_OUTPUT_BINARY_UNSUPPORTED'));
68
- return;
69
- }
70
- const trailer = '\nAW_EMPLOYEE_BRIDGE_RESULT ' + executionId + ' ', end = err.lastIndexOf(trailer);
69
+ let err = Buffer.concat(stderr);
70
+ const trailer = Buffer.from('\nAW_EMPLOYEE_BRIDGE_RESULT ' + executionId + ' '), end = err.lastIndexOf(trailer);
71
71
  let bridgeCode;
72
72
  if (end >= 0) {
73
73
  try {
74
- const value = JSON.parse(err.slice(end + trailer.length));
74
+ const value = JSON.parse(err.subarray(end + trailer.length).toString('utf8'));
75
75
  if (typeof value === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(value))
76
76
  bridgeCode = value;
77
77
  else if (value !== null)
78
78
  throw Error();
79
- err = err.slice(0, end);
79
+ err = err.subarray(0, end);
80
80
  }
81
81
  catch {
82
82
  no(unknown('EMPLOYEE_EXIT_UNKNOWN'));
83
83
  return;
84
84
  }
85
85
  }
86
- diagnostics?.record({ layer: 'relay', initiator: 'shell.process-close', reason: 'PROCESS_EXIT', action: 'exit', exitCode: code ?? null, signal: exitSignal ?? null, ...bridgeCode ? { remoteReason: bridgeCode } : {} });
87
- const header = 'AW_EMPLOYEE_SHELL_READY ' + executionId + '\n', started = 'AW_EMPLOYEE_SHELL_STARTED ' + executionId + '\n';
86
+ const header = Buffer.from('AW_EMPLOYEE_SHELL_READY ' + executionId + '\n'), started = Buffer.from('AW_EMPLOYEE_SHELL_STARTED ' + executionId + '\n');
88
87
  const start = err.indexOf(started, header.length);
89
- if (!err.startsWith(header) || start < header.length || start > header.length && err[start - 1] !== '\n') {
90
- const raw = err.startsWith(header) ? err.slice(header.length) : err;
88
+ if (!err.subarray(0, header.length).equals(header) || start < header.length || start > header.length && err[start - 1] !== 10) {
89
+ const raw = err.subarray(0, header.length).equals(header) ? err.subarray(header.length) : err;
91
90
  let source;
92
91
  try {
93
- const parsed = JSON.parse(raw);
92
+ const parsed = JSON.parse(raw.toString('utf8'));
94
93
  if (typeof parsed.code === 'string' && /^[A-Z][A-Z0-9_]{0,63}$/.test(parsed.code))
95
94
  source = parsed.code;
96
95
  }
97
96
  catch { /* Never expose arbitrary transport diagnostics. */ }
97
+ diagnostics?.record({ layer: 'relay', initiator: 'shell.process-close', reason: bridgeCode ?? source ?? 'EMPLOYEE_EXIT_UNKNOWN', action: 'failure', exitCode: code ?? null, signal: exitSignal ?? null });
98
98
  no(unknown(bridgeCode ?? source ?? 'EMPLOYEE_EXIT_UNKNOWN'));
99
99
  return;
100
100
  }
101
101
  if (code === null || code === undefined || code === 255 || end < 0) {
102
+ diagnostics?.record({ layer: 'relay', initiator: 'shell.process-close', reason: bridgeCode ?? 'EMPLOYEE_EXIT_UNKNOWN', action: 'failure', exitCode: code ?? null, signal: exitSignal ?? null });
102
103
  no(unknown(bridgeCode ?? 'EMPLOYEE_EXIT_UNKNOWN'));
103
104
  return;
104
105
  }
105
- yes({ stdout: out, stderr: err.slice(header.length, start) + err.slice(start + started.length), stderrSource: 'combined-ssh-and-command', exitCode: code, signal: null });
106
+ diagnostics?.record({ layer: 'relay', initiator: 'shell.process-close', reason: 'PROCESS_EXIT', operation: 'completed', action: 'exit', exitCode: code, signal: exitSignal ?? null, ...bridgeCode ? { remoteReason: bridgeCode } : {} });
107
+ const out = output(Buffer.concat(stdout)), diagnostic = output(Buffer.concat([err.subarray(header.length, start), err.subarray(start + started.length)]));
108
+ yes({ stdout: out.text, stderr: diagnostic.text, ...out.encoding ? { stdoutEncoding: out.encoding } : {}, ...diagnostic.encoding ? { stderrEncoding: diagnostic.encoding } : {}, stderrSource: 'combined-ssh-and-command', exitCode: code, signal: null });
106
109
  };
107
110
  const stop = (code) => { diagnostics?.record({ layer: 'executor', initiator: 'shell.stop', reason: code, action: 'terminate', changes: [{ field: 'shell.stop-code', before: reason?.code ?? null, after: settled || reason ? reason?.code ?? null : code }] }); if (settled || reason)
108
111
  return; reason = unknown(code); child.kill('SIGTERM'); grace = setTimeout(() => { if (child.exitCode === null && child.signalCode === null) {