@ai-workbench/remote-agent 0.9.0-toolbridge.36 → 0.9.0-toolbridge.37-rc.5

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,7 +27,6 @@ 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";
@@ -64,7 +65,7 @@ function readPointer(options, agent) {
64
65
  continue;
65
66
  const envelope = message.source.replayState;
66
67
  const pointer = envelope?.response;
67
- 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))
68
69
  continue;
69
70
  return { pointer: pointer, index };
70
71
  }
@@ -107,8 +108,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
107
108
  shuttingDown = false;
108
109
  detached = new Set();
109
110
  modelPresentation = new ModelPresentation();
110
- employeeNoticeSessions = new Set();
111
- pendingEmployeeNotices = new Set();
112
111
  constructor(config, resolveRuntime, approve, providerName = () => CODEX_AGENT.name.zh, agent = CODEX_AGENT, readImage, reportLoginFailure, directory, preflightDiagnostics, permissions, bridgeStopped, steeringReceipts, coldRecovery) {
113
112
  super();
114
113
  this.resolveRuntime = resolveRuntime;
@@ -279,8 +278,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
279
278
  this.shuttingDown = true;
280
279
  this.coldRecovery?.dispose?.();
281
280
  this.modelPresentation.clear();
282
- this.employeeNoticeSessions.clear();
283
- this.pendingEmployeeNotices.clear();
284
281
  const results = await Promise.allSettled([...new Set([...this.sessions.keys(), ...this.turns.keys()])].map(id => this.detachSession(id)));
285
282
  await this.bridgeLoop.dispose();
286
283
  this.lifetime.abort(Object.assign(new DOMException('远程模型插件已关闭', 'AbortError'), { kind: 'disposed' }));
@@ -306,10 +303,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
306
303
  let promptDispatched = !!options.sessionId && (this.sessions.get(options.sessionId)?.session.promptDispatchCount ?? 0) > 0;
307
304
  try {
308
305
  for await (const chunk of this.bridgeLoop.stream(options, (o, b) => this.generate(o, () => { promptDispatched = true; }, b))) {
309
- if (options.sessionId && this.pendingEmployeeNotices.has(options.sessionId) && chunk.type === 'text-delta' && chunk.text.startsWith(EMPLOYEE_EXECUTION_NOTICE)) {
310
- this.employeeNoticeSessions.add(options.sessionId);
311
- this.pendingEmployeeNotices.delete(options.sessionId);
312
- }
313
306
  yield chunk;
314
307
  }
315
308
  }
@@ -335,10 +328,6 @@ export class CodexRemoteAdapter extends LlmAdapter {
335
328
  }
336
329
  throw new LlmError(employeeFailure('TURN_FAILED', this.agent.loginProvider, promptDispatched), 'TURN_FAILED', { cause: error });
337
330
  }
338
- finally {
339
- if (options.sessionId)
340
- this.pendingEmployeeNotices.delete(options.sessionId);
341
- }
342
331
  }
343
332
  async *generate(original, onPromptDispatched, bridge) {
344
333
  if (this.lifetime.signal.aborted)
@@ -364,8 +353,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
364
353
  let activeMapper;
365
354
  let selected;
366
355
  let modelConfiguration;
367
- let coldPrelude = '';
368
- let employeeNoticeShown = false;
356
+ const coldPrelude = '';
369
357
  let permissionOff;
370
358
  let permissionEpoch = new AbortController();
371
359
  const information = [];
@@ -392,16 +380,19 @@ export class CodexRemoteAdapter extends LlmAdapter {
392
380
  let checkpointIndex = usedColdCheckpoint ? -1 : checkpoint?.index ?? -1;
393
381
  if (usedColdCheckpoint)
394
382
  options = { ...options, messages: options.messages.filter((m, index) => index > checkpoint.index || m.role === 'system' || m.role === 'developer') };
395
- employeeNoticeShown = !!key && this.employeeNoticeSessions.has(key) || false;
396
- if (employeeNoticeShown && key)
397
- this.employeeNoticeSessions.add(key);
398
383
  live = undefined;
399
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 }) });
400
- request.previousContextSha256 = previous?.contextSha256;
401
385
  const after = options.messages.findLastIndex(message => message.role === 'assistant');
402
386
  const tail = options.messages.slice(after + 1);
403
387
  const humanIds = tail.flatMap(message => message.role === 'user' && message.source?.kind === 'user' && typeof message.id === 'string' ? [message.id] : []);
404
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;
395
+ }
405
396
  earlyStage = 'source-context';
406
397
  await startupTiming.run('source-admission', async () => this.resolveRuntime.preflight?.(request));
407
398
  options = { ...await this.coldRecovery?.projectCancelledInputs?.(options) ?? options, signal };
@@ -419,11 +410,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
419
410
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '中途消息属于另一原生轮,未重复提交。', '原会话的注入回执与检查点'); return r.messageId; }));
420
411
  const withheld = new Set([...injected, ...uncertain]);
421
412
  if (currentInputs.length && currentInputs.every(message => typeof message.id === 'string' && withheld.has(message.id))) {
422
- if (receiptNotice) {
423
- const notice = new StreamMapper();
424
- yield* notice.text(receiptNotice);
425
- yield* notice.flush();
426
- }
413
+ if (receiptNotice)
414
+ await this.preflightDiagnostics?.record(request, this.agent.loginProvider, { kind: 'session', severity: 'warning', code: 'INPUT_DELIVERY_UNCONFIRMED', summary: receiptNotice });
427
415
  yield { type: 'finish', reason: { kind: 'stop' }, replayState: { response: previous } };
428
416
  succeeded = true;
429
417
  return;
@@ -431,15 +419,8 @@ export class CodexRemoteAdapter extends LlmAdapter {
431
419
  const projected = { ...options, messages: options.messages.filter((m, index) => index <= checkpointIndex || !('id' in m) || typeof m.id !== 'string' || !withheld.has(m.id)) };
432
420
  earlyStage = 'input-prepare';
433
421
  let input = await startupTiming.run('input-prepare', () => prepareInput(projected, this.readImage));
434
- const contextSha256 = createHash('sha256').update(input.systemPrompt ?? '').digest('hex');
435
- request.contextSha256 = contextSha256;
436
422
  const codex = this.agent.loginProvider === 'codex';
437
- const contextChanged = !!previous && codex && (previous.contextSha256 ?? '').toLowerCase() !== contextSha256;
438
- // Only identical durable context can prove a legacy context-bound journal.
439
- // New Codex transport scopes are independent of the native context digest.
440
- if (contextChanged)
441
- request.contextSha256 = undefined;
442
- 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)
443
424
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
444
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 };
445
426
  let modelSignal = signal;
@@ -459,7 +440,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
459
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))
460
441
  throw new NeedError('SESSION_CONTEXT_MISMATCH', '原会话的员工主机或工作区已改变,请新建会话', '原会话的可信目标和工作区');
461
442
  input = await prepareContinuation({ ...options, messages: projected.messages.slice(checkpointIndex + 1) }, input, this.readImage, { maxBytes: config.acpMaxMessageBytes, host: runtime.hostWorkspace });
462
- 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)
463
444
  throw new NeedError('ACP_MESSAGE_TOO_LARGE', '本轮输入超过已设置的会话消息容量,未截断或发送', '管理员调整acpMaxMessageBytes');
464
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 });
465
446
  startupTiming.bind(event => details.record(event));
@@ -478,27 +459,11 @@ export class CodexRemoteAdapter extends LlmAdapter {
478
459
  let id;
479
460
  let stop;
480
461
  const pointerRuntime = runtime;
481
- 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 } : {}) });
482
463
  if (runtime.employeePresentation)
483
464
  details.record({ kind: 'session', severity: 'warning', code: 'EMPLOYEE_EXECUTION_SCOPE', summary: runtime.employeePresentation, payload: { source: 'local' } });
484
465
  if (runtime.execution)
485
466
  details.record({ kind: 'session', severity: 'warning', code: 'CLAUDE_EMPLOYEE_SCOPE', summary: runtime.execution.notice, payload: runtime.execution.scope });
486
- if ((runtime.employeePresentation || runtime.execution) && !employeeNoticeShown) {
487
- coldPrelude = EMPLOYEE_EXECUTION_NOTICE + (bridge?.enabled ? '\n\n' + TOOLBRIDGE_NOTICE : '') + '\n\n';
488
- for (const chunk of mapper.text(coldPrelude)) {
489
- if (chunk.type === 'text-delta') {
490
- employeeNoticeShown = true;
491
- if (key) {
492
- if (bridge)
493
- this.pendingEmployeeNotices.add(key);
494
- else
495
- this.employeeNoticeSessions.add(key);
496
- }
497
- }
498
- yield chunk;
499
- }
500
- yield* mapper.flush();
501
- }
502
467
  { // 仅支持ACP会话模式;保留此块的局部变量作用域。
503
468
  if (!runtime.acpTransport)
504
469
  throw new NeedError('DEPENDENCY_REQUIRED', '我需要该员工主机上的ACP通道', 'S提供的ACP命令与aw-session');
@@ -509,8 +474,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
509
474
  const push = (chunks) => { queue.push(...chunks); wake?.(); wake = undefined; };
510
475
  let renderTail = Promise.resolve(), nativeUpdates = 0, coldPromptStarted = false;
511
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?.(); }); };
512
- const renderNotice = (text) => render(async () => { if (runtime.cold)
513
- 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 }); });
514
478
  if (receiptNotice)
515
479
  renderNotice(receiptNotice);
516
480
  let promptPermit;
@@ -614,7 +578,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
614
578
  };
615
579
  const task = (async () => {
616
580
  try {
617
- 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);
618
582
  }
619
583
  catch (error) {
620
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 } });
@@ -666,7 +630,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
666
630
  details.beginTurn(runtime.detailContext?.() ?? { turn: null, step: null });
667
631
  await renderTail;
668
632
  if (runtime.cold && this.coldRecovery)
669
- 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 });
670
634
  coldPromptStarted = true;
671
635
  await runtime.execution?.beginTurn(modelSignal);
672
636
  if (bridge?.enabled)
@@ -710,8 +674,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
710
674
  if (stop === 'cancelled')
711
675
  throw new NeedError('ABORTED', '远端本轮已取消', '核对主机任务状态');
712
676
  if (stop === 'refusal')
713
- for (const chunk of mapper.text('\n[远端拒绝] 此请求未执行。\n'))
714
- yield chunk;
677
+ details.record({ kind: 'session', severity: 'warning', code: 'ACP_IDLE_UPDATE', summary: '远端拒绝此请求,未执行。' });
715
678
  }
716
679
  mapper.flushMetadata();
717
680
  recordInformation();
@@ -733,7 +696,7 @@ export class CodexRemoteAdapter extends LlmAdapter {
733
696
  }
734
697
  catch (error) {
735
698
  if (original.signal?.reason?.kind === 'user' && runtime?.cold && this.coldRecovery)
736
- 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 });
737
700
  if (session && session.promptDispatchCount > promptBaseline)
738
701
  onPromptDispatched();
739
702
  if (bridge?.unsettled && !signal.aborted)
@@ -819,7 +782,7 @@ export function apply(ctx, live) {
819
782
  return attachments.readImage(ref, signal);
820
783
  };
821
784
  const sessionSources = createSessionSources(ctx, get);
822
- 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 } }) });
823
786
  const openByAgent = new Map(AGENTS.map(agent => [agent.id, brokerFactory(get, undefined, config, { coldStore: coldRecovery.store })]));
824
787
  const detailManagers = new Map();
825
788
  const managerForProfile = () => {
@@ -857,7 +820,14 @@ export function apply(ctx, live) {
857
820
  return managerForProfile().open({ sessionId: request.sessionId, provider: agent.loginProvider, identity: `${target.username}@${target.host}:${target.port}`, connection });
858
821
  };
859
822
  const open = async (...args) => {
860
- 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);
861
831
  runtime.detailContext = () => {
862
832
  const events = args[2].sessionId ? ctx.get('agents')?.get(SessionId(args[2].sessionId))?.session.snapshotEvents() : undefined;
863
833
  let turn = null, step = null;
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
+ }
@@ -0,0 +1,67 @@
1
+ export interface NativeContentFile {
2
+ path: string;
3
+ bytes: Uint8Array;
4
+ executable?: boolean;
5
+ }
6
+ export interface NativeSkillPackage {
7
+ name: string;
8
+ description: string;
9
+ files: readonly NativeContentFile[];
10
+ }
11
+ export interface NativeContentSnapshot {
12
+ scopeId: string;
13
+ employeeCwd: string;
14
+ project: readonly NativeContentFile[];
15
+ skills: readonly NativeSkillPackage[];
16
+ }
17
+ export interface NativeContentLayout {
18
+ generation: string;
19
+ hostCwd: string;
20
+ codexSkillsRoot: string;
21
+ claudePluginRoot: string;
22
+ claudeNamespace: string;
23
+ cwdMap: {
24
+ native: string;
25
+ employee: string;
26
+ };
27
+ }
28
+ export interface NativeContentLimits {
29
+ maxBytes: number;
30
+ signal?: AbortSignal;
31
+ }
32
+ /** Reads only an explicitly selected DSH package. Never scans the host native catalog. */
33
+ export declare function captureNativeSkill(input: {
34
+ name: string;
35
+ description: string;
36
+ skillFile: string;
37
+ resourceRoot: string;
38
+ content?: string;
39
+ }, options: NativeContentLimits): Promise<NativeSkillPackage>;
40
+ /** The caller supplies the exact instruction/import closure; no repository-wide copying. */
41
+ export declare function captureNativeProject(employeeCwd: string, paths: readonly string[], options: NativeContentLimits): Promise<NativeContentFile[]>;
42
+ interface WireFile {
43
+ path: string;
44
+ data: string;
45
+ sha256: string;
46
+ executable: boolean;
47
+ }
48
+ export interface NativeContentPlan {
49
+ version: 1;
50
+ generation: string;
51
+ scopeHash: string;
52
+ employeeCwd: string;
53
+ claudeNamespace: string;
54
+ files: readonly WireFile[];
55
+ }
56
+ /** Only native manifest metadata is generated. Skill bodies come verbatim from their provider; project files remain original bytes. */
57
+ export declare function nativeContentPlan(snapshot: NativeContentSnapshot, options: NativeContentLimits): NativeContentPlan;
58
+ /** Immutable generations coexist with user native skills; this never rewrites their files. */
59
+ export declare function materializeNativeContent(plan: NativeContentPlan, root: string, signal?: AbortSignal, employeeProject?: boolean): Promise<NativeContentLayout>;
60
+ /** Maps structured native paths only. Shell source is never searched or rewritten. */
61
+ export declare function employeePathForNative(path: string, map: NativeContentLayout['cwdMap']): string;
62
+ /** Register only this managed generation; user native packages are never overwritten. */
63
+ export declare function registerNativeContent(plan: NativeContentPlan, root: string, home: string): Promise<NativeContentLayout>;
64
+ export declare function activateNativeContent(plan: NativeContentPlan, root: string): Promise<void>;
65
+ /** Collect only project instruction files and their relative native imports. */
66
+ export declare function captureProjectInstructions(cwd: string, options: NativeContentLimits): Promise<NativeContentFile[]>;
67
+ export {};