@ai-workbench/remote-agent 0.9.0-toolbridge.12 → 0.9.0-toolbridge.14

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.
@@ -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 }]);
@@ -175,10 +179,24 @@ export function createEmployeeProvider(get, options, agent) {
175
179
  const execution = new EmployeeExecution({ closeDiagnostics, bindingId: admitted.bindingId, acpMaxMessageBytes: request.acpMaxMessageBytes, transport: signal => createEmployeeSshTransport(ssh, signal) });
176
180
  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 };
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 });
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type SteeringReceipts } from './live-steering.ts';
1
2
  import type { Context } from '@deepseek-ai/cordis';
2
3
  import Schema from '@deepseek-ai/schemastery';
3
4
  import { LlmAdapter, type GenerateOptions, type StreamChunk, type LlmResolvedModelInfo } from '@deepseek-ai/dsh-llm';
@@ -57,9 +58,11 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
57
58
  private readonly directory?;
58
59
  private readonly preflightDiagnostics?;
59
60
  private readonly permissions?;
61
+ private readonly steeringReceipts?;
60
62
  private bridgeLoop;
61
63
  private config;
62
64
  private sessions;
65
+ private injectedInputs;
63
66
  private turns;
64
67
  private lifetime;
65
68
  private shuttingDown;
@@ -67,11 +70,13 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
67
70
  private modelPresentation;
68
71
  private employeeNoticeSessions;
69
72
  private pendingEmployeeNotices;
70
- constructor(config: PluginConfig | (() => PluginConfig), resolveRuntime: RuntimeProvider, approve?: InvocationApproval | undefined, providerName?: () => string, agent?: AgentDefinition, readImage?: ImageReader | undefined, reportLoginFailure?: LoginFailureReporter | undefined, directory?: ModelDirectory | undefined, preflightDiagnostics?: PreflightDiagnostics | undefined, permissions?: PermissionSource | undefined, bridgeStopped?: (sessionId: string, notice: string) => void);
73
+ constructor(config: PluginConfig | (() => PluginConfig), resolveRuntime: RuntimeProvider, approve?: InvocationApproval | undefined, providerName?: () => string, agent?: AgentDefinition, readImage?: ImageReader | undefined, reportLoginFailure?: LoginFailureReporter | undefined, directory?: ModelDirectory | undefined, preflightDiagnostics?: PreflightDiagnostics | undefined, permissions?: PermissionSource | undefined, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts | undefined);
71
74
  providerInfo(provider: string): {
72
75
  id: string;
73
76
  name: string;
74
77
  };
78
+ canSteer(sessionId: string): boolean;
79
+ steer(sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
75
80
  private catalog;
76
81
  listModels(provider: string): Promise<(LlmResolvedModelInfo & {
77
82
  catalog: HostModel;
@@ -101,7 +106,7 @@ export declare class CodexRemoteAdapter extends LlmAdapter {
101
106
  /** One official registration owns both routes, preserving opaque replay ownership. */
102
107
  export declare class RemoteAgentsAdapter extends LlmAdapter {
103
108
  private adapters;
104
- constructor(config: () => PluginConfig, makeRuntime: (agent: AgentDefinition) => RuntimeProvider, approve: InvocationApproval, nameFor: (agent: AgentDefinition) => string, readImage?: ImageReader, reportLoginFailure?: LoginFailureReporter, directory?: ModelDirectory, preflightDiagnostics?: PreflightDiagnostics, permissions?: PermissionSource, bridgeStopped?: (sessionId: string, notice: string) => void);
109
+ constructor(config: () => PluginConfig, makeRuntime: (agent: AgentDefinition) => RuntimeProvider, approve: InvocationApproval, nameFor: (agent: AgentDefinition) => string, readImage?: ImageReader, reportLoginFailure?: LoginFailureReporter, directory?: ModelDirectory, preflightDiagnostics?: PreflightDiagnostics, permissions?: PermissionSource, bridgeStopped?: (sessionId: string, notice: string) => void, steeringReceipts?: SteeringReceipts);
105
110
  private adapter;
106
111
  providerInfo(provider: string): {
107
112
  id: string;
@@ -124,6 +129,8 @@ export declare class RemoteAgentsAdapter extends LlmAdapter {
124
129
  jitterRatio: number;
125
130
  };
126
131
  stream(options: GenerateOptions): AsyncGenerator<StreamChunk, any, any>;
132
+ canSteer(provider: string, sessionId: string): boolean;
133
+ steer(provider: string, sessionId: string, message: import('@deepseek-ai/dsh-llm').UserMessage, isCurrent?: () => boolean): Promise<void>;
127
134
  completeDshTurn(sessionId: string, messages: GenerateOptions['messages']): Promise<void>;
128
135
  disposeSession(sessionId: string): Promise<void>;
129
136
  detachSession(sessionId: string): Promise<void>;