@tbox.cn/dsh-acp-full 0.1.0-rc.14 → 0.1.0-rc.16
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/lib/index.d.ts +144 -17
- package/lib/index.js +1 -1
- package/package.json +2 -2
package/lib/index.d.ts
CHANGED
|
@@ -186,6 +186,15 @@ type SessionPromptPartAdmitted = {
|
|
|
186
186
|
readonly type: 'image';
|
|
187
187
|
readonly attachment: unknown;
|
|
188
188
|
};
|
|
189
|
+
/** 一张已准入的 URL 图片来源(抓取 + 归一化 + 出处记录之后)。 */
|
|
190
|
+
interface ImageSourceAdmitted {
|
|
191
|
+
/** 载体句柄:载体一 = durable 图片引用;载体二 = `{mediaType, data}` 或回执。 */
|
|
192
|
+
readonly attachment: unknown;
|
|
193
|
+
/** 内容寻址 id(两载体都有;投影表 seed 用)。 */
|
|
194
|
+
readonly attachmentId: string;
|
|
195
|
+
/** 服务端派生的展示名(URL 末段),仅载体二回传。 */
|
|
196
|
+
readonly name?: string;
|
|
197
|
+
}
|
|
189
198
|
/** 编排核心依赖(载体一装配 = cordis ctx 服务直捕;测试 = mock)。 */
|
|
190
199
|
interface SessionDeps {
|
|
191
200
|
createAgent(options: {
|
|
@@ -228,8 +237,31 @@ interface SessionDeps {
|
|
|
228
237
|
/**
|
|
229
238
|
* prompt 附件准入(载体一 = ctx.attachments.admitPromptContent)。
|
|
230
239
|
* ACP image / resource blob → durable ImageAttachmentRef;缺席时 image 拒绝。
|
|
240
|
+
*
|
|
241
|
+
* 错误契约:实现必须把领域失败归一化为 `RequestError(invalidParams)`
|
|
242
|
+
* (bridge 的 prompt 捕获只把 `RequestError` 透传,其余一律转 internal)。
|
|
231
243
|
*/
|
|
232
244
|
admitPromptContent?(parts: ReadonlyArray<SessionPromptPart>): Promise<ReadonlyArray<SessionPromptPartAdmitted>>;
|
|
245
|
+
/**
|
|
246
|
+
* 图片 URL 准入:抓取 → 归一化落盘 → 出处记录(先于 user/message)。
|
|
247
|
+
*
|
|
248
|
+
* 返回数组与入参**等长同序**(实现内部可按 URL 去重抓取);会话必须已激活
|
|
249
|
+
* (出处记录要求 store-owned 会话),冷会话返回明确错误。
|
|
250
|
+
* 错误契约同 {@link admitPromptContent}:领域失败归一化为 invalidParams。
|
|
251
|
+
*/
|
|
252
|
+
admitImageUrls?(sessionId: string, urls: readonly string[], opts?: {
|
|
253
|
+
readonly signal?: AbortSignal;
|
|
254
|
+
/** 与 `urls` 等长同序的客户端文件名(缺省/空串时由服务端从 URL 派生)。 */
|
|
255
|
+
readonly names?: readonly (string | undefined)[];
|
|
256
|
+
}): Promise<ReadonlyArray<ImageSourceAdmitted>>;
|
|
257
|
+
/**
|
|
258
|
+
* 读一张已落盘图片(历史回显用)。失败返回 undefined(调用方降级占位)——
|
|
259
|
+
* 读取失败不得中断整次回放。
|
|
260
|
+
*/
|
|
261
|
+
readImage?(sessionId: string, attachment: unknown, signal?: AbortSignal): Promise<{
|
|
262
|
+
readonly mediaType: string;
|
|
263
|
+
readonly data: string;
|
|
264
|
+
} | undefined>;
|
|
233
265
|
logger: {
|
|
234
266
|
warn(message: string): void;
|
|
235
267
|
info(message: string): void;
|
|
@@ -298,6 +330,24 @@ interface SessionDeps {
|
|
|
298
330
|
}
|
|
299
331
|
//#endregion
|
|
300
332
|
//#region src/session.d.ts
|
|
333
|
+
/** prompt 完成相关性的一槽三段:准入中 / 回合中 / 已取消。 */
|
|
334
|
+
type StopReason = 'end_turn' | 'cancelled' | 'max_tokens' | 'refusal';
|
|
335
|
+
/** ACP prompt 块的宽松读面(字段按类型选择性消费)。 */
|
|
336
|
+
interface PromptBlockInput {
|
|
337
|
+
type: string;
|
|
338
|
+
text?: string;
|
|
339
|
+
uri?: string;
|
|
340
|
+
name?: string;
|
|
341
|
+
mimeType?: string;
|
|
342
|
+
data?: string;
|
|
343
|
+
resource?: unknown;
|
|
344
|
+
/** ACP 扩展字段(内容块级 `_meta`;schema 允许,未知顶层键会被校验层剥掉)。 */
|
|
345
|
+
_meta?: Record<string, unknown>;
|
|
346
|
+
}
|
|
347
|
+
interface SessionPromptParams {
|
|
348
|
+
sessionId: string;
|
|
349
|
+
prompt: ReadonlyArray<PromptBlockInput>;
|
|
350
|
+
}
|
|
301
351
|
interface SessionChannelOptions {
|
|
302
352
|
sessionId: string;
|
|
303
353
|
cwd: string;
|
|
@@ -319,24 +369,20 @@ declare class SessionChannel {
|
|
|
319
369
|
/** 已入队 update 全部完成(approval 瀑布先排空 tool_call 再发请求的对位)。 */
|
|
320
370
|
drainUpdates(): Promise<void>;
|
|
321
371
|
/**
|
|
322
|
-
* session/prompt
|
|
323
|
-
*
|
|
372
|
+
* session/prompt 入口:**先占槽**再分派(命令路径 / 正常 prompt 路径)。
|
|
373
|
+
*
|
|
374
|
+
* 占槽必须先于任何 await:图片 URL 抓取是秒级异步,槽位若在准入之后才设置,
|
|
375
|
+
* 两条并发 prompt 会同时通过互斥检查、后者覆盖槽位、前者永不结算。
|
|
324
376
|
*/
|
|
325
|
-
prompt(params: {
|
|
326
|
-
|
|
327
|
-
prompt: ReadonlyArray<{
|
|
328
|
-
type: string;
|
|
329
|
-
text?: string;
|
|
330
|
-
uri?: string;
|
|
331
|
-
name?: string;
|
|
332
|
-
mimeType?: string;
|
|
333
|
-
data?: string;
|
|
334
|
-
resource?: unknown;
|
|
335
|
-
}>;
|
|
336
|
-
}, requestSignal: AbortSignal): Promise<{
|
|
337
|
-
stopReason: 'end_turn' | 'cancelled' | 'max_tokens' | 'refusal';
|
|
377
|
+
prompt(params: SessionPromptParams, requestSignal: AbortSignal): Promise<{
|
|
378
|
+
stopReason: StopReason;
|
|
338
379
|
}>;
|
|
339
|
-
/**
|
|
380
|
+
/**
|
|
381
|
+
* session/cancel(notification):in-flight prompt 走取消路径;无 prompt 取消自主工作。
|
|
382
|
+
*
|
|
383
|
+
* 准入期(抓取中)只中止准入通道即可——回合尚未建立,无需 agent.cancel;
|
|
384
|
+
* 回合期沿用既有语义(settle + 传导 abort + agent.cancel)。
|
|
385
|
+
*/
|
|
340
386
|
cancel(): Promise<void>;
|
|
341
387
|
/** agent/inbox/claimed 路由(messageId 匹配 → turn 关联)。 */
|
|
342
388
|
onInboxClaimed(message: {
|
|
@@ -472,6 +518,87 @@ declare class Bridge {
|
|
|
472
518
|
/** @internal 导出供单测钉住 access 常量(spy 真实 open 的实参)。 */
|
|
473
519
|
declare function createHistoryReadPort(open: PersistenceReadOpen['open']): (sessionId: string, signal?: AbortSignal) => Promise<HistoryReadHandle>;
|
|
474
520
|
//#endregion
|
|
521
|
+
//#region src/image-render.d.ts
|
|
522
|
+
/**
|
|
523
|
+
* image-render —— 历史与 live 回显的图片渲染漏斗(唯一的图片 I/O 编排点)。
|
|
524
|
+
*
|
|
525
|
+
* 投影核心是同步纯函数:URL 表由出处记录折叠而来(零 I/O),字节表由本模块
|
|
526
|
+
* 预读填充(per-call 快照)。四个投影点(会话 load、live 事件、子会话只读
|
|
527
|
+
* 回放、box 历史接口)都经 `prepare` 取得两张表,避免各写一套预算逻辑。
|
|
528
|
+
*
|
|
529
|
+
* 预算一条规则:一次解析 / 一条 live 消息的图片帧合计不超过 16 MiB(按 base64
|
|
530
|
+
* 后字节计)且不超过 40 张;选取最新优先、发射恒为日志正序;超出的上传图标注
|
|
531
|
+
* `'omitted'`(投影发占位并带 `_meta.imageRef`,客户端可懒加载)。URL 图不参与
|
|
532
|
+
* 预算——渲染只需 URL 字符串。
|
|
533
|
+
*/
|
|
534
|
+
/** 单次渲染的图片载荷预算。 */
|
|
535
|
+
declare const IMAGE_PAYLOAD_BUDGET: {
|
|
536
|
+
readonly bytes: number;
|
|
537
|
+
readonly images: 40;
|
|
538
|
+
};
|
|
539
|
+
interface RenderImageBytes {
|
|
540
|
+
readonly mediaType: string;
|
|
541
|
+
readonly data: string;
|
|
542
|
+
}
|
|
543
|
+
type ImageBytesReader = (attachment: unknown) => Promise<RenderImageBytes | undefined>;
|
|
544
|
+
/** 注入投影的两张表(`imageBytes` 的 `'omitted'` 表示预算外未读)。 */
|
|
545
|
+
interface ImageRenderOptions {
|
|
546
|
+
readonly imageSources: Map<string, string>;
|
|
547
|
+
readonly imageBytes: Map<string, RenderImageBytes | 'omitted'>;
|
|
548
|
+
}
|
|
549
|
+
interface EventLike {
|
|
550
|
+
readonly type?: string;
|
|
551
|
+
readonly data?: unknown;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* 一次会话渲染状态:出处表 per-channel 长期持有(live 与回放共享),字节表
|
|
555
|
+
* 每次 `prepare` 新建并由调用方在投影后丢弃。
|
|
556
|
+
*/
|
|
557
|
+
declare class ImageRenderState {
|
|
558
|
+
#private;
|
|
559
|
+
/** 出处表(attachmentId → URL);prompt 准入成功后即时 seed,记录事件随后幂等覆盖。 */
|
|
560
|
+
get sources(): Map<string, string>;
|
|
561
|
+
/**
|
|
562
|
+
* 准备一次投影所需的渲染表。
|
|
563
|
+
* @param events - 本次要投影的事件批次(回放为全量,live 为单条)。
|
|
564
|
+
* @param read - 载体提供的字节读取(失败返回 undefined 即降级占位)。
|
|
565
|
+
* @param budget - 可覆盖的预算(测试用)。
|
|
566
|
+
* @returns 注入 `ProjectOptions` 的两张表。
|
|
567
|
+
*/
|
|
568
|
+
prepare(events: readonly EventLike[], read: ImageBytesReader, budget?: {
|
|
569
|
+
readonly bytes: number;
|
|
570
|
+
readonly images: number;
|
|
571
|
+
}): Promise<ImageRenderOptions>;
|
|
572
|
+
}
|
|
573
|
+
//#endregion
|
|
574
|
+
//#region src/url-image.d.ts
|
|
575
|
+
/**
|
|
576
|
+
* url-image —— 入站 `image/tbox_url` 哨兵块的解析(纯函数,零 I/O)。
|
|
577
|
+
*
|
|
578
|
+
* 协议基线(agtcodingbox 原协议):`data` 字段承载 `base64(utf8(url))`,`uri`
|
|
579
|
+
* 字段冗余携带同一 URL。以 `data` 为主通道,缺失或不可解码时回落 `uri`;
|
|
580
|
+
* 两者都不成立即 invalidParams——不做"猜一个 URL"的容错。
|
|
581
|
+
*/
|
|
582
|
+
/** 单个图片 URL 的长度上限(超过即判不可用——签名 URL 通常远小于此)。 */
|
|
583
|
+
declare const MAX_IMAGE_URL_LENGTH = 8192;
|
|
584
|
+
type ImageUrlDecode = {
|
|
585
|
+
readonly ok: true;
|
|
586
|
+
readonly url: string;
|
|
587
|
+
} | {
|
|
588
|
+
readonly ok: false;
|
|
589
|
+
readonly reason: 'url-invalid' | 'url-too-long';
|
|
590
|
+
};
|
|
591
|
+
/**
|
|
592
|
+
* 解析一个哨兵块为 URL。
|
|
593
|
+
* @param block - ACP 图片块的最小读面(`data` / `uri`)。
|
|
594
|
+
* @param maxUrlLength - 可覆盖的长度上限。
|
|
595
|
+
* @returns 成功给出 URL,失败给出稳定 reason(调用方映射 invalidParams)。
|
|
596
|
+
*/
|
|
597
|
+
declare function decodeImageUrl(block: {
|
|
598
|
+
readonly data?: unknown;
|
|
599
|
+
readonly uri?: unknown;
|
|
600
|
+
}, maxUrlLength?: number): ImageUrlDecode;
|
|
601
|
+
//#endregion
|
|
475
602
|
//#region src/index.d.ts
|
|
476
603
|
declare const name = "dsh-acp-full";
|
|
477
604
|
declare const inject: readonly ["agents", "llm", "sessionPersistence", "sessions", "approval", "commands", "skills", "agentDefaultModel"];
|
|
@@ -584,4 +711,4 @@ declare function createSharedAcpCore(deps: SessionDeps, logger: {
|
|
|
584
711
|
debug(message: string): void;
|
|
585
712
|
}, _options?: SharedAcpCoreOptions): SharedAcpCore;
|
|
586
713
|
//#endregion
|
|
587
|
-
export { AcpMethodHooks, AgentAppWiring, type AgentLike, type ConfigModelInfo, type ConfigModelSelection, DshAcpFullConfig, type HistoryReadHandle, type HostAgentHandle, type HostStreamFrame, type LlmCatalogDeps, type PersistedHeader, type SessionDeps, type SessionLike, SharedAcpCore, SharedAcpCoreIo, SharedAcpCoreOptions, SharedConnection, apply, buildAgentApp, createHistoryReadPort, createSharedAcpCore, inject, name };
|
|
714
|
+
export { AcpMethodHooks, AgentAppWiring, type AgentLike, type ConfigModelInfo, type ConfigModelSelection, DshAcpFullConfig, type HistoryReadHandle, type HostAgentHandle, type HostStreamFrame, IMAGE_PAYLOAD_BUDGET, type ImageRenderOptions, ImageRenderState, type ImageUrlDecode, type LlmCatalogDeps, MAX_IMAGE_URL_LENGTH, type PersistedHeader, type RenderImageBytes, type SessionDeps, type SessionLike, SharedAcpCore, SharedAcpCoreIo, SharedAcpCoreOptions, SharedConnection, apply, buildAgentApp, createHistoryReadPort, createSharedAcpCore, decodeImageUrl, inject, name };
|
package/lib/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Readable as e,Writable as t}from"node:stream";import{RequestError as n,agent as r,methods as i,ndJsonStream as a}from"@agentclientprotocol/sdk";import{UserQuestionError as o}from"@deepseek-ai/dsh-user-questions";import{setSandboxMode as s}from"@deepseek-ai/dsh-sandbox-policy";import{setApprovalPolicy as c}from"@deepseek-ai/dsh-user-approval";import{createHash as l,randomUUID as u}from"node:crypto";import{isAbsolute as d,resolve as f}from"node:path";import{realpath as p}from"node:fs/promises";import{SessionAlreadyOwnedError as ee}from"@deepseek-ai/dsh-session-persistence";import{MODEL_CONFIG_ID as m,MODE_CONFIG_ID as te,PROVIDER_DEFAULT_REASONING_VALUE as h,REASONING_CONFIG_ID as g,StreamAttemptState as ne,SubagentCatalogState as _,ToolJournal as v,TurnFoldTracker as re,buildElicitationSchema as ie,commandGate as ae,commandsProjection as oe,isAcpSessionMode as se,mapRpcError as y,modeConfigOption as ce,modeFromSandbox as b,negotiateProtocolVersion as le,parseElicitationContent as ue,projectEvent as x,projectRecord as S,projectStreamFrame as C,projectSubagentChildEvent as w,resolveModelValue as T,settleToResponse as E,stopReasonFromTurnEnd as de,translateMode as D}from"@tbox.cn/dsh-acp-bridge-core";import{createUserMessage as fe}from"@deepseek-ai/dsh-llm";import{installModelSelection as O}from"@deepseek-ai/dsh-agent";import{validateHeaderName as k,validateHeaderValue as pe}from"node:http";import*as me from"@deepseek-ai/dsh-mcp-client";function A(e){return n.invalidParams(void 0,e)}function j(e){return n.internalError(void 0,e)}function he(e){let t=y(e);return new n(t.code,t.message,t.data)}function ge(e,t){return he({code:`session/writer-held`,message:t??`session "${e}" is owned by another writer (another window or process may hold it)`,data:{sessionId:e,reason:`writer-held`}})}var M=class extends Error{},N=class{#e;#t;#n;#r;#i=!1;#a=Promise.resolve();constructor(e,t,n,r){this.#t=e,this.#n=t,this.#e=n,this.#r=r}get mode(){return this.#e}async initializeMode(e,t){let n=D(e);if(n===void 0)throw new M(`unknown mode option: ${e}`);t&&await this.#r(n,{initial:!0}),this.#e=e}options(e){return this.#o(async()=>(await this.#c(e)).options)}set(e,t,n){return this.#o(async()=>{if(typeof t!=`string`)throw new M(`${e} requires a select value`);if(e===te){if(!se(t))throw new M(`unknown mode option: ${t}`);let e=D(t);if(e===void 0)throw new M(`unknown mode option: ${t}`);await this.#r(e),this.#e=t}else if(e===m){let e=(await this.#c(n)).choices.get(t);if(e===void 0)throw new M(`unknown model option: ${t}`);await this.#n.select(await this.#s(e,n))}else if(e===g){let e=this.#n.current();if(e===void 0)throw new M(`this session has no model selection`);let r=await this.#t.resolveModelInfo(e.provider,e.model,n),i=t===h&&r.reasoning?.defaultEffort===void 0;if(r.reasoning===void 0||!i&&!r.reasoning.efforts.some(e=>e.id===t))throw new M(`unknown reasoning effort for ${e.provider}/${e.model}: ${t}`);await this.#n.select(await this.#s({provider:e.provider,model:e.model,...i?{}:{reasoningEffort:t}},n))}else throw new M(`unknown session config option: ${e}`);return(await this.#c(n)).options})}#o(e){let t=this.#a.then(e);return this.#a=t.then(()=>void 0,()=>void 0),t}async#s(e,t){let n=await this.#t.resolveCallConfig(e,t);return{provider:n.provider,model:n.model,...n.reasoningEffort===void 0?{}:{reasoningEffort:n.reasoningEffort}}}async#c(e){let t=[ce(this.#e)],n=this.#n.current(),r=new Map,i=await Promise.all(this.#t.listProviders().map(async t=>{try{let n=(await this.#t.listModels(t.id,e)).map(e=>{let n={value:T(t.id,e.id),selection:{provider:t.id,model:e.id}};return r.set(n.value,n.selection),{value:n.value,name:e.name,...e.description===void 0?{}:{description:e.description}}});return{group:t.id,name:t.name,options:n}}catch{return{group:t.id,name:t.name,options:[]}}}));if(n===void 0)return{choices:r,options:t};let a,o=!0;try{a=await this.#s(n,e),this.#i=!0}catch(e){if(!this.#i)throw e;a=n,o=!1}let s=T(a.provider,a.model);if(!r.has(s)){r.set(s,{provider:a.provider,model:a.model});let e=i.find(e=>e.group===a.provider);e===void 0&&(e={group:a.provider,name:a.provider,options:[]},i.push(e)),e.options.unshift({value:s,name:a.model})}t.push({id:m,name:`Model`,category:`model`,type:`select`,currentValue:s,options:i.filter(e=>e.options.length>0)});let c=o?await this.#t.resolveModelInfo(a.provider,a.model,e):void 0;return c?.reasoning!==void 0&&t.push({id:g,name:`Reasoning effort`,category:`thought_level`,type:`select`,currentValue:a.reasoningEffort===void 0?h:String(a.reasoningEffort),options:[...c.reasoning.defaultEffort===void 0?[{value:h,name:`Provider default`}]:[],...c.reasoning.efforts.map(e=>({value:String(e.id),name:e.name,...e.description===void 0?{}:{description:e.description}}))]}),{choices:r,options:t}}};function P(e){if(e!==void 0)return{provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort}}}function F(e){let t=e.model;if(t===void 0||typeof t.current!=`function`||typeof t.select!=`function`)throw Error(`agent does not expose a model selection port`);return{current:()=>{let e=t.current();if(e!==void 0)return{provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:String(e.reasoningEffort)}}},select:e=>t.select({provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort}})}}function I(e,t){let n=e.sessionToolDenies();n.length!==0&&t.tools.restrict({deny:[...n]})}var L=class e{agent;session;deps;config;#e;#t;#n;#r=new v;#i=new _;#a=new ne;#o=new Map;#s;#c=new Map;#l=Promise.resolve();#u=[];#d;#f=!1;#p=``;#m;#h;#g=void 0;constructor(e,t,n,r){this.deps=e,this.#e=t,this.agent=t.agent,this.session=t.agent.session,this.config=r,this.#t=n.notify,this.#n=n.cwd,this.#s=new re(e=>{this.#b(async()=>{try{await this.#t(e)}catch(e){this.deps.logger.warn(`acp: session/update failed: ${String(e)}`)}})})}owns(e){return this.agent===e}ownsSession(e){return this.agent.session===e}drainUpdates(){return this.#l}async prompt(e,t){if(this.#f||this.#d!==void 0)throw j(`the session is closing`);if(this.#g!==void 0)throw A(`a prompt is already in flight for this session`);if(e.prompt.length===1&&e.prompt[0]?.type===`text`){let n=ae(e.prompt[0].text);if(n.hit&&!n.shadow&&e.prompt[0].text!==void 0)return this.#_(e.prompt[0].text.trim(),t)}return this.#v(e,t)}async#_(e,t){let n=new AbortController;this.#h=n;let r={settle:e=>{},fail:e=>{},messageId:``,turn:void 0,cancelRequested:!1};this.#g=r;try{return await this.deps.executeCommand(this.agent,e,n.signal??t)===void 0?await this.#v({sessionId:this.session.id,prompt:[{type:`text`,text:e}]},t):E({kind:`success`})}catch(r){return t.aborted||n.signal.aborted?E({kind:`aborted`}):(this.deps.logger.warn(`acp: command rejected without settle projection: ${e}: ${String(r)}`),E({kind:`success`}))}finally{this.#h=void 0,this.#g===r&&(this.#g=void 0)}}async#v(e,t){let n=[];for(let t of e.prompt){if(t.type===`text`){n.push({type:`text`,text:t.text??``});continue}if(t.type===`resource_link`){n.push({type:`text`,text:`[link] ${t.uri??``}`});continue}if(t.type===`image`&&typeof t.data==`string`){let e=t.mimeType??`image/png`;if(e===`image/tbox_url`){let e=Buffer.from(t.data,`base64`).toString(`utf8`);n.push({type:`text`,text:`[link] ${e}`})}else n.push({type:`image`,mediaType:e,data:t.data,...t.name===void 0?{}:{name:t.name}});continue}if(t.type===`resource`){let e=t.resource;e?.blob!==void 0&&e.mimeType?.startsWith(`image/`)===!0?n.push({type:`image`,mediaType:e.mimeType,data:e.blob}):n.push({type:`text`,text:e?.text??`[resource] ${e?.uri??``}`});continue}throw A(`unsupported prompt content type: ${t.type}`)}let r=n.some(e=>e.type===`image`),i;if(r){if(this.deps.admitPromptContent===void 0)throw A(`image prompt content requires the mounted attachment service`);i=await this.deps.admitPromptContent(n)}else i=n.filter(e=>e.type===`text`);let a=i.map(e=>e.type===`text`?{type:`text`,text:e.text}:{type:`image`,attachment:e.attachment}),o=()=>{},s=()=>{},c=new Promise((e,t)=>{o=e,s=t}),l={settle:e=>o(e),fail:e=>s(e),messageId:`acp-${u()}`,turn:void 0,cancelRequested:!1};this.#g=l;let d=e=>{l.cancelRequested||(l.cancelRequested=!0,l.settle(`cancelled`),this.agent.cancel({kind:`user`}).catch(t=>{this.deps.logger.warn(`acp: cancel failed (${e}): ${String(t)}`)}))},f=()=>d(`ACP prompt request cancelled`);t.addEventListener(`abort`,f,{once:!0});try{let e=fe({content:a,source:{kind:`user`}});return l.messageId=e.id,this.agent.followup(e),{stopReason:await c}}catch(e){if(l.cancelRequested)return{stopReason:`cancelled`};throw e}finally{t.removeEventListener(`abort`,f),this.#g===l&&(this.#g=void 0)}}async cancel(){let e=this.#g;if(e!==void 0){e.cancelRequested||(e.cancelRequested=!0,e.settle(`cancelled`)),this.#h?.abort(),await this.agent.cancel({kind:`user`}).catch(()=>{});return}await this.agent.cancel({kind:`user`}).catch(e=>{this.deps.logger.warn(`acp: cancel failed: ${String(e)}`)})}onInboxClaimed(e,t){let n=this.#g;n!==void 0&&(n.messageId===e?.id||n.turn===void 0)&&(n.turn=t)}async refreshCommands(){if(this.#f||this.#d!==void 0)return;let[e,t]=await Promise.all([this.deps.listCommands(this.agent),this.deps.listUserInvocableSkills(this.agent)]),n=oe(e,t),r=JSON.stringify(n);r!==this.#p&&(this.#p=r,await this.#b(async()=>{try{await this.#t({sessionUpdate:`available_commands_update`,availableCommands:n})}catch(e){this.deps.logger.warn(`acp: available_commands_update failed: ${String(e)}`)}}))}tracksChild(e){return this.#i.tracks(e)}onChildEvent(e,t){if(this.#f||this.#d!==void 0)return;let n=this.#o.get(e);n===void 0&&(n=new v,this.#o.set(e,n)),this.#b(()=>{let r=w(e,t,this.#i,{journal:n,supportsTerminalOutput:!1,cwd:this.#n});return this.#x(r)})}scheduleCommandsRefresh(e=500){this.#f||this.#d!==void 0||(this.#m!==void 0&&clearTimeout(this.#m),this.#m=setTimeout(()=>{this.#m=void 0,this.refreshCommands().catch(e=>{this.deps.logger.warn(`acp: commands refresh failed: ${String(e)}`)})},e))}onAgentError(e){let t=this.#g;t!==void 0&&t.fail(j(`turn failed: ${String(e)}`))}#y(e){let t=this.#g;if(t===void 0||t.turn===void 0)return;let n=e.data;if(e.type===`turn/end`&&n?.turn===t.turn){let e=de(n.reason);if(`error`in e){t.fail(j(`turn ended with error: ${JSON.stringify(n.reason)}`));return}e.warn!==void 0&&this.deps.logger.warn(`acp: ${e.warn}`),t.settle(e.stopReason)}}async replayHistory(e,t){let n=0;return await this.#b(async()=>{let{events:r}=await e.read(t);for(let e of r){let t=S(e,{live:!1,journal:this.#r,seen:this.#c,subagents:this.#i,supportsTerminalOutput:!1,cwd:this.#n},(e,t)=>{this.deps.logger.debug(`acp: unknown event ${e} (${t})`)});this.#s.accept(e),t.length>0&&(await this.#x(t,!1),n+=t.length)}}),n}static async create(t,n,r){let i,a=await t.createAgent({sessionId:n.sessionId,cwd:n.cwd,mcpServers:n.mcpServers,signal:r,configureScope:(e,n)=>{i=new N(t.llm,F(n),`build`,(e,r)=>t.applyModeKnobs(n.session,n,e,r)),O(e),I(t,e)}});if(i===void 0)throw await a.dispose().catch(()=>{}),j(`session create did not configure the model selection`);let o=new e(t,a,n,i);try{let e=t.sandboxModeOf?.(o.session,o.agent);await i.initializeMode(b(e),e!==void 0)}catch(e){throw await a.dispose().catch(()=>{}),e}return o}static async resume(t,n,r){let i,a=await t.resumeAgent({sessionId:n.sessionId,cwd:n.cwd,mcpServers:n.mcpServers,signal:r,configureScope:(e,n)=>{i=new N(t.llm,F(n),`build`,(e,r)=>t.applyModeKnobs(n.session,n,e,r)),O(e),I(t,e)}});if(i===void 0)throw await a.dispose().catch(()=>{}),j(`session resume did not configure the model selection`);let o=new e(t,a,n,i);try{let e=t.sandboxModeOf?.(o.session,o.agent);await i.initializeMode(b(e),e!==void 0)}catch(e){throw await a.dispose().catch(()=>{}),e}return o}configOptions(e){return this.config.options(e)}setConfigOption(e,t,n){if(this.#f||this.#d!==void 0)throw j(`the session is closing`);return this.config.set(e,t,n)}onSessionEvent(e,t){this.#f||this.ownsSession(e)===!1||this.#b(()=>{let e=x(t,{live:!0,journal:this.#r,seen:this.#c,attempts:this.#a,subagents:this.#i,supportsTerminalOutput:!1,cwd:this.#n},(e,t)=>{this.deps.logger.debug(`acp: unknown event ${e} (${t})`)});return this.#s.accept(t),this.#y(t),this.#x(e)})}onAssistantStream(e){this.#f||this.#b(()=>{let t=C(e,{live:!0,journal:this.#r,seen:this.#c,attempts:this.#a});return this.#x(t)})}captureWatermark(){return this.#u.length}timelineFrom(e){return this.#u.slice(e)}close(e){return this.#d===void 0&&(this.#d=(async()=>{this.#m!==void 0&&(clearTimeout(this.#m),this.#m=void 0);try{await this.agent.cancel({kind:`user`})}catch(t){this.deps.logger.warn(`acp: cancel on close failed (${e}): ${String(t)}`)}await this.drainUpdates(),await this.deps.sessionStore.flush(this.session),await this.#e.dispose(),this.deps.logger.debug(`acp: session ${this.session.id} closed (${e})`)})().finally(()=>{this.#f=!0,this.#a.clear()})),this.#d}#b(e){let t=this.#l.then(e,e);return this.#l=t.catch(e=>{this.deps.logger.warn(`acp: update pipeline failed: ${String(e)}`)}),t}async#x(e,t=!0){for(let n of e){t&&(this.#u.push(n),this.#u.length>1e3&&this.#u.shift());try{await this.#t(n)}catch(e){this.deps.logger.warn(`acp: session/update failed: ${String(e)}`)}}}};const R=6e3;function _e(e){if(e instanceof ee)return!0;let t=e;return t?.name===`SessionAlreadyOwnedError`?!0:t?.code===`session/writer-held`}function ve(){let e=process.env.TBOXCODE_ACP_WRITER_HELD_RETRY_MS;if(e===void 0||e===``)return R;let t=Number(e);return Number.isFinite(t)&&t>=0?t:R}function ye(e,t){return new Promise((n,r)=>{if(t?.aborted===!0){r(t.reason??Error(`aborted`));return}let i=()=>{clearTimeout(a),r(t?.reason??Error(`aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}function z(e){let t=e?.code;return t===`session/model-unavailable`||t===`session/provider-models-unavailable`}function B(e){if(!d(e.cwd))throw A(`cwd must be an absolute path: ${e.cwd}`);if(e.additionalDirectories!==void 0&&e.additionalDirectories!==null&&e.additionalDirectories.length>0)throw A(`additionalDirectories is not supported`)}async function V(e,t){if(e===void 0)return!1;try{let[n,r]=await Promise.all([p(e),p(t)]);return n===r}catch{return f(e)===f(t)}}function be(e){if(e!=null){if(!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`session/list cursor is invalid`);try{let t=JSON.parse(Buffer.from(e,`base64url`).toString(`utf8`)),n=Array.isArray(t)?t[0]:void 0,r=Array.isArray(t)?t[1]:void 0;if(!Array.isArray(t)||t.length!==2||typeof n!=`number`||!Number.isSafeInteger(n)||n<0||typeof r!=`string`||r.length===0)throw Error(`invalid cursor fields`);if(Buffer.from(JSON.stringify(t),`utf8`).toString(`base64url`)!==e)throw Error(`non-canonical cursor`);return{createdAt:n,sessionId:r}}catch{throw Error(`session/list cursor is invalid`)}}}function xe(e){return Buffer.from(JSON.stringify([e.createdAt,e.sessionId]),`utf8`).toString(`base64url`)}function H(e,t){return Buffer.compare(Buffer.from(e),Buffer.from(t))}var U=class{deps;#e;#t=new Map;#n=new Set;#r=!1;constructor(e,t){this.deps=e,this.#e=t}#i(){if(this.#r)throw j(`the ACP bridge has been disposed`)}#a(e){let t=this.#t.get(e);if(t===void 0)throw A(`unknown session: ${e}`);return t}#o=e=>async t=>{try{await this.#e.notify({sessionId:e,update:t})}catch(e){this.deps.logger.warn(`acp: session/update failed: ${String(e)}`)}};initialize(e){let{version:t,warn:n}=le(void 0);return n!==void 0&&this.deps.logger.warn(`acp: ${n}`),{protocolVersion:t,agentInfo:{name:`tboxcode-dsh-acp`,version:`0.0.0`},agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,embeddedContext:!0}},authMethods:[]}}authenticate(e){}async newSession(e,t){this.#i(),B(e);let r=u(),i;try{i=await L.create(this.deps,{sessionId:r,cwd:e.cwd,mcpServers:e.mcpServers,notify:this.#o(r)},t)}catch(e){throw e instanceof n?e:j(`session activation failed: ${String(e)}`)}if(this.#r)throw await i.close(`connection closed during session/new`),j(`connection closed during session/new`);this.#t.set(r,i);try{return await this.deps.sessionStore.flush(i.session),i.refreshCommands().catch(()=>{}),{sessionId:r,configOptions:await i.configOptions(t)}}catch(e){throw this.#t.delete(r),await i.close(`session/new activation failed`),e}}async resumeSession(e,t){this.#i(),B(e);let r=e.sessionId;if(this.#t.has(r)||this.#n.has(r)||this.deps.sessionStore.get(r)!==void 0)throw A(`session is already active: ${r}`);this.#n.add(r);try{let i=(await this.deps.persistence.stat(r,{signal:t}))?.header;if(i===void 0||i.origin===`subagent`||i.parentSession!==void 0)throw A(`session is not resumable: ${r}`);if(!await V(i.cwd,e.cwd))throw A(`session cwd does not match: ${e.cwd}`);let a;try{a=await this.#s({sessionId:r,cwd:e.cwd,mcpServers:e.mcpServers,notify:this.#o(r)},t)}catch(e){throw e instanceof n?e:j(`session resume failed: ${String(e)}`)}if(this.#r)throw await a.close(`connection closed during session/resume`),j(`connection closed during session/resume`);return this.#t.set(r,a),a.refreshCommands().catch(()=>{}),{configOptions:await a.configOptions(t)}}finally{this.#n.delete(r)}}async listSessions(e,t){if(this.#i(),e.cwd!==void 0&&e.cwd!==null&&!d(e.cwd))throw A(`cwd must be an absolute path: ${String(e.cwd)}`);let n;try{n=be(e.cursor)}catch(e){throw A(e.message)}let r=await this.deps.persistence.list({signal:t}),i=(await Promise.all(r.map(async({header:t})=>{if(!(this.#t.has(t.id)||this.#n.has(t.id)||this.deps.sessionStore.get(t.id)!==void 0||t.origin===`subagent`||t.parentSession!==void 0||t.cwd===void 0||!d(t.cwd))&&!(e.cwd!==void 0&&e.cwd!==null&&!await V(t.cwd,e.cwd)))return{sessionId:t.id,cwd:t.cwd,createdAt:t.createdAt}}))).filter(e=>e!==void 0).sort((e,t)=>t.createdAt-e.createdAt||H(e.sessionId,t.sessionId)),a=n===void 0?i:i.filter(e=>Se(e,n)),o=a.slice(0,20),s=a.length>o.length?o.at(-1):void 0;return{sessions:o.map(({sessionId:e,cwd:t})=>({sessionId:e,cwd:t})),...s===void 0?{}:{nextCursor:xe(s)}}}async closeSession(e){this.#i();let t=e.sessionId,n=this.#a(t);try{await n.close(`ACP session closed`)}catch(e){throw j(`session close failed: ${String(e)}`)}finally{this.#t.get(t)===n&&this.#t.delete(t)}return{}}hasSession(e){return this.#t.has(e)}async joinSession(e,t){this.#i();let n=this.#t.get(e.sessionId);if(n===void 0)throw A(`session is not active: ${e.sessionId}`);let r=(await this.deps.persistence.stat(e.sessionId,{signal:t}))?.header;if(r===void 0)throw A(`unknown session: ${e.sessionId}`);if(!await V(r.cwd,e.cwd))throw A(`session cwd does not match: ${e.cwd}`);return{configOptions:await n.configOptions(t),updates:n.timelineFrom(0)}}async prompt(e,t){this.#i();let r=this.#a(e.sessionId),i=t??new AbortController().signal;try{let n=e._meta?.configOptionValues;if(typeof n==`object`&&n&&!Array.isArray(n)){let i=JSON.stringify(await r.configOptions(t));for(let[e,i]of Object.entries(n))await r.setConfigOption(e,i,t);let a=await r.configOptions(t);JSON.stringify(a)!==i&&await this.#e.notify({sessionId:e.sessionId,update:{sessionUpdate:`config_option_update`,configOptions:a}})}return await r.prompt(e,i)}catch(e){throw e instanceof n?e:e instanceof M?A(e.message):z(e)?A(e instanceof Error?e.message:String(e)):j(`prompt failed: ${String(e)}`)}}async#s(e,t){let n=ve(),r=0;for(;;)try{return await L.resume(this.deps,e,t)}catch(i){if(!_e(i)||this.#r)throw i;if(r>=n){let t=i instanceof Error?i.message:String(i);throw ge(e.sessionId,t)}let a=Math.min(500,n-r);await ye(a,t),r+=a}}async loadSession(e,t){this.#i(),B(e);let n=e.sessionId;if(this.#t.has(n)||this.#n.has(n)||this.deps.sessionStore.get(n)!==void 0)throw A(`session is already active: ${n}`);this.#n.add(n);try{let r=(await this.deps.persistence.stat(n,{signal:t}))?.header;if(r===void 0)throw A(`unknown session: ${n}`);if(!await V(r.cwd,e.cwd))throw A(`session cwd does not match: ${e.cwd}`);if(r.origin===`subagent`){let r=await this.deps.persistence.openHistoryRead(n,t);try{let{events:i}=await r.read(t),a=new v,o=new Map,s=new _,c=0;for(let t of i){let r=x(t,{live:!1,journal:a,seen:o,subagents:s,supportsTerminalOutput:!1,cwd:e.cwd},()=>{});for(let e of r)await this.#e.notify({...e,sessionId:n});c+=r.length}return await this.#e.extNotify?.({method:`_tbox.cn/acp_replay_complete`,payload:{sessionId:n,notificationCount:c}}),{configOptions:[]}}finally{await r.close().catch(()=>{})}}if(r.parentSession!==void 0)throw A(`session is not loadable: ${n}`);let i=await this.deps.persistence.openHistoryRead(n,t),a;try{if(a=await this.#s({sessionId:n,cwd:e.cwd,mcpServers:e.mcpServers,notify:this.#o(n)},t),this.#r)throw j(`connection closed during session/load`);this.#t.set(n,a);let r=await a.replayHistory(i,t);return await this.#e.extNotify?.({method:`_tbox.cn/acp_replay_complete`,payload:{sessionId:n,notificationCount:r}}),a.refreshCommands().catch(()=>{}),{configOptions:await a.configOptions(t)}}catch(e){throw a!==void 0&&(this.#t.get(n)===a&&this.#t.delete(n),await a.close(`session/load activation failed`).catch(e=>{this.deps.logger.warn(`acp: session/load rollback close failed: ${String(e)}`)})),e}finally{await i.close().catch(()=>{})}}finally{this.#n.delete(n)}}broadcastCommandsChanged(){for(let e of this.#t.values())e.scheduleCommandsRefresh()}async setConfigOption(e,t){this.#i();let r=this.#a(e.sessionId);try{return{configOptions:await r.setConfigOption(e.configId,e.value,t)}}catch(e){throw e instanceof M?A(e.message):z(e)?A(e instanceof Error?e.message:String(e)):e instanceof n?e:j(`set config option failed: ${String(e)}`)}}async cancel(e){await this.#a(e).cancel()}async dispose(){if(this.#r)return;this.#r=!0;let e=[...this.#t.values()],t=await Promise.allSettled(e.map(e=>e.close(`ACP bridge disposed`)));for(let t of e)this.#t.get(t.session.id)===t&&this.#t.delete(t.session.id);let n=t.filter(e=>e.status===`rejected`);if(n.length>0)throw AggregateError(n.map(e=>e.reason),`ACP bridge teardown failed for ${n.length} session(s)`)}channelOf(e){return this.#t.get(e)}channelsAll(){return this.#t.values()}};function Se(e,t){return e.createdAt<t.createdAt||e.createdAt===t.createdAt&&H(e.sessionId,t.sessionId)>0}var W=class extends Error{constructor(e){super(e),this.name=`McpConfigError`}};const Ce=/^[A-Za-z0-9_-]{1,32}$/;async function G(e,t,n){if(t==null)return;if(!Array.isArray(t))throw new W(`mcpServers must be an array`);let r=we(t,n);for(let t of r)await e.plugin(me,t)}function we(e,t){if(!Array.isArray(e))throw new W(`mcpServers must be an array`);let n=new Set;return e.map((e,r)=>{let i=Te(e.name,r);if(n.has(i))throw new W(`mcpServers contains duplicate normalized name: ${i}`);if(n.add(i),`type`in e?e.type===`stdio`:typeof e.command==`string`){if(!d(e.command))throw new W(`mcpServers[${r}].command must be an absolute path`);let n=e.args===void 0?[]:e.args;if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new W(`mcpServers[${r}].args must be an array of strings`);let a=K(e.env,`mcpServers[${r}].env`,`environment`);return{transport:`stdio`,serverName:i,command:e.command,args:n,env:a,cwd:t,failOnStartupError:!0}}if(`type`in e&&e.type===`http`||typeof e.url==`string`){if(typeof e.url!=`string`)throw new W(`mcpServers[${r}].url must be a string`);Ee(e.url,`mcpServers[${r}].url`);let t=K(e.headers,`mcpServers[${r}].headers`,`header`);return{transport:`streamable-http`,serverName:i,url:e.url,headers:t,failOnStartupError:!0}}throw new W(`mcpServers[${r}] requires either command (stdio) or url (http)`)})}function K(e,t,n){if(e==null)return Object.create(null);if(!Array.isArray(e))throw new W(`${t} must be an array of {name, value} entries`);let r=Object.create(null),i=new Set;for(let a of e){let e=typeof a?.name==`string`?a.name:void 0,o=typeof a?.value==`string`?a.value:void 0;if(e===void 0||o===void 0)throw new W(`${t} contains an entry missing name or value`);if(n===`header`)try{k(e),pe(e,o)}catch{throw new W(`${t} contains an invalid header entry`)}else if(e.length===0||e.includes(`=`)||e.includes(`\0`)||o.includes(`\0`))throw new W(`${t} contains an invalid environment entry`);let s=n===`header`?e.toLowerCase():e;if(i.has(s))throw new W(`${t} contains duplicate name: ${e}`);i.add(s),r[e]=o}return r}function Te(e,t){if(typeof e!=`string`||e.trim().length===0||/[\u0000-\u001f\u007f]/.test(e))throw new W(`mcpServers[${t}] contains an invalid server name`);return Ce.test(e)?e:`${e.normalize(`NFKD`).replace(/[^A-Za-z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,20)||`server`}_${l(`sha256`).update(e).digest(`hex`).slice(0,8)}`.slice(0,32)}function Ee(e,t){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`)}catch{throw new W(`${t} must be an absolute HTTP(S) URL`)}}function De(e,t,n){n.sandboxOf(e)!==t.sandbox&&n.setSandbox(e,t.sandbox),n.approvalOf(e)!==t.approval&&n.setApproval(e,t.approval)}function q(e){return async(t,n)=>{let r=await e(t,`read`,n===void 0?void 0:{signal:n});return{read:async e=>({events:(e===void 0?await r.read():await r.read(0,void 0,{signal:e})).events}),close:()=>r.close()}}}const Oe=`dsh-acp-full`,ke=[`agents`,`llm`,`sessionPersistence`,`sessions`,`approval`,`commands`,`skills`,`agentDefaultModel`];function Ae(n){return n?.stream??a(t.toWeb(process.stdout),e.toWeb(process.stdin))}async function J(e){await e.get(`loader`)?.await()}async function je(e){let t=e.get(`agentPresets`);if(t===void 0)return`standard`;let n=t.defaultId;if((await t.list()).some(e=>e.id===n&&e.broken===void 0))return n;let r=t.config.default;return n!==r&&e.logger.warn(`[tboxcode-preset] selectedDefault="${n}" 不在当前 profile roster,回退 ${r}`),r}async function Y(e,t,n){let r=e.get(`agentPresets`);if(r!==void 0)try{await r.mount(t,n)}catch(e){throw A(`agent preset "${n}" 不可用:${e instanceof Error?e.message:String(e)}`)}}function Me(e,t){let n=t=>{try{return e.get(`sandboxPolicy`)?.resolve({session:t})?.mode}catch{return}},r=()=>{let t=e.agentDefaultModel.currentSelection();if(!(typeof t.provider!=`string`||typeof t.model!=`string`))return{provider:t.provider,model:t.model,...t.reasoningEffort===void 0?{}:{reasoningEffort:String(t.reasoningEffort)}}};return{async createAgent(t){await J(e);let n=await je(e),i=P(r());return e.agents.create({sessionId:t.sessionId,meta:{cwd:t.cwd,agentPreset:n},...i===void 0?{}:{agentOptions:i},signal:t.signal,setup:async(r,i)=>{await Y(e,r,n),await t.configureScope?.(r,i),await G(r,t.mcpServers,t.cwd)}})},async resumeAgent(t){await J(e);let n=P(r());return e.agents.resume({resumeSessionId:t.sessionId,...n===void 0?{}:{agentOptions:n},signal:t.signal,setup:async(n,r)=>{let i=r.session,a=e.get(`agentPresets`),o=null;try{o=a?.presetForSession?.(i)??null}catch{o=null}await Y(e,n,(typeof o==`string`&&o.length>0?o:null)??i.header.agentPreset??`standard`),await t.configureScope?.(n,r),await G(n,t.mcpServers,t.cwd)}})},persistence:{stat:async(t,n)=>{let r=await e.sessionPersistence.stat(t,n);return r===void 0?void 0:{header:r.header}},list:async t=>(await e.sessionPersistence.list(t)).map(e=>({header:e.header})),openHistoryRead:q((t,n,r)=>e.sessionPersistence.open(t,n,r))},llm:e.llm,sandboxModeOf:e=>n(e),applyModeKnobs:(t,r,i,a)=>{if(a?.initial===!0){De(t,i,{sandboxOf:e=>n(e),approvalOf:t=>{try{return e.approval.overrideOf(t)??e.approval.config.policy??`ask`}catch{return}},setSandbox:(e,t)=>s(e,t),setApproval:(e,t)=>c(e,t)});return}s(t,i.sandbox),e.approval.setPolicy(r,i.approval)},executeCommand:async(t,n,r)=>e.commands.execute(t,n,[],r??new AbortController().signal),listCommands:async t=>e.commands.list(t),listUserInvocableSkills:async t=>(await e.skills.snapshot({cwd:t.session.header.cwd})).skills,onCommandSurfaceChanged:t=>{let n=e.on(`commands/change`,t),r=e.on(`skills/change`,t);return()=>{n(),r()}},sessionToolDenies:()=>t()?[]:[`ask_user_question`],defaultSelection:r,sessionStore:{get:t=>e.sessions.get(t),flush:async t=>{await e.sessions.flush(t)}},admitPromptContent:async t=>{let n=e.get(`attachments`);if(n===void 0)throw A(`image prompt content requires the mounted attachment service`);return await n.admitPromptContent(t)},logger:{warn:t=>e.logger.warn(t),info:t=>e.logger.info(t),debug:t=>e.logger.debug(t)},onSessionEvent:t=>e.on(`session/event`,t),onAssistantStream:t=>e.on(`agent/assistant-stream`,t),onInboxClaimed:t=>e.on(`agent/inbox/claimed`,t),onAgentError:t=>e.on(`agent/error`,t)}}function X(e){if(e instanceof W)return A(e.message);let t=e instanceof Error?e.message:String(e);return t.includes(`mcp-client(`)?A(t):e}function Z(e,t,n){return r({name:`tboxcode-dsh-acp`}).onRequest(i.agent.initialize,({params:n})=>(t.elicitationForm=Ne(n)?.elicitation!=null,e.initialize(n))).onRequest(i.agent.authenticate,async()=>(e.authenticate({}),{})).onRequest(i.agent.session.new,async({params:t,signal:n})=>{try{return await e.newSession(t,n)}catch(e){throw X(e)}}).onRequest(i.agent.session.list,async({params:t,signal:n})=>e.listSessions(t,n)).onRequest(i.agent.session.resume,async({params:t,signal:n})=>{try{return await e.resumeSession(t,n)}catch(e){throw X(e)}}).onRequest(i.agent.session.close,async({params:t})=>e.closeSession(t)).onRequest(i.agent.session.prompt,async({params:t,signal:r})=>{let i=t.sessionId??``;n?.beforePrompt?.(i);try{return await e.prompt(t,r)}finally{n?.afterPrompt?.(i)}}).onRequest(i.agent.session.load,async({params:t,signal:n})=>{try{return await e.loadSession(t,n)}catch(e){throw X(e)}}).onNotification(i.agent.session.cancel,async({params:t})=>e.cancel(t.sessionId)).onRequest(i.agent.session.setConfigOption,async({params:t,signal:n})=>{try{return await e.setConfigOption(t,n)}catch(e){throw X(e)}})}function Q(e,t){e.onSessionEvent((e,n)=>{let r=e.id,i=t.channelOf(r);if(i!==void 0){i.onSessionEvent(e,n);return}for(let e of t.channelsAll())if(e.tracksChild(r)){e.onChildEvent(r,n);break}}),e.onAssistantStream(({agent:e,frame:n})=>{for(let r of t.channelsAll())if(r.owns(e)){r.onAssistantStream(n);break}}),e.onInboxClaimed(({agent:e,message:n,turn:r})=>{for(let i of t.channelsAll())if(i.owns(e)){i.onInboxClaimed(n,r);break}}),e.onAgentError(({agent:e,error:n})=>{for(let r of t.channelsAll())if(r.owns(e)){r.onAgentError(n);break}}),e.onCommandSurfaceChanged(()=>t.broadcastCommandsChanged())}function $(e,t,n){let r={notify:async()=>{t.warn(`acp: io.notify called before connection wiring`)}},a=new U(e,r);return{app:Z(a,n),io:r,onConnection:(t,s)=>{r.notify=async e=>{await s.notify(i.client.session.update,e)},r.extNotify=async e=>{await s.notify(e.method,e.payload)},e.logger.debug(`acp: connection established`),Q(e,a),t.on(`user-questions/request`,((e,t)=>{if(n.elicitationForm===!1)return t();let r=a.channelOf(e.agent?.session?.id??``);if(r===void 0||e.questions.length===0)return t();let c=e.questions,l=c.length===1?c[0]?.question??`Input requested`:`Answer ${c.length} questions`;return r.drainUpdates().then(async()=>{let e=await s.request(i.client.elicitation.create,{mode:`form`,message:l,sessionId:r.session.id,requestedSchema:ie(c)});if(e.action!==`accept`)throw new o(`ask_user_question ${e.action===`decline`?`declined`:`cancelled`} by client`,e.action===`decline`?`ASK_DECLINED`:`ASK_ABORTED`);return ue(c,e.content??{})})})),t.on(`approval/request`,((e,t)=>{let n=a.channelOf(e.agent?.session?.id??``);if(n===void 0||e.callId===void 0)return t();let r=e.callId;return n.drainUpdates().then(async()=>{let e=await s.request(i.client.session.requestPermission,{sessionId:n.session.id,toolCall:{toolCallId:r},options:[{optionId:`allow-once`,name:`Allow once`,kind:`allow_once`},{optionId:`reject-once`,name:`Reject`,kind:`reject_once`}]});return e.outcome.outcome===`cancelled`?`cancelled`:e.outcome.optionId===`allow-once`?`allowed-once`:`rejected`})}))},dispose:()=>a.dispose()}}function Ne(e){return e?.clientCapabilities}function Pe(e,t){let n={elicitationForm:!1},r=Me(e,()=>n.elicitationForm),i=$(r,e.logger,n),a=i.app.connect(Ae(t));i.onConnection(e,a.client),r.logger.debug(`acp: connection established`);let o,s=()=>(o??=i.dispose().catch(t=>{e.logger.warn(`acp: connection-close teardown failed: ${String(t)}`)}),o);a.closed.catch(t=>{e.logger.warn(`acp: connection closed with an error: ${String(t)}`)}).then(s),e.effect(()=>s,`dsh-acp-full.connection`)}function Fe(e,t,n={}){let r={notify:async()=>{t.warn(`acp: shared io.notify called before router binding`)}},i=new U(e,r),a={elicitationForm:!1};return Q(e,i),{io:r,capsHolder:a,attachConnection(e,t){let n=Z(i,a,t).connect(e);return{client:n.client,closed:n.closed}},hasSession:e=>i.hasSession(e),joinSession:(e,t)=>i.joinSession(e,t),dispose:()=>i.dispose()}}export{Pe as apply,$ as buildAgentApp,q as createHistoryReadPort,Fe as createSharedAcpCore,ke as inject,Oe as name};
|
|
1
|
+
import{Readable as e,Writable as t}from"node:stream";import{RequestError as n,agent as r,methods as i,ndJsonStream as a}from"@agentclientprotocol/sdk";import{UserQuestionError as o}from"@deepseek-ai/dsh-user-questions";import{setSandboxMode as s}from"@deepseek-ai/dsh-sandbox-policy";import{setApprovalPolicy as c}from"@deepseek-ai/dsh-user-approval";import{createHash as l,randomUUID as ee}from"node:crypto";import{isAbsolute as u,resolve as d}from"node:path";import{realpath as f}from"node:fs/promises";import{SessionAlreadyOwnedError as te}from"@deepseek-ai/dsh-session-persistence";import{IMAGE_SOURCE_RECORD as p,MODEL_CONFIG_ID as m,MODE_CONFIG_ID as ne,PROVIDER_DEFAULT_REASONING_VALUE as h,REASONING_CONFIG_ID as g,StreamAttemptState as re,SubagentCatalogState as _,ToolJournal as v,TurnFoldTracker as ie,buildElicitationSchema as ae,commandGate as oe,commandsProjection as se,decodeBase64Utf8 as ce,isAcpSessionMode as le,mapRpcError as ue,modeConfigOption as de,modeFromSandbox as y,negotiateProtocolVersion as fe,parseElicitationContent as pe,parseImageSourceRecord as me,projectEvent as b,projectRecord as he,projectStreamFrame as ge,projectSubagentChildEvent as _e,resolveModelValue as x,settleToResponse as S,stopReasonFromTurnEnd as ve,translateMode as C}from"@tbox.cn/dsh-acp-bridge-core";import{createUserMessage as ye}from"@deepseek-ai/dsh-llm";import{installModelSelection as w}from"@deepseek-ai/dsh-agent";import{validateHeaderName as be,validateHeaderValue as xe}from"node:http";import*as Se from"@deepseek-ai/dsh-mcp-client";function T(e){return n.invalidParams(void 0,e)}function E(e){return n.internalError(void 0,e)}function Ce(e){let t=ue(e);return new n(t.code,t.message,t.data)}function we(e,t){return Ce({code:`session/writer-held`,message:t??`session "${e}" is owned by another writer (another window or process may hold it)`,data:{sessionId:e,reason:`writer-held`}})}var D=class extends Error{},O=class{#e;#t;#n;#r;#i=!1;#a=Promise.resolve();constructor(e,t,n,r){this.#t=e,this.#n=t,this.#e=n,this.#r=r}get mode(){return this.#e}async initializeMode(e,t){let n=C(e);if(n===void 0)throw new D(`unknown mode option: ${e}`);t&&await this.#r(n,{initial:!0}),this.#e=e}options(e){return this.#o(async()=>(await this.#c(e)).options)}set(e,t,n){return this.#o(async()=>{if(typeof t!=`string`)throw new D(`${e} requires a select value`);if(e===ne){if(!le(t))throw new D(`unknown mode option: ${t}`);let e=C(t);if(e===void 0)throw new D(`unknown mode option: ${t}`);await this.#r(e),this.#e=t}else if(e===m){let e=(await this.#c(n)).choices.get(t);if(e===void 0)throw new D(`unknown model option: ${t}`);await this.#n.select(await this.#s(e,n))}else if(e===g){let e=this.#n.current();if(e===void 0)throw new D(`this session has no model selection`);let r=await this.#t.resolveModelInfo(e.provider,e.model,n),i=t===h&&r.reasoning?.defaultEffort===void 0;if(r.reasoning===void 0||!i&&!r.reasoning.efforts.some(e=>e.id===t))throw new D(`unknown reasoning effort for ${e.provider}/${e.model}: ${t}`);await this.#n.select(await this.#s({provider:e.provider,model:e.model,...i?{}:{reasoningEffort:t}},n))}else throw new D(`unknown session config option: ${e}`);return(await this.#c(n)).options})}#o(e){let t=this.#a.then(e);return this.#a=t.then(()=>void 0,()=>void 0),t}async#s(e,t){let n=await this.#t.resolveCallConfig(e,t);return{provider:n.provider,model:n.model,...n.reasoningEffort===void 0?{}:{reasoningEffort:n.reasoningEffort}}}async#c(e){let t=[de(this.#e)],n=this.#n.current(),r=new Map,i=await Promise.all(this.#t.listProviders().map(async t=>{try{let n=(await this.#t.listModels(t.id,e)).map(e=>{let n={value:x(t.id,e.id),selection:{provider:t.id,model:e.id}};return r.set(n.value,n.selection),{value:n.value,name:e.name,...e.description===void 0?{}:{description:e.description}}});return{group:t.id,name:t.name,options:n}}catch{return{group:t.id,name:t.name,options:[]}}}));if(n===void 0)return{choices:r,options:t};let a,o=!0;try{a=await this.#s(n,e),this.#i=!0}catch(e){if(!this.#i)throw e;a=n,o=!1}let s=x(a.provider,a.model);if(!r.has(s)){r.set(s,{provider:a.provider,model:a.model});let e=i.find(e=>e.group===a.provider);e===void 0&&(e={group:a.provider,name:a.provider,options:[]},i.push(e)),e.options.unshift({value:s,name:a.model})}t.push({id:m,name:`Model`,category:`model`,type:`select`,currentValue:s,options:i.filter(e=>e.options.length>0)});let c=o?await this.#t.resolveModelInfo(a.provider,a.model,e):void 0;return c?.reasoning!==void 0&&t.push({id:g,name:`Reasoning effort`,category:`thought_level`,type:`select`,currentValue:a.reasoningEffort===void 0?h:String(a.reasoningEffort),options:[...c.reasoning.defaultEffort===void 0?[{value:h,name:`Provider default`}]:[],...c.reasoning.efforts.map(e=>({value:String(e.id),name:e.name,...e.description===void 0?{}:{description:e.description}}))]}),{choices:r,options:t}}};const k={bytes:16*1024*1024,images:40};async function Te(e,t,n){let r=Array(e.length),i=0,a=Array.from({length:Math.min(t,e.length)},async()=>{for(;;){let t=i++;if(t>=e.length)return;r[t]=await n(e[t])}});return await Promise.all(a),r}var A=class{#e=new Map;get sources(){return this.#e}async prepare(e,t,n=k){for(let t of e)if(t.type===p)for(let e of me({type:p,data:t.data}))this.#e.set(e.attachmentId,e.url);let r=new Map;for(let t of e){if(t.type!==`user/message`)continue;let e=t.data?.content;if(Array.isArray(e))for(let t of e){if(typeof t!=`object`||!t||t.type!==`image`)continue;let e=t.attachment,n=e?.attachmentId;typeof n!=`string`||n===``||this.#e.has(n)||r.has(n)||r.set(n,e)}}let i=new Map;if(r.size===0)return{imageSources:this.#e,imageBytes:i};let a=[...r.entries()],o=[],s=0;for(let e=a.length-1;e>=0;--e){let[t,r]=a[e];if(o.length>=n.images)break;let i=Math.ceil((typeof r.bytes==`number`?r.bytes:0)/3)*4;if(s+i>n.bytes)break;s+=i,o.push(t)}let c=new Set(o);for(let e of r.keys())c.has(e)||i.set(e,`omitted`);return await Te(o,4,async e=>{let n=await t(r.get(e)).catch(()=>void 0);n!==void 0&&i.set(e,n)}),{imageSources:this.#e,imageBytes:i}}};const j=8192;function M(e,t=j){let n=(typeof e.data==`string`&&e.data!==``?ce(e.data):void 0)??(typeof e.uri==`string`&&e.uri!==``?e.uri:void 0);if(n===void 0||n===``)return{ok:!1,reason:`url-invalid`};if(n.length>t)return{ok:!1,reason:`url-too-long`};let r;try{r=new URL(n)}catch{return{ok:!1,reason:`url-invalid`}}return r.protocol!==`http:`&&r.protocol!==`https:`||r.username!==``||r.password!==``?{ok:!1,reason:`url-invalid`}:{ok:!0,url:n}}function N(e){if(e!==void 0)return{provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort}}}function P(e){let t=e.model;if(t===void 0||typeof t.current!=`function`||typeof t.select!=`function`)throw Error(`agent does not expose a model selection port`);return{current:()=>{let e=t.current();if(e!==void 0)return{provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:String(e.reasoningEffort)}}},select:e=>t.select({provider:e.provider,model:e.model,...e.reasoningEffort===void 0?{}:{reasoningEffort:e.reasoningEffort}})}}function Ee(e){if(typeof e.name==`string`&&e.name!==``)return e.name;let t=e._meta?.tboxcode?.name;return typeof t==`string`&&t!==``?t:void 0}function De(e){let t=[];for(let n of e){if(n.type===`text`){t.push({kind:`text`,text:n.text??``});continue}if(n.type===`resource_link`){t.push({kind:`text`,text:`[link] ${n.uri??``}`});continue}if(n.type===`image`){let e=n.mimeType??`image/png`;if(e===`image/tbox_url`){let e=M(n);if(!e.ok)throw T(e.reason===`url-too-long`?`image URL exceeds the supported length`:`image URL must be an absolute http(s) URL`);let r=Ee(n);t.push({kind:`image-url`,url:e.url,...r===void 0?{}:{name:r}});continue}if(typeof n.data!=`string`)throw T(`image content requires base64 data`);t.push({kind:`image-upload`,mediaType:e,data:n.data,...n.name===void 0?{}:{name:n.name}});continue}if(n.type===`resource`){let e=n.resource;if(e?.mimeType===`image/tbox_url`)throw T(`embedded resource does not accept image/tbox_url; use a top-level image block`);e?.blob!==void 0&&e.mimeType?.startsWith(`image/`)===!0?t.push({kind:`image-upload`,mediaType:e.mimeType,data:e.blob}):t.push({kind:`text`,text:e?.text??`[resource] ${e?.uri??``}`});continue}throw T(`unsupported prompt content type: ${n.type}`)}return t}function F(e,t){let n=e.sessionToolDenies();n.length!==0&&t.tools.restrict({deny:[...n]})}var I=class e{agent;session;deps;config;#e;#t;#n;#r=new v;#i=new _;#a=new re;#o=new Map;#s;#c=new Map;#l=Promise.resolve();#u=[];#d;#f=!1;#p=``;#m;#h;#g=new A;#_=void 0;constructor(e,t,n,r){this.deps=e,this.#e=t,this.agent=t.agent,this.session=t.agent.session,this.config=r,this.#t=n.notify,this.#n=n.cwd,this.#s=new ie(e=>{this.#w(async()=>{try{await this.#t(e)}catch(e){this.deps.logger.warn(`acp: session/update failed: ${String(e)}`)}})})}owns(e){return this.agent===e}ownsSession(e){return this.agent.session===e}drainUpdates(){return this.#l}async prompt(e,t){if(this.#f||this.#d!==void 0)throw E(`the session is closing`);if(this.#_!==void 0)throw T(`a prompt is already in flight for this session`);let n=()=>{},r=()=>{},i=new Promise((e,t)=>{n=e,r=t}),a={settle:e=>n(e),fail:e=>r(e),messageId:``,turn:void 0,cancelRequested:!1,phase:`admitting`,admissionAbort:new AbortController};this.#_=a;try{let n=e.prompt.length===1?e.prompt[0]:void 0;if(n?.type===`text`&&n.text!==void 0){let e=oe(n.text);if(e.hit&&!e.shadow){let e=await this.#v(a,n.text.trim(),t);if(e!==void 0)return e}}return await this.#y(a,e,t,i)}finally{this.#_===a&&(this.#_=void 0)}}async#v(e,t,n){let r=new AbortController;this.#h=r,e.phase=`turn`;try{if(await this.deps.executeCommand(this.agent,t,r.signal??n)===void 0){e.phase=`admitting`;return}return S({kind:`success`})}catch(e){return n.aborted||r.signal.aborted?S({kind:`aborted`}):(this.deps.logger.warn(`acp: command rejected without settle projection: ${t}: ${String(e)}`),S({kind:`success`}))}finally{this.#h=void 0}}async#y(e,t,n,r){let i=De(t.prompt),a=i.filter(e=>e.kind!==`text`).length;if(a>20)throw T(`a prompt may carry at most 20 images`);let o=AbortSignal.any([n,e.admissionAbort.signal]),s;try{s=a===0?i.map(e=>({type:`text`,text:e.text})):await this.#b(i,o)}catch(t){if(e.cancelRequested||o.aborted)return{stopReason:`cancelled`};throw t}if(e.cancelRequested)return{stopReason:`cancelled`};let c;try{let t=ye({content:s,source:{kind:`user`}});return e.messageId=t.id,e.phase=`turn`,c=()=>{e.cancelRequested||(e.cancelRequested=!0,e.settle(`cancelled`),this.agent.cancel({kind:`user`}).catch(e=>{this.deps.logger.warn(`acp: cancel failed (ACP prompt request cancelled): ${String(e)}`)}))},n.addEventListener(`abort`,c,{once:!0}),this.agent.followup(t),{stopReason:await r}}catch(t){if(e.cancelRequested||o.aborted)return{stopReason:`cancelled`};throw t}finally{c!==void 0&&n.removeEventListener(`abort`,c)}}async#b(e,t){let n=this.#x(e,t);n.catch(()=>void 0);let r=new Promise((e,n)=>{if(t.aborted){n(Error(`admission aborted`));return}t.addEventListener(`abort`,()=>n(Error(`admission aborted`)),{once:!0})});return await Promise.race([n,r])}async#x(e,t){let n=[],r=[];e.forEach((e,t)=>{e.kind===`image-upload`?n.push(t):e.kind===`image-url`&&r.push(t)});let i=new Map,a=new Map;if(n.length>0){if(this.deps.admitPromptContent===void 0)throw T(`image prompt content requires the mounted attachment service`);let t=n.map(t=>{let n=e[t];return{type:`image`,mediaType:n.mediaType,data:n.data,...n.name===void 0?{}:{name:n.name}}});(await this.deps.admitPromptContent(t)).forEach((e,t)=>{e.type===`image`&&i.set(n[t],e.attachment)})}if(r.length>0){if(this.deps.admitImageUrls===void 0)throw T(`image URL prompt content requires the mounted image source service`);let n=r.map(t=>e[t]),o=n.map(e=>e.url),s=n.map(e=>e.name);(await this.deps.admitImageUrls(this.session.id,o,{signal:t,names:s})).forEach((e,t)=>{let n=r[t];i.set(n,e.attachment);let s=e.attachment;!(typeof s==`object`&&s&&typeof s.name==`string`)&&e.name!==void 0&&a.set(n,e.name),this.#g.sources.set(e.attachmentId,o[t])})}return e.map((e,t)=>{if(e.kind===`text`)return{type:`text`,text:e.text};let n=a.get(t);return{type:`image`,attachment:i.get(t),...n===void 0?{}:{name:n}}})}async#S(e){if(this.deps.readImage!==void 0)try{return await this.deps.readImage(this.session.id,e)}catch{return}}async cancel(){let e=this.#_;if(e!==void 0){if(e.cancelRequested||(e.cancelRequested=!0,e.settle(`cancelled`)),e.phase===`admitting`){e.admissionAbort.abort();return}this.#h?.abort(),await this.agent.cancel({kind:`user`}).catch(()=>{});return}await this.agent.cancel({kind:`user`}).catch(e=>{this.deps.logger.warn(`acp: cancel failed: ${String(e)}`)})}onInboxClaimed(e,t){let n=this.#_;n!==void 0&&(n.messageId===e?.id||n.turn===void 0)&&(n.turn=t)}async refreshCommands(){if(this.#f||this.#d!==void 0)return;let[e,t]=await Promise.all([this.deps.listCommands(this.agent),this.deps.listUserInvocableSkills(this.agent)]),n=se(e,t),r=JSON.stringify(n);r!==this.#p&&(this.#p=r,await this.#w(async()=>{try{await this.#t({sessionUpdate:`available_commands_update`,availableCommands:n})}catch(e){this.deps.logger.warn(`acp: available_commands_update failed: ${String(e)}`)}}))}tracksChild(e){return this.#i.tracks(e)}onChildEvent(e,t){if(this.#f||this.#d!==void 0)return;let n=this.#o.get(e);n===void 0&&(n=new v,this.#o.set(e,n)),this.#w(()=>{let r=_e(e,t,this.#i,{journal:n,supportsTerminalOutput:!1,cwd:this.#n});return this.#T(r)})}scheduleCommandsRefresh(e=500){this.#f||this.#d!==void 0||(this.#m!==void 0&&clearTimeout(this.#m),this.#m=setTimeout(()=>{this.#m=void 0,this.refreshCommands().catch(e=>{this.deps.logger.warn(`acp: commands refresh failed: ${String(e)}`)})},e))}onAgentError(e){let t=this.#_;t!==void 0&&t.fail(E(`turn failed: ${String(e)}`))}#C(e){let t=this.#_;if(t===void 0||t.turn===void 0)return;let n=e.data;if(e.type===`turn/end`&&n?.turn===t.turn){let e=ve(n.reason);if(`error`in e){t.fail(E(`turn ended with error: ${JSON.stringify(n.reason)}`));return}e.warn!==void 0&&this.deps.logger.warn(`acp: ${e.warn}`),t.settle(e.stopReason)}}async replayHistory(e,t){let n=0;return await this.#w(async()=>{let{events:r}=await e.read(t),i=await this.#g.prepare(r,e=>this.#S(e));for(let e of r){let t=he(e,{live:!1,journal:this.#r,seen:this.#c,subagents:this.#i,supportsTerminalOutput:!1,cwd:this.#n,...i},(e,t)=>{this.deps.logger.debug(`acp: unknown event ${e} (${t})`)});this.#s.accept(e),t.length>0&&(await this.#T(t,!1),n+=t.length)}}),n}static async create(t,n,r){let i,a=await t.createAgent({sessionId:n.sessionId,cwd:n.cwd,mcpServers:n.mcpServers,signal:r,configureScope:(e,n)=>{i=new O(t.llm,P(n),`build`,(e,r)=>t.applyModeKnobs(n.session,n,e,r)),w(e),F(t,e)}});if(i===void 0)throw await a.dispose().catch(()=>{}),E(`session create did not configure the model selection`);let o=new e(t,a,n,i);try{let e=t.sandboxModeOf?.(o.session,o.agent);await i.initializeMode(y(e),e!==void 0)}catch(e){throw await a.dispose().catch(()=>{}),e}return o}static async resume(t,n,r){let i,a=await t.resumeAgent({sessionId:n.sessionId,cwd:n.cwd,mcpServers:n.mcpServers,signal:r,configureScope:(e,n)=>{i=new O(t.llm,P(n),`build`,(e,r)=>t.applyModeKnobs(n.session,n,e,r)),w(e),F(t,e)}});if(i===void 0)throw await a.dispose().catch(()=>{}),E(`session resume did not configure the model selection`);let o=new e(t,a,n,i);try{let e=t.sandboxModeOf?.(o.session,o.agent);await i.initializeMode(y(e),e!==void 0)}catch(e){throw await a.dispose().catch(()=>{}),e}return o}configOptions(e){return this.config.options(e)}setConfigOption(e,t,n){if(this.#f||this.#d!==void 0)throw E(`the session is closing`);return this.config.set(e,t,n)}onSessionEvent(e,t){this.#f||this.ownsSession(e)===!1||this.#w(async()=>{let e=await this.#g.prepare([t],e=>this.#S(e)),n=b(t,{live:!0,journal:this.#r,seen:this.#c,attempts:this.#a,subagents:this.#i,supportsTerminalOutput:!1,cwd:this.#n,...e},(e,t)=>{this.deps.logger.debug(`acp: unknown event ${e} (${t})`)});return this.#s.accept(t),this.#C(t),this.#T(n)})}onAssistantStream(e){this.#f||this.#w(()=>{let t=ge(e,{live:!0,journal:this.#r,seen:this.#c,attempts:this.#a});return this.#T(t)})}captureWatermark(){return this.#u.length}timelineFrom(e){return this.#u.slice(e)}close(e){return this.#d===void 0&&(this.#d=(async()=>{this.#m!==void 0&&(clearTimeout(this.#m),this.#m=void 0),this.#_?.admissionAbort.abort();try{await this.agent.cancel({kind:`user`})}catch(t){this.deps.logger.warn(`acp: cancel on close failed (${e}): ${String(t)}`)}await this.drainUpdates(),await this.deps.sessionStore.flush(this.session),await this.#e.dispose(),this.deps.logger.debug(`acp: session ${this.session.id} closed (${e})`)})().finally(()=>{this.#f=!0,this.#a.clear()})),this.#d}#w(e){let t=this.#l.then(e,e);return this.#l=t.catch(e=>{this.deps.logger.warn(`acp: update pipeline failed: ${String(e)}`)}),t}async#T(e,t=!0){for(let n of e){t&&(this.#u.push(n),this.#u.length>1e3&&this.#u.shift());try{await this.#t(n)}catch(e){this.deps.logger.warn(`acp: session/update failed: ${String(e)}`)}}}};const L=6e3;function Oe(e){if(e instanceof te)return!0;let t=e;return t?.name===`SessionAlreadyOwnedError`?!0:t?.code===`session/writer-held`}function ke(){let e=process.env.TBOXCODE_ACP_WRITER_HELD_RETRY_MS;if(e===void 0||e===``)return L;let t=Number(e);return Number.isFinite(t)&&t>=0?t:L}function Ae(e,t){return new Promise((n,r)=>{if(t?.aborted===!0){r(t.reason??Error(`aborted`));return}let i=()=>{clearTimeout(a),r(t?.reason??Error(`aborted`))},a=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);t?.addEventListener(`abort`,i,{once:!0})})}function R(e){let t=e?.code;return t===`session/model-unavailable`||t===`session/provider-models-unavailable`}function z(e){if(!u(e.cwd))throw T(`cwd must be an absolute path: ${e.cwd}`);if(e.additionalDirectories!==void 0&&e.additionalDirectories!==null&&e.additionalDirectories.length>0)throw T(`additionalDirectories is not supported`)}async function B(e,t){if(e===void 0)return!1;try{let[n,r]=await Promise.all([f(e),f(t)]);return n===r}catch{return d(e)===d(t)}}function je(e){if(e!=null){if(!/^[A-Za-z0-9_-]+$/.test(e))throw Error(`session/list cursor is invalid`);try{let t=JSON.parse(Buffer.from(e,`base64url`).toString(`utf8`)),n=Array.isArray(t)?t[0]:void 0,r=Array.isArray(t)?t[1]:void 0;if(!Array.isArray(t)||t.length!==2||typeof n!=`number`||!Number.isSafeInteger(n)||n<0||typeof r!=`string`||r.length===0)throw Error(`invalid cursor fields`);if(Buffer.from(JSON.stringify(t),`utf8`).toString(`base64url`)!==e)throw Error(`non-canonical cursor`);return{createdAt:n,sessionId:r}}catch{throw Error(`session/list cursor is invalid`)}}}function Me(e){return Buffer.from(JSON.stringify([e.createdAt,e.sessionId]),`utf8`).toString(`base64url`)}function V(e,t){return Buffer.compare(Buffer.from(e),Buffer.from(t))}var H=class{deps;#e;#t=new Map;#n=new Set;#r=!1;constructor(e,t){this.deps=e,this.#e=t}#i(){if(this.#r)throw E(`the ACP bridge has been disposed`)}#a(e){let t=this.#t.get(e);if(t===void 0)throw T(`unknown session: ${e}`);return t}#o=e=>async t=>{try{await this.#e.notify({sessionId:e,update:t})}catch(e){this.deps.logger.warn(`acp: session/update failed: ${String(e)}`)}};initialize(e){let{version:t,warn:n}=fe(void 0);return n!==void 0&&this.deps.logger.warn(`acp: ${n}`),{protocolVersion:t,agentInfo:{name:`tboxcode-dsh-acp`,version:`0.0.0`},agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,embeddedContext:!0}},authMethods:[]}}authenticate(e){}async newSession(e,t){this.#i(),z(e);let r=ee(),i;try{i=await I.create(this.deps,{sessionId:r,cwd:e.cwd,mcpServers:e.mcpServers,notify:this.#o(r)},t)}catch(e){throw e instanceof n?e:E(`session activation failed: ${String(e)}`)}if(this.#r)throw await i.close(`connection closed during session/new`),E(`connection closed during session/new`);this.#t.set(r,i);try{return await this.deps.sessionStore.flush(i.session),i.refreshCommands().catch(()=>{}),{sessionId:r,configOptions:await i.configOptions(t)}}catch(e){throw this.#t.delete(r),await i.close(`session/new activation failed`),e}}async resumeSession(e,t){this.#i(),z(e);let r=e.sessionId;if(this.#t.has(r)||this.#n.has(r)||this.deps.sessionStore.get(r)!==void 0)throw T(`session is already active: ${r}`);this.#n.add(r);try{let i=(await this.deps.persistence.stat(r,{signal:t}))?.header;if(i===void 0||i.origin===`subagent`||i.parentSession!==void 0)throw T(`session is not resumable: ${r}`);if(!await B(i.cwd,e.cwd))throw T(`session cwd does not match: ${e.cwd}`);let a;try{a=await this.#s({sessionId:r,cwd:e.cwd,mcpServers:e.mcpServers,notify:this.#o(r)},t)}catch(e){throw e instanceof n?e:E(`session resume failed: ${String(e)}`)}if(this.#r)throw await a.close(`connection closed during session/resume`),E(`connection closed during session/resume`);return this.#t.set(r,a),a.refreshCommands().catch(()=>{}),{configOptions:await a.configOptions(t)}}finally{this.#n.delete(r)}}async listSessions(e,t){if(this.#i(),e.cwd!==void 0&&e.cwd!==null&&!u(e.cwd))throw T(`cwd must be an absolute path: ${String(e.cwd)}`);let n;try{n=je(e.cursor)}catch(e){throw T(e.message)}let r=await this.deps.persistence.list({signal:t}),i=(await Promise.all(r.map(async({header:t})=>{if(!(this.#t.has(t.id)||this.#n.has(t.id)||this.deps.sessionStore.get(t.id)!==void 0||t.origin===`subagent`||t.parentSession!==void 0||t.cwd===void 0||!u(t.cwd))&&!(e.cwd!==void 0&&e.cwd!==null&&!await B(t.cwd,e.cwd)))return{sessionId:t.id,cwd:t.cwd,createdAt:t.createdAt}}))).filter(e=>e!==void 0).sort((e,t)=>t.createdAt-e.createdAt||V(e.sessionId,t.sessionId)),a=n===void 0?i:i.filter(e=>Ne(e,n)),o=a.slice(0,20),s=a.length>o.length?o.at(-1):void 0;return{sessions:o.map(({sessionId:e,cwd:t})=>({sessionId:e,cwd:t})),...s===void 0?{}:{nextCursor:Me(s)}}}async closeSession(e){this.#i();let t=e.sessionId,n=this.#a(t);try{await n.close(`ACP session closed`)}catch(e){throw E(`session close failed: ${String(e)}`)}finally{this.#t.get(t)===n&&this.#t.delete(t)}return{}}hasSession(e){return this.#t.has(e)}async joinSession(e,t){this.#i();let n=this.#t.get(e.sessionId);if(n===void 0)throw T(`session is not active: ${e.sessionId}`);let r=(await this.deps.persistence.stat(e.sessionId,{signal:t}))?.header;if(r===void 0)throw T(`unknown session: ${e.sessionId}`);if(!await B(r.cwd,e.cwd))throw T(`session cwd does not match: ${e.cwd}`);return{configOptions:await n.configOptions(t),updates:n.timelineFrom(0)}}async prompt(e,t){this.#i();let r=this.#a(e.sessionId),i=t??new AbortController().signal;try{let n=e._meta?.configOptionValues;if(typeof n==`object`&&n&&!Array.isArray(n)){let i=JSON.stringify(await r.configOptions(t));for(let[e,i]of Object.entries(n))await r.setConfigOption(e,i,t);let a=await r.configOptions(t);JSON.stringify(a)!==i&&await this.#e.notify({sessionId:e.sessionId,update:{sessionUpdate:`config_option_update`,configOptions:a}})}return await r.prompt(e,i)}catch(e){throw e instanceof n?e:e instanceof D?T(e.message):R(e)?T(e instanceof Error?e.message:String(e)):E(`prompt failed: ${String(e)}`)}}async#s(e,t){let n=ke(),r=0;for(;;)try{return await I.resume(this.deps,e,t)}catch(i){if(!Oe(i)||this.#r)throw i;if(r>=n){let t=i instanceof Error?i.message:String(i);throw we(e.sessionId,t)}let a=Math.min(500,n-r);await Ae(a,t),r+=a}}async loadSession(e,t){this.#i(),z(e);let n=e.sessionId;if(this.#t.has(n)||this.#n.has(n)||this.deps.sessionStore.get(n)!==void 0)throw T(`session is already active: ${n}`);this.#n.add(n);try{let r=(await this.deps.persistence.stat(n,{signal:t}))?.header;if(r===void 0)throw T(`unknown session: ${n}`);if(!await B(r.cwd,e.cwd))throw T(`session cwd does not match: ${e.cwd}`);if(r.origin===`subagent`){let r=await this.deps.persistence.openHistoryRead(n,t);try{let{events:i}=await r.read(t),a=new v,o=new Map,s=new _,c=0;for(let t of i){let r=b(t,{live:!1,journal:a,seen:o,subagents:s,supportsTerminalOutput:!1,cwd:e.cwd},()=>{});for(let e of r)await this.#e.notify({...e,sessionId:n});c+=r.length}return await this.#e.extNotify?.({method:`_tbox.cn/acp_replay_complete`,payload:{sessionId:n,notificationCount:c}}),{configOptions:[]}}finally{await r.close().catch(()=>{})}}if(r.parentSession!==void 0)throw T(`session is not loadable: ${n}`);let i=await this.deps.persistence.openHistoryRead(n,t),a;try{if(a=await this.#s({sessionId:n,cwd:e.cwd,mcpServers:e.mcpServers,notify:this.#o(n)},t),this.#r)throw E(`connection closed during session/load`);this.#t.set(n,a);let r=await a.replayHistory(i,t);return await this.#e.extNotify?.({method:`_tbox.cn/acp_replay_complete`,payload:{sessionId:n,notificationCount:r}}),a.refreshCommands().catch(()=>{}),{configOptions:await a.configOptions(t)}}catch(e){throw a!==void 0&&(this.#t.get(n)===a&&this.#t.delete(n),await a.close(`session/load activation failed`).catch(e=>{this.deps.logger.warn(`acp: session/load rollback close failed: ${String(e)}`)})),e}finally{await i.close().catch(()=>{})}}finally{this.#n.delete(n)}}broadcastCommandsChanged(){for(let e of this.#t.values())e.scheduleCommandsRefresh()}async setConfigOption(e,t){this.#i();let r=this.#a(e.sessionId);try{return{configOptions:await r.setConfigOption(e.configId,e.value,t)}}catch(e){throw e instanceof D?T(e.message):R(e)?T(e instanceof Error?e.message:String(e)):e instanceof n?e:E(`set config option failed: ${String(e)}`)}}async cancel(e){await this.#a(e).cancel()}async dispose(){if(this.#r)return;this.#r=!0;let e=[...this.#t.values()],t=await Promise.allSettled(e.map(e=>e.close(`ACP bridge disposed`)));for(let t of e)this.#t.get(t.session.id)===t&&this.#t.delete(t.session.id);let n=t.filter(e=>e.status===`rejected`);if(n.length>0)throw AggregateError(n.map(e=>e.reason),`ACP bridge teardown failed for ${n.length} session(s)`)}channelOf(e){return this.#t.get(e)}channelsAll(){return this.#t.values()}};function Ne(e,t){return e.createdAt<t.createdAt||e.createdAt===t.createdAt&&V(e.sessionId,t.sessionId)>0}var U=class extends Error{constructor(e){super(e),this.name=`McpConfigError`}};const Pe=/^[A-Za-z0-9_-]{1,32}$/;async function W(e,t,n){if(t==null)return;if(!Array.isArray(t))throw new U(`mcpServers must be an array`);let r=Fe(t,n);for(let t of r)await e.plugin(Se,t)}function Fe(e,t){if(!Array.isArray(e))throw new U(`mcpServers must be an array`);let n=new Set;return e.map((e,r)=>{let i=Ie(e.name,r);if(n.has(i))throw new U(`mcpServers contains duplicate normalized name: ${i}`);if(n.add(i),`type`in e?e.type===`stdio`:typeof e.command==`string`){if(!u(e.command))throw new U(`mcpServers[${r}].command must be an absolute path`);let n=e.args===void 0?[]:e.args;if(!Array.isArray(n)||n.some(e=>typeof e!=`string`))throw new U(`mcpServers[${r}].args must be an array of strings`);let a=G(e.env,`mcpServers[${r}].env`,`environment`);return{transport:`stdio`,serverName:i,command:e.command,args:n,env:a,cwd:t,failOnStartupError:!0}}if(`type`in e&&e.type===`http`||typeof e.url==`string`){if(typeof e.url!=`string`)throw new U(`mcpServers[${r}].url must be a string`);Le(e.url,`mcpServers[${r}].url`);let t=G(e.headers,`mcpServers[${r}].headers`,`header`);return{transport:`streamable-http`,serverName:i,url:e.url,headers:t,failOnStartupError:!0}}throw new U(`mcpServers[${r}] requires either command (stdio) or url (http)`)})}function G(e,t,n){if(e==null)return Object.create(null);if(!Array.isArray(e))throw new U(`${t} must be an array of {name, value} entries`);let r=Object.create(null),i=new Set;for(let a of e){let e=typeof a?.name==`string`?a.name:void 0,o=typeof a?.value==`string`?a.value:void 0;if(e===void 0||o===void 0)throw new U(`${t} contains an entry missing name or value`);if(n===`header`)try{be(e),xe(e,o)}catch{throw new U(`${t} contains an invalid header entry`)}else if(e.length===0||e.includes(`=`)||e.includes(`\0`)||o.includes(`\0`))throw new U(`${t} contains an invalid environment entry`);let s=n===`header`?e.toLowerCase():e;if(i.has(s))throw new U(`${t} contains duplicate name: ${e}`);i.add(s),r[e]=o}return r}function Ie(e,t){if(typeof e!=`string`||e.trim().length===0||/[\u0000-\u001f\u007f]/.test(e))throw new U(`mcpServers[${t}] contains an invalid server name`);return Pe.test(e)?e:`${e.normalize(`NFKD`).replace(/[^A-Za-z0-9_-]+/g,`_`).replace(/^_+|_+$/g,``).slice(0,20)||`server`}_${l(`sha256`).update(e).digest(`hex`).slice(0,8)}`.slice(0,32)}function Le(e,t){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw Error(`unsupported protocol`)}catch{throw new U(`${t} must be an absolute HTTP(S) URL`)}}function Re(e,t,n){n.sandboxOf(e)!==t.sandbox&&n.setSandbox(e,t.sandbox),n.approvalOf(e)!==t.approval&&n.setApproval(e,t.approval)}function K(e){return async(t,n)=>{let r=await e(t,`read`,n===void 0?void 0:{signal:n});return{read:async e=>({events:(e===void 0?await r.read():await r.read(0,void 0,{signal:e})).events}),close:()=>r.close()}}}const ze=`dsh-acp-full`,q=[`agents`,`llm`,`sessionPersistence`,`sessions`,`approval`,`commands`,`skills`,`agentDefaultModel`];function Be(n){return n?.stream??a(t.toWeb(process.stdout),e.toWeb(process.stdin))}async function J(e){await e.get(`loader`)?.await()}async function Ve(e){let t=e.get(`agentPresets`);if(t===void 0)return`standard`;let n=t.defaultId;if((await t.list()).some(e=>e.id===n&&e.broken===void 0))return n;let r=t.config.default;return n!==r&&e.logger.warn(`[tboxcode-preset] selectedDefault="${n}" 不在当前 profile roster,回退 ${r}`),r}async function Y(e,t,n){let r=e.get(`agentPresets`);if(r!==void 0)try{await r.mount(t,n)}catch(e){throw T(`agent preset "${n}" 不可用:${e instanceof Error?e.message:String(e)}`)}}function He(e,t){let n=t=>{try{return e.get(`sandboxPolicy`)?.resolve({session:t})?.mode}catch{return}},r=()=>{let t=e.agentDefaultModel.currentSelection();if(!(typeof t.provider!=`string`||typeof t.model!=`string`))return{provider:t.provider,model:t.model,...t.reasoningEffort===void 0?{}:{reasoningEffort:String(t.reasoningEffort)}}};return{async createAgent(t){await J(e);let n=await Ve(e),i=N(r());return e.agents.create({sessionId:t.sessionId,meta:{cwd:t.cwd,agentPreset:n},...i===void 0?{}:{agentOptions:i},signal:t.signal,setup:async(r,i)=>{await Y(e,r,n),await t.configureScope?.(r,i),await W(r,t.mcpServers,t.cwd)}})},async resumeAgent(t){await J(e);let n=N(r());return e.agents.resume({resumeSessionId:t.sessionId,...n===void 0?{}:{agentOptions:n},signal:t.signal,setup:async(n,r)=>{let i=r.session,a=e.get(`agentPresets`),o=null;try{o=a?.presetForSession?.(i)??null}catch{o=null}await Y(e,n,(typeof o==`string`&&o.length>0?o:null)??i.header.agentPreset??`standard`),await t.configureScope?.(n,r),await W(n,t.mcpServers,t.cwd)}})},persistence:{stat:async(t,n)=>{let r=await e.sessionPersistence.stat(t,n);return r===void 0?void 0:{header:r.header}},list:async t=>(await e.sessionPersistence.list(t)).map(e=>({header:e.header})),openHistoryRead:K((t,n,r)=>e.sessionPersistence.open(t,n,r))},llm:e.llm,sandboxModeOf:e=>n(e),applyModeKnobs:(t,r,i,a)=>{if(a?.initial===!0){Re(t,i,{sandboxOf:e=>n(e),approvalOf:t=>{try{return e.approval.overrideOf(t)??e.approval.config.policy??`ask`}catch{return}},setSandbox:(e,t)=>s(e,t),setApproval:(e,t)=>c(e,t)});return}s(t,i.sandbox),e.approval.setPolicy(r,i.approval)},executeCommand:async(t,n,r)=>e.commands.execute(t,n,[],r??new AbortController().signal),listCommands:async t=>e.commands.list(t),listUserInvocableSkills:async t=>(await e.skills.snapshot({cwd:t.session.header.cwd})).skills,onCommandSurfaceChanged:t=>{let n=e.on(`commands/change`,t),r=e.on(`skills/change`,t);return()=>{n(),r()}},sessionToolDenies:()=>t()?[]:[`ask_user_question`],defaultSelection:r,sessionStore:{get:t=>e.sessions.get(t),flush:async t=>{await e.sessions.flush(t)}},admitPromptContent:async t=>{let n=e.get(`attachments`);if(n===void 0)throw T(`image prompt content requires the mounted attachment service`);return await n.admitPromptContent(t)},admitImageUrls:async(t,n,r)=>{let i=e.get(`imageSources`);if(i===void 0)throw T(`image URL prompt content requires the mounted image source service`);try{return await i.admitUrls({sessionId:t,urls:n,...r?.names===void 0?{}:{names:r.names},...r?.signal===void 0?{}:{signal:r.signal}})}catch(e){throw T(e instanceof Error?e.message:String(e))}},readImage:async(t,n,r)=>{let i=e.get(`attachments`);if(i?.readImage!==void 0)try{let e=await i.readImage(n,r);return{mediaType:e.ref.mediaType,data:Buffer.from(e.data).toString(`base64`)}}catch(t){e.logger.warn(`acp: read image failed: ${String(t)}`);return}},logger:{warn:t=>e.logger.warn(t),info:t=>e.logger.info(t),debug:t=>e.logger.debug(t)},onSessionEvent:t=>e.on(`session/event`,t),onAssistantStream:t=>e.on(`agent/assistant-stream`,t),onInboxClaimed:t=>e.on(`agent/inbox/claimed`,t),onAgentError:t=>e.on(`agent/error`,t)}}function X(e){if(e instanceof U)return T(e.message);let t=e instanceof Error?e.message:String(e);return t.includes(`mcp-client(`)?T(t):e}function Z(e,t,n){return r({name:`tboxcode-dsh-acp`}).onRequest(i.agent.initialize,({params:n})=>(t.elicitationForm=Ue(n)?.elicitation!=null,e.initialize(n))).onRequest(i.agent.authenticate,async()=>(e.authenticate({}),{})).onRequest(i.agent.session.new,async({params:t,signal:n})=>{try{return await e.newSession(t,n)}catch(e){throw X(e)}}).onRequest(i.agent.session.list,async({params:t,signal:n})=>e.listSessions(t,n)).onRequest(i.agent.session.resume,async({params:t,signal:n})=>{try{return await e.resumeSession(t,n)}catch(e){throw X(e)}}).onRequest(i.agent.session.close,async({params:t})=>e.closeSession(t)).onRequest(i.agent.session.prompt,async({params:t,signal:r})=>{let i=t.sessionId??``;n?.beforePrompt?.(i);try{return await e.prompt(t,r)}finally{n?.afterPrompt?.(i)}}).onRequest(i.agent.session.load,async({params:t,signal:n})=>{try{return await e.loadSession(t,n)}catch(e){throw X(e)}}).onNotification(i.agent.session.cancel,async({params:t})=>e.cancel(t.sessionId)).onRequest(i.agent.session.setConfigOption,async({params:t,signal:n})=>{try{return await e.setConfigOption(t,n)}catch(e){throw X(e)}})}function Q(e,t){e.onSessionEvent((e,n)=>{let r=e.id,i=t.channelOf(r);if(i!==void 0){i.onSessionEvent(e,n);return}for(let e of t.channelsAll())if(e.tracksChild(r)){e.onChildEvent(r,n);break}}),e.onAssistantStream(({agent:e,frame:n})=>{for(let r of t.channelsAll())if(r.owns(e)){r.onAssistantStream(n);break}}),e.onInboxClaimed(({agent:e,message:n,turn:r})=>{for(let i of t.channelsAll())if(i.owns(e)){i.onInboxClaimed(n,r);break}}),e.onAgentError(({agent:e,error:n})=>{for(let r of t.channelsAll())if(r.owns(e)){r.onAgentError(n);break}}),e.onCommandSurfaceChanged(()=>t.broadcastCommandsChanged())}function $(e,t,n){let r={notify:async()=>{t.warn(`acp: io.notify called before connection wiring`)}},a=new H(e,r);return{app:Z(a,n),io:r,onConnection:(t,s)=>{r.notify=async e=>{await s.notify(i.client.session.update,e)},r.extNotify=async e=>{await s.notify(e.method,e.payload)},e.logger.debug(`acp: connection established`),Q(e,a),t.on(`user-questions/request`,((e,t)=>{if(n.elicitationForm===!1)return t();let r=a.channelOf(e.agent?.session?.id??``);if(r===void 0||e.questions.length===0)return t();let c=e.questions,l=c.length===1?c[0]?.question??`Input requested`:`Answer ${c.length} questions`;return r.drainUpdates().then(async()=>{let e=await s.request(i.client.elicitation.create,{mode:`form`,message:l,sessionId:r.session.id,requestedSchema:ae(c)});if(e.action!==`accept`)throw new o(`ask_user_question ${e.action===`decline`?`declined`:`cancelled`} by client`,e.action===`decline`?`ASK_DECLINED`:`ASK_ABORTED`);return pe(c,e.content??{})})})),t.on(`approval/request`,((e,t)=>{let n=a.channelOf(e.agent?.session?.id??``);if(n===void 0||e.callId===void 0)return t();let r=e.callId;return n.drainUpdates().then(async()=>{let e=await s.request(i.client.session.requestPermission,{sessionId:n.session.id,toolCall:{toolCallId:r},options:[{optionId:`allow-once`,name:`Allow once`,kind:`allow_once`},{optionId:`reject-once`,name:`Reject`,kind:`reject_once`}]});return e.outcome.outcome===`cancelled`?`cancelled`:e.outcome.optionId===`allow-once`?`allowed-once`:`rejected`})}))},dispose:()=>a.dispose()}}function Ue(e){return e?.clientCapabilities}function We(e,t){let n={elicitationForm:!1},r=He(e,()=>n.elicitationForm),i=$(r,e.logger,n),a=i.app.connect(Be(t));i.onConnection(e,a.client),r.logger.debug(`acp: connection established`);let o,s=()=>(o??=i.dispose().catch(t=>{e.logger.warn(`acp: connection-close teardown failed: ${String(t)}`)}),o);a.closed.catch(t=>{e.logger.warn(`acp: connection closed with an error: ${String(t)}`)}).then(s),e.effect(()=>s,`dsh-acp-full.connection`)}function Ge(e,t,n={}){let r={notify:async()=>{t.warn(`acp: shared io.notify called before router binding`)}},i=new H(e,r),a={elicitationForm:!1};return Q(e,i),{io:r,capsHolder:a,attachConnection(e,t){let n=Z(i,a,t).connect(e);return{client:n.client,closed:n.closed}},hasSession:e=>i.hasSession(e),joinSession:(e,t)=>i.joinSession(e,t),dispose:()=>i.dispose()}}export{k as IMAGE_PAYLOAD_BUDGET,A as ImageRenderState,j as MAX_IMAGE_URL_LENGTH,We as apply,$ as buildAgentApp,K as createHistoryReadPort,Ge as createSharedAcpCore,M as decodeImageUrl,q as inject,ze as name};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tbox.cn/dsh-acp-full",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.16",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "载体一:全功能 ACP server 插件(stdio / in-process 直调 Host 服务)",
|
|
6
6
|
"main": "./lib/index.js",
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@agentclientprotocol/sdk": "1.8.0",
|
|
13
13
|
"zod": "4.6.7",
|
|
14
|
-
"@tbox.cn/dsh-acp-bridge-core": "0.1.0-rc.
|
|
14
|
+
"@tbox.cn/dsh-acp-bridge-core": "0.1.0-rc.16"
|
|
15
15
|
},
|
|
16
16
|
"peerDependencies": {
|
|
17
17
|
"@deepseek-ai/cordis": "4.1.0",
|