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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.31 · 插件 → 添加插件
1
+ # AI Workbench 远程助手 · @ai-workbench/remote-agent@0.9.0-toolbridge.32 · 插件 → 添加插件
2
2
 
3
3
  ## 办公依赖与开工计时(O1,2026-11-15)
4
4
 
@@ -87,8 +87,4 @@ Codex 员工端只使用随包提供的原生组件,通道等待本次组件
87
87
 
88
88
  模型目录在官方启动读取时获取,并在连接变为 connected 时经官方注册刷新;官方菜单打开或重试读取缓存是 DSH 官方限制,本插件不改官方菜单或核心。真正不支持的推理档位由 DSH 预检,其英文提示保留为观察项。
89
89
 
90
- I3(0.9.0-toolbridge.27):同一 DSH 对话的系统规则更新后,续接原 Codex native 线程并在实际模型请求应用新版规则;需要主机含桥 Codex ACP aw.15。规则未变不重复追加历史;每次恢复仍带当前配置以支持压缩重建。用量说明已由 U1(0.9.0-toolbridge.28)更正:Codex aw.15 和 Claude 0.94.0 的 ACP 回执均按本次 prompt 统计,逐轮全额结算一次,不减历史基线;旧累计快照不再参与计算。冷接回只减同一 prompt 已在 DSH 落盘的部分,可靠终态先持久化,原 broker 回收后仍可补记其未落盘用量。订阅额度卡仍读取官方额度窗口,不能由 token 数推算百分比。Claude 的规则传递保持。无新增设置、限制或错误码。
91
-
92
- T3(0.9.0-toolbridge.31):在已连接、当前员工目录已接纳的 Codex 路径,同轮登录核验与端点准备重叠;两项均成功并再次核对目标、连接代次与物理目录后才开工,每轮核验与正常完成后结束 broker 的做法保留。当前输入已完整列出同一技能目录时,skill 工具省去重复名字数组;目录不完整或只有历史目录时保留原快照。未改变首轮工具可见性,没有新增设置、限制或错误码。本机受控时延与工具字节测量不代表远机实测速率或实际 API token 节省;DSH 原生本轮因缺独立登录未测。
93
-
94
- B6(0.9.0-toolbridge.30,本版继承):Codex 员工执行环境接纳原生 turn/steer,含桥主机组件需 aw.16;冷恢复在 DSH step preparation 前选择保存的模型与推理档,不在后置请求钩子改档。原失败冷轮可落定并按原 native 会话继续,原输入不重放。U1 的本次 prompt 用量修复来自 X.28,本版继续保留。
90
+ I3(0.9.0-toolbridge.27):同一 DSH 对话的系统规则更新后,续接原 Codex native 线程并在实际模型请求应用新版规则;需要主机含桥 Codex ACP aw.15。规则未变不重复追加历史;每次恢复仍带当前配置以支持压缩重建。用量说明已由 U1(0.9.0-toolbridge.32)更正:Codex aw.15 和 Claude 0.94.0 的 ACP 回执均按本次 prompt 统计,逐轮全额结算一次,不减历史基线;旧累计快照不再参与计算。冷接回只减同一 prompt 已在 DSH 落盘的部分,可靠终态先持久化,原 broker 回收后仍可补记其未落盘用量。订阅额度卡仍读取官方额度窗口,不能由 token 数推算百分比。Claude 的规则传递保持。无新增设置、限制或错误码。
package/dist/acp.d.ts CHANGED
@@ -77,16 +77,11 @@ export declare class AcpSession {
77
77
  private method?;
78
78
  private ready;
79
79
  private closeRequested;
80
- private updating;
81
- private cwd?;
82
80
  private codexNewSessionOnly;
83
- private creatingReplacement;
84
81
  private employeeMeta?;
85
- private employeeRouting?;
86
82
  private employeeNegotiated;
87
83
  private configuration?;
88
84
  private configRevision;
89
- private selected?;
90
85
  private selecting;
91
86
  private pendingConfigurations;
92
87
  private dispatchedPrompts;
package/dist/acp.js CHANGED
@@ -54,16 +54,11 @@ export class AcpSession {
54
54
  method;
55
55
  ready = false;
56
56
  closeRequested = false;
57
- updating = false;
58
- cwd;
59
57
  codexNewSessionOnly = false;
60
- creatingReplacement = false;
61
58
  employeeMeta;
62
- employeeRouting;
63
59
  employeeNegotiated = false;
64
60
  configuration;
65
61
  configRevision = 0;
66
- selected;
67
62
  selecting = false;
68
63
  pendingConfigurations = new Map();
69
64
  dispatchedPrompts = 0;
@@ -106,7 +101,6 @@ export class AcpSession {
106
101
  }
107
102
  pendingConfiguration(sessionId, options) { const pending = this.pendingConfigurations.get(sessionId) ?? []; pending.push(options); this.pendingConfigurations.set(sessionId, pending); }
108
103
  resetConfiguration(clearRoles = true) {
109
- this.selected = undefined;
110
104
  if (this.configuration) {
111
105
  try {
112
106
  this.configuration.invalidate(clearRoles);
@@ -138,11 +132,10 @@ export class AcpSession {
138
132
  async selectModel(model, effort, signal) {
139
133
  if (!this.ready || !this.sessionId)
140
134
  throw new ModelConfigurationError('远端会话尚未建立');
141
- if (this.busy || this.updating || this.selecting)
135
+ if (this.busy || this.selecting)
142
136
  throw new ModelConfigurationError('上一项会话操作尚未完成');
143
137
  signal?.throwIfAborted();
144
138
  this.selecting = true;
145
- this.selected = { model, ...(effort === undefined ? {} : { effort }) };
146
139
  this.turnSignal = signal;
147
140
  try {
148
141
  if (!this.configuration)
@@ -305,12 +298,6 @@ export class AcpSession {
305
298
  const app = acp.client({ name: '@ai-workbench/remote-agent' })
306
299
  .onNotification(acp.methods.client.session.update, ({ params: incoming }) => {
307
300
  const { notification, sequence } = this.hooks.broker?.stripOutputOrigin(incoming) ?? { notification: incoming, sequence: undefined };
308
- if (this.creatingReplacement) {
309
- if (notification.sessionId !== this.sessionId && notification.update.sessionUpdate === 'config_option_update')
310
- this.pendingConfiguration(notification.sessionId, notification.update.configOptions);
311
- this.detail({ kind: 'session', severity: 'info', code: 'ACP_IDLE_UPDATE', summary: '新会话建立期间的轨迹,未作为正文处理', method: 'session/update', payload: notification });
312
- return;
313
- }
314
301
  if (this.sessionId && notification.sessionId !== this.sessionId) {
315
302
  this.detail({ kind: 'session', severity: 'warning', code: 'ACP_FOREIGN_SESSION_UPDATE', summary: '收到不属于当前远端会话的通知,未作为正文处理', method: 'session/update', payload: notification });
316
303
  return;
@@ -541,7 +528,7 @@ export class AcpSession {
541
528
  throw new NeedError('PROMPT_CONTENT_UNSUPPORTED', `远端未声明此输入内容能力:${block.type};本轮未发送`, '对应内容类型的公开 ACP 输入能力');
542
529
  }
543
530
  setHooks(hooks) {
544
- if (this.busy || this.updating || this.selecting)
531
+ if (this.busy || this.selecting)
545
532
  throw new NeedError('TURN_BUSY', '上一轮或配置更新结束前不能更换会话钩子', '上一轮结束');
546
533
  this.hooks = hooks;
547
534
  this.employeeNoticeNames.clear();
@@ -583,7 +570,6 @@ export class AcpSession {
583
570
  if (prompt)
584
571
  this.validatePrompt(prompt);
585
572
  const routing = context?.employeeRouting ? structuredClone(context.employeeRouting) : undefined;
586
- this.employeeRouting = routing;
587
573
  const claudeCode = routing ? { options: employeeClaudeOptions(routing) } : this.codexNewSessionOnly ? undefined : { options: { settings: claudeSettings() } };
588
574
  const params = { cwd, mcpServers: context?.toolBridgeServers ? structuredClone(context.toolBridgeServers) : routing ? structuredClone(routing.mcpServers) : [], ...((claudeCode || this.employeeMeta || initialModel) ? { _meta: { ...(initialModel ? { awInitialModel: { version: 1, model: initialModel } } : {}), ...(this.employeeMeta ? { awEmployeeExecution: this.employeeMeta } : {}), ...(claudeCode ? { claudeCode } : {}) } } : {}), ...((systemPrompt !== undefined || context?.systemPromptChanged || nativeContext) && !(resumeId && this.codexNewSessionOnly && !context?.systemPromptChanged && !nativeContext) ? { systemPrompt: { mode: 'append', content: [{ type: 'text', text: systemPrompt ?? '' }] } } : {}) };
589
575
  const configRevision = this.resetConfiguration();
@@ -637,7 +623,6 @@ export class AcpSession {
637
623
  this.confirmBridgeStartupFailure();
638
624
  await this.hooks.sessionOwnership?.bind(this.sessionId, signal);
639
625
  this.ready = true;
640
- this.cwd = cwd;
641
626
  return this.sessionId;
642
627
  }
643
628
  catch (error) {
@@ -656,7 +641,7 @@ export class AcpSession {
656
641
  async prompt(input, signal) {
657
642
  if (!this.ready || !this.sessionId)
658
643
  throw new NeedError('SESSION_REQUIRED', '我需要先建立远端会话', 'ACP 会话');
659
- if (this.busy || this.updating || this.selecting)
644
+ if (this.busy || this.selecting)
660
645
  throw new NeedError('TURN_BUSY', '此远端会话正在处理上一轮或更新配置', '上一轮结束');
661
646
  signal?.throwIfAborted();
662
647
  const prompt = typeof input === 'string' ? [{ type: 'text', text: input }] : input;
@@ -115,7 +115,7 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
115
115
  broker = new BrokerTransport({ maxFrameBytes: options.maxFrameBytes, controlMaxBytes: record.controlMaxBytes, leased: true, inputProtocolVersion: 2, messageInput: true, recoverDisconnect: true, instanceId: record.instanceId, initialSequence: record.outputStart, restoreInput: { sequence: record.inputSequence, pending: record.pending }, beforeMessage, afterMessage, attach: (after = 0) => options.io.attach(command(['attach', record.brokerId, '--after', String(after), '--framed', '--leased', '--input-protocol', '2', '--message-input', '--if-instance', record.instanceId, '--cold-round', record.id, '--prompt-id', record.promptId, ...owner])) });
116
116
  const raw = acp.ndJsonStream(broker.writable, broker.readable, { maxMessageBytes: options.maxMessageBytes }), reader = raw.readable.getReader(), writer = raw.writable.getWriter();
117
117
  const mapper = new StreamMapper(), output = new StreamMapper(), trim = new Prefix(prefix);
118
- let terminal = false, replayed = false, delivered = false;
118
+ let replayed = false, delivered = false;
119
119
  const pendingRequests = new Map();
120
120
  let outboundTail = Promise.resolve();
121
121
  const enqueue = (work) => { outboundTail = outboundTail.then(work); void outboundTail.catch(error => broker.fail(error instanceof NeedError ? error : coldNeed())); };
@@ -329,7 +329,6 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
329
329
  throw readFailure;
330
330
  if (options.cancelOnly)
331
331
  return;
332
- terminal = true;
333
332
  await store.update(record.sessionId, record.provider, record.id, row => { row.terminal = { kind: m.error ? 'error' : 'result', value: m.error ?? m.result }; row.phase = 'terminal'; row.terminalAfter = broker.lastSequence; });
334
333
  if (m.error) {
335
334
  trim.finish();
@@ -369,8 +368,7 @@ export async function* recoverColdProtocol(record, store, prefix, options) {
369
368
  return;
370
369
  }
371
370
  }
372
- if (!terminal)
373
- throw coldNeed('CONNECTION_LOST');
371
+ throw coldNeed('CONNECTION_LOST');
374
372
  }
375
373
  finally {
376
374
  options.signal?.removeEventListener('abort', cancel);
@@ -359,12 +359,12 @@ export class ColdRecovery {
359
359
  * step's choice; it neither selects nor advertises capabilities for a new model. */
360
360
  recoveryModel(provider, model, signal) {
361
361
  for (const step of this.steps.values())
362
- if (step.signal === signal && step.row.provider === provider && (step.selection?.model ?? step.row.meta?.model) === model) {
363
- const effort = step.selection?.reasoningEffort;
362
+ if (step.signal === signal && step.row.provider === provider && step.selection.model === model) {
363
+ const effort = step.selection.reasoningEffort;
364
364
  return { provider, id: model, name: '接回原轮结果', ...(effort === undefined ? {} : { reasoning: { efforts: [{ id: ReasoningEffortId(effort), name: effort }] } }) };
365
365
  }
366
366
  }
367
- canRecover(options) { return !options.purpose && [...this.steps].some(([agent, step]) => agent.session.id === options.sessionId && step.row.provider === options.provider && (step.selection?.model ?? step.row.meta?.model) === options.model && step.signal === options.signal && (!step.signal.aborted || step.signal.reason?.kind === 'user') && options.messages.some(m => m.id === step.markerId && recoveryMarker(m) === step.row.id)); }
367
+ canRecover(options) { return !options.purpose && [...this.steps].some(([agent, step]) => agent.session.id === options.sessionId && step.row.provider === options.provider && step.selection.model === options.model && step.signal === options.signal && (!step.signal.aborted || step.signal.reason?.kind === 'user') && options.messages.some(m => m.id === step.markerId && recoveryMarker(m) === step.row.id)); }
368
368
  async connection(signal, binding) {
369
369
  for (;;) {
370
370
  signal?.throwIfAborted();
@@ -42,12 +42,10 @@ export interface ColdRound {
42
42
  revision: number;
43
43
  };
44
44
  hostSource?: unknown;
45
- contextSha256: string; /** 只读旧版字段;不再作为跨轮基线。 */
46
- baseline?: unknown;
45
+ contextSha256: string;
47
46
  modelConfiguration?: unknown;
48
47
  header: unknown;
49
- model: string; /** 只读旧版字段;不再覆盖DSH已冻结的本步配置。 */
50
- callConfig?: import('@deepseek-ai/dsh-llm').LlmCallConfig;
48
+ model: string;
51
49
  prelude?: string;
52
50
  inputDigests?: Record<string, string>;
53
51
  localDirectory?: {
@@ -69,7 +67,6 @@ export interface ColdRound {
69
67
  inputNotDelivered: true;
70
68
  receipt: unknown;
71
69
  };
72
- /** 只读旧版字段;不再参与恢复结算。 */ finalUsage?: unknown;
73
70
  errorDelivery?: {
74
71
  markerId: string;
75
72
  code: string;
@@ -4,7 +4,6 @@ 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';
8
7
  export interface EmployeeProviderOptions {
9
8
  getNetwork(): NetworkApi | undefined;
10
9
  workspace(request: RuntimeRequest): Promise<{
@@ -27,7 +26,6 @@ interface Admission {
27
26
  target: ConnectTarget;
28
27
  connection: ConnectionState;
29
28
  request: RuntimeRequest;
30
- preparation?: EmployeeStartup;
31
29
  }
32
30
  /** Inspect the current local workspace once at turn start, before host readiness. */
33
31
  export declare function inspectEmployeeWorkspace(get: () => ConnectApi | undefined, employee: EmployeeProviderOptions, agent: AgentDefinition, api: ConnectApi, request: RuntimeRequest): Promise<Readonly<LocalWorkspaceContext> | undefined>;
@@ -134,13 +134,13 @@ export function createEmployeeProvider(get, options, agent) {
134
134
  throw fail('EMPLOYEE_OPERATION_UNSUPPORTED');
135
135
  if (!Number.isSafeInteger(request.acpMaxMessageBytes) || request.acpMaxMessageBytes < 1)
136
136
  throw fail('SETTINGS_REQUIRED');
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();
137
+ const prepareLocation = () => 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 = () => employee.native();
139
139
  // 仅把无授权、无目标的静态包路径解析与本轮N准备重叠。两项都收敛后,
140
140
  // 按原顺序处理错误;每轮N准备、事件撤销、执行目标绑定仍完整执行。
141
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(),
142
+ request.startupTiming?.run('endpoint-prepare', prepareLocation) ?? prepareLocation(),
143
+ request.startupTiming?.run('native-metadata', resolveNative) ?? resolveNative(),
144
144
  ]);
145
145
  if (locationResult.status === 'rejected')
146
146
  throw locationResult.reason;
package/dist/index.js CHANGED
@@ -360,13 +360,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
360
360
  let session;
361
361
  let live;
362
362
  let succeeded = false;
363
- let remoteAttempted = false;
364
363
  let promptBaseline = 0;
365
364
  let failureCode;
366
365
  let activeMapper;
367
366
  let selected;
368
367
  let modelConfiguration;
369
- let turnFailure;
370
368
  let coldPrelude = '';
371
369
  let employeeNoticeShown = false;
372
370
  let permissionOff;
@@ -376,9 +374,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
376
374
  for (const entry of information.splice(0))
377
375
  runtime.details.record(entry); };
378
376
  const config = this.config();
379
- const mode = 'session';
380
377
  const startupTiming = new StartupTiming(this.preflightDiagnostics ? event => { void this.preflightDiagnostics.record(request, this.agent.loginProvider, event); } : undefined), endStartup = startupTiming.start('startup');
381
- request = { sessionId: options.sessionId, mode: mode ?? 'session', signal, toolBridge: bridge, startupTiming };
378
+ request = { sessionId: options.sessionId, mode: 'session', signal, toolBridge: bridge, startupTiming };
382
379
  const observeAbort = (source, initiator, reason) => { if (!source)
383
380
  return; const record = () => { (request?.closeDiagnostics ?? runtime?.closeDiagnostics)?.record({ layer: 'adapter', initiator, reason, action: 'abort', changes: [{ field: 'adapter.turn-aborted', before: false, after: source.aborted }] }); }; source.addEventListener('abort', record, { once: true }); abortOffs.push(() => source.removeEventListener('abort', record)); };
384
381
  observeAbort(original.signal, 'signal.caller', 'CALLER_ABORTED');
@@ -400,8 +397,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
400
397
  if (employeeNoticeShown && key)
401
398
  this.employeeNoticeSessions.add(key);
402
399
  live = undefined;
403
- const configuration = JSON.stringify([config.acpMaxMessageBytes, config.brokerMaxFrameBytes, config.brokerControlMaxBytes, config.employeeShellKillGraceMs]);
404
- Object.assign(request, { acpMaxMessageBytes: config.acpMaxMessageBytes, resumeSessionId: previous?.sessionId, sessionId: options.sessionId, mode, hostSource: previous?.hostSource, cwd: previous?.cwd, identity: previous?.identity, bindingId: previous?.bindingId, workspaceId: previous?.workspaceId, agent: this.agent, signal, brokerSettings: Object.freeze({ brokerMaxFrameBytes: config.brokerMaxFrameBytes, brokerControlMaxBytes: config.brokerControlMaxBytes }) });
400
+ Object.assign(request, { acpMaxMessageBytes: config.acpMaxMessageBytes, resumeSessionId: previous?.sessionId, sessionId: options.sessionId, mode: 'session', hostSource: previous?.hostSource, cwd: previous?.cwd, identity: previous?.identity, bindingId: previous?.bindingId, workspaceId: previous?.workspaceId, agent: this.agent, signal, brokerSettings: Object.freeze({ brokerMaxFrameBytes: config.brokerMaxFrameBytes, brokerControlMaxBytes: config.brokerControlMaxBytes }) });
405
401
  request.previousContextSha256 = previous?.contextSha256;
406
402
  const after = options.messages.findLastIndex(message => message.role === 'assistant');
407
403
  const tail = options.messages.slice(after + 1);
@@ -453,7 +449,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
453
449
  // New Codex transport scopes are independent of the native context digest.
454
450
  if (contextChanged)
455
451
  request.contextSha256 = undefined;
456
- if (mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
452
+ if (Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
457
453
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
458
454
  selected = this.modelPresentation.find(options.model) ?? { id: options.model, value: options.model, name: options.model, resolvedModel: null, reasoning: { options: [], defaultValue: null, defaultKnown: false }, source: null };
459
455
  let modelSignal = signal;
@@ -473,7 +469,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
473
469
  if (previous && !runtime.hostSource && (previous.identity !== runtime.identity || previous.cwd !== runtime.cwd || previous.bindingId && previous.bindingId !== runtime.binding?.bindingId || previous.workspaceId && previous.workspaceId !== runtime.binding?.workspaceId))
474
470
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
475
471
  input = await prepareContinuation({ ...options, messages: projected.messages.slice(checkpointIndex + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
476
- if (runtime.hostWorkspace && mode === 'session' && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
472
+ if (runtime.hostWorkspace && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
477
473
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
478
474
  const details = runtime.details ?? await createRemoteDetails({ warn: line => console.warn(line) }).open({ sessionId: options.sessionId ?? 'unscoped', provider: this.agent.loginProvider, identity: runtime.identity, connection: runtime.connection });
479
475
  startupTiming.bind(event => details.record(event));
@@ -513,7 +509,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
513
509
  }
514
510
  yield* mapper.flush();
515
511
  }
516
- if (mode === 'session') {
512
+ { // 仅支持ACP会话模式;保留此块的局部变量作用域。
517
513
  if (!runtime.acpTransport)
518
514
  throw new NeedError('DEPENDENCY_REQUIRED', '我需要该员工主机上的ACP通道', 'S提供的ACP命令与aw-session');
519
515
  const queue = [];
@@ -581,7 +577,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
581
577
  }), onDetail: detail => details.record(detail) };
582
578
  const transport = runtime.acpTransport instanceof acp.AgentApp || runtime.acpTransport instanceof unstable.AgentApp ? runtime.acpTransport : acp.ndJsonStream(runtime.acpTransport.writable, runtime.acpTransport.readable, { maxMessageBytes: config.acpMaxMessageBytes });
583
579
  session = new AcpSession(transport, hooks);
584
- live = { session, runtime, configuration, contextSha256, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
580
+ live = { session, runtime, options, acceptingSteer: true, turnId: randomUUID(), steerIds: new Map(), steerTail: Promise.resolve(), maxBytes: config.acpMaxMessageBytes, notice: renderNotice };
585
581
  if (key)
586
582
  this.sessions.set(key, live);
587
583
  promptBaseline = session.promptDispatchCount;
@@ -627,7 +623,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
627
623
  }
628
624
  };
629
625
  const task = (async () => {
630
- remoteAttempted = true;
631
626
  try {
632
627
  await session.start(runtime.execution?.hostCwd ?? runtime.cwd, previous?.sessionId, modelSignal, { systemPrompt: input.systemPrompt, systemPromptChanged: contextChanged, ...(bridgeMcp ? { toolBridgeServers: bridgeMcp.mcpServers } : {}), ...(runtime.execution ? { employeeRouting: runtime.execution.routing } : {}), ...(codex ? { codexNewSessionOnly: true, initialModel: selected.value } : {}), ...(runtime.employeeExecutionMeta ? { employeeExecution: runtime.employeeExecutionMeta } : {}) }, input.prompt);
633
628
  }
@@ -753,7 +748,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
753
748
  onPromptDispatched();
754
749
  if (bridge?.unsettled && !signal.aborted)
755
750
  bridge.abandon('HOST_PROMPT_FAILED');
756
- turnFailure = error;
757
751
  runtime?.closeDiagnostics?.record({ layer: 'adapter', initiator: 'adapter.turn-failure', reason: closeCode(error, signal.aborted ? 'ABORTED' : 'TURN_FAILED'), action: 'failure' });
758
752
  recordInformation();
759
753
  failureCode = error instanceof NeedError || error instanceof ModelConfigurationError ? error.code : error instanceof LlmError ? error.code : 'TURN_PREPARATION_FAILED';
@@ -767,8 +761,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
767
761
  throw withFirstFailureEvidence(error, runtime?.closeDiagnostics?.first?.reason, failureCode);
768
762
  }
769
763
  finally {
770
- if (request)
771
- this.resolveRuntime.releasePreparation?.(request);
772
764
  permissionOff?.();
773
765
  permissionOff = undefined;
774
766
  permissionEpoch.abort();
@@ -113,7 +113,6 @@ export interface RuntimeRequest extends Invocation {
113
113
  }
114
114
  export type RuntimeProvider = ((request: RuntimeRequest) => Promise<Runtime>) & {
115
115
  preflight?: (request: RuntimeRequest) => Promise<void>;
116
- releasePreparation?: (request: RuntimeRequest) => void;
117
116
  };
118
117
  export interface ConnectTarget {
119
118
  host: string;
package/dist/provider.js CHANGED
@@ -149,16 +149,6 @@ export function connectProvider(get, options = {}) {
149
149
  // Cache the initialization promise so concurrent sessions share this provider's binding lifetimes.
150
150
  let employee;
151
151
  const admissions = new WeakMap();
152
- const preparations = new WeakMap();
153
- const releasePreparation = (request) => { const owned = preparations.get(request); preparations.delete(request); admissions.delete(request); owned?.restore(); owned?.preparation.cancel(); };
154
- const ownPreparation = (request, preparation) => {
155
- const original = request.recordEarlyFailure;
156
- const wrapped = async (error, stage) => { releasePreparation(request); if (original)
157
- await original(error, stage); };
158
- preparations.set(request, { preparation, restore: () => { if (request.recordEarlyFailure === wrapped)
159
- request.recordEarlyFailure = original; } });
160
- request.recordEarlyFailure = wrapped;
161
- };
162
152
  const preflight = async (request) => {
163
153
  request.signal?.throwIfAborted();
164
154
  const api = get();
@@ -167,7 +157,6 @@ export function connectProvider(get, options = {}) {
167
157
  requireNativeWorkspace(api);
168
158
  requireLoginCoordinator(api);
169
159
  let sourceStage = 'input-acceptance';
170
- let preparation;
171
160
  try {
172
161
  request.workspaceSource = options.source ? await options.source(request, api) : request.hostSource;
173
162
  if (!options.source && !request.workspaceSource && options.workspace && request.sessionId && api.getContractInfo().workspaceLocations === 1) {
@@ -180,12 +169,6 @@ export function connectProvider(get, options = {}) {
180
169
  request.localContext = await module.inspectEmployeeWorkspace(get, options.employee, agent, api, request);
181
170
  }
182
171
  sourceStage = 'login-readiness';
183
- if (!host && agent.loginProvider === 'codex' && options.employee && request.localContext) {
184
- const module = await import("./employee-startup.js");
185
- preparation = module.beginEmployeeStartup(get, options.employee, api, request);
186
- if (preparation)
187
- ownPreparation(request, preparation);
188
- }
189
172
  const loginReady = async () => {
190
173
  request.localAdmissionCheck?.();
191
174
  const before = api.getConnectionState();
@@ -208,13 +191,8 @@ export function connectProvider(get, options = {}) {
208
191
  throw connectNeedError(locations.need);
209
192
  if (!host)
210
193
  await options.local?.admit?.(request, api, connection, target);
211
- if (preparation) {
212
- await preparation.ready;
213
- preparation.confirm(target, connection);
214
- }
215
194
  }
216
195
  catch (error) {
217
- preparation?.cancel();
218
196
  admissions.delete(request);
219
197
  const record = request.recordEarlyFailure;
220
198
  request.recordEarlyFailure = undefined;
@@ -229,51 +207,41 @@ export function connectProvider(get, options = {}) {
229
207
  const admitted = admissions.get(request);
230
208
  admissions.delete(request);
231
209
  const { api, target, connection } = admitted;
232
- const owned = preparations.get(request);
233
- preparations.delete(request);
234
- owned?.restore();
235
- const preparation = owned?.preparation;
236
- try {
237
- if (!request.sessionId)
238
- throw new NeedError('PROJECT_BINDING_REQUIRED', '我需要当前会话和已选择的工作区,请使用原生工作区入口', 'DSH会话与原生工作区');
239
- const host = request.workspaceSource?.source === 'host';
240
- if (!host && options.employee) {
241
- employee ??= import("./employee-provider.js").then(module => module.createEmployeeProvider(get, options, agent));
242
- const local = await (await employee)({ api, target, connection, request, preparation });
243
- if (local) {
244
- local.loginRequired = () => offerLogin(api, request, get, agent);
245
- return local;
246
- }
247
- }
248
- if (!host && agent.loginProvider === 'claude' && options.local) {
249
- const runtime = await options.local(request, api, connection, target);
250
- if (runtime)
251
- return runtime;
210
+ if (!request.sessionId)
211
+ throw new NeedError('PROJECT_BINDING_REQUIRED', '我需要当前会话和已选择的工作区,请使用原生工作区入口', 'DSH会话与原生工作区');
212
+ const host = request.workspaceSource?.source === 'host';
213
+ if (!host && options.employee) {
214
+ employee ??= import("./employee-provider.js").then(module => module.createEmployeeProvider(get, options, agent));
215
+ const local = await (await employee)({ api, target, connection, request });
216
+ if (local) {
217
+ local.loginRequired = () => offerLogin(api, request, get, agent);
218
+ return local;
252
219
  }
253
- // A local source must have been handled by its employee provider above.
254
- // Host execution requires an explicit host location; no name-based resolver.
255
- if (!host)
256
- throw new NeedError('WORKSPACE_LOCATION_REQUIRED', '请选择文件夹来源;改变来源后请新建会话。', '已选择的本机或主机文件夹');
257
- const resolved = await resolveHostWorkspace(api, request, agent.loginProvider);
258
- const project = resolved.project;
259
- const details = await options.details?.(request, api, connection, target);
260
- if (!options.open)
261
- throw new NeedError('RUNTIME_REQUIRED', '我需要主机运行适配器', '主机broker适配');
262
- const runtime = await options.open(resolved.target, project, { ...request, agent, bindingId: undefined, workspaceId: undefined, bindingRevision: undefined, detailChannel: details });
263
- runtime.hostSource = Object.freeze({ ...request.workspaceSource });
264
- runtime.hostWorkspace = Object.freeze({ cwd: project.path });
265
- // The transport can outlive a turn; presentation belongs only to this invocation.
266
- runtime.details = details ?? runtime.details;
267
- runtime.binding = undefined;
268
- runtime.connection = { ...connection };
269
- runtime.loginRequired = () => offerLogin(api, request, get, agent);
270
- return runtime;
271
220
  }
272
- finally {
273
- preparation?.cancel();
221
+ if (!host && agent.loginProvider === 'claude' && options.local) {
222
+ const runtime = await options.local(request, api, connection, target);
223
+ if (runtime)
224
+ return runtime;
274
225
  }
226
+ // A local source must have been handled by its employee provider above.
227
+ // Host execution requires an explicit host location; no name-based resolver.
228
+ if (!host)
229
+ throw new NeedError('WORKSPACE_LOCATION_REQUIRED', '请选择文件夹来源;改变来源后请新建会话。', '已选择的本机或主机文件夹');
230
+ const resolved = await resolveHostWorkspace(api, request, agent.loginProvider);
231
+ const project = resolved.project;
232
+ const details = await options.details?.(request, api, connection, target);
233
+ if (!options.open)
234
+ throw new NeedError('RUNTIME_REQUIRED', '我需要主机运行适配器', '主机broker适配');
235
+ const runtime = await options.open(resolved.target, project, { ...request, agent, bindingId: undefined, workspaceId: undefined, bindingRevision: undefined, detailChannel: details });
236
+ runtime.hostSource = Object.freeze({ ...request.workspaceSource });
237
+ runtime.hostWorkspace = Object.freeze({ cwd: project.path });
238
+ // The transport can outlive a turn; presentation belongs only to this invocation.
239
+ runtime.details = details ?? runtime.details;
240
+ runtime.binding = undefined;
241
+ runtime.connection = { ...connection };
242
+ runtime.loginRequired = () => offerLogin(api, request, get, agent);
243
+ return runtime;
275
244
  };
276
245
  resolve.preflight = preflight;
277
- resolve.releasePreparation = releasePreparation;
278
246
  return resolve;
279
247
  }
@@ -8,4 +8,4 @@ export interface BridgeTool {
8
8
  wire: Tool;
9
9
  }
10
10
  export declare function dshSkillCatalog(messages?: GenerateOptions['messages']): readonly string[] | undefined;
11
- export declare function bridgeTable(tools?: readonly ToolSchema[], catalog?: readonly string[], catalogInCurrentPrompt?: boolean): ReadonlyMap<string, BridgeTool>;
11
+ export declare function bridgeTable(tools?: readonly ToolSchema[], catalog?: readonly string[]): ReadonlyMap<string, BridgeTool>;
@@ -17,7 +17,7 @@ export function dshSkillCatalog(messages = []) {
17
17
  return source.entries.map(entry => entry.name);
18
18
  }
19
19
  }
20
- export function bridgeTable(tools = [], catalog, catalogInCurrentPrompt = false) {
20
+ export function bridgeTable(tools = [], catalog) {
21
21
  const table = new Map(), names = new Set();
22
22
  for (const tool of tools) {
23
23
  if (excluded.has(tool.name))
@@ -29,7 +29,7 @@ export function bridgeTable(tools = [], catalog, catalogInCurrentPrompt = false)
29
29
  if (table.has(alias))
30
30
  throw new NeedError('TOOLBRIDGE_NAME_COLLISION', '工具桥名称冲突,未执行。', '唯一工具桥名称');
31
31
  const schema = structuredClone(tool);
32
- const skill = schema.name === 'skill' ? ' 这是DSH技能加载器,名字取自DSH的<available_skills>目录;主机Claude/Codex的原生技能按各自原生技能指令加载。' + (catalogInCurrentPrompt ? '实际可用性由DSH调用时确认。' : catalog === undefined ? '请以当前DSH技能目录为准。' : '本次DSH公布的目录快照:' + JSON.stringify(catalog) + ';实际可用性由DSH调用时确认。') + '技能资源按返回的<skill_resources>基址读取。' : '';
32
+ const skill = schema.name === 'skill' ? ' 这是DSH技能加载器,名字取自DSH的<available_skills>目录;主机Claude/Codex的原生技能按各自原生技能指令加载。' + (catalog === undefined ? '请以当前DSH技能目录为准。' : '本次DSH公布的目录快照:' + JSON.stringify(catalog) + ';实际可用性由DSH调用时确认。') + '技能资源按返回的<skill_resources>基址读取。' : '';
33
33
  table.set(alias, { alias, schema, wire: { name: alias, description: 'DSH工具 ' + schema.name + ':' + schema.description + skill, inputSchema: structuredClone(schema.parameters) } });
34
34
  }
35
35
  return table;
@@ -16,26 +16,7 @@ export class ToolBridge {
16
16
  readImage;
17
17
  controller = new AbortController();
18
18
  snapshot;
19
- get table() {
20
- if (this.snapshot)
21
- return this.snapshot;
22
- const messages = this.options.messages, catalog = dshSkillCatalog(messages);
23
- // prepareInput只转发最后assistant之后的user内容;历史目录不能代替当前prompt。
24
- // 正文不含目录全部名字时仍保留原schema快照,避免分支/切模型时丢发现入口。
25
- const current = messages.slice(messages.findLastIndex(message => message.role === 'assistant') + 1);
26
- const forwarded = catalog !== undefined && catalog.length > 0 && current.some(message => {
27
- const names = dshSkillCatalog([message]);
28
- if (names === undefined || JSON.stringify(names) !== JSON.stringify(catalog))
29
- return false;
30
- const text = message.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
31
- // 只认官方目录中明确声明的完整名字;子串命中不能证明office也已随office-xlsx送达。
32
- // 未识别的格式继续携带原名字快照,不推测目录内容。
33
- const declared = new Set([...text.matchAll(/<available_skills>([\s\S]*?)<\/available_skills>/g)]
34
- .flatMap(section => [...section[1].matchAll(/^[ \t]*-[ \t]+`([^`\r\n]+)`[ \t]*:/gm)].map(item => item[1])));
35
- return catalog.every(name => declared.has(name));
36
- });
37
- return this.snapshot = bridgeTable(this.options.tools, catalog, forwarded);
38
- }
19
+ get table() { return this.snapshot ??= bridgeTable(this.options.tools, dshSkillCatalog(this.options.messages)); }
39
20
  calls = new Map();
40
21
  enabled = false;
41
22
  ended = false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ai-workbench/remote-agent",
3
- "version": "0.9.0-toolbridge.31",
3
+ "version": "0.9.0-toolbridge.32",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -1,18 +0,0 @@
1
- import type { NetworkApi } from '@ai-workbench/network/api';
2
- import type { LocalWorkspaceContext } from '@ai-workbench/connect/api';
3
- import type { EmployeeProviderOptions } from './employee-provider.ts';
4
- import { type ConnectApi, type ConnectTarget, type ConnectionState, type RuntimeRequest } from './provider.ts';
5
- import { admitEmployeeLocation } from './employee-location.ts';
6
- type Location = Awaited<ReturnType<typeof admitEmployeeLocation>>;
7
- /** 只拥有本次请求的等待和围栏,不拥有、关闭或缓存N的共享设备服务。 */
8
- export interface EmployeeStartup {
9
- ready: Promise<void>;
10
- confirm(target: ConnectTarget, connection: ConnectionState): void;
11
- location(network: NetworkApi, context: Readonly<LocalWorkspaceContext>): Promise<Location>;
12
- native(): Promise<{
13
- path: string;
14
- }>;
15
- cancel(): void;
16
- }
17
- export declare function beginEmployeeStartup(get: () => ConnectApi | undefined, employee: EmployeeProviderOptions, api: ConnectApi, request: RuntimeRequest): EmployeeStartup | undefined;
18
- export {};
@@ -1,95 +0,0 @@
1
- import { isDeepStrictEqual } from 'node:util';
2
- import { awaitL, sameTarget, validateTarget } from "./provider.js";
3
- import { admitEmployeeLocation } from "./employee-location.js";
4
- import { connectNeedError } from "./connect-need.js";
5
- import { NeedError } from "./remote.js";
6
- const failure = (code) => new NeedError(code, '员工电脑的工作区或执行连接已变化,本轮没有继续执行。', '当前工作区绑定与员工端执行器');
7
- export function beginEmployeeStartup(get, employee, api, request) {
8
- const context = request.localContext ? structuredClone(request.localContext) : undefined, connection = api.getConnectionState();
9
- // 只在原context已接纳且已有执行用途可信target的路径重叠;首次未连接仍按原顺序开通。
10
- if (!context || connection.phase !== 'connected' || typeof api.getSshTarget !== 'function')
11
- return;
12
- const network = employee.getNetwork(), lifetime = new AbortController(), offs = [];
13
- const signal = AbortSignal.any([lifetime.signal, ...request.signal ? [request.signal] : []]);
14
- let closed = false, target, location, native;
15
- const nativeMetadata = () => native ??= (request.startupTiming?.run('native-metadata', () => employee.native()) ?? Promise.resolve().then(() => employee.native()));
16
- const close = () => { if (closed)
17
- return; closed = true; for (const off of offs.splice(0))
18
- off(); };
19
- const cancel = () => { lifetime.abort(failure('ABORTED')); close(); };
20
- const check = () => {
21
- signal.throwIfAborted();
22
- request.localAdmissionCheck?.();
23
- if (get() !== api || employee.getNetwork() !== network)
24
- throw failure('EMPLOYEE_CONTEXT_CHANGED');
25
- const now = api.getConnectionState();
26
- if (now.phase !== 'connected' || now.instanceId !== connection.instanceId || now.epoch !== connection.epoch)
27
- throw failure('CONNECTION_LOST');
28
- if (!network || network.getState().phase !== 'online')
29
- throw failure('CONNECTION_LOST');
30
- };
31
- const changed = () => { try {
32
- check();
33
- }
34
- catch (error) {
35
- lifetime.abort(error);
36
- close();
37
- } };
38
- const revokeNetwork = (event) => { if (event.kind === 'lost') {
39
- lifetime.abort(failure('CONNECTION_LOST'));
40
- close();
41
- }
42
- else
43
- changed(); };
44
- const aborted = () => close();
45
- signal.addEventListener('abort', aborted, { once: true });
46
- offs.push(() => signal.removeEventListener('abort', aborted));
47
- const pending = (async () => {
48
- if (typeof api.onConnectionState !== 'function' || typeof api.onWorkspaceLocationState !== 'function' || !network || typeof network.onState !== 'function' || typeof network.prepareEmployeeEndpoint !== 'function')
49
- throw failure('DEPENDENCY_REQUIRED');
50
- const watch = (off) => { if (closed)
51
- off();
52
- else
53
- offs.push(off); };
54
- watch(api.onConnectionState(changed));
55
- watch(api.onWorkspaceLocationState(changed));
56
- watch(network.onState(revokeNetwork));
57
- if (network.getState().phase !== 'online')
58
- throw failure('EMPLOYEE_ENDPOINT_UNAVAILABLE');
59
- check();
60
- const current = await awaitL(() => api.getSshTarget(), signal);
61
- if (!current.ok)
62
- throw connectNeedError(current.error);
63
- target = structuredClone(current.value);
64
- validateTarget(target);
65
- check();
66
- // 保留O1既有的纯静态解析重叠;实际执行与broker仍须等待两道门及静态结果。
67
- void nativeMetadata().catch(() => { });
68
- const prepare = () => admitEmployeeLocation({ api: api, network, workspace: { id: context.workspaceId, path: context.directory.path }, connection, expectedLocal: { instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, bindingId: context.bindingId, directory: { ...context.directory } }, settingsPath: target.session.settingsPath, signal });
69
- location = await awaitL(() => request.startupTiming?.run('endpoint-prepare', prepare) ?? prepare(), signal);
70
- check();
71
- })();
72
- // 登录失败始终优先;端点提前失败也先被观察,不能产生未处理拒绝或抢先改变失败语义。
73
- void pending.catch(() => { });
74
- const confirm = (current, ready) => { check(); if (!target || !sameTarget(target, current) || ready.instanceId !== connection.instanceId || ready.epoch !== connection.epoch)
75
- throw failure('EMPLOYEE_CONTEXT_CHANGED'); };
76
- return { ready: pending, confirm, cancel, native: nativeMetadata, async location(currentNetwork, currentContext) {
77
- await pending;
78
- check();
79
- if (currentNetwork !== network || !isDeepStrictEqual(currentContext, context))
80
- throw failure('EMPLOYEE_CONTEXT_CHANGED');
81
- // 准备完成至登录结束之间仍可能替换物理目录;只重读L的只读context,不再prepare第二次。
82
- const [current, physical] = await Promise.all([
83
- awaitL(() => api.getSshTarget(), signal),
84
- awaitL(() => api.getLocalWorkspaceContext({ instanceId: context.instanceId, epoch: context.epoch, workspaceId: context.workspaceId, expectedBindingId: context.bindingId }), signal),
85
- ]);
86
- check();
87
- if (!current.ok)
88
- throw connectNeedError(current.error);
89
- if (!physical.ok)
90
- throw connectNeedError(physical.error);
91
- if (!target || !sameTarget(target, current.value) || !isDeepStrictEqual(physical.value, context))
92
- throw failure('EMPLOYEE_CONTEXT_CHANGED');
93
- return location;
94
- } };
95
- }