@openma/deepseek-harness-acp 0.1.0-beta.0

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 ADDED
@@ -0,0 +1,1889 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __esm = (fn, res, err) => function __init() {
5
+ if (err) throw err[0];
6
+ try {
7
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ } catch (e) {
9
+ throw err = [e], e;
10
+ }
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name3 in all)
14
+ __defProp(target, name3, { get: all[name3], enumerable: true });
15
+ };
16
+
17
+ // src/bridge/self-harness.ts
18
+ var self_harness_exports = {};
19
+ __export(self_harness_exports, {
20
+ selfHarness: () => selfHarness
21
+ });
22
+ import { createUserMessage, errorChain } from "@deepseek-ai/dsh-llm";
23
+ import { SessionId } from "@deepseek-ai/dsh-session";
24
+ import { foldSessionTitle } from "@deepseek-ai/dsh-session-title";
25
+ import { SANDBOX_MODES, setSandboxMode } from "@deepseek-ai/dsh-sandbox-policy";
26
+ import { credentialRef } from "@deepseek-ai/dsh-credentials";
27
+ import * as mcpClient from "@deepseek-ai/dsh-mcp-client";
28
+ function selfHarness() {
29
+ return {
30
+ createUserMessage,
31
+ errorChain,
32
+ sessionId: SessionId,
33
+ foldSessionTitle,
34
+ setSandboxMode,
35
+ sandboxModes: SANDBOX_MODES,
36
+ credentialRef,
37
+ mcpClient
38
+ };
39
+ }
40
+ var init_self_harness = __esm({
41
+ "src/bridge/self-harness.ts"() {
42
+ "use strict";
43
+ }
44
+ });
45
+
46
+ // src/app.ts
47
+ var app_exports = {};
48
+ __export(app_exports, {
49
+ apply: () => apply2,
50
+ name: () => name2
51
+ });
52
+
53
+ // src/bridge/index.ts
54
+ var bridge_exports = {};
55
+ __export(bridge_exports, {
56
+ apply: () => apply,
57
+ inject: () => inject,
58
+ name: () => name
59
+ });
60
+ import { randomUUID } from "node:crypto";
61
+ import { isAbsolute } from "node:path";
62
+ import { Readable, Writable } from "node:stream";
63
+ import {
64
+ AgentSideConnection,
65
+ ndJsonStream,
66
+ PROTOCOL_VERSION,
67
+ RequestError
68
+ } from "@agentclientprotocol/sdk";
69
+
70
+ // src/version.ts
71
+ var VERSION = "0.1.0";
72
+
73
+ // src/log.ts
74
+ var PREFIX = "[dsh-acp]";
75
+ function logWarn(message) {
76
+ process.stderr.write(`${PREFIX} warn: ${message}
77
+ `);
78
+ }
79
+ function logError(message) {
80
+ process.stderr.write(`${PREFIX} error: ${message}
81
+ `);
82
+ }
83
+ function logDebug(message) {
84
+ if (process.env["DSH_ACP_DEBUG"]) process.stderr.write(`${PREFIX} debug: ${message}
85
+ `);
86
+ }
87
+
88
+ // src/bridge/translate.ts
89
+ var MAX_TITLE_LENGTH = 80;
90
+ var MAX_RESULT_TEXT = 2e4;
91
+ function firstLine(text, limit = MAX_TITLE_LENGTH) {
92
+ const line = text.split("\n", 1)[0] ?? "";
93
+ return line.length > limit ? `${line.slice(0, limit - 1)}\u2026` : line;
94
+ }
95
+ function asString(value) {
96
+ return typeof value === "string" && value.length > 0 ? value : void 0;
97
+ }
98
+ function pathLocations(args) {
99
+ const locations = [];
100
+ for (const key of ["path", "file_path", "filePath", "file"]) {
101
+ const path = asString(args[key]);
102
+ if (path !== void 0) {
103
+ locations.push({ path });
104
+ break;
105
+ }
106
+ }
107
+ return locations;
108
+ }
109
+ function classifyToolCall(name3, rawArguments) {
110
+ let args = {};
111
+ try {
112
+ const parsed = JSON.parse(rawArguments);
113
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
114
+ args = parsed;
115
+ }
116
+ } catch {
117
+ args = { arguments: rawArguments };
118
+ }
119
+ const locations = pathLocations(args);
120
+ const path = locations[0]?.path;
121
+ const facts = (kind, title) => ({
122
+ kind,
123
+ title,
124
+ locations,
125
+ rawInput: args
126
+ });
127
+ switch (name3) {
128
+ case "bash": {
129
+ const command = asString(args["command"]);
130
+ const restart = args["restart"] === true;
131
+ return facts("execute", command !== void 0 ? firstLine(command) : restart ? "Restart bash" : "bash");
132
+ }
133
+ case "read":
134
+ return facts("read", path !== void 0 ? `Read ${path}` : "Read file");
135
+ case "write":
136
+ return facts("edit", path !== void 0 ? `Write ${path}` : "Write file");
137
+ case "edit":
138
+ return facts("edit", path !== void 0 ? `Edit ${path}` : "Edit file");
139
+ case "str_replace_editor": {
140
+ const command = asString(args["command"]) ?? "edit";
141
+ const kind = command === "view" ? "read" : "edit";
142
+ return facts(kind, path !== void 0 ? `${command} ${path}` : command);
143
+ }
144
+ case "todo_write":
145
+ return facts("think", "Update plan");
146
+ case "subagent":
147
+ case "subagent_fork": {
148
+ const task = asString(args["task"]) ?? asString(args["prompt"]);
149
+ return facts("other", task !== void 0 ? `Subagent: ${firstLine(task, 60)}` : "Subagent");
150
+ }
151
+ case "skill": {
152
+ const skillName = asString(args["name"]) ?? asString(args["skill"]);
153
+ return facts("other", skillName !== void 0 ? `Skill: ${skillName}` : "Skill");
154
+ }
155
+ default:
156
+ break;
157
+ }
158
+ const lowered = name3.toLowerCase();
159
+ if (/(^|_)(grep|glob|find|search|ls|list)($|_)/.test(lowered)) {
160
+ const query = asString(args["query"]) ?? asString(args["pattern"]);
161
+ return facts("search", query !== void 0 ? `Search for '${firstLine(query, 50)}'` : name3);
162
+ }
163
+ if (/(fetch|web|http|browse)/.test(lowered)) {
164
+ const url = asString(args["url"]) ?? asString(args["query"]);
165
+ return facts("fetch", url !== void 0 ? `Fetch ${firstLine(url, 60)}` : name3);
166
+ }
167
+ if (/(job|task|run|exec)/.test(lowered)) return facts("execute", name3);
168
+ return facts("other", name3);
169
+ }
170
+ function diffsFromToolMeta(meta) {
171
+ if (meta === null || typeof meta !== "object") return [];
172
+ const diffs = meta["diffs"];
173
+ if (!Array.isArray(diffs)) return [];
174
+ const result = [];
175
+ for (const entry of diffs) {
176
+ if (entry === null || typeof entry !== "object") continue;
177
+ const diff = entry;
178
+ const path = asString(diff["path"]);
179
+ const newText = diff["newText"];
180
+ const oldText = diff["oldText"];
181
+ if (path === void 0 || typeof newText !== "string") continue;
182
+ result.push({ path, oldText: typeof oldText === "string" ? oldText : null, newText });
183
+ }
184
+ return result;
185
+ }
186
+ function extractToolResult(data) {
187
+ let failed = data["error"] !== void 0 && data["error"] !== null;
188
+ const parts = [];
189
+ const message = data["message"];
190
+ const content = message !== null && typeof message === "object" ? message["content"] : void 0;
191
+ if (Array.isArray(content)) {
192
+ for (const block of content) {
193
+ if (block === null || typeof block !== "object") continue;
194
+ const b = block;
195
+ if (b["type"] !== "tool-result") continue;
196
+ if (b["isError"] === true) failed = true;
197
+ const inner = b["content"];
198
+ if (!Array.isArray(inner)) continue;
199
+ for (const innerBlock of inner) {
200
+ if (innerBlock === null || typeof innerBlock !== "object") continue;
201
+ const ib = innerBlock;
202
+ if (ib["type"] === "text" && typeof ib["text"] === "string") parts.push(ib["text"]);
203
+ }
204
+ }
205
+ }
206
+ let text = parts.join("");
207
+ if (text.length > MAX_RESULT_TEXT) text = `${text.slice(0, MAX_RESULT_TEXT)}
208
+ \u2026 (truncated)`;
209
+ return { failed, text, diffs: diffsFromToolMeta(data["meta"]) };
210
+ }
211
+ function extractMessageTexts(message) {
212
+ const texts = [];
213
+ const reasoning = [];
214
+ const content = message !== null && typeof message === "object" ? message["content"] : void 0;
215
+ if (Array.isArray(content)) {
216
+ for (const block of content) {
217
+ if (block === null || typeof block !== "object") continue;
218
+ const b = block;
219
+ if (b["type"] === "text" && typeof b["text"] === "string") texts.push(b["text"]);
220
+ else if (b["type"] === "reasoning" && typeof b["text"] === "string") reasoning.push(b["text"]);
221
+ else if (b["type"] === "image") texts.push("[image attachment]");
222
+ }
223
+ }
224
+ return { text: texts.join(""), reasoning: reasoning.join("") };
225
+ }
226
+ function planEntries(data) {
227
+ const todos = data["todos"];
228
+ if (!Array.isArray(todos)) return [];
229
+ const entries = [];
230
+ for (const todo of todos) {
231
+ if (todo === null || typeof todo !== "object") continue;
232
+ const t = todo;
233
+ const content = asString(t["content"]);
234
+ const status = t["status"];
235
+ if (content === void 0) continue;
236
+ entries.push({
237
+ content,
238
+ priority: "medium",
239
+ status: status === "in_progress" || status === "completed" ? status : "pending"
240
+ });
241
+ }
242
+ return entries;
243
+ }
244
+ function turnEndToStopReason(reason) {
245
+ switch (reason?.kind) {
246
+ case "completed":
247
+ return "end_turn";
248
+ case "max-tokens":
249
+ return "max_tokens";
250
+ case "blocked":
251
+ return "refusal";
252
+ case "interrupted":
253
+ return "cancelled";
254
+ case "aborted": {
255
+ const cause = reason.reason?.kind;
256
+ return cause === "user" || cause === "disposed" ? "cancelled" : "end_turn";
257
+ }
258
+ default:
259
+ return "end_turn";
260
+ }
261
+ }
262
+ function emptyWindow() {
263
+ return {
264
+ usage: { input: 0, output: 0, cachedRead: 0, cachedWrite: 0, thought: 0 },
265
+ sawUsage: false,
266
+ turnEnds: /* @__PURE__ */ new Map(),
267
+ lastTurnEnd: void 0,
268
+ error: void 0
269
+ };
270
+ }
271
+ var SessionProjection = class {
272
+ /** Context capacity from the latest `request/context` event, when known. */
273
+ contextWindow;
274
+ /** Latest `session/title` text observed on the log. */
275
+ title;
276
+ streamedText = /* @__PURE__ */ new Set();
277
+ streamedReasoning = /* @__PURE__ */ new Set();
278
+ toolCalls = /* @__PURE__ */ new Map();
279
+ window = emptyWindow();
280
+ lastContextUse;
281
+ constructor(contextWindow) {
282
+ this.contextWindow = contextWindow;
283
+ }
284
+ /** Reset per-prompt accumulators; call when a new `session/prompt` starts. */
285
+ beginPrompt() {
286
+ this.window = emptyWindow();
287
+ }
288
+ /** The captured ending for a specific turn, when it already ended. */
289
+ turnEndFor(turn) {
290
+ return this.window.turnEnds.get(turn);
291
+ }
292
+ /** The last turn ending inside the current prompt window. */
293
+ get lastTurnEnd() {
294
+ return this.window.lastTurnEnd;
295
+ }
296
+ /** The first failed-turn error inside the current prompt window. */
297
+ get turnError() {
298
+ return this.window.error;
299
+ }
300
+ /** Accumulated ACP usage for the current prompt window. */
301
+ promptUsage() {
302
+ if (!this.window.sawUsage) return void 0;
303
+ const { input, output, cachedRead, cachedWrite, thought } = this.window.usage;
304
+ return {
305
+ totalTokens: input + output + cachedRead + cachedWrite,
306
+ inputTokens: input,
307
+ outputTokens: output,
308
+ ...thought > 0 ? { thoughtTokens: thought } : {},
309
+ ...cachedRead > 0 ? { cachedReadTokens: cachedRead } : {},
310
+ ...cachedWrite > 0 ? { cachedWriteTokens: cachedWrite } : {}
311
+ };
312
+ }
313
+ /**
314
+ * Project one session event onto zero or more ACP updates.
315
+ */
316
+ onEvent(event) {
317
+ const data = event.data ?? {};
318
+ switch (event.type) {
319
+ case "assistant/chunk":
320
+ return this.onChunk(data);
321
+ case "assistant/message":
322
+ return this.onAssistantMessage(data);
323
+ case "tool/call":
324
+ return this.onToolCall(data);
325
+ case "tool/result":
326
+ return this.onToolResult(data);
327
+ case "todo/write": {
328
+ const entries = planEntries(data);
329
+ return entries.length > 0 ? [{ sessionUpdate: "plan", entries }] : [];
330
+ }
331
+ case "turn/end":
332
+ return this.onTurnEnd(data);
333
+ case "request/context": {
334
+ const contextWindow = data["contextWindow"];
335
+ if (typeof contextWindow === "number" && contextWindow > 0) this.contextWindow = contextWindow;
336
+ return [];
337
+ }
338
+ case "session/title": {
339
+ const title = asString(data["title"]);
340
+ if (title === void 0 || title === this.title) return [];
341
+ this.title = title;
342
+ return [{ sessionUpdate: "session_info_update", title, updatedAt: (/* @__PURE__ */ new Date()).toISOString() }];
343
+ }
344
+ default:
345
+ return [];
346
+ }
347
+ }
348
+ stepKey(data) {
349
+ return `${String(data["turn"])}:${String(data["step"])}`;
350
+ }
351
+ onChunk(data) {
352
+ const chunk = data["chunk"];
353
+ if (chunk === null || typeof chunk === "undefined" || typeof chunk !== "object") return [];
354
+ const c = chunk;
355
+ const text = c["text"];
356
+ if (typeof text !== "string" || text.length === 0) return [];
357
+ if (c["type"] === "text-delta") {
358
+ this.streamedText.add(this.stepKey(data));
359
+ return [{ sessionUpdate: "agent_message_chunk", content: { type: "text", text } }];
360
+ }
361
+ if (c["type"] === "reasoning-delta") {
362
+ this.streamedReasoning.add(this.stepKey(data));
363
+ return [{ sessionUpdate: "agent_thought_chunk", content: { type: "text", text } }];
364
+ }
365
+ return [];
366
+ }
367
+ onAssistantMessage(data) {
368
+ const updates = [];
369
+ const key = this.stepKey(data);
370
+ const { text, reasoning } = extractMessageTexts(data["message"]);
371
+ if (reasoning.length > 0 && !this.streamedReasoning.has(key)) {
372
+ updates.push({ sessionUpdate: "agent_thought_chunk", content: { type: "text", text: reasoning } });
373
+ }
374
+ if (text.length > 0 && !this.streamedText.has(key)) {
375
+ updates.push({ sessionUpdate: "agent_message_chunk", content: { type: "text", text } });
376
+ }
377
+ this.streamedText.delete(key);
378
+ this.streamedReasoning.delete(key);
379
+ const usage = data["usage"];
380
+ if (usage !== null && typeof usage === "object") {
381
+ const u = usage;
382
+ const num = (v) => typeof v === "number" && Number.isFinite(v) && v > 0 ? v : 0;
383
+ const input = num(u["inputTokens"]);
384
+ const output = num(u["outputTokens"]);
385
+ const cachedRead = num(u["cacheReadTokens"]);
386
+ const cachedWrite = num(u["cacheWriteTokens"]);
387
+ this.window.usage.input += input;
388
+ this.window.usage.output += output;
389
+ this.window.usage.cachedRead += cachedRead;
390
+ this.window.usage.cachedWrite += cachedWrite;
391
+ this.window.usage.thought += num(u["reasoningTokens"]);
392
+ this.window.sawUsage = true;
393
+ this.lastContextUse = input + cachedRead + cachedWrite + output;
394
+ if (this.contextWindow !== void 0 && this.lastContextUse > 0) {
395
+ updates.push({
396
+ sessionUpdate: "usage_update",
397
+ used: this.lastContextUse,
398
+ size: this.contextWindow
399
+ });
400
+ }
401
+ }
402
+ return updates;
403
+ }
404
+ onToolCall(data) {
405
+ const callId = asString(data["callId"]);
406
+ const name3 = asString(data["name"]) ?? "tool";
407
+ if (callId === void 0) return [];
408
+ const rawArguments = typeof data["arguments"] === "string" ? data["arguments"] : "{}";
409
+ const facts = classifyToolCall(name3, rawArguments);
410
+ this.toolCalls.set(callId, facts);
411
+ return [
412
+ {
413
+ sessionUpdate: "tool_call",
414
+ toolCallId: callId,
415
+ title: facts.title,
416
+ name: name3,
417
+ kind: facts.kind,
418
+ status: "in_progress",
419
+ rawInput: facts.rawInput,
420
+ ...facts.locations.length > 0 ? { locations: facts.locations } : {}
421
+ }
422
+ ];
423
+ }
424
+ onToolResult(data) {
425
+ const message = data["message"];
426
+ const callId = asString(
427
+ message !== null && typeof message === "object" ? (() => {
428
+ const content2 = message["content"];
429
+ if (!Array.isArray(content2)) return void 0;
430
+ const block = content2.find(
431
+ (b) => b !== null && typeof b === "object" && b["type"] === "tool-result"
432
+ );
433
+ return block === void 0 ? void 0 : block["toolCallId"];
434
+ })() : void 0
435
+ ) ?? asString(data["callId"]);
436
+ if (callId === void 0) return [];
437
+ const { failed, text, diffs } = extractToolResult(data);
438
+ const content = diffs.map((diff) => ({
439
+ type: "diff",
440
+ path: diff.path,
441
+ ...diff.oldText !== null ? { oldText: diff.oldText } : {},
442
+ newText: diff.newText
443
+ }));
444
+ if (text.length > 0 && diffs.length === 0) {
445
+ const block = { type: "text", text };
446
+ content.push({ type: "content", content: block });
447
+ }
448
+ this.toolCalls.delete(callId);
449
+ return [
450
+ {
451
+ sessionUpdate: "tool_call_update",
452
+ toolCallId: callId,
453
+ status: failed ? "failed" : "completed",
454
+ ...content.length > 0 ? { content } : {},
455
+ ...text.length > 0 ? { rawOutput: { output: text, isError: failed } } : {}
456
+ }
457
+ ];
458
+ }
459
+ onTurnEnd(data) {
460
+ const reason = data["reason"];
461
+ const turn = data["turn"];
462
+ if (reason !== null && typeof reason === "object") {
463
+ const r = reason;
464
+ if (typeof turn === "number") this.window.turnEnds.set(turn, r);
465
+ this.window.lastTurnEnd = r;
466
+ if (r.kind === "error" && this.window.error === void 0) {
467
+ this.window.error = { message: r.error?.message ?? "model turn failed" };
468
+ }
469
+ }
470
+ return [];
471
+ }
472
+ };
473
+
474
+ // src/bridge/history.ts
475
+ function userText(data) {
476
+ if (data === void 0) return void 0;
477
+ const source = data["source"];
478
+ const kind = source !== null && typeof source === "object" ? source["kind"] : void 0;
479
+ if (kind !== "user") return void 0;
480
+ const content = data["content"];
481
+ if (!Array.isArray(content)) return void 0;
482
+ const parts = [];
483
+ for (const block of content) {
484
+ if (block !== null && typeof block === "object") {
485
+ const b = block;
486
+ if (b["type"] === "text" && typeof b["text"] === "string") parts.push(b["text"]);
487
+ }
488
+ }
489
+ const text = parts.join("");
490
+ return text.length > 0 ? text : void 0;
491
+ }
492
+ function buildReplay(events) {
493
+ const projection = new SessionProjection();
494
+ const updates = [];
495
+ let plan;
496
+ let title;
497
+ for (const event of events) {
498
+ if (event.type === "user/message") {
499
+ const text = userText(event.data);
500
+ if (text !== void 0) {
501
+ updates.push({ sessionUpdate: "user_message_chunk", content: { type: "text", text } });
502
+ }
503
+ continue;
504
+ }
505
+ if (event.type === "session/title") {
506
+ const t = event.data?.["title"];
507
+ if (typeof t === "string" && t.length > 0) title = t;
508
+ continue;
509
+ }
510
+ for (const update of projection.onEvent(event)) {
511
+ if (update.sessionUpdate === "usage_update") continue;
512
+ if (update.sessionUpdate === "plan") {
513
+ plan = update;
514
+ continue;
515
+ }
516
+ updates.push(update);
517
+ }
518
+ }
519
+ if (plan !== void 0) updates.push(plan);
520
+ return { updates, title, contextWindow: projection.contextWindow };
521
+ }
522
+
523
+ // src/bridge/prompt.ts
524
+ var UnsupportedPromptContentError = class extends Error {
525
+ constructor(contentType) {
526
+ super(`unsupported prompt content type: ${contentType}`);
527
+ this.contentType = contentType;
528
+ }
529
+ contentType;
530
+ };
531
+ function contextBlock(uri, text) {
532
+ return `<context ref=${JSON.stringify(uri)}>
533
+ ${text}
534
+ </context>`;
535
+ }
536
+ function convertPrompt(prompt) {
537
+ const parts = [];
538
+ const display = [];
539
+ for (const block of prompt) {
540
+ switch (block.type) {
541
+ case "text":
542
+ parts.push(block.text);
543
+ display.push(block.text);
544
+ break;
545
+ case "resource_link":
546
+ parts.push(`
547
+ [resource_link name=${JSON.stringify(block.name)} uri=${JSON.stringify(block.uri)}]
548
+ `);
549
+ display.push(`@${block.name}`);
550
+ break;
551
+ case "resource": {
552
+ const resource = block.resource;
553
+ if ("text" in resource && typeof resource.text === "string") {
554
+ parts.push(`
555
+ ${contextBlock(resource.uri, resource.text)}
556
+ `);
557
+ display.push(`@${resource.uri}`);
558
+ break;
559
+ }
560
+ throw new UnsupportedPromptContentError("resource (binary)");
561
+ }
562
+ default:
563
+ throw new UnsupportedPromptContentError(block.type);
564
+ }
565
+ }
566
+ const text = parts.join("");
567
+ return {
568
+ blocks: text.length > 0 ? [{ type: "text", text }] : [],
569
+ displayText: display.join(" ").trim()
570
+ };
571
+ }
572
+
573
+ // src/bridge/index.ts
574
+ var name = "acp-bridge";
575
+ var inject = ["agents"];
576
+ function invalidParams(detail) {
577
+ return RequestError.invalidParams(void 0, detail);
578
+ }
579
+ function internalError(detail) {
580
+ return RequestError.internalError(void 0, detail);
581
+ }
582
+ function authRequired(detail) {
583
+ return RequestError.authRequired(void 0, detail);
584
+ }
585
+ function envCredentialPresent() {
586
+ return Boolean(process.env["DEEPSEEK_API_KEY"] || process.env["DEEPSEEK_BASE_URL"]);
587
+ }
588
+ var MODE_LABELS = {
589
+ "read-only": { name: "Read-only", description: "Bash and file mutations are denied by the sandbox" },
590
+ "workspace-write": {
591
+ name: "Workspace write",
592
+ description: "Writes are confined to the session workspace; wider access asks for permission"
593
+ },
594
+ "danger-full-access": {
595
+ name: "Full access",
596
+ description: "No sandbox confinement and no permission prompts"
597
+ }
598
+ };
599
+ async function apply(ctx, config = {}) {
600
+ const agents = ctx.agents;
601
+ const harness = config.harness ?? (await Promise.resolve().then(() => (init_self_harness(), self_harness_exports))).selfHarness();
602
+ const { createUserMessage: createUserMessage2, errorChain: errorChain2, sessionId: SessionId2, foldSessionTitle: foldSessionTitle2, setSandboxMode: setSandboxMode2 } = harness;
603
+ const SANDBOX_MODES2 = harness.sandboxModes;
604
+ const sessions = /* @__PURE__ */ new Map();
605
+ let closed = false;
606
+ let conn;
607
+ const modelCandidates = () => {
608
+ const seen = /* @__PURE__ */ new Set();
609
+ if (config.model !== void 0) seen.add(config.model);
610
+ for (const model of config.models ?? []) if (model.trim().length > 0) seen.add(model.trim());
611
+ return [...seen];
612
+ };
613
+ const defaultSelection = () => {
614
+ const service = ctx.get("agentDefaultModel");
615
+ if (service === void 0) return {};
616
+ try {
617
+ return service.currentSelection();
618
+ } catch (error) {
619
+ logDebug(`agentDefaultModel.currentSelection failed: ${String(error)}`);
620
+ return {};
621
+ }
622
+ };
623
+ const defaultProvider = () => config.provider ?? defaultSelection().provider;
624
+ const encodeChoice = (provider, model) => provider === void 0 || provider === defaultProvider() ? model : `${provider}::${model}`;
625
+ const decodeChoice = (value) => {
626
+ const i = value.indexOf("::");
627
+ if (i <= 0) return { provider: defaultProvider(), model: value };
628
+ return { provider: value.slice(0, i), model: value.slice(i + 2) };
629
+ };
630
+ let liveCatalog;
631
+ const discoverModels = async () => {
632
+ if (liveCatalog !== void 0) return liveCatalog;
633
+ const llm = ctx.get("llm");
634
+ const found = [];
635
+ if (llm !== void 0) {
636
+ try {
637
+ const providers = llm.listProviders();
638
+ const multi = providers.length > 1;
639
+ for (const provider of providers) {
640
+ const models = await llm.listModels(provider.id).catch((error) => {
641
+ logDebug(`listModels(${provider.id}) failed: ${String(error)}`);
642
+ return [];
643
+ });
644
+ for (const model of models) {
645
+ found.push({
646
+ provider: provider.id,
647
+ model: model.id,
648
+ label: multi ? `${model.name} (${provider.name})` : model.name
649
+ });
650
+ }
651
+ }
652
+ } catch (error) {
653
+ logDebug(`model discovery failed: ${String(error)}`);
654
+ }
655
+ }
656
+ liveCatalog = found;
657
+ return found;
658
+ };
659
+ ctx.on("llm/adapters-updated", () => {
660
+ liveCatalog = void 0;
661
+ });
662
+ const credentialPresent = async () => {
663
+ if (envCredentialPresent()) return true;
664
+ const brand = harness.credentialRef;
665
+ if (brand === void 0) return false;
666
+ const deadline = Date.now() + 5e3;
667
+ for (; ; ) {
668
+ const seam = ctx.get("credentials");
669
+ if (seam !== void 0) {
670
+ try {
671
+ return await seam.resolve(brand("DEEPSEEK_API_KEY")) !== void 0;
672
+ } catch (error) {
673
+ logWarn(`credential lookup failed: ${String(error)}`);
674
+ return false;
675
+ }
676
+ }
677
+ if (Date.now() >= deadline) {
678
+ logDebug("credential gate: no credentials service registered within 5s");
679
+ return false;
680
+ }
681
+ await new Promise((resolve2) => setTimeout(resolve2, 100));
682
+ }
683
+ };
684
+ const agentOptionsFor = (model, provider) => ({
685
+ ...provider !== void 0 ? { provider } : config.provider !== void 0 ? { provider: config.provider } : {},
686
+ ...model !== void 0 ? { model } : {},
687
+ ...config.maxTokens !== void 0 ? { maxTokens: config.maxTokens } : {}
688
+ });
689
+ const ownedRecord = (agent) => {
690
+ const record = sessions.get(String(agent.session.id));
691
+ return record?.agent === agent ? record : void 0;
692
+ };
693
+ const requireSession = (sessionId) => {
694
+ const record = sessions.get(sessionId);
695
+ if (record === void 0) throw invalidParams(`unknown session: ${sessionId}`);
696
+ return record;
697
+ };
698
+ const assertOpen = () => {
699
+ if (closed) throw internalError("the ACP bridge has been disposed");
700
+ };
701
+ const notify = (sessionId, update) => {
702
+ void conn.sessionUpdate({ sessionId, update }).catch((error) => {
703
+ logWarn(`session/update failed: ${String(error)}`);
704
+ });
705
+ };
706
+ const settlePrompt = (record, reason) => {
707
+ const inflight = record.inflight;
708
+ if (inflight === void 0) return;
709
+ record.inflight = void 0;
710
+ inflight.resolve(reason);
711
+ };
712
+ const modeState = (record) => ({
713
+ currentModeId: record.modeId,
714
+ availableModes: SANDBOX_MODES2.map((mode) => {
715
+ const label = MODE_LABELS[mode] ?? { name: mode, description: "" };
716
+ return { id: mode, name: label.name, description: label.description };
717
+ })
718
+ });
719
+ const configOptions = async (record) => {
720
+ const seen = /* @__PURE__ */ new Set();
721
+ const options = [];
722
+ const push = (value, name3) => {
723
+ if (seen.has(value)) return;
724
+ seen.add(value);
725
+ options.push({ value, name: name3 });
726
+ };
727
+ const current = encodeChoice(
728
+ record.provider,
729
+ record.model ?? config.model ?? defaultSelection().model ?? record.agent.options.model ?? ""
730
+ );
731
+ if (current.length === 0) return [];
732
+ const discovered = await discoverModels();
733
+ push(current, discovered.find((c) => encodeChoice(c.provider, c.model) === current)?.label ?? current);
734
+ for (const choice of discovered) {
735
+ push(encodeChoice(choice.provider, choice.model), choice.label);
736
+ }
737
+ for (const model of modelCandidates()) push(encodeChoice(void 0, model), model);
738
+ if (options.length < 2) return [];
739
+ return [
740
+ {
741
+ type: "select",
742
+ id: "model",
743
+ name: "Model",
744
+ category: "model",
745
+ currentValue: current,
746
+ options
747
+ }
748
+ ];
749
+ };
750
+ const publishCommands = (sessionId) => {
751
+ notify(sessionId, {
752
+ sessionUpdate: "available_commands_update",
753
+ availableCommands: [
754
+ { name: "status", description: "Show adapter, model, mode, and token status" },
755
+ {
756
+ name: "login",
757
+ description: "Save a DeepSeek API key into the harness credential store (~/.dsh/.credentials.yaml)",
758
+ input: { hint: "<api-key>" }
759
+ },
760
+ { name: "logout", description: "Remove the API key stored in the harness credential store" }
761
+ ]
762
+ });
763
+ };
764
+ const credentialStore = () => {
765
+ const brand = harness.credentialRef;
766
+ const store = ctx.get("credentials");
767
+ if (brand === void 0 || store === void 0) return void 0;
768
+ return { store, ref: brand("DEEPSEEK_API_KEY") };
769
+ };
770
+ const maskKey = (value) => value.length <= 8 ? "\u2026" : `${value.slice(0, 4)}\u2026${value.slice(-4)}`;
771
+ const describeCredential = async () => {
772
+ if (envCredentialPresent()) {
773
+ const viaEnv = process.env["DEEPSEEK_API_KEY"] !== void 0 ? "DEEPSEEK_API_KEY" : "DEEPSEEK_BASE_URL";
774
+ return `process environment (${viaEnv})`;
775
+ }
776
+ const cs = credentialStore();
777
+ if (cs === void 0) return "not configured";
778
+ try {
779
+ const info = await cs.store.describe(cs.ref);
780
+ if (!info.configured) return "not configured";
781
+ return info.source ?? "credential store";
782
+ } catch (error) {
783
+ logWarn(`credential describe failed: ${String(error)}`);
784
+ return "unknown";
785
+ }
786
+ };
787
+ const loginText = async (rawArgument) => {
788
+ const key = rawArgument.trim();
789
+ const cs = credentialStore();
790
+ if (cs === void 0) {
791
+ return "This composition has no writable credential store; export DEEPSEEK_API_KEY in the environment that launches the agent instead.";
792
+ }
793
+ if (key.length === 0) {
794
+ return [
795
+ "Usage: `/login <api-key>` \u2014 stores the key in the harness credential store",
796
+ "(`~/.dsh/.credentials.yaml`, the same file the dsh Web UI writes; mode 600).",
797
+ "",
798
+ `Current credential source: ${await describeCredential()}.`,
799
+ "",
800
+ "Note: text entered here also lands in your client's chat history. If you",
801
+ "prefer to keep the key out of it, save the key in the dsh Web UI instead."
802
+ ].join("\n");
803
+ }
804
+ try {
805
+ await cs.store.set(cs.ref, key);
806
+ } catch (error) {
807
+ return [
808
+ `Could not store the key: ${error instanceof Error ? error.message : String(error)}`,
809
+ "",
810
+ "A read-only source (usually the process environment) is currently supplying",
811
+ "this credential, so a stored value would be shadowed. Unset DEEPSEEK_API_KEY",
812
+ "in the launching environment, or keep using it as the credential."
813
+ ].join("\n");
814
+ }
815
+ return `Saved DEEPSEEK_API_KEY (${maskKey(key)}) to the harness credential store \u2014 source now: ${await describeCredential()}. The dsh Web UI sees the same key.`;
816
+ };
817
+ const logoutText = async () => {
818
+ const cs = credentialStore();
819
+ if (cs === void 0) return "This composition has no writable credential store; nothing to remove.";
820
+ try {
821
+ await cs.store.unset(cs.ref);
822
+ } catch (error) {
823
+ return `Could not remove the stored key: ${error instanceof Error ? error.message : String(error)}`;
824
+ }
825
+ const remaining = await describeCredential();
826
+ return remaining === "not configured" ? "Removed the stored DEEPSEEK_API_KEY. No credential is configured now." : `Removed the stored DEEPSEEK_API_KEY; requests now authenticate via: ${remaining}.`;
827
+ };
828
+ const statusText = async (record) => {
829
+ const used = record.projection.contextWindow;
830
+ const lines = [
831
+ `**dsh-acp** ${VERSION} \u2014 DeepSeek Harness ACP bridge`,
832
+ "",
833
+ `| | |`,
834
+ `|---|---|`,
835
+ `| Provider | ${record.provider ?? defaultProvider() ?? "(composition default)"} |`,
836
+ `| Model | ${record.model ?? config.model ?? defaultSelection().model ?? record.agent.options.model ?? "(composition default)"} |`,
837
+ `| Credential | ${await describeCredential()} |`,
838
+ `| Permission mode | ${record.modeId} |`,
839
+ `| Workspace | ${record.agent.session.header.cwd ?? process.cwd()} |`,
840
+ `| Session | ${String(record.agent.session.id)} |`,
841
+ ...used !== void 0 ? [`| Context window | ${used.toLocaleString()} tokens |`] : []
842
+ ];
843
+ return lines.join("\n");
844
+ };
845
+ const registerRecord = (sessionId, agent, dispose, model, modeId, projection) => {
846
+ const record = {
847
+ agent,
848
+ dispose,
849
+ projection: projection ?? new SessionProjection(),
850
+ modeId,
851
+ model,
852
+ cancelled: false,
853
+ inflight: void 0
854
+ };
855
+ sessions.set(sessionId, record);
856
+ return record;
857
+ };
858
+ ctx.on("session/event", (session, event) => {
859
+ const sessionId = String(session.header.id);
860
+ const record = sessions.get(sessionId);
861
+ if (record === void 0 || record.agent.session !== session) return;
862
+ try {
863
+ for (const update of record.projection.onEvent(event)) {
864
+ notify(sessionId, update);
865
+ }
866
+ } finally {
867
+ const inflight = record.inflight;
868
+ if (inflight !== void 0 && event.type === "turn/end" && inflight.turn === event.data.turn) {
869
+ if (event.data.reason.kind === "error") {
870
+ record.inflight = void 0;
871
+ inflight.reject(internalError(`turn failed: ${event.data.reason.error.message}`));
872
+ }
873
+ }
874
+ }
875
+ });
876
+ ctx.on("agent/inbox/claimed", ({ agent, message, turn }) => {
877
+ const record = ownedRecord(agent);
878
+ const inflight = record?.inflight;
879
+ if (inflight !== void 0 && inflight.messageId === message.id) inflight.turn = turn;
880
+ });
881
+ ctx.on("agent/error", ({ agent, turn, error }) => {
882
+ const record = ownedRecord(agent);
883
+ const inflight = record?.inflight;
884
+ if (record === void 0 || inflight === void 0 || inflight.turn === turn) return;
885
+ record.inflight = void 0;
886
+ inflight.reject(internalError(`turn failed: ${errorChain2(error)}`));
887
+ });
888
+ ctx.on("approval/request", (request, next) => {
889
+ const record = ownedRecord(request.agent);
890
+ if (record === void 0 || request.callId === void 0) return next();
891
+ return conn.requestPermission({
892
+ sessionId: String(record.agent.session.id),
893
+ toolCall: { toolCallId: request.callId },
894
+ options: [
895
+ { optionId: "allow-once", name: "Allow once", kind: "allow_once" },
896
+ { optionId: "allow-always", name: "Always allow (this session)", kind: "allow_always" },
897
+ { optionId: "reject-once", name: "Reject", kind: "reject_once" }
898
+ ]
899
+ }).then(({ outcome }) => {
900
+ if (outcome.outcome === "cancelled") return "cancelled";
901
+ if (outcome.optionId === "allow-always") {
902
+ try {
903
+ ctx.get("approval")?.setPolicy?.(record.agent, "never");
904
+ } catch (error) {
905
+ logWarn(`approval policy switch failed: ${String(error)}`);
906
+ }
907
+ return "allowed-once";
908
+ }
909
+ return outcome.optionId === "allow-once" ? "allowed-once" : "rejected";
910
+ });
911
+ });
912
+ const makeAgent = (connection) => {
913
+ conn = connection;
914
+ return {
915
+ initialize(params) {
916
+ const hasPersistence = ctx.get("sessionPersistence") !== void 0;
917
+ const requested = params.protocolVersion;
918
+ return Promise.resolve({
919
+ protocolVersion: typeof requested === "number" && requested >= 1 && requested < PROTOCOL_VERSION ? requested : PROTOCOL_VERSION,
920
+ agentInfo: { name: "dsh-acp", title: "DeepSeek Harness", version: VERSION },
921
+ agentCapabilities: {
922
+ loadSession: hasPersistence,
923
+ promptCapabilities: { image: false, audio: false, embeddedContext: true },
924
+ // Stdio servers always work; streamable HTTP maps onto
925
+ // mcp-client's second transport. Legacy SSE does not.
926
+ mcpCapabilities: { http: true, sse: false },
927
+ ...hasPersistence ? { sessionCapabilities: { list: {} } } : {}
928
+ },
929
+ authMethods: []
930
+ });
931
+ },
932
+ async authenticate(_params) {
933
+ if (!await credentialPresent()) {
934
+ throw authRequired(
935
+ "no DeepSeek credential found: save one in the dsh Web UI (Settings \u2192 Models) or set DEEPSEEK_API_KEY"
936
+ );
937
+ }
938
+ },
939
+ async newSession(params) {
940
+ assertOpen();
941
+ validateCwd(params.cwd);
942
+ syncMcpServers(params.mcpServers, params.cwd);
943
+ const sessionId = SessionId2(randomUUID());
944
+ const handle = await agents.create({
945
+ sessionId,
946
+ meta: { cwd: params.cwd },
947
+ agentOptions: agentOptionsFor(config.model)
948
+ });
949
+ if (closed) {
950
+ await handle.dispose();
951
+ throw internalError("connection closed during session/new");
952
+ }
953
+ const record = registerRecord(
954
+ String(sessionId),
955
+ handle.agent,
956
+ () => handle.dispose(),
957
+ config.model,
958
+ config.permissionMode ?? "workspace-write"
959
+ );
960
+ queueMicrotask(() => publishCommands(String(sessionId)));
961
+ const options = await configOptions(record);
962
+ return {
963
+ sessionId: String(sessionId),
964
+ modes: modeState(record),
965
+ ...options.length > 0 ? { configOptions: options } : {}
966
+ };
967
+ },
968
+ async loadSession(params) {
969
+ assertOpen();
970
+ validateCwd(params.cwd);
971
+ syncMcpServers(params.mcpServers, params.cwd);
972
+ const persistence = requirePersistence();
973
+ const sessionId = params.sessionId;
974
+ const existing = sessions.get(sessionId);
975
+ if (existing !== void 0) {
976
+ sessions.delete(sessionId);
977
+ existing.agent.cancel({ kind: "user" });
978
+ settlePrompt(existing, "cancelled");
979
+ await existing.dispose().catch((error) => {
980
+ logWarn(`dispose before reload failed: ${String(error)}`);
981
+ });
982
+ }
983
+ let events;
984
+ try {
985
+ ({ events } = await persistence.inspect(SessionId2(sessionId)));
986
+ } catch (error) {
987
+ throw invalidParams(`session not found: ${sessionId} (${errorChain2(error)})`);
988
+ }
989
+ const replay = buildReplay(events);
990
+ for (const update of replay.updates) notify(sessionId, update);
991
+ if (replay.title !== void 0) {
992
+ notify(sessionId, {
993
+ sessionUpdate: "session_info_update",
994
+ title: replay.title
995
+ });
996
+ }
997
+ const handle = await agents.resume({
998
+ resumeSessionId: SessionId2(sessionId),
999
+ agentOptions: agentOptionsFor(config.model)
1000
+ });
1001
+ const projection = new SessionProjection(replay.contextWindow);
1002
+ projection.title = replay.title;
1003
+ const record = registerRecord(
1004
+ sessionId,
1005
+ handle.agent,
1006
+ () => handle.dispose(),
1007
+ config.model,
1008
+ config.permissionMode ?? "workspace-write",
1009
+ projection
1010
+ );
1011
+ queueMicrotask(() => publishCommands(sessionId));
1012
+ const options = await configOptions(record);
1013
+ return {
1014
+ modes: modeState(record),
1015
+ ...options.length > 0 ? { configOptions: options } : {}
1016
+ };
1017
+ },
1018
+ async listSessions(params) {
1019
+ assertOpen();
1020
+ const persistence = requirePersistence();
1021
+ const headers = await persistence.list();
1022
+ headers.sort((a, b) => (b.createdAt ?? 0) - (a.createdAt ?? 0));
1023
+ const filtered = params.cwd !== void 0 && params.cwd !== null ? headers.filter((header) => header.cwd === params.cwd) : headers;
1024
+ const page = filtered.slice(0, 100);
1025
+ const withTitles = await Promise.allSettled(
1026
+ page.slice(0, 20).map(async (header) => {
1027
+ const { events } = await persistence.inspect(header.id);
1028
+ return foldSessionTitle2(events)?.title;
1029
+ })
1030
+ );
1031
+ const sessionsInfo = page.map((header, index) => {
1032
+ const settled = withTitles[index];
1033
+ const title = settled !== void 0 && settled.status === "fulfilled" ? settled.value : void 0;
1034
+ return {
1035
+ sessionId: String(header.id),
1036
+ cwd: header.cwd ?? "",
1037
+ ...title !== void 0 ? { title } : {},
1038
+ ...header.createdAt !== void 0 ? { updatedAt: new Date(header.createdAt).toISOString() } : {}
1039
+ };
1040
+ });
1041
+ return { sessions: sessionsInfo };
1042
+ },
1043
+ async prompt(params) {
1044
+ assertOpen();
1045
+ const record = requireSession(params.sessionId);
1046
+ if (record.inflight !== void 0) {
1047
+ throw invalidParams("a prompt is already in flight for this session");
1048
+ }
1049
+ let converted;
1050
+ try {
1051
+ converted = convertPrompt(params.prompt);
1052
+ } catch (error) {
1053
+ if (error instanceof UnsupportedPromptContentError) throw invalidParams(error.message);
1054
+ throw error;
1055
+ }
1056
+ if (converted.blocks.length === 0) throw invalidParams("empty prompt");
1057
+ const trimmed = converted.displayText.trim();
1058
+ const commandMatch = trimmed.match(/^\/(\w[\w-]*)\b/);
1059
+ const respond = (text) => {
1060
+ notify(params.sessionId, {
1061
+ sessionUpdate: "agent_message_chunk",
1062
+ content: { type: "text", text }
1063
+ });
1064
+ return { stopReason: "end_turn" };
1065
+ };
1066
+ if (commandMatch?.[1] === "status") return respond(await statusText(record));
1067
+ if (commandMatch?.[1] === "login") {
1068
+ return respond(await loginText(trimmed.slice(commandMatch[0].length)));
1069
+ }
1070
+ if (commandMatch?.[1] === "logout") return respond(await logoutText());
1071
+ if (!await credentialPresent()) {
1072
+ return respond(
1073
+ [
1074
+ "No DeepSeek credential is configured, so this prompt was not sent to the model.",
1075
+ "",
1076
+ "Configure one of:",
1077
+ "- `/login <api-key>` \u2014 store a key in the harness credential store right here,",
1078
+ "- the dsh Web UI (`dsh web`, Settings \u2192 Models),",
1079
+ "- `DEEPSEEK_API_KEY` in the environment that launches this agent."
1080
+ ].join("\n")
1081
+ );
1082
+ }
1083
+ if (agents.get(record.agent.id) !== record.agent) {
1084
+ throw internalError("prompt was not queued: the agent was disposed outside the bridge");
1085
+ }
1086
+ record.cancelled = false;
1087
+ record.projection.beginPrompt();
1088
+ const message = createUserMessage2({
1089
+ content: converted.blocks,
1090
+ source: { kind: "user" }
1091
+ });
1092
+ const stopReason = await new Promise((resolve2, reject) => {
1093
+ const inflight = { resolve: resolve2, reject, messageId: message.id, turn: void 0 };
1094
+ record.inflight = inflight;
1095
+ try {
1096
+ record.agent.followup(message);
1097
+ } catch (error) {
1098
+ record.inflight = void 0;
1099
+ const detail = error instanceof Error ? error.message : String(error);
1100
+ throw internalError(`prompt was not queued: ${detail}`);
1101
+ }
1102
+ void record.agent.whenIdle().then(() => {
1103
+ if (record.inflight !== inflight) return;
1104
+ record.inflight = void 0;
1105
+ if (record.cancelled) {
1106
+ resolve2("cancelled");
1107
+ return;
1108
+ }
1109
+ const end = inflight.turn !== void 0 ? record.projection.turnEndFor(inflight.turn) ?? record.projection.lastTurnEnd : record.projection.lastTurnEnd;
1110
+ resolve2(end === void 0 ? "cancelled" : turnEndToStopReason(end));
1111
+ });
1112
+ });
1113
+ const usage = record.projection.promptUsage();
1114
+ return { stopReason, ...usage !== void 0 ? { usage } : {} };
1115
+ },
1116
+ setSessionMode(params) {
1117
+ const record = requireSession(params.sessionId);
1118
+ const mode = SANDBOX_MODES2.find((candidate) => candidate === params.modeId);
1119
+ if (mode === void 0) throw invalidParams(`unknown mode: ${params.modeId}`);
1120
+ setSandboxMode2(record.agent.session, mode);
1121
+ try {
1122
+ ctx.get("approval")?.setPolicy?.(record.agent, mode === "danger-full-access" ? "never" : "ask");
1123
+ } catch (error) {
1124
+ logWarn(`approval policy switch failed: ${String(error)}`);
1125
+ }
1126
+ record.modeId = mode;
1127
+ notify(params.sessionId, { sessionUpdate: "current_mode_update", currentModeId: mode });
1128
+ return Promise.resolve({});
1129
+ },
1130
+ async setSessionConfigOption(params) {
1131
+ const record = requireSession(params.sessionId);
1132
+ if (params.configId !== "model") throw invalidParams(`unknown config option: ${params.configId}`);
1133
+ if (record.inflight !== void 0) {
1134
+ throw invalidParams("cannot switch models while a prompt is running");
1135
+ }
1136
+ const value = typeof params.value === "string" ? params.value : void 0;
1137
+ if (value === void 0) throw invalidParams(`unknown model: ${String(params.value)}`);
1138
+ const choice = decodeChoice(value);
1139
+ const known = /* @__PURE__ */ new Set([
1140
+ ...modelCandidates().map((model) => encodeChoice(void 0, model)),
1141
+ ...(await discoverModels()).map((entry) => encodeChoice(entry.provider, entry.model)),
1142
+ encodeChoice(record.provider, record.model ?? "")
1143
+ ]);
1144
+ if (!known.has(value)) throw invalidParams(`unknown model: ${value}`);
1145
+ if (choice.model !== record.model || choice.provider !== (record.provider ?? defaultProvider())) {
1146
+ const sessionId = record.agent.session.id;
1147
+ await record.dispose().catch((error) => {
1148
+ logWarn(`dispose during model switch failed: ${String(error)}`);
1149
+ });
1150
+ let handle;
1151
+ try {
1152
+ handle = await agents.resume({
1153
+ resumeSessionId: sessionId,
1154
+ agentOptions: agentOptionsFor(choice.model, choice.provider)
1155
+ });
1156
+ } catch (error) {
1157
+ sessions.delete(params.sessionId);
1158
+ throw internalError(`model switch failed: ${errorChain2(error)}`);
1159
+ }
1160
+ record.agent = handle.agent;
1161
+ record.dispose = () => handle.dispose();
1162
+ record.model = choice.model;
1163
+ if (choice.provider !== void 0 && choice.provider !== defaultProvider()) {
1164
+ record.provider = choice.provider;
1165
+ } else {
1166
+ delete record.provider;
1167
+ }
1168
+ }
1169
+ return { configOptions: await configOptions(record) };
1170
+ },
1171
+ async closeSession(params) {
1172
+ const record = sessions.get(params.sessionId);
1173
+ if (record === void 0) return;
1174
+ sessions.delete(params.sessionId);
1175
+ record.agent.cancel({ kind: "user" });
1176
+ settlePrompt(record, "cancelled");
1177
+ await record.dispose().catch((error) => {
1178
+ logWarn(`session close failed: ${String(error)}`);
1179
+ });
1180
+ },
1181
+ cancel(params) {
1182
+ const record = sessions.get(params.sessionId);
1183
+ if (record === void 0) return Promise.resolve();
1184
+ record.cancelled = true;
1185
+ record.agent.cancel({ kind: "user" });
1186
+ settlePrompt(record, "cancelled");
1187
+ return Promise.resolve();
1188
+ }
1189
+ };
1190
+ };
1191
+ function requirePersistence() {
1192
+ const persistence = getPersistence();
1193
+ if (persistence === void 0) {
1194
+ throw internalError("session persistence is not composed; session history is unavailable");
1195
+ }
1196
+ return persistence;
1197
+ }
1198
+ function getPersistence() {
1199
+ return ctx.get("sessionPersistence");
1200
+ }
1201
+ function validateCwd(cwd) {
1202
+ if (!isAbsolute(cwd)) throw invalidParams(`cwd must be an absolute path: ${cwd}`);
1203
+ }
1204
+ const mcpMounts = /* @__PURE__ */ new Map();
1205
+ let warnedNoMcpClient = false;
1206
+ const sanitizeServerName = (raw) => {
1207
+ const cleaned = raw.replace(/[^A-Za-z0-9_-]/g, "_").slice(0, 32);
1208
+ return cleaned.length > 0 ? cleaned : "server";
1209
+ };
1210
+ const mcpConfigFor = (server, cwd, serverName) => {
1211
+ const envList = (list) => Object.fromEntries(
1212
+ (Array.isArray(list) ? list : []).map((e) => [
1213
+ e.name,
1214
+ e.value
1215
+ ])
1216
+ );
1217
+ if (typeof server["command"] === "string") {
1218
+ return {
1219
+ transport: "stdio",
1220
+ serverName,
1221
+ command: server["command"],
1222
+ args: Array.isArray(server["args"]) ? server["args"] : [],
1223
+ env: envList(server["env"]),
1224
+ cwd: typeof server["cwd"] === "string" ? server["cwd"] : cwd,
1225
+ // A dead or misconfigured server must not take the session
1226
+ // down; the client surfaces missing tools on its own.
1227
+ failOnStartupError: false
1228
+ };
1229
+ }
1230
+ if (server["type"] === "http" && typeof server["url"] === "string") {
1231
+ return {
1232
+ transport: "streamable-http",
1233
+ serverName,
1234
+ url: server["url"],
1235
+ headers: envList(server["headers"]),
1236
+ failOnStartupError: false
1237
+ };
1238
+ }
1239
+ return void 0;
1240
+ };
1241
+ const syncMcpServers = (servers, cwd) => {
1242
+ if (servers === void 0 || servers.length === 0) return;
1243
+ const mcpClient2 = harness.mcpClient;
1244
+ if (mcpClient2 === void 0) {
1245
+ if (!warnedNoMcpClient) {
1246
+ warnedNoMcpClient = true;
1247
+ logWarn(
1248
+ `ignoring ${servers.length} MCP server(s): this DeepSeek Harness installation lacks @deepseek-ai/dsh-mcp-client`
1249
+ );
1250
+ }
1251
+ return;
1252
+ }
1253
+ const taken = /* @__PURE__ */ new Set();
1254
+ for (const entry of servers) {
1255
+ const server = entry;
1256
+ const base = sanitizeServerName(typeof server["name"] === "string" ? server["name"] : "server");
1257
+ let serverName = base;
1258
+ for (let n = 2; taken.has(serverName); n += 1) serverName = `${base.slice(0, 28)}_${n}`;
1259
+ const cfg = mcpConfigFor(server, cwd, serverName);
1260
+ if (cfg === void 0) {
1261
+ logWarn(`skipping MCP server "${serverName}": unsupported transport`);
1262
+ continue;
1263
+ }
1264
+ const configJson = JSON.stringify(cfg);
1265
+ const existing = mcpMounts.get(serverName);
1266
+ if (existing !== void 0) {
1267
+ if (existing.configJson === configJson) {
1268
+ taken.add(serverName);
1269
+ continue;
1270
+ }
1271
+ try {
1272
+ void existing.fiber.dispose();
1273
+ } catch (error) {
1274
+ logWarn(`disposing MCP server "${serverName}": ${String(error)}`);
1275
+ }
1276
+ mcpMounts.delete(serverName);
1277
+ }
1278
+ try {
1279
+ const fiber = ctx.plugin(mcpClient2, cfg);
1280
+ mcpMounts.set(serverName, { configJson, fiber });
1281
+ taken.add(serverName);
1282
+ logDebug(`mounted MCP server "${serverName}" (${String(cfg["transport"])})`);
1283
+ } catch (error) {
1284
+ logWarn(`failed to mount MCP server "${serverName}": ${String(error)}`);
1285
+ }
1286
+ }
1287
+ };
1288
+ const stream = config.stream ?? ndJsonStream(
1289
+ Writable.toWeb(process.stdout),
1290
+ Readable.toWeb(process.stdin)
1291
+ );
1292
+ conn = new AgentSideConnection(makeAgent, stream);
1293
+ let quiescing;
1294
+ const quiesce = () => {
1295
+ if (quiescing !== void 0) return quiescing;
1296
+ closed = true;
1297
+ const records = [...sessions.values()];
1298
+ sessions.clear();
1299
+ for (const record of records) {
1300
+ record.agent.cancel({ kind: "user" });
1301
+ settlePrompt(record, "cancelled");
1302
+ }
1303
+ quiescing = (async () => {
1304
+ const subagents = ctx.get("subagents");
1305
+ if (subagents !== void 0) {
1306
+ try {
1307
+ await subagents.drainContinuableDescendants(records.map((record) => record.agent));
1308
+ } catch (error) {
1309
+ logWarn(`continuable subagent teardown failed: ${String(error)}`);
1310
+ }
1311
+ }
1312
+ const disposals = await Promise.allSettled(records.map((record) => record.dispose()));
1313
+ const failures = disposals.filter(
1314
+ (result) => result.status === "rejected"
1315
+ );
1316
+ if (failures.length > 0) {
1317
+ const detail = failures.map((failure) => errorChain2(failure.reason)).join("; ");
1318
+ throw new AggregateError(
1319
+ failures.map((failure) => failure.reason),
1320
+ `ACP agent teardown failed for ${failures.length} session(s): ${detail}`
1321
+ );
1322
+ }
1323
+ })();
1324
+ return quiescing;
1325
+ };
1326
+ void conn.closed.catch((error) => {
1327
+ logWarn(`connection closed with an error: ${String(error)}`);
1328
+ }).then(quiesce).catch((error) => {
1329
+ logWarn(`connection-close teardown failed: ${String(error)}`);
1330
+ });
1331
+ ctx.effect(() => quiesce, "acp-bridge.connection");
1332
+ }
1333
+
1334
+ // src/harness.ts
1335
+ import { execFileSync } from "node:child_process";
1336
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
1337
+ import { delimiter, dirname, isAbsolute as isAbsolute2, join, resolve, sep } from "node:path";
1338
+ import { pathToFileURL, fileURLToPath } from "node:url";
1339
+ var HarnessNotFoundError = class extends Error {
1340
+ constructor(probed) {
1341
+ super(
1342
+ [
1343
+ "could not find a DeepSeek Harness installation.",
1344
+ "",
1345
+ "Install it first:",
1346
+ " npm install -g @deepseek-ai/dsh",
1347
+ "",
1348
+ "or point dsh-acp at an existing installation:",
1349
+ " DSH_PATH=/path/to/dsh dsh-acp (dsh binary, package dir, or npm root)",
1350
+ "",
1351
+ probed.length > 0 ? `Probed:
1352
+ ${probed.map((p) => ` ${p}`).join("\n")}` : ""
1353
+ ].join("\n").trimEnd()
1354
+ );
1355
+ }
1356
+ };
1357
+ var ANCHOR = "@deepseek-ai/dsh-agent";
1358
+ function packageDirFrom(base, name3) {
1359
+ let dir = resolve(base);
1360
+ for (; ; ) {
1361
+ const candidate = join(dir, "node_modules", ...name3.split("/"));
1362
+ if (existsSync(join(candidate, "package.json"))) return candidate;
1363
+ const direct = join(dir, ...name3.split("/"));
1364
+ if (dir.endsWith(`${sep}node_modules`) && existsSync(join(direct, "package.json"))) return direct;
1365
+ const parent = dirname(dir);
1366
+ if (parent === dir) return void 0;
1367
+ dir = parent;
1368
+ }
1369
+ }
1370
+ function versionOf(packageDir) {
1371
+ try {
1372
+ const parsed = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
1373
+ return typeof parsed.version === "string" ? parsed.version : void 0;
1374
+ } catch {
1375
+ return void 0;
1376
+ }
1377
+ }
1378
+ function hostAt(base, source) {
1379
+ const anchor = packageDirFrom(base, ANCHOR);
1380
+ if (anchor === void 0) return void 0;
1381
+ return { base: resolve(base), version: versionOf(anchor), source };
1382
+ }
1383
+ function hostFromExplicit(explicit) {
1384
+ const path = resolve(explicit);
1385
+ const bases = [];
1386
+ let stat;
1387
+ try {
1388
+ stat = realpathSync(path) !== void 0 && existsSync(join(path, ".")) ? "dir" : "file";
1389
+ } catch {
1390
+ stat = void 0;
1391
+ }
1392
+ if (existsSync(path)) {
1393
+ try {
1394
+ const real = realpathSync(path);
1395
+ stat = real === path && existsSync(join(path, "package.json")) ? "dir" : stat;
1396
+ bases.push(dirname(real));
1397
+ } catch {
1398
+ bases.push(dirname(path));
1399
+ }
1400
+ bases.push(path, join(path, "node_modules"), join(path, "lib", "node_modules"));
1401
+ }
1402
+ for (const base of bases) {
1403
+ const host = hostAt(base, `--dsh-path/DSH_PATH (${explicit})`);
1404
+ if (host !== void 0) return host;
1405
+ }
1406
+ return void 0;
1407
+ }
1408
+ function hostFromPathLookup() {
1409
+ const pathEnv = process.env["PATH"] ?? "";
1410
+ for (const dir of pathEnv.split(delimiter)) {
1411
+ if (dir.length === 0) continue;
1412
+ const candidate = join(dir, "dsh");
1413
+ if (!existsSync(candidate)) continue;
1414
+ try {
1415
+ const real = realpathSync(candidate);
1416
+ const host = hostAt(dirname(real), `dsh on PATH (${candidate})`);
1417
+ if (host !== void 0) return host;
1418
+ } catch {
1419
+ continue;
1420
+ }
1421
+ }
1422
+ return void 0;
1423
+ }
1424
+ function hostFromGlobalNpm() {
1425
+ try {
1426
+ const root = execFileSync("npm", ["root", "-g"], { encoding: "utf8", timeout: 1e4 }).trim();
1427
+ if (root.length > 0 && isAbsolute2(root)) return hostAt(root, `npm root -g (${root})`);
1428
+ } catch {
1429
+ }
1430
+ return void 0;
1431
+ }
1432
+ function resolveHost(explicit) {
1433
+ const probed = [];
1434
+ if (explicit !== void 0) {
1435
+ const host = hostFromExplicit(explicit);
1436
+ if (host !== void 0) return host;
1437
+ probed.push(`--dsh-path/DSH_PATH: ${explicit}`);
1438
+ throw new HarnessNotFoundError(probed);
1439
+ }
1440
+ const own = hostAt(dirname(fileURLToPath(import.meta.url)), "dsh-acp package tree");
1441
+ if (own !== void 0) return own;
1442
+ probed.push("dsh-acp package tree");
1443
+ const local = hostAt(process.cwd(), `invoking directory (${process.cwd()})`);
1444
+ if (local !== void 0) return local;
1445
+ probed.push(`invoking directory: ${process.cwd()}`);
1446
+ const onPath = hostFromPathLookup();
1447
+ if (onPath !== void 0) return onPath;
1448
+ probed.push("dsh on PATH");
1449
+ const globalNpm = hostFromGlobalNpm();
1450
+ if (globalNpm !== void 0) return globalNpm;
1451
+ probed.push("npm root -g");
1452
+ throw new HarnessNotFoundError(probed);
1453
+ }
1454
+ function entryFile(packageDir, subpath) {
1455
+ const manifest = JSON.parse(readFileSync(join(packageDir, "package.json"), "utf8"));
1456
+ const key = subpath === void 0 ? "." : `./${subpath}`;
1457
+ const exportsMap = manifest.exports;
1458
+ let target;
1459
+ if (typeof exportsMap === "string") {
1460
+ if (key === ".") target = exportsMap;
1461
+ } else if (exportsMap !== null && typeof exportsMap === "object") {
1462
+ const entry = exportsMap[key];
1463
+ target = entry;
1464
+ }
1465
+ if (target !== null && typeof target === "object") {
1466
+ const conditions = target;
1467
+ target = conditions["import"] ?? conditions["default"] ?? conditions["node"];
1468
+ if (target !== null && typeof target === "object") {
1469
+ const nested = target;
1470
+ target = nested["default"] ?? nested["import"];
1471
+ }
1472
+ }
1473
+ if (typeof target !== "string" && key === "." && typeof manifest.main === "string") {
1474
+ target = manifest.main;
1475
+ }
1476
+ if (typeof target !== "string") {
1477
+ throw new Error(`cannot resolve entry ${key} of ${packageDir}`);
1478
+ }
1479
+ return join(packageDir, target);
1480
+ }
1481
+ async function loadHostModule(host, specifier) {
1482
+ const [scope, packageName, ...rest] = specifier.split("/");
1483
+ if (scope === void 0 || packageName === void 0) throw new Error(`invalid specifier: ${specifier}`);
1484
+ const name3 = `${scope}/${packageName}`;
1485
+ const packageDir = packageDirFrom(host.base, name3);
1486
+ if (packageDir === void 0) {
1487
+ throw new Error(
1488
+ `the DeepSeek Harness installation at ${host.base} (${host.source}) does not provide ${name3}; update it with: npm install -g @deepseek-ai/dsh`
1489
+ );
1490
+ }
1491
+ const file = entryFile(packageDir, rest.length > 0 ? rest.join("/") : void 0);
1492
+ logDebug(`loading ${specifier} from ${file}`);
1493
+ return await import(pathToFileURL(file).href);
1494
+ }
1495
+ var PLUGIN_SPECIFIERS = {
1496
+ timer: "@deepseek-ai/cordis-plugin-timer",
1497
+ llmRuntime: "@deepseek-ai/dsh-llm",
1498
+ sessionStore: "@deepseek-ai/dsh-session",
1499
+ sessionTitle: "@deepseek-ai/dsh-session-title",
1500
+ systemPrompt: "@deepseek-ai/dsh-system-prompt",
1501
+ tools: "@deepseek-ai/dsh-tools",
1502
+ agents: "@deepseek-ai/dsh-agent",
1503
+ agentLoop: "@deepseek-ai/dsh-agent-loop",
1504
+ llmRetry: "@deepseek-ai/dsh-llm-retry",
1505
+ jobs: "@deepseek-ai/dsh-jobs-local",
1506
+ invariants: "@deepseek-ai/dsh-invariants",
1507
+ sessionInvariant: "@deepseek-ai/dsh-session/invariant",
1508
+ agentInvariant: "@deepseek-ai/dsh-agent/invariant",
1509
+ scopeInvariant: "@deepseek-ai/dsh-scope/invariant",
1510
+ agentLoopInvariant: "@deepseek-ai/dsh-agent-loop/invariant",
1511
+ homePaths: "@deepseek-ai/dsh-home-paths",
1512
+ bashEnv: "@deepseek-ai/dsh-shell-env",
1513
+ toolBash: "@deepseek-ai/dsh-tool-bash",
1514
+ workspaceContext: "@deepseek-ai/dsh-agent-instructions",
1515
+ llmDeepseek: "@deepseek-ai/dsh-llm-deepseek",
1516
+ persistence: "@deepseek-ai/dsh-session-persistence-jsonl",
1517
+ checkpoints: "@deepseek-ai/dsh-session-checkpoint-policy",
1518
+ sandbox: "@deepseek-ai/dsh-sandbox-local",
1519
+ sandboxPolicy: "@deepseek-ai/dsh-sandbox-policy",
1520
+ subprocess: "@deepseek-ai/dsh-subprocess-local",
1521
+ bash: "@deepseek-ai/dsh-bash-sandbox",
1522
+ approval: "@deepseek-ai/dsh-user-approval",
1523
+ fs: "@deepseek-ai/dsh-fs-sandbox",
1524
+ fsObservationPolicy: "@deepseek-ai/dsh-fs-observation-policy",
1525
+ toolFs: "@deepseek-ai/dsh-tool-fs",
1526
+ toolTodo: "@deepseek-ai/dsh-tool-todo",
1527
+ tokenMeter: "@deepseek-ai/dsh-token-meter",
1528
+ compaction: "@deepseek-ai/dsh-compaction-basic"
1529
+ };
1530
+ var OPTIONAL_PLUGIN_SPECIFIERS = {
1531
+ credentials: "@deepseek-ai/dsh-credentials-local",
1532
+ credentialsSeam: "@deepseek-ai/dsh-credentials",
1533
+ mcpClient: "@deepseek-ai/dsh-mcp-client"
1534
+ };
1535
+ async function loadKit(host) {
1536
+ const keys = Object.keys(PLUGIN_SPECIFIERS);
1537
+ const optionalKeys = Object.keys(OPTIONAL_PLUGIN_SPECIFIERS);
1538
+ const [cordis, ...pluginModules] = await Promise.all([
1539
+ loadHostModule(host, "@deepseek-ai/cordis"),
1540
+ ...keys.map((key) => loadHostModule(host, PLUGIN_SPECIFIERS[key])),
1541
+ ...optionalKeys.map(
1542
+ (key) => loadHostModule(host, OPTIONAL_PLUGIN_SPECIFIERS[key]).catch((error) => {
1543
+ logDebug(`optional module ${OPTIONAL_PLUGIN_SPECIFIERS[key]} unavailable: ${String(error)}`);
1544
+ return void 0;
1545
+ })
1546
+ )
1547
+ ]);
1548
+ const plugins = {};
1549
+ [...keys, ...optionalKeys].forEach((key, index) => {
1550
+ const module = pluginModules[index];
1551
+ if (module !== void 0) plugins[key] = module;
1552
+ });
1553
+ return {
1554
+ host,
1555
+ cordis,
1556
+ llm: plugins["llmRuntime"],
1557
+ session: plugins["sessionStore"],
1558
+ sessionTitle: plugins["sessionTitle"],
1559
+ sandboxPolicy: plugins["sandboxPolicy"],
1560
+ plugins
1561
+ };
1562
+ }
1563
+ function pluginOf(module) {
1564
+ return module["default"] ?? module;
1565
+ }
1566
+
1567
+ // src/app.ts
1568
+ var name2 = "dsh-acp-app";
1569
+ var SESSION_TITLE_CONFIG = { fallbackMaxWords: 5, fallbackMaxBytes: 40, maxTitleBytes: 80 };
1570
+ function applySpine(ctx, kit, settings) {
1571
+ const p = kit.plugins;
1572
+ const anyCtx = ctx;
1573
+ const resolveDshHome = p["homePaths"].resolveDshHome;
1574
+ const dshHome = resolveDshHome?.();
1575
+ anyCtx.plugin(pluginOf(p["timer"]));
1576
+ anyCtx.plugin(pluginOf(p["llmRuntime"]));
1577
+ anyCtx.plugin(pluginOf(p["sessionStore"]));
1578
+ anyCtx.plugin(pluginOf(p["sessionTitle"]), SESSION_TITLE_CONFIG);
1579
+ anyCtx.plugin(pluginOf(p["systemPrompt"]), {
1580
+ includeHarnessIdentity: true,
1581
+ includeRuntimeContext: true,
1582
+ persona: settings.persona
1583
+ });
1584
+ anyCtx.plugin(pluginOf(p["tools"]), {});
1585
+ anyCtx.plugin(pluginOf(p["agents"]));
1586
+ anyCtx.plugin(p["llmRetry"]);
1587
+ anyCtx.plugin(pluginOf(p["jobs"]), {});
1588
+ anyCtx.plugin(pluginOf(p["invariants"]), {});
1589
+ anyCtx.plugin(p["sessionInvariant"]);
1590
+ anyCtx.plugin(p["agentInvariant"]);
1591
+ anyCtx.plugin(p["scopeInvariant"]);
1592
+ anyCtx.plugin(p["agentLoopInvariant"]);
1593
+ anyCtx.plugin(p["bashEnv"], dshHome !== void 0 ? { dshHome } : {});
1594
+ anyCtx.plugin(p["toolBash"], {});
1595
+ anyCtx.plugin(p["workspaceContext"], { maxBytes: 65536 });
1596
+ anyCtx.plugin(pluginOf(p["agentLoop"]), { agents: [] });
1597
+ }
1598
+ async function apply2(ctx, config) {
1599
+ const { settings, kit } = config;
1600
+ const p = kit.plugins;
1601
+ const anyCtx = ctx;
1602
+ const credentialsSeam = p["credentialsSeam"];
1603
+ const harness = {
1604
+ createUserMessage: kit.llm.createUserMessage,
1605
+ errorChain: kit.llm.errorChain,
1606
+ sessionId: kit.session.SessionId,
1607
+ foldSessionTitle: kit.sessionTitle.foldSessionTitle,
1608
+ setSandboxMode: kit.sandboxPolicy.setSandboxMode,
1609
+ sandboxModes: kit.sandboxPolicy.SANDBOX_MODES,
1610
+ ...credentialsSeam?.credentialRef !== void 0 ? { credentialRef: credentialsSeam.credentialRef } : {},
1611
+ ...p["mcpClient"] !== void 0 ? { mcpClient: p["mcpClient"] } : {}
1612
+ };
1613
+ await ctx.effect(async function* () {
1614
+ const spine = anyCtx.plugin(
1615
+ { name: "dsh-acp-spine", apply: (child) => applySpine(child, kit, settings) },
1616
+ {}
1617
+ );
1618
+ await spine;
1619
+ yield spine.dispose;
1620
+ const credentialsModule = p["credentials"];
1621
+ if (credentialsModule !== void 0) {
1622
+ const credentials = anyCtx.plugin(pluginOf(credentialsModule), {});
1623
+ await credentials;
1624
+ yield credentials.dispose;
1625
+ }
1626
+ const llm = anyCtx.plugin(p["llmDeepseek"], {
1627
+ thinking: settings.thinking ? "enabled" : "disabled",
1628
+ reasoningEffort: settings.reasoningEffort
1629
+ });
1630
+ await llm;
1631
+ yield llm.dispose;
1632
+ const persistence = anyCtx.plugin(pluginOf(p["persistence"]), {
1633
+ root: settings.sessionRoot,
1634
+ compression: "none"
1635
+ });
1636
+ await persistence;
1637
+ yield persistence.dispose;
1638
+ const checkpoints = anyCtx.plugin(p["checkpoints"]);
1639
+ await checkpoints;
1640
+ yield checkpoints.dispose;
1641
+ const sandbox = anyCtx.plugin(pluginOf(p["sandbox"]), {});
1642
+ await sandbox;
1643
+ yield sandbox.dispose;
1644
+ const sandboxPolicy = anyCtx.plugin(pluginOf(p["sandboxPolicy"]), {
1645
+ mode: settings.permissionMode,
1646
+ workspaceRoot: process.cwd()
1647
+ });
1648
+ await sandboxPolicy;
1649
+ yield sandboxPolicy.dispose;
1650
+ const subprocess = anyCtx.plugin(pluginOf(p["subprocess"]));
1651
+ await subprocess;
1652
+ yield subprocess.dispose;
1653
+ const bash = anyCtx.plugin(pluginOf(p["bash"]), { timeoutMs: settings.bashTimeoutMs });
1654
+ await bash;
1655
+ yield bash.dispose;
1656
+ const approval = anyCtx.plugin(pluginOf(p["approval"]), {
1657
+ policy: settings.permissionMode === "danger-full-access" ? "never" : "ask"
1658
+ });
1659
+ await approval;
1660
+ yield approval.dispose;
1661
+ const fs = anyCtx.plugin(pluginOf(p["fs"]), {});
1662
+ await fs;
1663
+ yield fs.dispose;
1664
+ const fsPolicy = anyCtx.plugin(p["fsObservationPolicy"]);
1665
+ await fsPolicy;
1666
+ yield fsPolicy.dispose;
1667
+ const fsTools = anyCtx.plugin(p["toolFs"], {});
1668
+ await fsTools;
1669
+ yield fsTools.dispose;
1670
+ const todo = anyCtx.plugin(p["toolTodo"], { allowParallelInProgress: true });
1671
+ await todo;
1672
+ yield todo.dispose;
1673
+ const meter = anyCtx.plugin(pluginOf(p["tokenMeter"]));
1674
+ await meter;
1675
+ yield meter.dispose;
1676
+ const compaction = anyCtx.plugin(pluginOf(p["compaction"]), {
1677
+ thresholdRatio: 0.8,
1678
+ retainRatio: 0.08,
1679
+ maxTokens: 8192,
1680
+ compactionRetries: 1
1681
+ });
1682
+ await compaction;
1683
+ yield compaction.dispose;
1684
+ const bridge = anyCtx.plugin(bridge_exports, {
1685
+ provider: settings.provider,
1686
+ model: settings.model,
1687
+ models: settings.models,
1688
+ ...settings.maxTokens !== void 0 ? { maxTokens: settings.maxTokens } : {},
1689
+ permissionMode: settings.permissionMode,
1690
+ harness
1691
+ });
1692
+ await bridge;
1693
+ yield bridge.dispose;
1694
+ }, "dsh-acp-app.composition");
1695
+ }
1696
+
1697
+ // src/settings.ts
1698
+ import { homedir } from "node:os";
1699
+ import { join as join2 } from "node:path";
1700
+ var DEFAULT_PERSONA = `You are a coding assistant powered by the {{model}} model, working inside an editor via the Agent Client Protocol. Your working directory is {{cwd}}. Your bash tool runs under a file sandbox \u2014 a \`[sandbox: file access denied \u2026]\` result is policy, not a command bug.
1701
+
1702
+ Verify your work by running the code or tests. Keep answers brief and factual.`;
1703
+ var PERMISSION_MODES = ["read-only", "workspace-write", "danger-full-access"];
1704
+ var SettingsError = class extends Error {
1705
+ };
1706
+ function envString(name3) {
1707
+ const value = process.env[name3];
1708
+ return value !== void 0 && value.length > 0 ? value : void 0;
1709
+ }
1710
+ function parseFlags(argv) {
1711
+ const flags = /* @__PURE__ */ new Map();
1712
+ for (let i = 0; i < argv.length; i += 1) {
1713
+ const arg = argv[i];
1714
+ if (arg === void 0 || !arg.startsWith("--")) {
1715
+ throw new SettingsError(`unexpected argument: ${String(arg)}`);
1716
+ }
1717
+ const eq = arg.indexOf("=");
1718
+ if (eq >= 0) {
1719
+ flags.set(arg.slice(2, eq), arg.slice(eq + 1));
1720
+ continue;
1721
+ }
1722
+ const name3 = arg.slice(2);
1723
+ const next = argv[i + 1];
1724
+ if (next !== void 0 && !next.startsWith("--") && FLAGS_WITH_VALUES.has(name3)) {
1725
+ flags.set(name3, next);
1726
+ i += 1;
1727
+ } else {
1728
+ flags.set(name3, true);
1729
+ }
1730
+ }
1731
+ return { flags };
1732
+ }
1733
+ var FLAGS_WITH_VALUES = /* @__PURE__ */ new Set([
1734
+ "dsh-path",
1735
+ "provider",
1736
+ "model",
1737
+ "models",
1738
+ "max-tokens",
1739
+ "permission-mode",
1740
+ "session-root",
1741
+ "persona",
1742
+ "reasoning-effort",
1743
+ "bash-timeout"
1744
+ ]);
1745
+ function stringFlag(parsed, name3) {
1746
+ const value = parsed.flags.get(name3);
1747
+ if (value === void 0) return void 0;
1748
+ if (value === true) throw new SettingsError(`--${name3} requires a value`);
1749
+ return value;
1750
+ }
1751
+ function resolveSettings(argv) {
1752
+ const parsed = parseFlags(argv);
1753
+ for (const name3 of parsed.flags.keys()) {
1754
+ if (!FLAGS_WITH_VALUES.has(name3) && name3 !== "no-thinking") {
1755
+ throw new SettingsError(`unknown flag: --${name3}`);
1756
+ }
1757
+ }
1758
+ const model = stringFlag(parsed, "model") ?? envString("DSH_MODEL") ?? "deepseek-v4-flash";
1759
+ const modelsRaw = stringFlag(parsed, "models") ?? envString("DSH_ACP_MODELS");
1760
+ const models = (modelsRaw !== void 0 ? modelsRaw.split(",") : ["deepseek-v4-flash", "deepseek-v4-pro"]).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
1761
+ const permissionModeRaw = stringFlag(parsed, "permission-mode") ?? envString("DSH_PERMISSION_MODE") ?? "workspace-write";
1762
+ const permissionMode = PERMISSION_MODES.find((candidate) => candidate === permissionModeRaw);
1763
+ if (permissionMode === void 0) {
1764
+ throw new SettingsError(
1765
+ `invalid --permission-mode: ${permissionModeRaw} (expected ${PERMISSION_MODES.join(" | ")})`
1766
+ );
1767
+ }
1768
+ const maxTokensRaw = stringFlag(parsed, "max-tokens") ?? envString("DSH_MAX_TOKENS");
1769
+ let maxTokens;
1770
+ if (maxTokensRaw !== void 0) {
1771
+ maxTokens = Number(maxTokensRaw);
1772
+ if (!Number.isSafeInteger(maxTokens) || maxTokens <= 0) {
1773
+ throw new SettingsError(`invalid --max-tokens: ${maxTokensRaw}`);
1774
+ }
1775
+ }
1776
+ const reasoningRaw = stringFlag(parsed, "reasoning-effort") ?? envString("DSH_REASONING_EFFORT") ?? "high";
1777
+ if (reasoningRaw !== "off" && reasoningRaw !== "high" && reasoningRaw !== "max") {
1778
+ throw new SettingsError(`invalid --reasoning-effort: ${reasoningRaw} (expected off | high | max)`);
1779
+ }
1780
+ const bashTimeoutRaw = stringFlag(parsed, "bash-timeout") ?? envString("DSH_BASH_TIMEOUT_MS") ?? "60000";
1781
+ const bashTimeoutMs = Number(bashTimeoutRaw);
1782
+ if (!Number.isSafeInteger(bashTimeoutMs) || bashTimeoutMs <= 0) {
1783
+ throw new SettingsError(`invalid --bash-timeout: ${bashTimeoutRaw}`);
1784
+ }
1785
+ return {
1786
+ dshPath: stringFlag(parsed, "dsh-path") ?? envString("DSH_PATH"),
1787
+ provider: stringFlag(parsed, "provider") ?? envString("DSH_PROVIDER") ?? "deepseek-official",
1788
+ model,
1789
+ models,
1790
+ maxTokens,
1791
+ permissionMode,
1792
+ sessionRoot: stringFlag(parsed, "session-root") ?? envString("DSH_SESSION_ROOT") ?? join2(homedir(), ".dsh-acp", "sessions"),
1793
+ persona: stringFlag(parsed, "persona") ?? envString("DSH_SYSTEM_PROMPT") ?? DEFAULT_PERSONA,
1794
+ thinking: !parsed.flags.has("no-thinking"),
1795
+ reasoningEffort: reasoningRaw,
1796
+ bashTimeoutMs
1797
+ };
1798
+ }
1799
+ var HELP_TEXT = `Usage: dsh-acp [options]
1800
+
1801
+ Agent Client Protocol (ACP) stdio server for DeepSeek Harness. Speak ACP on
1802
+ stdin/stdout from an ACP client such as Zed; diagnostics go to stderr.
1803
+
1804
+ Options:
1805
+ --dsh-path <path> DeepSeek Harness installation: the dsh binary, its
1806
+ package dir, or any dir carrying node_modules/@deepseek-ai
1807
+ (DSH_PATH; auto-detected when unset \u2014 own tree, ./node_modules,
1808
+ dsh on PATH, npm root -g)
1809
+ --provider <route> Provider route (DSH_PROVIDER, default deepseek-official)
1810
+ --model <id> Default model (DSH_MODEL, default deepseek-v4-flash)
1811
+ --models <a,b,...> Selectable models for the session "Model" option
1812
+ (DSH_ACP_MODELS, default deepseek-v4-flash,deepseek-v4-pro)
1813
+ --max-tokens <n> Per-request output-token cap (DSH_MAX_TOKENS)
1814
+ --permission-mode <mode> read-only | workspace-write | danger-full-access
1815
+ (DSH_PERMISSION_MODE, default workspace-write)
1816
+ --session-root <dir> JSONL session store (DSH_SESSION_ROOT, default ~/.dsh-acp/sessions)
1817
+ --persona <text> System-prompt persona (DSH_SYSTEM_PROMPT)
1818
+ --reasoning-effort <level> off | high | max (DSH_REASONING_EFFORT, default high)
1819
+ --no-thinking Disable model thinking output
1820
+ --bash-timeout <ms> Foreground bash timeout (DSH_BASH_TIMEOUT_MS, default 60000)
1821
+ --version Print version and exit
1822
+ --help Show this help
1823
+
1824
+ Environment:
1825
+ DSH_PATH DeepSeek Harness installation (see --dsh-path)
1826
+ DEEPSEEK_API_KEY DeepSeek (or compatible) API credential
1827
+ DEEPSEEK_BASE_URL OpenAI-compatible endpoint override
1828
+ DSH_ACP_DEBUG Verbose stderr diagnostics
1829
+ `;
1830
+
1831
+ // src/index.ts
1832
+ var NAME = "@openma/deepseek-harness-acp";
1833
+ async function main() {
1834
+ const argv = process.argv.slice(2);
1835
+ if (argv.includes("--version")) {
1836
+ console.log(`${NAME} ${VERSION}`);
1837
+ return;
1838
+ }
1839
+ if (argv.includes("--help")) {
1840
+ console.log(HELP_TEXT.trimEnd());
1841
+ return;
1842
+ }
1843
+ let settings;
1844
+ try {
1845
+ settings = resolveSettings(argv);
1846
+ } catch (error) {
1847
+ if (error instanceof SettingsError) {
1848
+ logError(error.message);
1849
+ process.stderr.write(`
1850
+ ${HELP_TEXT}`);
1851
+ process.exitCode = 2;
1852
+ return;
1853
+ }
1854
+ throw error;
1855
+ }
1856
+ let kit;
1857
+ try {
1858
+ const host = resolveHost(settings.dshPath);
1859
+ logDebug(`harness host: ${host.base} via ${host.source} (${host.version ?? "unknown version"})`);
1860
+ kit = await loadKit(host);
1861
+ } catch (error) {
1862
+ if (error instanceof HarnessNotFoundError) {
1863
+ logError(error.message);
1864
+ process.exitCode = 1;
1865
+ return;
1866
+ }
1867
+ throw error;
1868
+ }
1869
+ const ctx = new kit.cordis.Context();
1870
+ await ctx.plugin(app_exports, { settings, kit });
1871
+ let disposing = false;
1872
+ const shutdown = (code) => {
1873
+ if (disposing) return;
1874
+ disposing = true;
1875
+ void ctx.fiber.dispose().catch((error) => {
1876
+ logError(`teardown failed: ${String(error)}`);
1877
+ }).finally(() => {
1878
+ process.exit(code);
1879
+ });
1880
+ };
1881
+ process.stdin.on("end", () => shutdown(0));
1882
+ process.stdin.on("close", () => shutdown(0));
1883
+ process.on("SIGINT", () => shutdown(130));
1884
+ process.on("SIGTERM", () => shutdown(143));
1885
+ }
1886
+ main().catch((error) => {
1887
+ logError(error instanceof Error ? error.stack ?? error.message : String(error));
1888
+ process.exit(1);
1889
+ });