@ai-workbench/remote-agent 0.9.0-toolbridge.2 → 0.9.0-toolbridge.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +23 -8
  2. package/dist/acp.d.ts +23 -1
  3. package/dist/acp.js +127 -17
  4. package/dist/broker-runtime.d.ts +2 -0
  5. package/dist/broker-runtime.js +52 -3
  6. package/dist/broker.d.ts +56 -1
  7. package/dist/broker.js +300 -10
  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 +358 -0
  14. package/dist/cold-recovery.d.ts +63 -0
  15. package/dist/cold-recovery.js +598 -0
  16. package/dist/cold-store.d.ts +100 -0
  17. package/dist/cold-store.js +29 -0
  18. package/dist/employee-endpoint.js +15 -1
  19. package/dist/employee-mcp.js +1 -1
  20. package/dist/employee-provider.js +26 -6
  21. package/dist/employee-relay.js +148 -1
  22. package/dist/employee-shell.d.ts +2 -0
  23. package/dist/employee-shell.js +22 -19
  24. package/dist/employee-tools.js +2 -2
  25. package/dist/employee-workspace.d.ts +20 -4
  26. package/dist/employee-workspace.js +26 -5
  27. package/dist/index.d.ts +12 -3
  28. package/dist/index.js +205 -40
  29. package/dist/input.js +4 -1
  30. package/dist/live-steering.d.ts +46 -0
  31. package/dist/live-steering.js +45 -0
  32. package/dist/model-catalog.d.ts +2 -0
  33. package/dist/model-catalog.js +5 -1
  34. package/dist/preflight-diagnostic.js +1 -1
  35. package/dist/presentation.js +1 -0
  36. package/dist/provider.d.ts +13 -0
  37. package/dist/rpc-namespace.js +16 -2
  38. package/dist/session-source.d.ts +3 -1
  39. package/dist/session-source.js +2 -1
  40. package/dist/toolbridge-loop.d.ts +3 -2
  41. package/dist/toolbridge-loop.js +4 -2
  42. package/dist/toolbridge-table.d.ts +4 -3
  43. package/dist/toolbridge-table.js +15 -5
  44. package/dist/toolbridge.d.ts +1 -1
  45. package/dist/toolbridge.js +4 -4
  46. package/package.json +23 -16
@@ -0,0 +1,100 @@
1
+ import type { Context } from '@deepseek-ai/cordis';
2
+ import { NeedError } from './remote.ts';
3
+ import type { ConnectTarget } from './provider.ts';
4
+ import type { UsageSnapshot } from './mapping.ts';
5
+ export interface ColdWrite {
6
+ id: string;
7
+ sha256: string;
8
+ wire: string;
9
+ baseSequence: number;
10
+ chunkBytes: number;
11
+ chunks: number;
12
+ method?: string;
13
+ rpcId?: string | number | null;
14
+ }
15
+ export interface ColdRound {
16
+ version: 1;
17
+ id: string;
18
+ sessionId: string;
19
+ provider: string;
20
+ brand: 'codex' | 'claude';
21
+ phase: 'opening' | 'running' | 'terminal' | 'committed';
22
+ target: ConnectTarget;
23
+ brokerId: string;
24
+ instanceId: string;
25
+ controlMaxBytes: number;
26
+ heartbeatIntervalMs: number;
27
+ nativeId?: string;
28
+ promptId?: string;
29
+ promptSha256?: string;
30
+ promptBytes?: number;
31
+ originTurn?: number;
32
+ originStep?: number;
33
+ rpcIds: (string | number | null)[];
34
+ answered: (string | number | null)[];
35
+ inputSequence: number;
36
+ pending?: ColdWrite;
37
+ meta?: {
38
+ identity: string;
39
+ cwd: string;
40
+ binding?: {
41
+ bindingId: string;
42
+ workspaceId: string;
43
+ revision: number;
44
+ };
45
+ hostSource?: unknown;
46
+ contextSha256: string;
47
+ baseline: UsageSnapshot | null;
48
+ modelConfiguration?: unknown;
49
+ header: unknown;
50
+ model: string;
51
+ callConfig?: import('@deepseek-ai/dsh-llm').LlmCallConfig;
52
+ prelude?: string;
53
+ inputDigests?: Record<string, string>;
54
+ localDirectory?: {
55
+ path: string;
56
+ device: number;
57
+ inode: number;
58
+ };
59
+ };
60
+ localNotices?: {
61
+ beforeUpdate: number;
62
+ text: string;
63
+ kind?: 'text' | 'reasoning';
64
+ }[];
65
+ cancelIntent?: {
66
+ source: 'user-signal' | 'official-user' | 'wire';
67
+ delivered?: boolean;
68
+ };
69
+ cancelCheckpoint?: {
70
+ inputNotDelivered: true;
71
+ receipt: unknown;
72
+ };
73
+ finalUsage?: UsageSnapshot | null;
74
+ errorDelivery?: {
75
+ markerId: string;
76
+ code: string;
77
+ promptId?: string;
78
+ token: string;
79
+ message: string;
80
+ };
81
+ terminalAfter?: number;
82
+ outputStart?: number;
83
+ outputAfter: number;
84
+ officialSeq?: number;
85
+ terminal?: {
86
+ kind: 'result' | 'error' | 'local-cancel';
87
+ value: unknown;
88
+ };
89
+ failure?: string;
90
+ }
91
+ export interface ColdStore {
92
+ read(sessionId: string, provider: string): Promise<ColdRound | undefined>;
93
+ put(round: ColdRound): Promise<void>;
94
+ update(sessionId: string, provider: string, id: string, change: (round: ColdRound) => void): Promise<ColdRound>;
95
+ }
96
+ export declare const coldKey: (sessionId: string, provider: string) => string;
97
+ export declare function coldNeed(code?: string): NeedError;
98
+ export declare function createColdStore(ctx: Context): ColdStore;
99
+ export declare const wireDigest: (bytes: Uint8Array) => string;
100
+ 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(); }
@@ -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']),
@@ -111,6 +111,10 @@ export function createEmployeeProvider(get, options, agent) {
111
111
  const revoke = (reason, initiator, changes) => { lifetime.abort(reason); if (candidate)
112
112
  void candidate.dispose(reason, { layer: 'endpoint', initiator, reason: reason.code, action: 'invalidate', changes }).catch(() => { }); };
113
113
  disposers.push(api.onWorkspaceLocationState(next => {
114
+ if (next.phase !== 'ready') {
115
+ revoke(fail('CONNECTION_LOST'), 'endpoint.workspace-offline');
116
+ return;
117
+ }
114
118
  const matches = next.items.filter(item => item.workspaceId === context.workspaceId);
115
119
  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
120
  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 }]);
@@ -173,12 +177,26 @@ export function createEmployeeProvider(get, options, agent) {
173
177
  if (get() !== api || employee.getNetwork() !== network)
174
178
  throw fail('EMPLOYEE_CONTEXT_CHANGED');
175
179
  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 };
180
+ 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
181
  runtime.employeeRemoteCloseReason = () => execution.remoteClose?.reason;
182
+ let hostFinalized = false;
183
+ const finishHost = (reason, cause) => {
184
+ if (hostFinalized)
185
+ return;
186
+ hostFinalized = true;
187
+ const detach = cause.action === 'detach' && host.broker?.supportsRecovery;
188
+ if (!detach)
189
+ host.broker?.fail(reason ?? fail('EMPLOYEE_EXEC_CLOSED'));
190
+ void Promise.resolve(detach ? host.detach?.(cause) : host.dispose?.(cause)).catch(() => console.warn('[remote-agent] 原主机资源暂未确认清理,将由主机生命周期回收'));
191
+ };
178
192
  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
193
  closeDiagnostics.record({ ...cause, changes: cause.changes ?? [{ field: 'provider.ended', before: entry.ended, after: true }] });
180
- if (entry.ended)
194
+ const preserve = !!host.broker?.supportsRecovery && !!reason && ['CONNECTION_LOST', 'EMPLOYEE_EXEC_UNKNOWN'].includes(reason.code);
195
+ if (entry.ended) {
196
+ if (!preserve)
197
+ finishHost(reason, cause);
181
198
  return Promise.resolve();
199
+ }
182
200
  entry.ended = true;
183
201
  entry.reason = reason;
184
202
  if (live.get(sessionId) === entry)
@@ -186,9 +204,11 @@ export function createEmployeeProvider(get, options, agent) {
186
204
  execution.invalidate(reason ?? fail('EMPLOYEE_EXEC_CLOSED'), { layer: 'executor', initiator: 'provider.invalidate-executor', reason: reason?.code ?? 'EMPLOYEE_EXEC_CLOSED', action: 'invalidate' });
187
205
  for (const off of disposers)
188
206
  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] 员工执行通道的旧资源将由主机回收'); });
207
+ // Keep the model's original prompt and SDK alive through transport loss.
208
+ // The old employee execution stays UNKNOWN, never swapped for a fresh process.
209
+ if (!preserve)
210
+ finishHost(reason, cause);
211
+ void execution.dispose({ layer: 'executor', initiator: 'provider.cleanup-executor', reason: 'RUNTIME_CLEANUP', action: 'dispose' }).catch(() => console.warn('[remote-agent] 员工执行端旧资源将由主机回收'));
192
212
  return Promise.resolve();
193
213
  } };
194
214
  candidate = entry;
@@ -209,7 +229,7 @@ export function createEmployeeProvider(get, options, agent) {
209
229
  runtime.dispose = cause => entry.dispose(undefined, cause ?? { layer: 'runtime', initiator: 'runtime.dispose', reason: 'RUNTIME_DISPOSE', action: 'dispose' });
210
230
  runtime.detach = cause => entry.dispose(undefined, cause ?? { layer: 'runtime', initiator: 'runtime.detach', reason: 'RUNTIME_DETACH', action: 'detach' });
211
231
  if (host.broker)
212
- disposers.push(host.broker.onChange(() => { if (!host.broker.online)
232
+ disposers.push(host.broker.onChange(() => { if (!host.broker.online && !host.broker.recovering)
213
233
  revoke(fail('EMPLOYEE_EXEC_UNKNOWN'), 'endpoint.broker-offline'); }));
214
234
  live.set(sessionId, entry);
215
235
  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) {
@@ -94,7 +94,7 @@ export function createEmployeeTools(options) {
94
94
  throw failure('EMPLOYEE_OUTPUT_TOO_LARGE'); };
95
95
  async function run(command, args, signal, detail, timeout) {
96
96
  signal.throwIfAborted();
97
- const diagnostics = options.closeDiagnostics?.child(detail);
97
+ const diagnostics = options.closeDiagnostics?.child(detail, true);
98
98
  const operation = new Promise((yes, no) => {
99
99
  const child = spawn(command, args, { cwd: options.cwd, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] });
100
100
  child.stdin.end();
@@ -118,7 +118,7 @@ export function createEmployeeTools(options) {
118
118
  } if (signal.aborted)
119
119
  aborted(); });
120
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)
121
+ child.on('close', (exitCode, exitSignal) => { diagnostics?.record({ layer: 'executor', initiator: 'tools.process-close', reason: failed?.code ?? 'PROCESS_EXIT', ...!failed && !exitSignal && exitCode !== null ? { operation: 'completed' } : {}, action: 'exit', exitCode, signal: exitSignal }); signal.removeEventListener('abort', aborted); if (killTimer)
122
122
  clearTimeout(killTimer); if (timeoutTimer)
123
123
  clearTimeout(timeoutTimer); failed ? no(failed) : yes({ stdout: Buffer.concat(stdout).toString('utf8'), stderr: Buffer.concat(stderr).toString('utf8'), exitCode, signal: exitSignal }); });
124
124
  signal.addEventListener('abort', aborted, { once: true });
@@ -4,6 +4,25 @@ interface Services {
4
4
  get(name: string): unknown;
5
5
  inject: Context['inject'];
6
6
  }
7
+ interface LiveSessions {
8
+ get(id: string): {
9
+ header: {
10
+ id: string;
11
+ cwd?: string;
12
+ parentSession?: string;
13
+ };
14
+ } | undefined;
15
+ }
16
+ /**
17
+ * DSH subagent/workflow child sessions are never workspaceRegistry members; they work in the
18
+ * workspace of their nearest registered ancestor along the live parentSession chain. The
19
+ * child's own header.cwd still has to equal that workspace path at each caller.
20
+ */
21
+ export declare function registeredSessionId(sessionId: string, registry: {
22
+ list(): readonly {
23
+ sessionIds: readonly string[];
24
+ }[];
25
+ }, sessions: LiveSessions | undefined): string;
7
26
  /** Session headers do not have workspaceId. Resolve only the official registry relationship. */
8
27
  export declare function readEmployeeWorkspace(ctx: Services, sessionId: string): Promise<EmployeeWorkspace>;
9
28
  interface RegisteredWorkspace {
@@ -16,10 +35,7 @@ interface OfficialRegistry {
16
35
  get(id: string): RegisteredWorkspace | undefined;
17
36
  }
18
37
  /** Same official membership/header boundary as L. No basename or first-workspace inference. */
19
- export declare function officialEmployeeWorkspace(sessionId: string, registry: OfficialRegistry | undefined, header: {
20
- id: string;
21
- cwd?: string;
22
- } | undefined): {
38
+ export declare function officialEmployeeWorkspace(sessionId: string, registry: OfficialRegistry | undefined, sessions: LiveSessions | undefined): {
23
39
  id: string;
24
40
  path: string;
25
41
  };
@@ -1,6 +1,24 @@
1
1
  import { lstat, realpath } from 'node:fs/promises';
2
2
  import { isAbsolute } from 'node:path';
3
3
  import { NeedError } from "./remote.js";
4
+ /**
5
+ * DSH subagent/workflow child sessions are never workspaceRegistry members; they work in the
6
+ * workspace of their nearest registered ancestor along the live parentSession chain. The
7
+ * child's own header.cwd still has to equal that workspace path at each caller.
8
+ */
9
+ export function registeredSessionId(sessionId, registry, sessions) {
10
+ const member = (id) => registry.list().some(row => Array.isArray(row.sessionIds) && row.sessionIds.includes(id));
11
+ const seen = new Set();
12
+ let id = sessionId;
13
+ while (!member(id)) {
14
+ seen.add(id);
15
+ const parent = sessions?.get(id)?.header.parentSession;
16
+ if (!parent || seen.has(parent) || !sessions?.get(parent))
17
+ return sessionId;
18
+ id = parent;
19
+ }
20
+ return id;
21
+ }
4
22
  const invalid = () => new NeedError('EMPLOYEE_WORKSPACE_INVALID', '无法核对当前会话的本机文件夹,本轮未执行。', '官方工作区唯一会话关系与当前原生cwd');
5
23
  /** Session headers do not have workspaceId. Resolve only the official registry relationship. */
6
24
  export async function readEmployeeWorkspace(ctx, sessionId) {
@@ -32,11 +50,12 @@ async function readWorkspace(ctx, sessionId, fence) {
32
50
  // Service proxies are caller-scoped; injection owns the lifecycle fence.
33
51
  if (!currentRegistry || ctx.get('sessions')?.get(sessionId) !== live)
34
52
  throw invalid();
35
- const matches = currentRegistry.list().filter(row => Array.isArray(row.sessionIds) && row.sessionIds.includes(sessionId));
53
+ const member = registeredSessionId(sessionId, currentRegistry, sessions);
54
+ const matches = currentRegistry.list().filter(row => Array.isArray(row.sessionIds) && row.sessionIds.includes(member));
36
55
  if (matches.length !== 1)
37
56
  throw invalid();
38
57
  const row = matches[0], entry = currentRegistry.get(row.id), header = sessions.get(sessionId)?.header;
39
- if (!entry || row.id !== entry.id || row.path !== entry.path || !entry.sessionIds.includes(sessionId) || !isAbsolute(row.path) || !header || header.id !== sessionId || !isAbsolute(header.cwd))
58
+ if (!entry || row.id !== entry.id || row.path !== entry.path || !entry.sessionIds.includes(member) || !isAbsolute(row.path) || !header || header.id !== sessionId || !isAbsolute(header.cwd))
40
59
  throw invalid();
41
60
  return { workspaceId: row.id, path: row.path, cwd: header.cwd };
42
61
  };
@@ -47,15 +66,17 @@ async function readWorkspace(ctx, sessionId, fence) {
47
66
  return { workspaceId: first.workspaceId, directory: { path, device: info.dev, inode: info.ino } };
48
67
  }
49
68
  /** Same official membership/header boundary as L. No basename or first-workspace inference. */
50
- export function officialEmployeeWorkspace(sessionId, registry, header) {
69
+ export function officialEmployeeWorkspace(sessionId, registry, sessions) {
51
70
  const fail = () => new NeedError('EMPLOYEE_WORKSPACE_UNAVAILABLE', '无法确认这次会话的本机工作区,本轮没有执行;请从原生工作区打开会话。', '官方workspaceRegistry成员关系与会话header.cwd');
71
+ const header = sessionId ? sessions?.get(sessionId)?.header : undefined;
52
72
  if (!sessionId || !registry || !header || header.id !== sessionId || typeof header.cwd !== 'string')
53
73
  throw fail();
54
- const matches = registry.list().filter(w => Array.isArray(w.sessionIds) && w.sessionIds.includes(sessionId));
74
+ const member = registeredSessionId(sessionId, registry, sessions);
75
+ const matches = registry.list().filter(w => Array.isArray(w.sessionIds) && w.sessionIds.includes(member));
55
76
  if (matches.length !== 1)
56
77
  throw fail();
57
78
  const item = matches[0], current = registry.get(item.id);
58
- if (!current || current.id !== item.id || current.path !== item.path || !current.sessionIds.includes(sessionId) || !item.path.startsWith('/') || item.path.includes('\0') || header.cwd !== item.path)
79
+ if (!current || current.id !== item.id || current.path !== item.path || !current.sessionIds.includes(member) || !item.path.startsWith('/') || item.path.includes('\0') || header.cwd !== item.path)
59
80
  throw fail();
60
81
  return { id: item.id, path: item.path };
61
82
  }