@ai-workbench/remote-agent 0.9.0-toolbridge.35 → 0.9.0-toolbridge.37-rc.4

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/dist/index.js CHANGED
@@ -1,8 +1,10 @@
1
+ import { syncNativeSessionContent } from "./native-content-transport.js";
2
+ import { readCustomInstructions } from "./custom-instructions.js";
1
3
  import { StartupTiming } from "./startup-timing.js";
2
4
  import { ColdRecovery } from "./cold-recovery.js";
3
5
  import { createSteeringReceipts, installLiveSteering, steeringMessageDigest } from "./live-steering.js";
4
6
  import { ToolBridgeLoop } from "./toolbridge-loop.js";
5
- import { openToolBridgeMcp, TOOLBRIDGE_NOTICE } from "./toolbridge.js";
7
+ import { openToolBridgeMcp } from "./toolbridge.js";
6
8
  import { connectNeedMessage } from "./connect-need.js";
7
9
  import { CloseDiagnostics, withFirstFailureEvidence, failureEvidenceSummary, closeCode } from "./close-diagnostics.js";
8
10
  import { withRemoteFailureEvidence } from "./failure-evidence.js";
@@ -10,7 +12,7 @@ import { SessionId } from '@deepseek-ai/dsh-session';
10
12
  import { createAssistantMessage } from '@deepseek-ai/dsh-llm';
11
13
  import Schema from '@deepseek-ai/schemastery';
12
14
  import { LlmAdapter, LlmError } from '@deepseek-ai/dsh-llm';
13
- import { createHash, randomUUID } from 'node:crypto';
15
+ import { randomUUID } from 'node:crypto';
14
16
  import * as unstable from '@agentclientprotocol/sdk/unstable';
15
17
  import * as acp from '@agentclientprotocol/sdk';
16
18
  import { AcpSession } from "./acp.js";
@@ -25,13 +27,11 @@ import { createRemoteDetails } from "./remote-details.js";
25
27
  import { approvalLabel } from "./approval-label.js";
26
28
  import { ModelCatalog, modelInfo } from "./model-catalog.js";
27
29
  import { ModelPresentation } from "./model-presentation.js";
28
- import { EMPLOYEE_EXECUTION_NOTICE } from "./employee-presentation.js";
29
30
  import { ModelConfigurationError } from "./model-configuration.js";
30
31
  import { officialEmployeeWorkspace } from "./employee-workspace.js";
31
32
  import { createSessionSources } from "./session-source.js";
32
33
  import { resolveEmployeeNative } from "./employee-native.js";
33
34
  import { createClaudeLocalProvider } from "./claude-local.js";
34
- import { readLocalUserTurn } from "./local-user-turn.js";
35
35
  import { readEmployeeWorkspace } from "./employee-workspace.js";
36
36
  import { createPreflightDiagnostics } from "./preflight-diagnostic.js";
37
37
  import { installModelInputRetention, markModelPreparationFailure } from "./model-input-retention.js";
@@ -65,7 +65,7 @@ function readPointer(options, agent) {
65
65
  continue;
66
66
  const envelope = message.source.replayState;
67
67
  const pointer = envelope?.response;
68
- if (pointer?.version !== 2 || pointer.agent !== agent.id || pointer.dshSessionId !== options.sessionId || ![pointer.identity, pointer.cwd, pointer.sessionId].every(value => typeof value === 'string' && value.length > 0) || pointer.contextSha256 !== undefined && typeof pointer.contextSha256 !== 'string')
68
+ if (pointer?.version !== 2 || pointer.agent !== agent.id || pointer.dshSessionId !== options.sessionId || ![pointer.identity, pointer.cwd, pointer.sessionId].every(value => typeof value === 'string' && value.length > 0))
69
69
  continue;
70
70
  return { pointer: pointer, index };
71
71
  }
@@ -108,8 +108,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
108
108
  shuttingDown = false;
109
109
  detached = new Set();
110
110
  modelPresentation = new ModelPresentation();
111
- employeeNoticeSessions = new Set();
112
- pendingEmployeeNotices = new Set();
113
111
  constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) {
114
112
  super();
115
113
  this.resolveRuntime = resolveRuntime;
@@ -280,8 +278,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
280
278
  this.shuttingDown = true;
281
279
  this.coldRecovery?.dispose?.();
282
280
  this.modelPresentation.clear();
283
- this.employeeNoticeSessions.clear();
284
- this.pendingEmployeeNotices.clear();
285
281
  const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
286
282
  await this.bridgeLoop.dispose();
287
283
  this.lifetime.abort(Object.assign(new DOMException('远程模型插件已关闭', 'AbortError'), { kind: 'disposed' }));
@@ -307,10 +303,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
307
303
  let promptDispatched = !!options.sessionId && (this.sessions.get(options.sessionId)?.session.promptDispatchCount ?? 0) > 0;
308
304
  try {
309
305
  for await (const chunk of this.bridgeLoop.stream(options, (o, b) => this.generate(o, () => { promptDispatched = true; }, b))) {
310
- if (options.sessionId && this.pendingEmployeeNotices.has(options.sessionId) && chunk.type === 'text-delta' && chunk.text.startsWith(EMPLOYEE_EXECUTION_NOTICE)) {
311
- this.employeeNoticeSessions.add(options.sessionId);
312
- this.pendingEmployeeNotices.delete(options.sessionId);
313
- }
314
306
  yield chunk;
315
307
  }
316
308
  }
@@ -336,10 +328,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
336
328
  }
337
329
  throw new LlmError(employeeFailure('TURN_FAILED', this.agent.loginProvider, promptDispatched), 'TURN_FAILED', { cause: error });
338
330
  }
339
- finally {
340
- if (options.sessionId)
341
- this.pendingEmployeeNotices.delete(options.sessionId);
342
- }
343
331
  }
344
332
  async *generate(original, onPromptDispatched, bridge) {
345
333
  if (this.lifetime.signal.aborted)
@@ -365,8 +353,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
365
353
  let activeMapper;
366
354
  let selected;
367
355
  let modelConfiguration;
368
- let coldPrelude = '';
369
- let employeeNoticeShown = false;
356
+ const coldPrelude = '';
370
357
  let permissionOff;
371
358
  let permissionEpoch = new AbortController();
372
359
  const information = [];
@@ -393,25 +380,19 @@ export class CodexRemoteAdapter extends LlmAdapter {
393
380
  let checkpointIndex = usedColdCheckpoint ? -1 : checkpoint?.index ?? -1;
394
381
  if (usedColdCheckpoint)
395
382
  options = { ...options, messages: options.messages.filter((m, index) => index > checkpoint.index || m.role === 'system' || m.role === 'developer') };
396
- employeeNoticeShown = !!key && this.employeeNoticeSessions.has(key) || false;
397
- if (employeeNoticeShown && key)
398
- this.employeeNoticeSessions.add(key);
399
383
  live = undefined;
400
384
  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 }) });
401
- request.previousContextSha256 = previous?.contextSha256;
402
385
  const after = options.messages.findLastIndex(message => message.role === 'assistant');
403
386
  const tail = options.messages.slice(after + 1);
404
387
  const humanIds = tail.flatMap(message => message.role === 'user' && message.source?.kind === 'user' && typeof message.id === 'string' ? [message.id] : []);
405
- // An official approval may continue the same native turn without another
406
- // human message. This is a CAS candidate only: live turn/L proof must still
407
- // bind it. The actual input delta remains prepareInput's unchanged tail.
408
- if (!humanIds.length && tail.some(message => message.role === 'user' && message.source?.kind === 'user-approval')) {
409
- const original = options.messages.slice(0, after + 1).findLast(message => message.role === 'user' && message.source?.kind === 'user' && typeof message.id === 'string');
410
- if (typeof original?.id === 'string')
411
- humanIds.push(original.id);
388
+ const currentInputs = tail.filter(message => message.role === 'user');
389
+ if (currentInputs.some(message => message.source?.kind === 'user-approval') && currentInputs.every(message => ['user-approval', 'runtime-context', 'skill-catalog', 'agent-instructions', 'model-selection'].includes(message.source?.kind ?? ''))) {
390
+ // A policy control event updates the native permission setter on the next
391
+ // active turn; it is neither a new task nor a reason to require human text.
392
+ yield { type: 'finish', reason: { kind: 'stop' } };
393
+ succeeded = true;
394
+ return;
412
395
  }
413
- request.userInputIds = Object.freeze(humanIds);
414
- request.userMessageIds = request.userInputIds;
415
396
  earlyStage = 'source-context';
416
397
  await startupTiming.run('source-admission', async () => this.resolveRuntime.preflight?.(request));
417
398
  options = { ...await this.coldRecovery?.projectCancelledInputs?.(options) ?? options, signal };
@@ -428,12 +409,9 @@ export class CodexRemoteAdapter extends LlmAdapter {
428
409
  const injected = new Set(matching.filter(r => r.outcome === 'injected').map(r => { if (!previous || r.nativeSessionId !== previous.sessionId)
429
410
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的注入回执与检查点'); return r.messageId; }));
430
411
  const withheld = new Set([...injected, ...uncertain]);
431
- if (humanIds.length && humanIds.every(id => withheld.has(id))) {
432
- if (receiptNotice) {
433
- const notice = new StreamMapper();
434
- yield* notice.text(receiptNotice);
435
- yield* notice.flush();
436
- }
412
+ if (currentInputs.length && currentInputs.every(message => typeof message.id === 'string' && withheld.has(message.id))) {
413
+ if (receiptNotice)
414
+ await this.preflightDiagnostics?.record(request, this.agent.loginProvider, { kind: 'session', severity: 'warning', code: 'INPUT_DELIVERY_UNCONFIRMED', summary: receiptNotice });
437
415
  yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: previous } };
438
416
  succeeded = true;
439
417
  return;
@@ -441,15 +419,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
441
419
  const projected = { ...options, messages: options.messages.filter((m, index) => index <= checkpointIndex || !('id' in m) || typeof m.id !== 'string' || !withheld.has(m.id)) };
442
420
  earlyStage = 'input-prepare';
443
421
  let input = await startupTiming.run('input-prepare', () => prepareInput(projected, this.readImage));
444
- const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
445
- request.contextSha256 = contextSha256;
446
422
  const codex = this.agent.loginProvider === 'codex';
447
- const contextChanged = !!previous && codex && (previous.contextSha256 ?? '').toLowerCase() !== contextSha256;
448
- // Only identical durable context can prove a legacy context-bound journal.
449
- // New Codex transport scopes are independent of the native context digest.
450
- if (contextChanged)
451
- request.contextSha256 = undefined;
452
- if (Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
423
+ if (Buffer.byteLength(JSON.stringify({ prompt: input.prompt }), 'utf8') > config.acpMaxMessageBytes)
453
424
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
454
425
  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 };
455
426
  let modelSignal = signal;
@@ -469,7 +440,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
469
440
  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))
470
441
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
471
442
  input = await prepareContinuation({ ...options, messages: projected.messages.slice(checkpointIndex + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
472
- if (runtime.hostWorkspace && Buffer.byteLength(JSON.stringify({ prompt: input.prompt, systemPrompt: input.systemPrompt }), 'utf8') > config.acpMaxMessageBytes)
443
+ if (runtime.hostWorkspace && Buffer.byteLength(JSON.stringify({ prompt: input.prompt }), 'utf8') > config.acpMaxMessageBytes)
473
444
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
474
445
  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 });
475
446
  startupTiming.bind(event => details.record(event));
@@ -488,27 +459,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
488
459
  let id;
489
460
  let stop;
490
461
  const pointerRuntime = runtime;
491
- const makePointer = (nativeId) => ({ ...(pointerRuntime.cold ? { coldRoundId: pointerRuntime.cold.id } : {}), ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, contextSha256, ...(options.sessionId ? { dshSessionId: options.sessionId } : {}), identity: pointerRuntime.identity, cwd: pointerRuntime.cwd, sessionId: nativeId, ...(pointerRuntime.binding ? { bindingId: pointerRuntime.binding.bindingId, workspaceId: pointerRuntime.binding.workspaceId } : {}) });
462
+ const makePointer = (nativeId) => ({ ...(pointerRuntime.cold ? { coldRoundId: pointerRuntime.cold.id } : {}), ...(pointerRuntime.hostSource ? { hostSource: pointerRuntime.hostSource } : {}), ...(modelConfiguration ? { modelConfiguration } : {}), version: 2, agent: this.agent.id, ...(options.sessionId ? { dshSessionId: options.sessionId } : {}), identity: pointerRuntime.identity, cwd: pointerRuntime.cwd, sessionId: nativeId, ...(pointerRuntime.binding ? { bindingId: pointerRuntime.binding.bindingId, workspaceId: pointerRuntime.binding.workspaceId } : {}) });
492
463
  if (runtime.employeePresentation)
493
464
  details.record({ kind: 'session', severity: 'warning', code: 'EMPLOYEE_EXECUTION_SCOPE', summary: runtime.employeePresentation, payload: { source: 'local' } });
494
465
  if (runtime.execution)
495
466
  details.record({ kind: 'session', severity: 'warning', code: 'CLAUDE_EMPLOYEE_SCOPE', summary: runtime.execution.notice, payload: runtime.execution.scope });
496
- if ((runtime.employeePresentation || runtime.execution) && !employeeNoticeShown) {
497
- coldPrelude = EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n';
498
- for (const chunk of mapper.text(coldPrelude)) {
499
- if (chunk.type === 'text-delta') {
500
- employeeNoticeShown = true;
501
- if (key) {
502
- if (bridge)
503
- this.pendingEmployeeNotices.add(key);
504
- else
505
- this.employeeNoticeSessions.add(key);
506
- }
507
- }
508
- yield chunk;
509
- }
510
- yield* mapper.flush();
511
- }
512
467
  { // 仅支持ACP会话模式;保留此块的局部变量作用域。
513
468
  if (!runtime.acpTransport)
514
469
  throw new NeedError('DEPENDENCY_REQUIRED', '我需要该员工主机上的ACP通道', 'S提供的ACP命令与aw-session');
@@ -519,8 +474,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
519
474
  const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
520
475
  let renderTail = Promise.resolve(), nativeUpdates = 0, coldPromptStarted = false;
521
476
  const render = (work) => { renderTail = renderTail.then(work); void renderTail.catch(error => { failure ??= error; session?.close({ layer: 'adapter', initiator: 'adapter.render-failure', reason: closeCode(error, 'MAPPING_FAILED'), action: 'close' }); wake?.(); }); };
522
- const renderNotice = (text) => render(async () => { if (runtime.cold)
523
- await runtime.cold.store.update(options.sessionId, options.provider, runtime.cold.id, row => { (row.localNotices ??= []).push({ beforeUpdate: nativeUpdates, text }); }); push(mapper.text(text)); });
477
+ const renderNotice = (text) => render(() => { details.record({ kind: 'session', severity: 'info', code: 'ACP_IDLE_UPDATE', summary: text }); });
524
478
  if (receiptNotice)
525
479
  renderNotice(receiptNotice);
526
480
  let promptPermit;
@@ -624,7 +578,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
624
578
  };
625
579
  const task = (async () => {
626
580
  try {
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);
581
+ await session.start(runtime.execution?.hostCwd ?? runtime.cwd, previous?.sessionId, modelSignal, { ...(bridgeMcp ? { toolBridgeServers: bridgeMcp.mcpServers } : {}), ...(runtime.execution ? { employeeRouting: runtime.execution.routing } : {}), ...(runtime.nativeContent ? { nativeContent: runtime.nativeContent } : {}), ...(runtime.customInstructions === undefined ? {} : { customInstructions: runtime.customInstructions }), ...(codex ? { codexNewSessionOnly: true, initialModel: selected.value } : {}), ...(runtime.employeeExecutionMeta ? { employeeExecution: runtime.employeeExecutionMeta } : {}) }, input.prompt);
628
582
  }
629
583
  catch (error) {
630
584
  details.record({ kind: 'session', severity: 'action-required', code: 'SESSION_START_FAILED', summary: '远端会话建立或恢复失败,本轮用户输入未发送。', payload: { operation: previous ? 'resume-or-load' : 'new', reason: closeCode(error, 'ACP_FAILED'), promptDispatched: false } });
@@ -676,7 +630,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
676
630
  details.beginTurn(runtime.detailContext?.() ?? { turn: null, step: null });
677
631
  await renderTail;
678
632
  if (runtime.cold && this.coldRecovery)
679
- await this.coldRecovery.capture(runtime, options, session.id, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256, modelConfiguration, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
633
+ await this.coldRecovery.capture(runtime, options, session.id, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, modelConfiguration, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
680
634
  coldPromptStarted = true;
681
635
  await runtime.execution?.beginTurn(modelSignal);
682
636
  if (bridge?.enabled)
@@ -720,8 +674,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
720
674
  if (stop === 'cancelled')
721
675
  throw new NeedError('ABORTED', '远端本轮已取消', '核对主机任务状态');
722
676
  if (stop === 'refusal')
723
- for (const chunk of mapper.text('\n[远端拒绝] 此请求未执行。\n'))
724
- yield chunk;
677
+ details.record({ kind: 'session', severity: 'warning', code: 'ACP_IDLE_UPDATE', summary: '远端拒绝此请求,未执行。' });
725
678
  }
726
679
  mapper.flushMetadata();
727
680
  recordInformation();
@@ -743,7 +696,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
743
696
  }
744
697
  catch (error) {
745
698
  if (original.signal?.reason?.kind === 'user' && runtime?.cold && this.coldRecovery)
746
- await this.coldRecovery.recordUserCancellation(runtime, options, session?.id ?? request?.resumeSessionId, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, contextSha256: request?.contextSha256 ?? '', modelConfiguration: modelConfiguration ?? { selected }, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
699
+ await this.coldRecovery.recordUserCancellation(runtime, options, session?.id ?? request?.resumeSessionId, { identity: runtime.identity, cwd: runtime.cwd, binding: runtime.binding, hostSource: runtime.hostSource, modelConfiguration: modelConfiguration ?? { selected }, model: options.model, prelude: coldPrelude, localDirectory: runtime.localDirectory });
747
700
  if (session && session.promptDispatchCount > promptBaseline)
748
701
  onPromptDispatched();
749
702
  if (bridge?.unsettled && !signal.aborted)
@@ -829,7 +782,7 @@ export function apply(ctx, live) {
829
782
  return attachments.readImage(ref, signal);
830
783
  };
831
784
  const sessionSources = createSessionSources(ctx, get);
832
- const coldRecovery = new ColdRecovery(ctx, get, config, { readSource: sessionSources.read });
785
+ const coldRecovery = new ColdRecovery(ctx, get, config, { readSource: sessionSources.read, notice: (row, text) => managerForProfile().recordLocalFailure({ sessionId: row.sessionId, provider: row.brand, code: 'ACP_IDLE_UPDATE', observation: { kind: 'session', severity: 'info', code: 'ACP_IDLE_UPDATE', summary: text } }) });
833
786
  const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config, { coldStore: coldRecovery.store })]));
834
787
  const detailManagers = new Map();
835
788
  const managerForProfile = () => {
@@ -867,7 +820,14 @@ export function apply(ctx, live) {
867
820
  return managerForProfile().open({ sessionId: request.sessionId, provider: agent.loginProvider, identity: `${target.username}@${target.host}:${target.port}`, connection });
868
821
  };
869
822
  const open = async (...args) => {
870
- const runtime = await openByAgent.get(agent.id)(...args);
823
+ const [target, project, request] = args;
824
+ const services = ctx;
825
+ const scope = request.sessionId ? ctx.get('agents')?.get(SessionId(request.sessionId)) : undefined;
826
+ const nativeContent = await syncNativeSessionContent({ target, request, employeeCwd: request.nativeEmployeeCwd, scope, skills: services.get('skills') });
827
+ const actualProject = agent.loginProvider === 'claude' && request.nativeEmployeeCwd && nativeContent ? { ...project, path: nativeContent.hostCwd } : project;
828
+ const runtime = await openByAgent.get(agent.id)(target, actualProject, request);
829
+ runtime.nativeContent = nativeContent;
830
+ runtime.customInstructions = readCustomInstructions(services, scope);
871
831
  runtime.detailContext = () => {
872
832
  const events = args[2].sessionId ? ctx.get('agents')?.get(SessionId(args[2].sessionId))?.session.snapshotEvents() : undefined;
873
833
  let turn = null, step = null;
@@ -889,7 +849,7 @@ export function apply(ctx, live) {
889
849
  };
890
850
  return runtime;
891
851
  };
892
- const local = agent.loginProvider === 'claude' ? createClaudeLocalProvider({ getConnect: get, getNetwork: () => ctx.get('aiWorkbenchNetwork'), readWorkspace: id => readEmployeeWorkspace(ctx, id), readUserTurn: request => readLocalUserTurn(ctx, { sessionId: request.sessionId, route: agent.id, userMessageIds: request.userMessageIds ?? [] }), reportAdmissionFailure: (request, code) => preflightDiagnostics.failure(request, 'claude', code, 'local-admission'), recordUnscoped: (request, observation) => managerForProfile().recordLocalFailure({ sessionId: request.sessionId, provider: 'claude', code: observation.code, observation }), configuration: config, details, open }) : undefined;
852
+ const local = agent.loginProvider === 'claude' ? createClaudeLocalProvider({ getConnect: get, getNetwork: () => ctx.get('aiWorkbenchNetwork'), readWorkspace: id => readEmployeeWorkspace(ctx, id), recordUnscoped: (request, observation) => managerForProfile().recordLocalFailure({ sessionId: request.sessionId, provider: 'claude', code: observation.code, observation }), configuration: config, details, open }) : undefined;
893
853
  const workspace = async (request) => {
894
854
  const services = ctx;
895
855
  const registry = services.get('workspaceRegistry');
package/dist/input.d.ts CHANGED
@@ -18,22 +18,16 @@ export interface HistoryTransfer {
18
18
  export interface HostWorkspacePresentation {
19
19
  readonly cwd: string;
20
20
  }
21
- type RuntimeSection = {
22
- name: string;
23
- text: string;
24
- };
25
21
  export interface PreparedInput {
26
22
  prompt: AcpContentBlock[];
27
23
  users: {
28
24
  id: string | undefined;
29
25
  prompt: AcpContentBlock[];
30
26
  }[];
31
- systemPrompt?: string;
32
27
  historyTransfer?: HistoryTransfer;
33
- runtimeSnapshots?: ReadonlyMap<AcpContentBlock, readonly RuntimeSection[]>;
34
28
  }
35
- /** Invocation-only model context; never modifies the native session/history. */
36
- export declare function projectHostWorkspaceInput(input: PreparedInput, host?: HostWorkspacePresentation): PreparedInput;
29
+ /** Execution location belongs to native cwd and tool routing, not model prose. */
30
+ export declare function projectHostWorkspaceInput(input: PreparedInput, _host?: HostWorkspacePresentation): PreparedInput;
37
31
  /** Role-labelled public history only; never serialize source/replay/tool internals. */
38
32
  export declare function prepareContinuation(options: GenerateOptions, input: PreparedInput, readImage: ImageReader | undefined, capacity: {
39
33
  maxBytes: number;
@@ -41,4 +35,3 @@ export declare function prepareContinuation(options: GenerateOptions, input: Pre
41
35
  }): Promise<PreparedInput>;
42
36
  /** The attachment service supplies verified bytes; client paths never cross SSH. */
43
37
  export declare function prepareInput(options: GenerateOptions, readImage?: ImageReader): Promise<PreparedInput>;
44
- export {};
package/dist/input.js CHANGED
@@ -1,44 +1,13 @@
1
1
  import { NeedError } from "./remote.js";
2
- import { dshSkillCatalog } from "./toolbridge-table.js";
3
- function runtimeSections(message) {
4
- const source = message.source;
5
- if (message.role !== 'user' || source?.kind !== 'runtime-context' || source.form !== 'snapshot' || !Array.isArray(source.sections) || message.content.length !== 1 || message.content[0].type !== 'text')
6
- return;
7
- if (!source.sections.every(s => s && typeof s.name === 'string' && typeof s.text === 'string'))
8
- return;
9
- const sections = source.sections, body = sections.map(s => s.text).join('\n\n');
10
- // Only official, structurally attributed snapshot text is projected. Employee
11
- // text and opaque contributions are never searched for or rewritten as paths.
12
- if (body && message.content[0].text.endsWith('\n\n' + body))
13
- return sections;
14
- }
15
- /** Invocation-only model context; never modifies the native session/history. */
16
- export function projectHostWorkspaceInput(input, host) {
17
- if (!host)
18
- return input;
19
- const context = `当前会话使用远程主机上的工作区:${JSON.stringify(host.cwd)}。文件和命令在该主机目录执行,受主机账号的操作系统权限约束;本机 DSH 文件沙箱的工作区路径不适用于这些远程操作。`;
20
- const mapped = new Map();
21
- for (const [block, sections] of input.runtimeSnapshots ?? []) {
22
- if (block.type !== 'text' || !sections.some(s => s.name === 'sandbox:policy'))
23
- continue;
24
- const body = sections.map(s => s.text).join('\n\n');
25
- mapped.set(block, { ...block, text: block.text.slice(0, -body.length) + sections.map(s => s.name === 'sandbox:policy' ? context : s.text).join('\n\n') });
26
- }
27
- const project = (blocks) => blocks.map(block => mapped.get(block) ?? block);
28
- const prompt = project(input.prompt);
29
- // Confirm this invocation after all current and historical text. A projected
30
- // historical snapshot must not suppress host facts for an opaque current one;
31
- // warm steps also need no new native snapshot to retain their host location.
32
- prompt.push({ type: 'text', text: context });
33
- return { ...input, prompt, users: input.users.map(user => ({ ...user, prompt: project(user.prompt) })) };
34
- }
2
+ /** Execution location belongs to native cwd and tool routing, not model prose. */
3
+ export function projectHostWorkspaceInput(input, _host) { return input; }
35
4
  async function publicBlock(block, options, readImage, history = false) {
36
5
  options.signal?.throwIfAborted();
37
6
  if (block.type === 'text')
38
7
  return { type: 'text', text: block.text };
39
8
  if (block.type === 'image') {
40
9
  if (block.offloaded) {
41
- return { type: 'text', text: `图片 ${block.attachment.name ?? block.attachment.attachmentId} 已按官方会话策略移出当前上下文。` };
10
+ return { type: 'text', text: JSON.stringify({ type: 'image', attachment: block.attachment, offloaded: true }) };
42
11
  }
43
12
  if (!readImage)
44
13
  throw new NeedError('ATTACHMENT_REQUIRED', '我需要官方附件组件读取这张图片', '官方attachments.readImage');
@@ -57,6 +26,8 @@ export async function prepareContinuation(options, input, readImage, capacity) {
57
26
  for (const message of options.messages.slice(0, after + 1)) {
58
27
  // Runtime snapshots, approval answers and tool state are not employee-visible
59
28
  // conversation. Current runtime/system context stays on its original path.
29
+ if (message.role === 'assistant' && message.source.provider === 'ai-workbench-toolbridge')
30
+ continue;
60
31
  if (message.role !== 'assistant' && (message.role !== 'user' || message.source?.kind !== 'user'))
61
32
  continue;
62
33
  if (!message.content.some(block => block.type === 'text' || block.type === 'image'))
@@ -69,18 +40,18 @@ export async function prepareContinuation(options, input, readImage, capacity) {
69
40
  if (!groups.length)
70
41
  return base;
71
42
  const historyTransfer = { scope: 'visible-user-assistant-text-and-images', textBlocks: 0, imageBlocks: 0, offloadedImagePlaceholders: 0, omittedReasoningBlocks: 0, reasoningOmissionReason: 'dsh-internal-reasoning', retainedRounds: 0, omittedRounds: groups.length, maxBytes: capacity.maxBytes };
72
- const separator = { type: 'text', text: '此前可见对话结束。以下为当前用户输入:\n' };
43
+ const separator = { type: 'text', text: JSON.stringify({ role: 'user' }) };
73
44
  const retained = [];
74
45
  // prepareInput guarantees a nonempty current prompt. Each inserted block adds
75
46
  // its JSON bytes and one comma; count each round once, not the whole prefix.
76
- let bytes = Buffer.byteLength(JSON.stringify({ prompt: base.prompt, systemPrompt: base.systemPrompt }), 'utf8') + Buffer.byteLength(JSON.stringify(separator), 'utf8') + 1;
47
+ let bytes = Buffer.byteLength(JSON.stringify({ prompt: base.prompt }), 'utf8') + Buffer.byteLength(JSON.stringify(separator), 'utf8') + 1;
77
48
  // Whole consecutive rounds, newest first. The existing byte capacity is the
78
49
  // only bound; N is computed from actual encoded text/image sizes, not a cap.
79
50
  for (const group of groups.toReversed()) {
80
51
  const blocks = [], counts = { textBlocks: 0, imageBlocks: 0, offloadedImagePlaceholders: 0, omittedReasoningBlocks: 0 };
81
52
  for (const message of group) {
82
53
  options.signal?.throwIfAborted();
83
- blocks.push({ type: 'text', text: `此前可见对话(历史角色:${message.role};仅为历史记录):\n` });
54
+ blocks.push({ type: 'text', text: JSON.stringify({ role: message.role }) });
84
55
  for (const block of message.content) {
85
56
  if (block.type === 'reasoning') {
86
57
  counts.omittedReasoningBlocks++;
@@ -96,7 +67,6 @@ export async function prepareContinuation(options, input, readImage, capacity) {
96
67
  else
97
68
  counts.imageBlocks++;
98
69
  }
99
- blocks.push({ type: 'text', text: `\n(历史角色:${message.role} 的记录结束)\n` });
100
70
  }
101
71
  const additional = Buffer.byteLength(JSON.stringify(blocks), 'utf8') - 1; // Strip [] and add the comma before the retained suffix.
102
72
  if (bytes + additional > capacity.maxBytes)
@@ -114,41 +84,22 @@ export async function prepareContinuation(options, input, readImage, capacity) {
114
84
  export async function prepareInput(options, readImage) {
115
85
  options.signal?.throwIfAborted();
116
86
  const messages = options.messages;
117
- const context = [];
118
- if (options.system)
119
- context.push('系统上下文:\n' + options.system);
120
- for (const message of messages) {
121
- if (message.role !== 'system' && message.role !== 'developer')
122
- continue;
123
- const parts = message.content.map(block => {
124
- if (block.type !== 'text')
125
- throw new NeedError('SYSTEM_CONTEXT_TYPE_UNSUPPORTED', '系统或开发者要求包含暂不支持的非文本内容,本轮未新建或发送', '系统及开发者仅支持公开text上下文;非文本内容需要已定义的公开ACP投影');
126
- return block.text;
127
- });
128
- if (parts.length)
129
- context.push((message.role === 'system' ? '系统上下文:' : '开发者上下文:') + '\n' + parts.join('\n'));
130
- }
131
87
  const after = messages.findLastIndex(message => message.role === 'assistant');
132
- const users = messages.slice(after + 1).filter(message => message.role === 'user');
88
+ const users = messages.slice(after + 1).filter(message => message.role === 'user' && !['runtime-context', 'skill-catalog', 'agent-instructions', 'model-selection', 'user-approval'].includes(message.source?.kind ?? ''));
133
89
  if (!users.length)
134
90
  throw new NeedError('INPUT_REQUIRED', '我需要本轮用户输入', '用户输入');
135
91
  const prompt = [];
136
92
  const preparedUsers = [];
137
- const runtimeSnapshots = new Map();
138
93
  for (const message of users) {
139
94
  const before = prompt.length;
140
- const sections = runtimeSections(message);
141
95
  for (const block of message.content) {
142
- let prepared = await publicBlock(block, options, readImage);
143
- if (prepared.type === 'text' && dshSkillCatalog([message]) !== undefined)
144
- prepared = { ...prepared, text: '以下是DSH的技能目录,供DSH工具skill使用;主机Claude/Codex原生技能按各自原生指令加载。加载后请按<skill_resources>给出的资源基址读取资源。\n' + prepared.text };
145
- prompt.push(prepared);
146
- if (sections)
147
- runtimeSnapshots.set(prepared, sections);
96
+ if (block.type === 'image' && block.offloaded)
97
+ continue;
98
+ prompt.push(await publicBlock(block, options, readImage));
148
99
  }
149
100
  preparedUsers.push({ id: message.id, prompt: prompt.slice(before) });
150
101
  }
151
102
  if (!prompt.length)
152
103
  throw new NeedError('INPUT_REQUIRED', '我需要本轮用户输入', '用户输入');
153
- return { prompt, users: preparedUsers, runtimeSnapshots, ...(context.length ? { systemPrompt: context.join('\n\n') } : {}) };
104
+ return { prompt, users: preparedUsers };
154
105
  }
@@ -0,0 +1,42 @@
1
+ import { type NativeContentLayout } from './native-content.ts';
2
+ import { type BrokerIo } from './broker.ts';
3
+ import type { ConnectTarget, RuntimeRequest } from './provider.ts';
4
+ export type NativeSessionContent = NativeContentLayout;
5
+ interface SkillSummary {
6
+ name: string;
7
+ description: string;
8
+ provider?: string;
9
+ source?: string;
10
+ path?: string;
11
+ resourceBase?: {
12
+ kind: string;
13
+ path?: string;
14
+ };
15
+ invocation?: {
16
+ modelInvocable?: boolean;
17
+ };
18
+ }
19
+ interface SkillLookup {
20
+ cwd: string;
21
+ scope?: unknown;
22
+ signal?: AbortSignal;
23
+ }
24
+ interface SkillRegistry {
25
+ snapshot(options: SkillLookup): Promise<{
26
+ complete: boolean;
27
+ skills: SkillSummary[];
28
+ }>;
29
+ get(name: string, options: SkillLookup): Promise<(SkillSummary & {
30
+ content: string;
31
+ }) | undefined>;
32
+ }
33
+ /** The source is the official scoped DSH catalog, never its rendered system prompt. */
34
+ export declare function syncNativeSessionContent(options: {
35
+ target: ConnectTarget;
36
+ request: RuntimeRequest;
37
+ employeeCwd?: string;
38
+ scope?: unknown;
39
+ skills?: SkillRegistry;
40
+ io?: BrokerIo;
41
+ }): Promise<NativeSessionContent | undefined>;
42
+ export {};
@@ -0,0 +1,83 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { readFile } from 'node:fs/promises';
10
+ import { join } from 'node:path';
11
+ import { captureNativeSkill, captureProjectInstructions, nativeContentPlan, materializeNativeContent, activateNativeContent } from "./native-content.js";
12
+ import { sshIo } from "./broker.js";
13
+ import { NeedError } from "./remote.js";
14
+ /** The source is the official scoped DSH catalog, never its rendered system prompt. */
15
+ export async function syncNativeSessionContent(options) {
16
+ const { target, request, employeeCwd } = options, limits = { maxBytes: request.acpMaxMessageBytes, signal: request.signal };
17
+ const skills = [];
18
+ if (options.skills) {
19
+ const lookup = { cwd: employeeCwd ?? request.cwd ?? target.projectRoot, scope: options.scope, signal: request.signal };
20
+ const snapshot = await options.skills.snapshot(lookup);
21
+ if (!snapshot.complete)
22
+ throw new NeedError('EMPLOYEE_CONTEXT_UNAVAILABLE', '技能目录未能完整读取,本轮尚未发送。', '官方skills.snapshot');
23
+ for (const summary of snapshot.skills) {
24
+ if (summary.invocation?.modelInvocable === false)
25
+ continue;
26
+ const loaded = await options.skills.get(summary.name, lookup);
27
+ if (!loaded || typeof loaded.content !== 'string' || ['name', 'description', 'provider', 'source', 'path'].some(key => loaded[key] !== summary[key]) || loaded.resourceBase?.kind !== summary.resourceBase?.kind || loaded.resourceBase?.path !== summary.resourceBase?.path || loaded.invocation?.modelInvocable === false)
28
+ throw new NeedError('EMPLOYEE_CONTEXT_CHANGED', '技能原文与目录快照发生变化,本轮尚未发送。', '同一scope与技能来源');
29
+ const root = loaded.resourceBase?.kind === 'directory' ? loaded.resourceBase.path : undefined;
30
+ if (!root) {
31
+ if (loaded.resourceBase)
32
+ throw new NeedError('EMPLOYEE_CONTEXT_UNAVAILABLE', '技能原文件与资源目录无法确认,本轮尚未发送。', '原生技能完整文件包');
33
+ skills.push({ name: loaded.name, description: loaded.description, files: [{ path: 'SKILL.md', bytes: Buffer.from('---\nname: ' + JSON.stringify(loaded.name) + '\ndescription: ' + JSON.stringify(loaded.description) + '\n---\n' + loaded.content) }] });
34
+ continue;
35
+ }
36
+ skills.push(await captureNativeSkill({ name: loaded.name, description: loaded.description, resourceRoot: root, skillFile: loaded.path ?? join(root, 'SKILL.md'), content: loaded.content }, limits));
37
+ }
38
+ }
39
+ if (!employeeCwd && !skills.length)
40
+ return;
41
+ const project = employeeCwd && request.agent?.loginProvider === 'claude' ? await captureProjectInstructions(employeeCwd, limits) : [];
42
+ const plan = nativeContentPlan({ scopeId: JSON.stringify({ host: target.host, user: target.username, binding: request.bindingId, workspace: request.workspaceId, session: request.sessionId }), employeeCwd: employeeCwd ?? request.cwd ?? target.projectRoot, project, skills }, limits);
43
+ const root = '/private/tmp/aw-nc-' + plan.scopeHash.slice(0, 24);
44
+ if (employeeCwd) {
45
+ await materializeNativeContent(plan, root, request.signal, true);
46
+ await activateNativeContent(plan, root);
47
+ }
48
+ let io = options.io;
49
+ if (!io) {
50
+ const module = '@ai-workbench/connect', connect = await import(__rewriteRelativeImportExtension(module));
51
+ io = sshIo(target, connect.sshArgs, request.acpMaxMessageBytes);
52
+ }
53
+ // A fixed file sink runs as the trusted host account. Content travels over stdin,
54
+ // never in process arguments, shell interpolation, a model message or a tool schema.
55
+ const implementation = await readFile(new URL('./native-content.js', import.meta.url), 'utf8');
56
+ const program = implementation + `\nimport {homedir} from 'node:os';\nconst plan=${JSON.stringify(plan)},root=${JSON.stringify(root)};\nconst result=await registerNativeContent(plan,root,homedir());\nprocess.stdout.write(JSON.stringify(result));\n`;
57
+ if (Buffer.byteLength(program) > limits.maxBytes)
58
+ throw new NeedError('ACP_MESSAGE_TOO_LARGE', '原生技能和项目说明超过现有会话消息容量。', 'acpMaxMessageBytes');
59
+ const child = await io.attach('/usr/bin/env node --input-type=module');
60
+ let output = '', diagnosticBytes = 0;
61
+ const aborted = () => child.kill('SIGTERM');
62
+ request.signal?.addEventListener('abort', aborted, { once: true });
63
+ try {
64
+ child.stdout.setEncoding('utf8');
65
+ child.stdout.on('data', (bytes) => { output += bytes; if (Buffer.byteLength(output) > limits.maxBytes)
66
+ child.kill('SIGTERM'); });
67
+ child.stderr.on('data', (bytes) => { diagnosticBytes += bytes.byteLength; });
68
+ child.stdin.on('error', () => { });
69
+ const closed = new Promise((resolve, reject) => { child.once('error', reject); child.once('close', resolve); });
70
+ child.stdin.end(program);
71
+ const code = await closed;
72
+ request.signal?.throwIfAborted();
73
+ if (code !== 0 || Buffer.byteLength(output) > limits.maxBytes)
74
+ throw new NeedError('EMPLOYEE_CONTEXT_UNAVAILABLE', '原生技能或项目说明同步未完成,本轮尚未发送。', '受控文件同步;退出状态' + code + ',诊断字节' + diagnosticBytes);
75
+ const result = JSON.parse(output);
76
+ if (result.generation !== plan.generation || result.cwdMap.employee !== plan.employeeCwd)
77
+ throw new NeedError('EMPLOYEE_CONTEXT_CHANGED', '原生内容同步回执与本轮不一致。', '同一员工与generation');
78
+ return result;
79
+ }
80
+ finally {
81
+ request.signal?.removeEventListener('abort', aborted);
82
+ }
83
+ }