@norman-else/dsh-claude 0.1.1 → 0.1.2

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/INSTALL.md CHANGED
@@ -14,17 +14,9 @@ node lib/bin.mjs doctor
14
14
 
15
15
  Stop if Doctor cannot find an authenticated local Claude Code installation. Do not request, copy, or write credentials.
16
16
 
17
- ## 2. Install the managed Agent Preset
17
+ ## 2. Link the bundle into the current Web profile
18
18
 
19
- Host activation normally does this automatically. Running it explicitly is safe:
20
-
21
- ```sh
22
- node lib/bin.mjs install-preset
23
- ```
24
-
25
- Expected output is `installed` on first run or `unchanged` on later runs. A conflict is terminal until a human chooses what to do with the existing user preset.
26
-
27
- ## 3. Link the bundle into the current Web profile
19
+ The bundle registers its package-contained Claude preset as a system preset; no files are copied into the user preset root.
28
20
 
29
21
  ```sh
30
22
  dsh plugin --profile web add "link:$(pwd)"
@@ -32,7 +24,7 @@ dsh plugin --profile web add "link:$(pwd)"
32
24
 
33
25
  Do not start another DSH Web server. This bundle must load in the existing app at `http://127.0.0.1:56454`.
34
26
 
35
- ## 4. Refresh and smoke test
27
+ ## 3. Refresh and smoke test
36
28
 
37
29
  1. Refresh the existing DSH Web page.
38
30
  2. Confirm **Claude** appears in the new-session Agent Preset picker.
@@ -45,14 +37,10 @@ Do not start another DSH Web server. This bundle must load in the existing app a
45
37
 
46
38
  A live prompt can consume the user's Claude subscription. Keep it minimal.
47
39
 
48
- ## 5. Uninstall safely
49
-
50
- Run before removing the link:
40
+ ## 4. Uninstall
51
41
 
52
42
  ```sh
53
- cd /path/to/dsh-claude
54
- node lib/bin.mjs remove-preset
55
43
  dsh plugin --profile web remove @norman-else/dsh-claude
56
44
  ```
57
45
 
58
- The remover refuses to delete any user-modified preset file.
46
+ The package-contained system preset disappears with the dependency. No source checkout or separate cleanup command is required.
package/README.md CHANGED
@@ -33,13 +33,7 @@ dsh plugin --profile web add @norman-else/dsh-claude
33
33
 
34
34
  Wait for the Web profile to rebuild, then refresh the existing DSH page. Open a new conversation and select **Claude** from the Agent Preset picker.
35
35
 
36
- The Host plugin automatically installs a two-file managed preset at:
37
-
38
- ```text
39
- $DSH_HOME/.agent-presets/claude/
40
- ```
41
-
42
- It writes only absent files. If that preset id already contains different content, activation fails rather than overwriting user work.
36
+ The package ships the Claude preset as a read-only system preset. It does not copy files into `$DSH_HOME/.agent-presets`, so removing the package also removes the preset.
43
37
 
44
38
  ## Use
45
39
 
@@ -106,7 +100,7 @@ To configure a nonstandard path, edit the plugin row in the Web profile composit
106
100
 
107
101
  ```yaml
108
102
  - id: llm-claude
109
- name: @norman-else/dsh-claude
103
+ name: '@norman-else/dsh-claude'
110
104
  config:
111
105
  executablePath: /absolute/path/to/claude
112
106
  model: default
@@ -145,31 +139,25 @@ pnpm release:check
145
139
  pnpm release
146
140
  ```
147
141
 
148
- The release script requires `HEAD` to match the current branch on `origin`. It runs the full project check and npm package preview, publishes the public npm package, verifies npm's `gitHead`, and creates a matching `v<version>` GitHub Release with generated notes. It is safe to rerun after a partial failure: an existing npm version or GitHub Release is accepted only when it points to the current commit.
142
+ The release script requires `HEAD` to match the current branch on `origin`. It runs the full project check and npm package preview, publishes the public npm package, waits for npm metadata propagation, verifies npm's `gitHead`, and creates a matching `v<version>` GitHub Release with generated notes. It is safe to rerun after a partial failure: an existing npm version or GitHub Release is accepted only when it points to the current commit.
149
143
 
150
144
  The project uses fixture/state-machine tests and a minimal SDK-level handshake probe (a tool-disabled, one-turn `query()` against the resolved local executable). Full DSH-linked live acceptance (native coexistence, Claude turn, permission allow/deny, cancel, resume, orphan-process check) is run after the Host restart per `INSTALL.md`. The Agent SDK is pinned to `0.3.233`; runtime execution is forced to the resolved local Claude executable through `pathToClaudeCodeExecutable`.
151
145
 
152
146
  ## Uninstall
153
147
 
154
- Remove the managed preset while this package is still present:
155
-
156
- ```sh
157
- node lib/bin.mjs remove-preset
158
- ```
159
-
160
- Then remove the package from the Web profile:
148
+ Remove the package from the profile where it was installed:
161
149
 
162
150
  ```sh
163
151
  dsh plugin --profile web remove @norman-else/dsh-claude
164
152
  ```
165
153
 
166
- The preset remover deletes only files whose contents exactly match the package-managed copies. It refuses to delete modified content.
154
+ The preset is package-contained and disappears with the dependency. Upgrading from a version that copied a managed preset into `$DSH_HOME/.agent-presets` removes that exact legacy copy automatically while preserving user-modified content.
167
155
 
168
156
  ## Troubleshooting
169
157
 
170
158
  ### Claude preset appears broken
171
159
 
172
- Run `node lib/bin.mjs install-preset`. If it reports a conflict, move or rename the existing `$DSH_HOME/.agent-presets/claude` directory; the plugin will not overwrite it.
160
+ Confirm the package remains installed in the intended profile with `dsh plugin --profile web why @norman-else/dsh-claude`, then restart that profile so its bundle patch and package-contained system preset are reloaded.
173
161
 
174
162
  ### Executable is missing
175
163
 
package/cordis.patch.yml CHANGED
@@ -1,5 +1,12 @@
1
- # dsh-claude host bundle. The plugin registers the local Claude Code bridge
2
- # and installs the small managed Agent Preset into the DSH user preset root.
1
+ # dsh-claude host bundle. The preset stays inside this package as a system
2
+ # preset, so removing the profile dependency removes the complete integration.
3
+ - id: agent-presets
4
+ config:
5
+ default: standard
6
+ roots:
7
+ - path: !!js "process.getBuiltinModule('node:path').join(process.getBuiltinModule('node:path').dirname(process.getBuiltinModule('node:module').createRequire(ctx.baseUrl).resolve('@norman-else/dsh-claude/package.json')), 'preset')"
8
+ trust: system
9
+
3
10
  - insert:
4
11
  - id: llm-claude
5
- name: @norman-else/dsh-claude
12
+ name: '@norman-else/dsh-claude'
package/lib/bin.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { n as removeManagedPreset, r as parseClaudeVersion, t as ensureManagedPreset } from "./preset-installer-DUVN1J6P.mjs";
2
+ import { i as parseClaudeVersion, n as ensureManagedPreset, r as removeManagedPreset } from "./preset-installer-XBN9ywDk.mjs";
3
3
  import { access } from "node:fs/promises";
4
4
  import { delimiter, isAbsolute, join } from "node:path";
5
5
  import { homedir } from "node:os";
package/lib/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as latestClaudeTasks, b as isClaudePresetId, c as normalizeTasksEvent, d as CLAUDE_ACTIVITY_EVENT, f as CLAUDE_CODE_PRESET_ID, g as CLAUDE_PROJECTION_PATH, h as CLAUDE_DOCTOR_PATH, i as latestClaudeSessionBinding, l as redactText, m as CLAUDE_CODE_PROVIDER_IDS, n as currentClaudeActivityCursor, o as normalizeActivity, p as CLAUDE_CODE_PROVIDER, r as latestClaudeContextUsage, s as normalizeContextUsage, t as boundText, u as safeDetail, y as TASK_TOOL_NAMES } from "./events-qlmU1KrH.mjs";
2
2
  import { a as ClaudeCommandBridge, i as CLAUDE_COMMANDS_SERVICE, r as dynamicPresenterDefinition, t as CLAUDE_PRESENTER_NAMES } from "./presenters-DbfG-9KQ.mjs";
3
- import { a as runClaudeDoctor, i as resolveClaudeExecutable, t as ensureManagedPreset } from "./preset-installer-DUVN1J6P.mjs";
3
+ import { a as resolveClaudeExecutable, o as runClaudeDoctor, r as removeManagedPreset, t as ManagedPresetConflictError } from "./preset-installer-XBN9ywDk.mjs";
4
4
  import z from "@deepseek-ai/schemastery";
5
5
  import { CallId, LlmAdapter, ReasoningEffortId, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
6
6
  import { randomUUID } from "node:crypto";
@@ -2180,7 +2180,12 @@ function mountClaudeMetadata(ctx, supervisor, agent, model, sidecar, resolveComm
2180
2180
  }, "dsh-claude: agent metadata bridge");
2181
2181
  }
2182
2182
  async function apply(ctx, config) {
2183
- await ensureManagedPreset();
2183
+ try {
2184
+ await removeManagedPreset();
2185
+ } catch (error) {
2186
+ if (!(error instanceof ManagedPresetConflictError)) throw error;
2187
+ ctx.logger.warn(`dsh-claude: preserving user-modified legacy preset at ${error.path}`);
2188
+ }
2184
2189
  const supervisorConfig = {
2185
2190
  executablePath: "",
2186
2191
  defaultModel: config.model ?? "default",
package/lib/index.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["record","string","#pending","#readNow","#update","#writeNow","#path","#values","#pending","#closed","#failure","#exitCode","#signalCode","#killed","#entries","#runtime","#approval","#config","#queryFactory","#runDetached","#sidecar","#dynamicPresenterNames","#contextWindows","claudeQuery","#runMetadata","#admissionGate","#runTurnAdmitted","#disposed","#disposeEntry","#makeRoom","#createEntry","#armInitializationTimer","#syncPermissionMode","#appendActivity","#armIdleTimer","#interrupt","#metadataEntry","#whenInitialized","#pump","#handleMessage","#handleDisconnect","#flushTasksSnapshot","#trackTask","#trackBackgroundLevel","#completeTurn","#ensureDynamicPresenter","#appendNativeToolCall","#appendNativeToolResult","#scheduleTasksSnapshot","#appendSafely","#supervisor","#agents","#presetIdFor"],"sources":["../src/sidecar.ts","../src/async-queue.ts","../src/permission.ts","../src/sdk-messages.ts","../src/spawn.ts","../src/supervisor.ts","../src/adapter.ts","../src/http.ts","../src/doctor-routes.ts","../src/projection-routes.ts","../src/index.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths'\nimport type { SessionEvent } from '@deepseek-ai/dsh-session'\nimport {\n latestClaudeContextUsage,\n latestClaudeSessionBinding,\n latestClaudeTasks,\n normalizeActivity,\n normalizeContextUsage,\n normalizeTasksEvent,\n redactText,\n type ClaudeActivityEvent,\n type ClaudeActivityInput,\n type ClaudeContextUsageEvent,\n type ClaudeContextUsageInput,\n type ClaudeSessionBoundEvent,\n type ClaudeTaskInfo,\n type ClaudeTasksEvent,\n} from './events.ts'\nimport { CLAUDE_ACTIVITY_EVENT, SDK_VERSION } from './constants.ts'\n\nconst SIDECAR_SCHEMA_VERSION = 1\nconst MAX_ACTIVITIES = 10_000\n\nexport interface ClaudeSidecarProjection {\n readonly schemaVersion: typeof SIDECAR_SCHEMA_VERSION\n readonly revision: number\n readonly binding?: ClaudeSessionBoundEvent\n readonly activities: readonly ClaudeActivityEvent[]\n readonly contextUsage?: ClaudeContextUsageEvent\n readonly tasks?: ClaudeTasksEvent\n}\n\nexport interface ClaudeSidecarRepositoryOptions {\n readonly root?: string\n readonly legacyRoot?: string\n}\n\nfunction emptyProjection(): ClaudeSidecarProjection {\n return { schemaVersion: SIDECAR_SCHEMA_VERSION, revision: 0, activities: [] }\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n}\n\nfunction finiteInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction string(value: unknown, max: number): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= max\n}\n\nfunction binding(value: unknown): ClaudeSessionBoundEvent | undefined {\n const input = record(value)\n if (input === undefined\n || !string(input.claudeSessionId, 512)\n || !string(input.sdkVersion, 128)\n || !string(input.cwd, 4_096)\n || (input.cliVersion !== undefined && !string(input.cliVersion, 128))) return undefined\n return {\n claudeSessionId: input.claudeSessionId,\n sdkVersion: input.sdkVersion,\n cwd: input.cwd,\n ...(input.cliVersion === undefined ? {} : { cliVersion: input.cliVersion }),\n }\n}\n\nconst ACTIVITY_KINDS = new Set(['status', 'thinking', 'tool-call', 'tool-result', 'permission', 'subagent', 'usage', 'warning', 'error'])\nconst ACTIVITY_PHASES = new Set(['started', 'updated', 'completed', 'denied', 'failed'])\n\nfunction activity(value: unknown): ClaudeActivityEvent | undefined {\n const input = record(value)\n if (input === undefined\n || !finiteInteger(input.turn)\n || !finiteInteger(input.step)\n || !finiteInteger(input.ordinal)\n || typeof input.kind !== 'string'\n || !ACTIVITY_KINDS.has(input.kind)\n || (input.phase !== undefined && (typeof input.phase !== 'string' || !ACTIVITY_PHASES.has(input.phase)))) return undefined\n return normalizeActivity(input as unknown as ClaudeActivityEvent)\n}\n\nfunction contextUsage(value: unknown): ClaudeContextUsageEvent | undefined {\n const input = record(value)\n if (input === undefined || !Array.isArray(input.categories)) return undefined\n return normalizeContextUsage(input as unknown as ClaudeContextUsageInput)\n}\n\nfunction tasks(value: unknown): ClaudeTasksEvent | undefined {\n const input = record(value)\n if (input === undefined || !Array.isArray(input.tasks)) return undefined\n return normalizeTasksEvent(input.tasks as ClaudeTaskInfo[])\n}\n\nexport function parseClaudeSidecar(value: unknown): ClaudeSidecarProjection {\n const input = record(value)\n if (input === undefined\n || input.schemaVersion !== SIDECAR_SCHEMA_VERSION\n || !finiteInteger(input.revision)\n || !Array.isArray(input.activities)\n || input.activities.length > MAX_ACTIVITIES) {\n throw new Error('dsh-claude: invalid sidecar document')\n }\n const activities = input.activities.map(activity)\n if (activities.some(item => item === undefined)) throw new Error('dsh-claude: invalid sidecar activity')\n const parsedBinding = input.binding === undefined ? undefined : binding(input.binding)\n const parsedUsage = input.contextUsage === undefined ? undefined : contextUsage(input.contextUsage)\n const parsedTasks = input.tasks === undefined ? undefined : tasks(input.tasks)\n if ((input.binding !== undefined && parsedBinding === undefined)\n || (input.contextUsage !== undefined && parsedUsage === undefined)\n || (input.tasks !== undefined && parsedTasks === undefined)) {\n throw new Error('dsh-claude: invalid sidecar projection')\n }\n return {\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n revision: input.revision,\n activities: activities as ClaudeActivityEvent[],\n ...(parsedBinding === undefined ? {} : { binding: parsedBinding }),\n ...(parsedUsage === undefined ? {} : { contextUsage: parsedUsage }),\n ...(parsedTasks === undefined ? {} : { tasks: parsedTasks }),\n }\n}\n\nfunction compareActivity(left: ClaudeActivityEvent, right: ClaudeActivityEvent): number {\n return left.turn - right.turn || left.step - right.step || left.ordinal - right.ordinal\n}\n\nfunction activityKey(value: ClaudeActivityEvent): string {\n return `${value.turn}:${value.step}:${value.ordinal}`\n}\n\nfunction mergeActivities(\n existing: readonly ClaudeActivityEvent[],\n additions: readonly ClaudeActivityEvent[],\n): ClaudeActivityEvent[] {\n const merged = new Map(existing.map(item => [activityKey(item), item]))\n for (const item of additions) merged.set(activityKey(item), item)\n return [...merged.values()].sort(compareActivity).slice(-MAX_ACTIVITIES)\n}\n\nfunction normalizeBinding(\n input: Omit<ClaudeSessionBoundEvent, 'sdkVersion'> & { sdkVersion?: string },\n): ClaudeSessionBoundEvent {\n return {\n claudeSessionId: redactText(input.claudeSessionId, 512),\n sdkVersion: redactText(input.sdkVersion ?? SDK_VERSION, 128),\n cwd: redactText(input.cwd, 4_096),\n ...(input.cliVersion === undefined ? {} : { cliVersion: redactText(input.cliVersion, 128) }),\n }\n}\n\nexport class ClaudeSidecarRepository {\n readonly root: string\n readonly legacyRoot: string | undefined\n readonly #pending = new Map<string, Promise<unknown>>()\n\n constructor(options: ClaudeSidecarRepositoryOptions = {}) {\n this.root = options.root ?? dshHomePath('plugins', 'dsh-claude', 'sessions')\n this.legacyRoot = options.legacyRoot\n ?? (options.root === undefined ? dshHomePath('plugins', 'dsh-claude-code', 'sessions') : undefined)\n }\n\n async read(sessionId: string): Promise<ClaudeSidecarProjection> {\n await this.#pending.get(sessionId)?.catch(() => undefined)\n return this.#readNow(sessionId)\n }\n\n writeBinding(\n sessionId: string,\n value: Omit<ClaudeSessionBoundEvent, 'sdkVersion'> & { sdkVersion?: string },\n ): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeBinding(value)\n return this.#update(sessionId, current => ({ ...current, binding: normalized }))\n }\n\n appendActivity(\n sessionId: string,\n value: ClaudeActivityInput & { turn: number; step: number; ordinal: number },\n ): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeActivity(value)\n return this.#update(sessionId, current => ({\n ...current,\n activities: mergeActivities(current.activities, [normalized]),\n }))\n }\n\n writeContextUsage(sessionId: string, value: ClaudeContextUsageInput): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeContextUsage(value)\n return this.#update(sessionId, current => ({ ...current, contextUsage: normalized }))\n }\n\n writeTasks(sessionId: string, value: readonly ClaudeTaskInfo[]): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeTasksEvent(value)\n return this.#update(sessionId, current => ({ ...current, tasks: normalized }))\n }\n\n importLegacy(sessionId: string, events: readonly SessionEvent[]): Promise<ClaudeSidecarProjection> {\n const importedActivities = events\n .filter(event => event.type === CLAUDE_ACTIVITY_EVENT)\n .map(event => activity(event.data))\n .filter((item): item is ClaudeActivityEvent => item !== undefined)\n const importedBinding = latestClaudeSessionBinding(events)\n const importedUsage = latestClaudeContextUsage(events)\n const importedTasks = latestClaudeTasks(events)\n return this.#update(sessionId, current => ({\n ...current,\n activities: mergeActivities(importedActivities, current.activities),\n ...(current.binding !== undefined || importedBinding === undefined ? {} : { binding: normalizeBinding(importedBinding) }),\n ...(current.contextUsage !== undefined || importedUsage === undefined ? {} : { contextUsage: normalizeContextUsage(importedUsage) }),\n ...(current.tasks !== undefined || importedTasks === undefined ? {} : { tasks: normalizeTasksEvent(importedTasks.tasks) }),\n }), true)\n }\n\n #path(sessionId: string, root = this.root): string {\n if (sessionId.length === 0 || sessionId.length > 1_024) throw new Error('dsh-claude: invalid session id')\n return join(root, `${Buffer.from(sessionId).toString('base64url')}.json`)\n }\n\n #update(\n sessionId: string,\n change: (current: ClaudeSidecarProjection) => Omit<ClaudeSidecarProjection, 'revision' | 'schemaVersion'> & Partial<Pick<ClaudeSidecarProjection, 'revision' | 'schemaVersion'>>,\n skipUnchanged = false,\n ): Promise<ClaudeSidecarProjection> {\n const previous = this.#pending.get(sessionId) ?? Promise.resolve()\n const operation = previous.catch(() => undefined).then(async () => {\n const current = await this.#readNow(sessionId)\n const changed = parseClaudeSidecar({\n ...change(current),\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n revision: current.revision,\n })\n if (skipUnchanged && JSON.stringify(changed) === JSON.stringify(current)) return current\n const next = { ...changed, revision: current.revision + 1 }\n await this.#writeNow(sessionId, next)\n return next\n })\n this.#pending.set(sessionId, operation)\n void operation.finally(() => {\n if (this.#pending.get(sessionId) === operation) this.#pending.delete(sessionId)\n }).catch(() => undefined)\n return operation\n }\n\n async #readNow(sessionId: string): Promise<ClaudeSidecarProjection> {\n try {\n return parseClaudeSidecar(JSON.parse(await readFile(this.#path(sessionId), 'utf8')))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (this.legacyRoot === undefined) return emptyProjection()\n try {\n return parseClaudeSidecar(JSON.parse(await readFile(this.#path(sessionId, this.legacyRoot), 'utf8')))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return emptyProjection()\n throw error\n }\n }\n\n async #writeNow(sessionId: string, projection: ClaudeSidecarProjection): Promise<void> {\n await mkdir(this.root, { recursive: true, mode: 0o700 })\n await chmod(this.root, 0o700)\n const target = this.#path(sessionId)\n const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`\n try {\n await writeFile(temporary, `${JSON.stringify(projection)}\\n`, { mode: 0o600, flag: 'wx' })\n await chmod(temporary, 0o600)\n await rename(temporary, target)\n await chmod(target, 0o600)\n } finally {\n await rm(temporary, { force: true }).catch(() => undefined)\n }\n }\n}\n","export class AsyncQueueClosedError extends Error {\n constructor() {\n super('Async queue is closed')\n this.name = 'AsyncQueueClosedError'\n }\n}\n\ninterface Pending<T> {\n resolve: (result: IteratorResult<T>) => void\n reject: (error: unknown) => void\n}\n\nexport class AsyncQueue<T> implements AsyncIterable<T>, AsyncIterator<T> {\n readonly #values: T[] = []\n readonly #pending: Pending<T>[] = []\n #closed = false\n #failure: unknown\n\n get closed(): boolean {\n return this.#closed\n }\n\n push(value: T): void {\n if (this.#closed) throw new AsyncQueueClosedError()\n const waiter = this.#pending.shift()\n if (waiter !== undefined) waiter.resolve({ value, done: false })\n else this.#values.push(value)\n }\n\n close(): void {\n if (this.#closed) return\n this.#closed = true\n for (const waiter of this.#pending.splice(0)) waiter.resolve({ value: undefined, done: true })\n }\n\n fail(error: unknown): void {\n if (this.#closed) return\n this.#closed = true\n this.#failure = error\n for (const waiter of this.#pending.splice(0)) waiter.reject(error)\n }\n\n discard(error?: unknown): void {\n this.#values.splice(0)\n if (this.#closed) return\n this.#closed = true\n if (error === undefined) {\n for (const waiter of this.#pending.splice(0)) waiter.resolve({ value: undefined, done: true })\n return\n }\n this.#failure = error\n for (const waiter of this.#pending.splice(0)) waiter.resolve({ value: undefined, done: true })\n }\n\n next(): Promise<IteratorResult<T>> {\n const value = this.#values.shift()\n if (value !== undefined) return Promise.resolve({ value, done: false })\n if (this.#closed) {\n return this.#failure === undefined\n ? Promise.resolve({ value: undefined, done: true })\n : Promise.reject(this.#failure)\n }\n return new Promise<IteratorResult<T>>((resolve, reject) => {\n this.#pending.push({ resolve, reject })\n })\n }\n\n return(): Promise<IteratorResult<T>> {\n this.close()\n return Promise.resolve({ value: undefined, done: true })\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this\n }\n}\n","import type { CanUseTool, PermissionResult } from '@anthropic-ai/claude-agent-sdk'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type { ApprovalOutcome, ApprovalService } from '@deepseek-ai/dsh-user-approval'\nimport {\n boundText,\n safeDetail,\n type ClaudeActivityInput,\n type ClaudeActivityCursor,\n} from './events.ts'\n\nexport type ApprovalRequester = Pick<ApprovalService, 'request'>\n\nexport interface ActivePermissionContext {\n agent: Agent\n cursor: ClaudeActivityCursor\n markActivity?: () => void\n recordDenial?: (toolUseId: string) => void\n appendActivity: (activity: ClaudeActivityInput) => Promise<void>\n}\n\nexport type ActivePermissionContextProvider = () => ActivePermissionContext | undefined\n\nfunction denialMessage(outcome: ApprovalOutcome): string {\n switch (outcome) {\n case 'rejected': return 'The user rejected this action in DeepSeek Harness.'\n case 'cancelled': return 'The permission request was cancelled in DeepSeek Harness.'\n case 'unavailable': return 'No DeepSeek Harness approval surface was available; the action was denied.'\n case 'allowed-once': return ''\n }\n}\n\nexport function permissionReason(\n toolName: string,\n input: Readonly<Record<string, unknown>>,\n options: Parameters<CanUseTool>[2],\n): string {\n const prompt = options.title ?? options.description ?? options.decisionReason ?? `Claude Code wants to use ${toolName}.`\n const detail = safeDetail(input)\n return boundText(detail === undefined ? prompt : `${prompt}\\nInput: ${detail}`, 1_200)\n}\n\nexport function mapApprovalOutcome(\n outcome: ApprovalOutcome,\n input: Record<string, unknown>,\n toolUseID: string,\n): PermissionResult {\n if (outcome === 'allowed-once') {\n return {\n behavior: 'allow',\n updatedInput: input,\n toolUseID,\n decisionClassification: 'user_temporary',\n }\n }\n return {\n behavior: 'deny',\n message: denialMessage(outcome),\n toolUseID,\n decisionClassification: 'user_reject',\n }\n}\n\nexport function createPermissionBridge(\n approval: ApprovalRequester,\n activeContext: ActivePermissionContextProvider,\n): CanUseTool {\n return async (toolName, input, options) => {\n const active = activeContext()\n if (active === undefined) {\n return {\n behavior: 'deny',\n message: 'No active DeepSeek Harness turn owns this Claude Code action.',\n toolUseID: options.toolUseID,\n decisionClassification: 'user_reject',\n }\n }\n\n active.markActivity?.()\n const reason = permissionReason(toolName, input, options)\n try {\n await active.appendActivity({\n kind: 'permission',\n phase: 'started',\n toolUseId: options.toolUseID,\n toolName,\n title: options.displayName ?? toolName,\n summary: options.title ?? options.description ?? reason,\n detail: input,\n })\n const outcome = await approval.request({\n agent: active.agent,\n toolName,\n reason,\n signal: options.signal,\n })\n const result = mapApprovalOutcome(outcome, input, options.toolUseID)\n if (result.behavior === 'deny') active.recordDenial?.(options.toolUseID)\n await active.appendActivity({\n kind: 'permission',\n phase: outcome === 'allowed-once' ? 'completed' : 'denied',\n toolUseId: options.toolUseID,\n toolName,\n title: options.displayName ?? toolName,\n summary: outcome === 'allowed-once' ? 'Allowed once in DeepSeek Harness' : denialMessage(outcome),\n })\n return result\n } catch (error) {\n const message = options.signal.aborted\n ? 'The permission request was cancelled in DeepSeek Harness.'\n : 'DeepSeek Harness could not record or answer the permission request; the action was denied.'\n try {\n await active.appendActivity({\n kind: 'permission',\n phase: 'failed',\n toolUseId: options.toolUseID,\n toolName,\n title: options.displayName ?? toolName,\n summary: message,\n isError: true,\n detail: error,\n })\n } catch {\n // The permission path is already fail-closed; a second audit failure cannot widen it.\n }\n return {\n behavior: 'deny',\n message,\n toolUseID: options.toolUseID,\n decisionClassification: 'user_reject',\n }\n }\n }\n}\n","import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk'\nimport type { ClaudeUsage } from './events.ts'\n\nexport type NormalizedSdkMessage =\n | { kind: 'init'; sessionId: string; cliVersion: string; cwd: string }\n | { kind: 'text-delta'; text: string; parentToolUseId?: string }\n | { kind: 'assistant-text'; text: string; parentToolUseId?: string }\n | { kind: 'thinking'; text: string; phase: 'updated' | 'completed'; parentToolUseId?: string }\n | { kind: 'tool-call'; toolUseId: string; toolName: string; input: unknown; parentToolUseId?: string }\n | { kind: 'tool-result'; toolUseId: string; output: unknown; isError: boolean; parentToolUseId?: string }\n | {\n kind: 'subagent'\n title: string\n summary?: string\n detail?: unknown\n phase: 'started' | 'updated' | 'completed' | 'failed'\n /** Structured task-board fields for task_started/progress/updated/notification. */\n taskId?: string\n taskStatus?: 'running' | 'completed' | 'failed' | 'stopped' | 'killed'\n description?: string\n subagentType?: string\n taskType?: string\n lastToolName?: string\n usage?: { totalTokens?: number; toolUses?: number; durationMs?: number }\n /** Ambient/housekeeping task: hide from chat rows, keep on the task board. */\n skipTranscript?: boolean\n }\n | {\n /** Level signal: full live background-task set (REPLACE semantics). */\n kind: 'background-tasks'\n tasks: readonly { taskId: string; taskType?: string; description: string }[]\n }\n | { kind: 'status'; title: string; summary?: string; detail?: unknown }\n | { kind: 'warning'; title: string; summary?: string; detail?: unknown }\n | { kind: 'permission-denied'; toolUseId: string; toolName: string; summary: string }\n | { kind: 'result'; success: boolean; text?: string; errors?: readonly string[]; usage: ClaudeUsage; sessionId: string; userMessageUuid?: string; terminalReason?: string; permissionDenials?: readonly { toolName: string; toolUseId: string }[] }\n | { kind: 'protocol-error'; title: string; detail: unknown }\n | { kind: 'unknown'; title: string; detail: unknown }\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' ? value as Record<string, unknown> : undefined\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction contentText(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content.map(item => {\n const block = record(item)\n if (block?.type === 'text') return string(block.text) ?? ''\n return ''\n }).join('')\n}\n\nfunction taskUsageOf(usage: Record<string, unknown> | undefined): { totalTokens?: number; toolUses?: number; durationMs?: number } | undefined {\n if (usage === undefined) return undefined\n const normalized: { totalTokens?: number; toolUses?: number; durationMs?: number } = {}\n if (typeof usage.total_tokens === 'number') normalized.totalTokens = usage.total_tokens\n if (typeof usage.tool_uses === 'number') normalized.toolUses = usage.tool_uses\n if (typeof usage.duration_ms === 'number') normalized.durationMs = usage.duration_ms\n return Object.keys(normalized).length === 0 ? undefined : normalized\n}\n\nfunction resultUsage(message: Record<string, unknown>): ClaudeUsage {\n const usage = record(message.usage)\n const normalized: ClaudeUsage = {}\n if (usage !== undefined) {\n if (typeof usage.input_tokens === 'number') normalized.inputTokens = usage.input_tokens\n if (typeof usage.output_tokens === 'number') normalized.outputTokens = usage.output_tokens\n if (typeof usage.cache_read_input_tokens === 'number') normalized.cacheReadTokens = usage.cache_read_input_tokens\n if (typeof usage.cache_creation_input_tokens === 'number') normalized.cacheCreationTokens = usage.cache_creation_input_tokens\n }\n if (typeof message.total_cost_usd === 'number') normalized.cumulativeCostUsd = message.total_cost_usd\n return normalized\n}\n\nfunction normalizeAssistant(message: Record<string, unknown>): NormalizedSdkMessage[] {\n const envelope = record(message.message)\n const content = envelope?.content\n if (!Array.isArray(content)) return [{ kind: 'protocol-error', title: 'Malformed Claude assistant message', detail: message }]\n const parentToolUseId = string(message.parent_tool_use_id)\n const normalized: NormalizedSdkMessage[] = []\n for (const item of content) {\n const block = record(item)\n if (block === undefined) continue\n if (block.type === 'text') {\n const text = string(block.text)\n if (text !== undefined && text.length > 0) normalized.push({ kind: 'assistant-text', text, ...(parentToolUseId === undefined ? {} : { parentToolUseId }) })\n } else if (block.type === 'thinking') {\n const text = string(block.thinking)\n if (text !== undefined && text.length > 0) normalized.push({ kind: 'thinking', text, phase: 'completed', ...(parentToolUseId === undefined ? {} : { parentToolUseId }) })\n } else if (block.type === 'tool_use') {\n const toolUseId = string(block.id)\n const toolName = string(block.name)\n if (toolUseId !== undefined && toolName !== undefined) {\n normalized.push({\n kind: 'tool-call',\n toolUseId,\n toolName,\n input: block.input,\n ...(parentToolUseId === undefined ? {} : { parentToolUseId }),\n })\n }\n }\n }\n return normalized\n}\n\nfunction normalizeUser(message: Record<string, unknown>): NormalizedSdkMessage[] {\n const envelope = record(message.message)\n const content = envelope?.content\n if (!Array.isArray(content)) return [{ kind: 'protocol-error', title: 'Malformed Claude user message', detail: message }]\n const parentToolUseId = string(message.parent_tool_use_id)\n const normalized: NormalizedSdkMessage[] = []\n for (const item of content) {\n const block = record(item)\n if (block?.type !== 'tool_result') continue\n const toolUseId = string(block.tool_use_id)\n if (toolUseId === undefined) continue\n normalized.push({\n kind: 'tool-result',\n toolUseId,\n output: message.tool_use_result ?? block.content,\n isError: block.is_error === true,\n ...(parentToolUseId === undefined ? {} : { parentToolUseId }),\n })\n }\n return normalized\n}\n\nfunction normalizeSystem(message: Record<string, unknown>): NormalizedSdkMessage[] {\n const subtype = string(message.subtype)\n if (subtype === 'init') {\n const sessionId = string(message.session_id)\n const cliVersion = string(message.claude_code_version)\n const cwd = string(message.cwd)\n return sessionId !== undefined && cliVersion !== undefined && cwd !== undefined\n ? [{ kind: 'init', sessionId, cliVersion, cwd }]\n : [{ kind: 'protocol-error', title: 'Malformed Claude initialization message', detail: message }]\n }\n if (subtype === 'status') {\n const status = message.status\n if (status === null) return [{ kind: 'status', title: 'Claude Code is ready' }]\n return [{ kind: 'status', title: `Claude Code ${String(status)}`, detail: message }]\n }\n if (subtype === 'session_state_changed') {\n return [{ kind: 'status', title: `Claude session ${String(message.state)}` }]\n }\n if (subtype === 'permission_denied') {\n const toolUseId = string(message.tool_use_id)\n const toolName = string(message.tool_name)\n if (toolUseId !== undefined && toolName !== undefined) {\n return [{\n kind: 'permission-denied',\n toolUseId,\n toolName,\n summary: string(message.message) ?? 'Claude Code denied the action',\n }]\n }\n }\n if (subtype === 'task_started') {\n const taskId = string(message.task_id)\n const description = string(message.description)\n const subagentType = string(message.subagent_type)\n const taskType = string(message.task_type)\n return [{\n kind: 'subagent',\n title: description ?? taskId ?? 'Claude subagent started',\n phase: 'started',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n taskStatus: 'running' as const,\n ...(description === undefined ? {} : { description }),\n ...(subagentType === undefined ? {} : { subagentType }),\n ...(taskType === undefined ? {} : { taskType }),\n ...(message.skip_transcript === true ? { skipTranscript: true } : {}),\n }]\n }\n if (subtype === 'task_progress') {\n const taskId = string(message.task_id)\n const description = string(message.description)\n const summary = string(message.summary)\n const subagentType = string(message.subagent_type)\n const lastToolName = string(message.last_tool_name)\n const usage = taskUsageOf(record(message.usage))\n return [{\n kind: 'subagent',\n title: summary ?? description ?? 'Claude subagent update',\n phase: 'updated',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n taskStatus: 'running' as const,\n ...(description === undefined ? {} : { description }),\n ...(subagentType === undefined ? {} : { subagentType }),\n ...(lastToolName === undefined ? {} : { lastToolName }),\n ...(summary === undefined ? {} : { summary }),\n ...(usage === undefined ? {} : { usage }),\n }]\n }\n if (subtype === 'task_updated') {\n const patch = record(message.patch)\n const status = string(patch?.status)\n const taskId = string(message.task_id)\n const description = string(patch?.description)\n const error = string(patch?.error)\n const taskStatus = status === undefined\n ? undefined\n : status === 'killed'\n ? 'killed' as const\n : status === 'completed'\n ? 'completed' as const\n : status === 'failed'\n ? 'failed' as const\n : 'running' as const\n return [{\n kind: 'subagent',\n title: description ?? 'Claude subagent update',\n phase: status === 'failed' || status === 'killed' ? 'failed' : status === 'completed' ? 'completed' : 'updated',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n ...(taskStatus === undefined ? {} : { taskStatus }),\n ...(description === undefined ? {} : { description }),\n ...(error === undefined ? {} : { summary: error }),\n }]\n }\n if (subtype === 'task_notification') {\n const failed = message.status === 'failed'\n const stopped = message.status === 'stopped' || message.status === 'cancelled'\n const taskId = string(message.task_id)\n const summary = string(message.summary)\n const taskStatus = failed ? 'failed' as const : stopped ? 'stopped' as const : 'completed' as const\n const usage = taskUsageOf(record(message.usage))\n return [{\n kind: 'subagent',\n title: summary ?? taskId ?? 'Claude subagent finished',\n phase: failed || stopped ? 'failed' : 'completed',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n taskStatus,\n ...(summary === undefined ? {} : { summary }),\n ...(usage === undefined ? {} : { usage }),\n }]\n }\n if (subtype === 'background_tasks_changed') {\n const tasks = Array.isArray(message.tasks) ? message.tasks : []\n return [{\n kind: 'background-tasks',\n tasks: tasks.flatMap(item => {\n const entry = record(item)\n const taskId = string(entry?.task_id)\n const description = string(entry?.description)\n const taskType = string(entry?.task_type)\n if (taskId === undefined || description === undefined) return []\n return [{\n taskId,\n description,\n ...(taskType === undefined ? {} : { taskType }),\n }]\n }),\n }]\n }\n if (subtype === 'api_retry') {\n return [{ kind: 'warning', title: 'Claude API retry', detail: message }]\n }\n if (subtype === 'informational' || subtype === 'notification' || subtype === 'local_command_output') {\n return [{\n kind: message.level === 'warning' ? 'warning' : 'status',\n title: string(message.content) ?? string(message.text) ?? 'Claude Code notice',\n detail: message,\n }]\n }\n if (subtype?.startsWith('hook_') === true || subtype === 'plugin_install') {\n return [{ kind: 'status', title: `Claude Code ${subtype.replaceAll('_', ' ')}`, detail: message }]\n }\n if (subtype !== undefined) {\n // Preserve unknown system lifecycle evidence (background tasks, resets,\n // worker/mirror lifecycle) as a bounded activity instead of silently\n // dropping it; the activity layer redacts and bounds the detail.\n return [{ kind: 'status', title: `Claude Code ${subtype.replaceAll('_', ' ')}`, detail: message }]\n }\n return []\n}\n\nconst RESULT_ERROR_SUBTYPES = new Set([\n 'error_during_execution',\n 'error_max_turns',\n 'error_max_budget_usd',\n 'error_max_structured_output_retries',\n])\n\nexport function normalizeSdkMessage(message: SDKMessage): NormalizedSdkMessage[] {\n const value = message as unknown as Record<string, unknown>\n if (value.type === 'stream_event') {\n const event = record(value.event)\n const parentToolUseId = string(value.parent_tool_use_id)\n if (event?.type === 'content_block_delta') {\n const delta = record(event.delta)\n if (delta?.type === 'text_delta') {\n const text = string(delta.text)\n return text === undefined ? [] : [{ kind: 'text-delta', text, ...(parentToolUseId === undefined ? {} : { parentToolUseId }) }]\n }\n if (delta?.type === 'thinking_delta') {\n const text = string(delta.thinking)\n return text === undefined ? [] : [{ kind: 'thinking', text, phase: 'updated', ...(parentToolUseId === undefined ? {} : { parentToolUseId }) }]\n }\n }\n return []\n }\n if (value.type === 'assistant') return normalizeAssistant(value)\n if (value.type === 'user') return normalizeUser(value)\n if (value.type === 'system') return normalizeSystem(value)\n if (value.type === 'result') {\n const sessionId = string(value.session_id)\n if (sessionId === undefined || (value.subtype !== 'success' && !RESULT_ERROR_SUBTYPES.has(String(value.subtype)))) {\n return [{ kind: 'protocol-error', title: 'Malformed Claude result message', detail: value }]\n }\n // A result is a success only when it is not flagged as an error. Local\n // 2.1.233 emits subtype:\"success\" with is_error:true for API/auth failures\n // (e.g. terminal_reason:\"api_error\"), so subtype alone is not authoritative.\n const success = value.subtype === 'success' && value.is_error !== true\n const errors = Array.isArray(value.errors)\n ? value.errors.filter((item): item is string => typeof item === 'string')\n : undefined\n const terminalReason = string(value.terminal_reason)\n const userMessageUuid = string(value.user_message_uuid)\n const permissionDenials = Array.isArray(value.permission_denials)\n ? value.permission_denials\n .map(item => record(item))\n .filter((item): item is Record<string, unknown> => item !== undefined)\n .map(item => {\n const toolName = string(item.tool_name)\n const toolUseId = string(item.tool_use_id)\n return toolName === undefined || toolUseId === undefined ? undefined : { toolName, toolUseId }\n })\n .filter((item): item is { toolName: string; toolUseId: string } => item !== undefined)\n .slice(0, 40)\n : undefined\n return [{\n kind: 'result',\n success,\n ...(success && typeof value.result === 'string' ? { text: value.result } : {}),\n ...(errors === undefined ? {} : { errors }),\n ...(terminalReason === undefined ? {} : { terminalReason }),\n ...(permissionDenials === undefined || permissionDenials.length === 0 ? {} : { permissionDenials }),\n usage: resultUsage(value),\n sessionId,\n ...(userMessageUuid === undefined ? {} : { userMessageUuid }),\n }]\n }\n if (value.type === 'auth_status') {\n return [{\n kind: value.error === undefined ? 'status' : 'warning',\n title: value.error === undefined ? 'Claude authentication status changed' : 'Claude authentication failed',\n detail: value.error ?? value.output,\n }]\n }\n if (value.type === 'rate_limit_event') {\n // The CLI pushes subscription-quota status after API activity. Only a\n // non-allowed state is a real warning; healthy updates stay audit-only.\n const info = record(value.rate_limit_info)\n const status = string(info?.status)\n const blocking = status !== undefined && status !== 'allowed'\n return [{\n kind: blocking ? 'warning' : 'status',\n title: blocking ? 'Claude rate limit is blocking requests' : 'Claude rate limit status changed',\n detail: value.rate_limit_info,\n }]\n }\n return [{ kind: 'unknown', title: `Unknown Claude SDK message: ${String(value.type)}`, detail: value }]\n}\n\nexport function extractSdkContentText(content: unknown): string {\n return contentText(content)\n}\n","import { EventEmitter } from 'node:events'\nimport type { Readable, Writable } from 'node:stream'\nimport type { SpawnOptions, SpawnedProcess } from '@anthropic-ai/claude-agent-sdk'\nimport {\n DSH_ENV_PREFIX,\n SENSITIVE_ENV_PATTERN,\n type SubprocessHandle,\n type SubprocessRuntime,\n} from '@deepseek-ai/dsh-subprocess'\n\nexport const CLAUDE_PROCESS_GRACE_MS = 2_000\nexport const CLAUDE_STDERR_TAIL_BYTES = 32 * 1024\n\nconst ADDITIONAL_SENSITIVE_ENV_PATTERN = /(?:authorization|cookie|credential|database[_-]?url|private[_-]?key|netrc)/iu\n\nexport function scrubClaudeSpawnEnv(env: Readonly<Record<string, string | undefined>>): NodeJS.ProcessEnv {\n const safe: NodeJS.ProcessEnv = {}\n for (const [key, value] of Object.entries(env)) {\n if (value === undefined) continue\n if (key.toUpperCase().startsWith(DSH_ENV_PREFIX)) continue\n if (SENSITIVE_ENV_PATTERN.test(key)) continue\n if (ADDITIONAL_SENSITIVE_ENV_PATTERN.test(key)) continue\n safe[key] = value\n }\n return safe\n}\n\nexport class ManagedClaudeProcess extends EventEmitter implements SpawnedProcess {\n readonly stdin: Writable\n readonly stdout: Readable\n readonly handle: SubprocessHandle\n #killed = false\n #exitCode: number | null = null\n #signalCode: NodeJS.Signals | null = null\n\n constructor(handle: SubprocessHandle) {\n super()\n if (handle.stdin === undefined || handle.stdout === undefined) {\n throw new Error('dsh-claude: managed Claude process requires piped stdin/stdout')\n }\n this.handle = handle\n this.stdin = handle.stdin\n this.stdout = handle.stdout\n void handle.done.then(\n outcome => {\n this.#exitCode = outcome.exitCode\n this.#signalCode = outcome.signal\n this.emit('exit', outcome.exitCode, outcome.signal)\n },\n error => {\n this.emit('error', error instanceof Error ? error : new Error(String(error)))\n },\n )\n }\n\n get killed(): boolean {\n return this.#killed\n }\n\n get exitCode(): number | null {\n return this.#exitCode\n }\n\n get signalCode(): NodeJS.Signals | null {\n return this.#signalCode\n }\n\n kill(signal: NodeJS.Signals): boolean {\n if (this.#exitCode !== null || this.#signalCode !== null) return false\n this.#killed = true\n this.handle.terminate()\n return true\n }\n\n stderrTail(): string {\n return this.handle.collected.stderr?.readFrom(0).text ?? ''\n }\n}\n\nexport type SpawnObserver = (process: ManagedClaudeProcess, options: SpawnOptions) => void\n\nexport function createManagedClaudeSpawner(\n runtime: Pick<SubprocessRuntime, 'spawn'>,\n executablePath: string,\n observe?: SpawnObserver,\n): (options: SpawnOptions) => SpawnedProcess {\n return options => {\n if (options.command !== executablePath) {\n throw new Error(`dsh-claude: SDK requested unexpected executable ${JSON.stringify(options.command)}`)\n }\n const handle = runtime.spawn({\n argv: [executablePath, ...options.args],\n cwd: options.cwd ?? process.cwd(),\n stdio: {\n stdin: 'pipe',\n stdout: 'pipe',\n stderr: { maxBytes: CLAUDE_STDERR_TAIL_BYTES },\n },\n graceMs: CLAUDE_PROCESS_GRACE_MS,\n signal: options.signal,\n env: scrubClaudeSpawnEnv(options.env),\n })\n const managed = new ManagedClaudeProcess(handle)\n observe?.(managed, options)\n return managed\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n query as claudeQuery,\n type EffortLevel,\n type Options as ClaudeOptions,\n type PermissionMode,\n type Query,\n type SDKControlGetContextUsageResponse,\n type SDKMessage,\n type SDKUserMessage,\n type Settings as ClaudeSettings,\n type SlashCommand,\n} from '@anthropic-ai/claude-agent-sdk'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport { CallId, createToolResultMessage } from '@deepseek-ai/dsh-llm'\nimport type { ApprovalService } from '@deepseek-ai/dsh-user-approval'\nimport type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'\nimport { AsyncQueue } from './async-queue.ts'\nimport { TASK_TOOL_NAMES } from './constants.ts'\nimport {\n currentClaudeActivityCursor,\n redactText,\n safeDetail,\n type ClaudeActivityCursor,\n type ClaudeActivityInput,\n type ClaudeTaskInfo,\n type ClaudeUsage,\n} from './events.ts'\nimport { createPermissionBridge } from './permission.ts'\nimport { ClaudeSidecarRepository } from './sidecar.ts'\nimport { CLAUDE_PRESENTER_NAMES, dynamicPresenterDefinition } from './presenters.ts'\nimport { normalizeSdkMessage, type NormalizedSdkMessage } from './sdk-messages.ts'\nimport { createManagedClaudeSpawner, type ManagedClaudeProcess } from './spawn.ts'\n\nexport const CLAUDE_INITIALIZATION_TIMEOUT_MS = 30_000\nexport const CLAUDE_INTERRUPT_TIMEOUT_MS = 5_000\n/** Control requests must settle; a wedged one must not clog the metadata chain. */\nexport const CLAUDE_METADATA_TIMEOUT_MS = 15_000\n\nexport type ClaudeSupervisorState =\n | 'starting'\n | 'idle'\n | 'running'\n | 'interrupting'\n | 'disconnected'\n | 'outcome-unknown'\n | 'disposed'\n\nexport interface ClaudeSupervisorConfig {\n executablePath: string\n idleTimeoutMs: number\n maxProcesses: number\n defaultModel: string\n}\n\nexport type ClaudeTurnStreamEvent =\n | { type: 'text-delta'; text: string }\n | { type: 'usage'; usage: ClaudeUsage }\n | { type: 'complete'; text: string }\n\nexport type ClaudeThinkingMode = 'off' | 'ultracode' | EffortLevel\n\nexport type DshSandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access'\n\nconst CLAUDE_MODE_BY_SANDBOX: Readonly<Record<DshSandboxMode, PermissionMode>> = {\n 'read-only': 'plan',\n 'workspace-write': 'acceptEdits',\n 'danger-full-access': 'bypassPermissions',\n}\n\n/** Fold DSH's native access selector into Claude Code's closest permission mode. */\nexport function claudePermissionMode(events: readonly { type: string; data: unknown }[]): PermissionMode {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index]\n if (event?.type !== 'sandbox/mode') continue\n const mode = (event.data as { mode?: unknown }).mode\n return typeof mode === 'string' && mode in CLAUDE_MODE_BY_SANDBOX\n ? CLAUDE_MODE_BY_SANDBOX[mode as DshSandboxMode]\n : 'plan'\n }\n return 'plan'\n}\n\nexport interface ClaudeTurnRequest {\n agent: Agent\n prompt: string\n model?: string\n thinkingMode?: ClaudeThinkingMode\n signal?: AbortSignal\n}\n\nexport interface ClaudeSupervisorSnapshot {\n sessionId: string\n claudeSessionId?: string\n state: ClaudeSupervisorState\n cwd: string\n model: string\n thinkingMode?: ClaudeThinkingMode\n lastUsedAt: number\n pid?: number\n}\n\nexport class ClaudeTurnBusyError extends Error {\n constructor(sessionId: string) {\n super(`Claude Code session ${sessionId} already has an active or interrupting turn`)\n this.name = 'ClaudeTurnBusyError'\n }\n}\n\nexport class ClaudeOutcomeUnknownError extends Error {\n constructor(message = 'Claude Code exited after activity; side-effect outcome is unknown and the prompt was not replayed') {\n super(message)\n this.name = 'ClaudeOutcomeUnknownError'\n }\n}\n\nexport class ClaudeProtocolError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ClaudeProtocolError'\n }\n}\n\nexport class ClaudeProcessLimitError extends Error {\n constructor(maxProcesses: number) {\n super(`Claude Code process limit reached (${maxProcesses}) and no idle session can be evicted`)\n this.name = 'ClaudeProcessLimitError'\n }\n}\n\nexport type ClaudeQueryFactory = (params: {\n prompt: AsyncIterable<SDKUserMessage>\n options: ClaudeOptions\n}) => Query\n\ninterface ActiveTurn {\n agent: Agent\n cursor: ClaudeActivityCursor\n output: AsyncQueue<ClaudeTurnStreamEvent>\n promptUuid: ReturnType<typeof randomUUID>\n sawActivity: boolean\n sawTextDelta: boolean\n text: string\n thinking: string\n aborted: boolean\n deniedToolUseIds: Set<string>\n /** Root call names by toolUseId; tool results carry none of their own. */\n callNames: Map<string, string>\n signal?: AbortSignal\n abortListener?: () => void\n}\n\ninterface SupervisorEntry {\n sessionId: string\n ownerAgent: Agent\n cwd: string\n model: string\n thinkingMode: ClaudeThinkingMode | undefined\n permissionMode: PermissionMode\n state: ClaudeSupervisorState\n lastUsedAt: number\n input: AsyncQueue<SDKUserMessage>\n query: Query\n lifetime: AbortController\n process: ManagedClaudeProcess | undefined\n claudeSessionId: string | undefined\n active: ActiveTurn | undefined\n idleTimer: ReturnType<typeof setTimeout> | undefined\n initTimer: ReturnType<typeof setTimeout> | undefined\n initialized: boolean\n expectedResume: string | undefined\n /** Settled when init arrives; rejected on disconnect before init. */\n initWaiters: Array<(error: unknown) => void>\n /** Uuid of the startup handshake prompt; its local-command result is never a DSH turn outcome. */\n handshakeUuid: ReturnType<typeof randomUUID>\n /** True until the handshake's settlement arrives; its output is swallowed. */\n handshakePending: boolean\n /** Live Claude task board (subagents and background tasks), keyed by task id. */\n tasks: Map<string, ClaudeTaskInfo>\n /** Last time a task snapshot was persisted (progress throttling). */\n taskSnapshotAt: number\n /** Pending throttled snapshot flush timer. */\n taskSnapshotTimer: ReturnType<typeof setTimeout> | undefined\n pump: Promise<void>\n}\n\nfunction abortFailure(): Error {\n const error = new Error('Claude Code turn aborted')\n error.name = 'AbortError'\n return error\n}\n\nfunction signalAborted(signal: AbortSignal | undefined): boolean {\n return signal?.aborted === true\n}\n\nasync function withTimeout<T>(operation: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs)\n timer.unref?.()\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\nfunction sdkUserMessage(prompt: string, uuid: ReturnType<typeof randomUUID>): SDKUserMessage {\n return {\n type: 'user',\n message: { role: 'user', content: prompt },\n parent_tool_use_id: null,\n uuid,\n }\n}\n\n/** CLI ≥ 2.1.235 emits system/init only after its first stdin input, while\n * the supervisor must see init before submitting any real turn. A local\n * slash command nudges startup without costing a model call; its lifecycle\n * messages are ignored because no DSH turn is active while they arrive. */\nconst CLAUDE_HANDSHAKE_PROMPT = '/status'\n\nfunction usageSummary(usage: ClaudeUsage): string {\n const input = usage.inputTokens ?? 0\n const output = usage.outputTokens ?? 0\n const cost = usage.cumulativeCostUsd === undefined\n ? ''\n : ` · $${usage.cumulativeCostUsd.toFixed(4)} cumulative`\n return `${input} input / ${output} output tokens${cost}`\n}\n\nfunction errorSummary(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Root-call activity summary; subagent dispatches lead with Claude's own task description. */\nfunction rootCallSummary(toolName: string, input: unknown): string {\n if (TASK_TOOL_NAMES.has(toolName)) {\n const description = input !== null && typeof input === 'object'\n ? (input as Record<string, unknown>).description\n : undefined\n if (typeof description === 'string' && description.length > 0) return description\n return 'Claude dispatched a subagent'\n }\n return `Claude called ${toolName}`\n}\n\nexport class ClaudeSupervisor {\n readonly #entries = new Map<string, SupervisorEntry>()\n readonly #runtime: Pick<SubprocessRuntime, 'spawn'>\n readonly #approval: Pick<ApprovalService, 'request'>\n readonly #config: ClaudeSupervisorConfig\n readonly #queryFactory: ClaudeQueryFactory\n readonly #runDetached: <T>(operation: () => T) => T\n readonly #sidecar: ClaudeSidecarRepository\n readonly #dynamicPresenterNames = new WeakMap<Agent, Set<string>>()\n readonly #contextWindows = new Map<string, number>()\n #disposed = false\n #admissionGate: Promise<void> = Promise.resolve()\n\n constructor(dependencies: {\n runtime: Pick<SubprocessRuntime, 'spawn'>\n approval: Pick<ApprovalService, 'request'>\n config: ClaudeSupervisorConfig\n queryFactory?: ClaudeQueryFactory\n runDetached?: <T>(operation: () => T) => T\n sidecar?: ClaudeSidecarRepository\n }) {\n this.#runtime = dependencies.runtime\n this.#approval = dependencies.approval\n this.#config = dependencies.config\n this.#queryFactory = dependencies.queryFactory ?? (params => claudeQuery(params))\n this.#runDetached = dependencies.runDetached ?? (operation => operation())\n this.#sidecar = dependencies.sidecar ?? new ClaudeSidecarRepository()\n }\n\n snapshots(): ClaudeSupervisorSnapshot[] {\n return [...this.#entries.values()].map(entry => ({\n sessionId: entry.sessionId,\n ...(entry.claudeSessionId === undefined ? {} : { claudeSessionId: entry.claudeSessionId }),\n state: entry.state,\n cwd: entry.cwd,\n model: entry.model,\n ...(entry.thinkingMode === undefined ? {} : { thinkingMode: entry.thinkingMode }),\n lastUsedAt: entry.lastUsedAt,\n ...(entry.process === undefined ? {} : { pid: entry.process.handle.pid }),\n }))\n }\n\n supportedCommands(agent: Agent, model = this.#config.defaultModel): Promise<readonly SlashCommand[]> {\n return this.#runMetadata(agent, model, query => query.supportedCommands())\n }\n\n async contextUsage(agent: Agent, model = this.#config.defaultModel): Promise<SDKControlGetContextUsageResponse> {\n const usage = await this.#runMetadata(agent, model, query => query.getContextUsage())\n const contextWindow = usage.rawMaxTokens > 0 ? usage.rawMaxTokens : usage.maxTokens\n if (contextWindow > 0) {\n this.#contextWindows.set(model, contextWindow)\n this.#contextWindows.set(usage.model, contextWindow)\n }\n return usage\n }\n\n contextWindow(model: string): number | undefined {\n return this.#contextWindows.get(model)\n }\n\n runTurn(request: ClaudeTurnRequest): Promise<AsyncIterable<ClaudeTurnStreamEvent>> {\n const operation = this.#admissionGate.then(() => this.#runTurnAdmitted(request))\n this.#admissionGate = operation.then(() => undefined, () => undefined)\n return operation\n }\n\n async #runTurnAdmitted(request: ClaudeTurnRequest): Promise<AsyncIterable<ClaudeTurnStreamEvent>> {\n if (this.#disposed) throw new Error('dsh-claude: supervisor is disposed')\n if (signalAborted(request.signal)) throw abortFailure()\n const sessionId = request.agent.id as string\n let entry = this.#entries.get(sessionId)\n if (entry?.state === 'disposed' || entry?.state === 'disconnected' || entry?.state === 'outcome-unknown') {\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n entry = undefined\n }\n if (entry === undefined) {\n await this.#makeRoom()\n entry = await this.#createEntry(request.agent, request.model ?? this.#config.defaultModel, request.thinkingMode)\n this.#entries.set(sessionId, entry)\n this.#armInitializationTimer(entry)\n }\n if (entry.ownerAgent !== request.agent) {\n throw new Error(`dsh-claude: live agent identity changed for session ${sessionId}`)\n }\n if (entry.active !== undefined || entry.state === 'interrupting') throw new ClaudeTurnBusyError(sessionId)\n\n if (entry.idleTimer !== undefined) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = undefined\n }\n const model = request.model ?? this.#config.defaultModel\n if (request.thinkingMode !== entry.thinkingMode) {\n // The SDK only accepts effort/thinking at query start, so rebuild the\n // query; the persisted Claude session binding keeps the context.\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n entry = await this.#createEntry(request.agent, model, request.thinkingMode)\n this.#entries.set(sessionId, entry)\n this.#armInitializationTimer(entry)\n } else {\n await this.#syncPermissionMode(entry)\n if (model !== entry.model) {\n await entry.query.setModel(model)\n entry.model = model\n }\n }\n\n const promptUuid = randomUUID()\n const cursor = currentClaudeActivityCursor(request.agent.session.events)\n const projection = await this.#sidecar.read(sessionId)\n cursor.nextOrdinal = projection.activities.reduce((next, activity) => (\n activity.turn === cursor.turn && activity.step === cursor.step\n ? Math.max(next, activity.ordinal + 1)\n : next\n ), 0)\n const active: ActiveTurn = {\n agent: request.agent,\n cursor,\n output: new AsyncQueue<ClaudeTurnStreamEvent>(),\n promptUuid,\n sawActivity: false,\n sawTextDelta: false,\n text: '',\n thinking: '',\n aborted: false,\n deniedToolUseIds: new Set(),\n callNames: new Map(),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n }\n entry.active = active\n entry.state = 'running'\n entry.lastUsedAt = Date.now()\n try {\n await this.#appendActivity(active, {\n kind: 'status',\n phase: 'started',\n title: 'Claude Code turn started',\n })\n } catch (error) {\n active.output.fail(error)\n entry.active = undefined\n if (this.#entries.get(sessionId) === entry) this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n throw error\n }\n if (signalAborted(request.signal)) {\n active.aborted = true\n active.output.fail(abortFailure())\n await this.#appendActivity(active, {\n kind: 'status',\n phase: 'failed',\n title: 'Claude Code turn cancelled before submission',\n })\n entry.active = undefined\n entry.state = 'idle'\n entry.lastUsedAt = Date.now()\n this.#armIdleTimer(entry)\n return active.output\n }\n if (request.signal !== undefined) {\n const abortListener = () => { void this.#interrupt(entry as SupervisorEntry) }\n active.abortListener = abortListener\n request.signal.addEventListener('abort', abortListener, { once: true })\n }\n entry.input.push(sdkUserMessage(request.prompt, promptUuid))\n return active.output\n }\n\n #runMetadata<T>(\n agent: Agent,\n model: string,\n operation: (query: Query, entry: SupervisorEntry) => Promise<T>,\n ): Promise<T> {\n const admitted = this.#admissionGate.then(async () => {\n if (this.#disposed) throw new Error('dsh-claude: supervisor is disposed')\n const entry = await this.#metadataEntry(agent, model)\n try {\n // Control requests go out only after the CLI finishes initializing;\n // issued earlier they can wedge and clog the caller's refresh chain.\n await withTimeout(this.#whenInitialized(entry), CLAUDE_INITIALIZATION_TIMEOUT_MS, 'Claude metadata initialization')\n return await withTimeout(operation(entry.query, entry), CLAUDE_METADATA_TIMEOUT_MS, 'Claude metadata request')\n } finally {\n entry.lastUsedAt = Date.now()\n if (entry.active === undefined && entry.state === 'idle') this.#armIdleTimer(entry)\n }\n })\n this.#admissionGate = admitted.then(() => undefined, () => undefined)\n return admitted\n }\n\n #whenInitialized(entry: SupervisorEntry): Promise<void> {\n if (entry.initialized) return Promise.resolve()\n if (entry.state === 'disposed' || entry.state === 'disconnected' || entry.state === 'outcome-unknown') {\n return Promise.reject(new Error(`dsh-claude: session ${entry.sessionId} is ${entry.state}`))\n }\n return new Promise<void>((resolve, reject) => {\n entry.initWaiters.push(error => (error === undefined ? resolve() : reject(error instanceof Error ? error : new Error(String(error)))))\n })\n }\n\n async #metadataEntry(agent: Agent, model: string): Promise<SupervisorEntry> {\n const sessionId = agent.id as string\n let entry = this.#entries.get(sessionId)\n if (entry?.state === 'disposed' || entry?.state === 'disconnected' || entry?.state === 'outcome-unknown') {\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n entry = undefined\n }\n if (entry === undefined) {\n await this.#makeRoom()\n entry = await this.#createEntry(agent, model)\n this.#entries.set(sessionId, entry)\n this.#armInitializationTimer(entry)\n }\n if (entry.ownerAgent !== agent) {\n throw new Error(`dsh-claude: live agent identity changed for session ${sessionId}`)\n }\n if (entry.active !== undefined || entry.state === 'interrupting') throw new ClaudeTurnBusyError(sessionId)\n if (entry.idleTimer !== undefined) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = undefined\n }\n await this.#syncPermissionMode(entry)\n if (model !== entry.model) {\n await entry.query.setModel(model)\n entry.model = model\n }\n return entry\n }\n\n async #syncPermissionMode(entry: SupervisorEntry): Promise<void> {\n const mode = claudePermissionMode(entry.ownerAgent.session.events)\n if (mode === entry.permissionMode) return\n await entry.query.setPermissionMode(mode)\n entry.permissionMode = mode\n }\n\n async disposeSession(sessionId: string): Promise<void> {\n const entry = this.#entries.get(sessionId)\n if (entry === undefined) return\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n }\n\n async dispose(): Promise<void> {\n if (this.#disposed) return\n this.#disposed = true\n const entries = [...this.#entries.values()]\n this.#entries.clear()\n await Promise.allSettled(entries.map(entry => this.#disposeEntry(entry)))\n }\n\n async #makeRoom(): Promise<void> {\n if (this.#entries.size < this.#config.maxProcesses) return\n const idle = [...this.#entries.values()]\n .filter(entry => entry.active === undefined && entry.state === 'idle')\n .sort((left, right) => left.lastUsedAt - right.lastUsedAt)[0]\n if (idle === undefined) throw new ClaudeProcessLimitError(this.#config.maxProcesses)\n this.#entries.delete(idle.sessionId)\n await this.#disposeEntry(idle)\n }\n\n async #createEntry(agent: Agent, model: string, thinkingMode?: ClaudeThinkingMode): Promise<SupervisorEntry> {\n const sessionId = agent.id as string\n const cwd = agent.session.header.cwd ?? process.cwd()\n const input = new AsyncQueue<SDKUserMessage>()\n const lifetime = new AbortController()\n const projection = await this.#sidecar.importLegacy(sessionId, agent.session.events)\n const binding = projection.binding\n const permissionMode = claudePermissionMode(agent.session.events)\n const entry = {\n sessionId,\n ownerAgent: agent,\n cwd,\n model,\n thinkingMode,\n permissionMode,\n state: 'starting' as ClaudeSupervisorState,\n lastUsedAt: Date.now(),\n input,\n lifetime,\n claudeSessionId: binding?.claudeSessionId,\n expectedResume: binding?.claudeSessionId,\n handshakeUuid: randomUUID(),\n handshakePending: true,\n initialized: false,\n initWaiters: [] as Array<(error: unknown) => void>,\n initTimer: undefined,\n idleTimer: undefined,\n tasks: new Map<string, ClaudeTaskInfo>(),\n taskSnapshotAt: 0,\n taskSnapshotTimer: undefined,\n } as SupervisorEntry\n\n const canUseTool = createPermissionBridge(this.#approval, () => {\n const active = entry.active\n return active === undefined ? undefined : {\n agent: active.agent,\n cursor: active.cursor,\n markActivity: () => { active.sawActivity = true },\n recordDenial: toolUseId => { active.deniedToolUseIds.add(toolUseId) },\n appendActivity: activity => this.#appendActivity(active, activity),\n }\n })\n const options: ClaudeOptions = {\n pathToClaudeCodeExecutable: this.#config.executablePath,\n cwd,\n settingSources: ['user', 'project', 'local'],\n systemPrompt: { type: 'preset', preset: 'claude_code' },\n tools: { type: 'preset', preset: 'claude_code' },\n includePartialMessages: true,\n permissionMode,\n allowDangerouslySkipPermissions: true,\n canUseTool,\n abortController: lifetime,\n spawnClaudeCodeProcess: createManagedClaudeSpawner(this.#runtime, this.#config.executablePath, process => {\n entry.process = process\n }),\n ...(binding === undefined ? {} : { resume: binding.claudeSessionId }),\n model,\n ...(thinkingMode === undefined\n ? {}\n : thinkingMode === 'off'\n ? { thinking: { type: 'disabled' } as const }\n : thinkingMode === 'ultracode'\n ? { settings: { ultracode: true } satisfies ClaudeSettings }\n : { effort: thinkingMode }),\n }\n entry.query = this.#queryFactory({ prompt: input, options })\n entry.input.push(sdkUserMessage(CLAUDE_HANDSHAKE_PROMPT, entry.handshakeUuid))\n entry.pump = this.#runDetached(() => this.#pump(entry))\n return entry\n }\n\n async #pump(entry: SupervisorEntry): Promise<void> {\n try {\n for await (const sdkMessage of entry.query) {\n for (const message of normalizeSdkMessage(sdkMessage as SDKMessage)) {\n await this.#handleMessage(entry, message)\n }\n }\n if (entry.state !== 'disposed') await this.#handleDisconnect(entry, new Error('Claude Code stream ended'))\n } catch (error) {\n if (entry.state !== 'disposed') await this.#handleDisconnect(entry, error)\n }\n }\n\n async #handleMessage(entry: SupervisorEntry, message: NormalizedSdkMessage): Promise<void> {\n if (message.kind === 'init') {\n // Claude Code can re-emit system/init across turns in long-lived\n // streaming-input mode (e.g. the auth-error path). Treat it idempotently:\n // refresh the session id/version and negotiated state, and only reject a\n // genuine identity/cwd mismatch.\n if (entry.expectedResume !== undefined && message.sessionId !== entry.expectedResume) {\n throw new ClaudeProtocolError(`Claude Code resumed unexpected session ${message.sessionId}; expected ${entry.expectedResume}`)\n }\n if (message.cwd !== entry.cwd) {\n throw new ClaudeProtocolError(`Claude Code initialized in unexpected cwd ${message.cwd}; expected ${entry.cwd}`)\n }\n if (entry.initTimer !== undefined) {\n clearTimeout(entry.initTimer)\n entry.initTimer = undefined\n }\n entry.initialized = true\n entry.claudeSessionId = message.sessionId\n entry.state = entry.active === undefined ? 'idle' : 'running'\n for (const waiter of entry.initWaiters.splice(0)) waiter(undefined)\n // The SDK emits no background-task level at startup; reset the board on\n // every (re)start and let membership changes repopulate it.\n if (entry.tasks.size > 0) {\n entry.tasks.clear()\n await this.#flushTasksSnapshot(entry)\n }\n await this.#sidecar.writeBinding(entry.sessionId, {\n claudeSessionId: message.sessionId,\n cliVersion: message.cliVersion,\n cwd: message.cwd,\n })\n return\n }\n\n // Task lifecycle is session-scoped, not turn-scoped: background tasks and\n // subagents settle while no DSH turn is active, and their notifications\n // must still reach the task board instead of being dropped with turn-less\n // messages below.\n const taskId = message.kind === 'subagent' ? message.taskId : undefined\n if (message.kind === 'subagent' && taskId !== undefined) {\n await this.#trackTask(entry, message, taskId, entry.active?.cursor.turn)\n } else if (message.kind === 'background-tasks') {\n this.#trackBackgroundLevel(entry, message.tasks, entry.active?.cursor.turn)\n }\n\n if (entry.handshakePending) {\n // Startup-handshake output of the local `/status` nudge: never part of\n // any DSH turn. Protocol failures stay loud; the settlement clears the\n // phase so subsequent messages belong to real turns.\n if (message.kind === 'protocol-error') {\n throw new ClaudeProtocolError(`${message.title}: ${JSON.stringify(message.detail).slice(0, 1_000)}`)\n }\n if (message.kind === 'result') entry.handshakePending = false\n return\n }\n\n const active = entry.active\n if (active === undefined) return\n if (message.kind === 'result') {\n if (message.userMessageUuid !== undefined && message.userMessageUuid === entry.handshakeUuid) {\n // Startup handshake settlement; never a DSH turn outcome.\n return\n }\n if (entry.claudeSessionId === undefined) {\n throw new ClaudeProtocolError('Claude Code sent a result before initialization')\n }\n if (message.sessionId !== entry.claudeSessionId) {\n throw new ClaudeProtocolError(`Claude Code result session ${message.sessionId} does not match ${entry.claudeSessionId}`)\n }\n if (message.userMessageUuid !== undefined && message.userMessageUuid !== active.promptUuid) {\n throw new ClaudeProtocolError(`Claude Code result for user message ${message.userMessageUuid} does not match active request ${active.promptUuid}`)\n }\n await this.#completeTurn(entry, active, message)\n return\n }\n if (message.kind === 'protocol-error') {\n throw new ClaudeProtocolError(`${message.title}: ${JSON.stringify(message.detail).slice(0, 1_000)}`)\n }\n active.sawActivity = true\n\n switch (message.kind) {\n case 'text-delta':\n if (message.parentToolUseId !== undefined) return\n active.sawTextDelta = true\n active.text += message.text\n active.output.push({ type: 'text-delta', text: message.text })\n return\n case 'assistant-text':\n if (message.parentToolUseId !== undefined) return\n if (!active.sawTextDelta) {\n // Complete assistant text is the fallback when no partial text delta\n // streamed. Mark text-delta seen so that additional complete\n // assistant records sharing the same message.id (one per completed\n // content block) do not duplicate the text.\n active.sawTextDelta = true\n active.text += message.text\n active.output.push({ type: 'text-delta', text: message.text })\n }\n return\n case 'thinking':\n if (message.parentToolUseId !== undefined) return\n if (message.phase === 'updated') {\n active.thinking += message.text\n return\n }\n active.thinking = message.text\n await this.#appendActivity(active, {\n kind: 'thinking',\n phase: 'completed',\n title: 'Claude thinking',\n summary: message.text,\n })\n return\n case 'tool-call':\n await this.#appendActivity(active, {\n kind: message.parentToolUseId === undefined ? 'tool-call' : 'subagent',\n phase: 'started',\n toolUseId: message.toolUseId,\n ...(message.parentToolUseId === undefined ? {} : { parentToolUseId: message.parentToolUseId }),\n toolName: message.toolName,\n title: message.toolName,\n summary: message.parentToolUseId === undefined ? rootCallSummary(message.toolName, message.input) : `Subagent called ${message.toolName}`,\n detail: message.input,\n })\n if (message.parentToolUseId === undefined) {\n active.callNames.set(message.toolUseId, message.toolName)\n this.#ensureDynamicPresenter(active.agent, message.toolName)\n // Task dispatches render as plugin-owned group cards gathering the\n // subagents' nested work; only ordinary tools mirror natively.\n if (!TASK_TOOL_NAMES.has(message.toolName)) await this.#appendNativeToolCall(active, message)\n }\n return\n case 'tool-result':\n await this.#appendActivity(active, {\n kind: message.parentToolUseId === undefined ? 'tool-result' : 'subagent',\n phase: message.isError ? 'failed' : 'completed',\n toolUseId: message.toolUseId,\n ...(message.parentToolUseId === undefined ? {} : { parentToolUseId: message.parentToolUseId }),\n title: message.isError ? 'Tool failed' : 'Tool completed',\n detail: message.output,\n isError: message.isError,\n })\n if (message.parentToolUseId === undefined\n && !TASK_TOOL_NAMES.has(active.callNames.get(message.toolUseId) ?? '')) {\n await this.#appendNativeToolResult(active, message)\n }\n return\n case 'subagent':\n await this.#appendActivity(active, {\n kind: 'subagent',\n phase: message.phase,\n ...(message.taskId === undefined ? {} : { taskId: message.taskId }),\n title: message.title,\n summary: message.summary,\n detail: message.detail,\n isError: message.phase === 'failed',\n })\n return\n case 'status':\n case 'warning':\n case 'unknown':\n await this.#appendActivity(active, {\n kind: message.kind === 'status' ? 'status' : 'warning',\n phase: 'updated',\n title: message.title,\n ...('summary' in message ? { summary: message.summary } : {}),\n ...('detail' in message ? { detail: message.detail } : {}),\n })\n return\n case 'permission-denied':\n await this.#appendActivity(active, {\n kind: 'permission',\n phase: 'denied',\n toolUseId: message.toolUseId,\n toolName: message.toolName,\n title: message.toolName,\n summary: message.summary,\n })\n return\n }\n }\n\n /** Merge one task lifecycle message into the session's task board. */\n async #trackTask(\n entry: SupervisorEntry,\n message: Extract<NormalizedSdkMessage, { kind: 'subagent' }>,\n taskId: string,\n originTurn: number | undefined,\n ): Promise<void> {\n const previous = entry.tasks.get(taskId)\n const next: ClaudeTaskInfo = {\n taskId,\n description: message.description ?? previous?.description ?? message.title,\n status: message.taskStatus ?? previous?.status ?? 'running',\n }\n const resolvedOriginTurn = previous?.originTurn ?? originTurn\n if (resolvedOriginTurn !== undefined) next.originTurn = resolvedOriginTurn\n const subagentType = message.subagentType ?? previous?.subagentType\n if (subagentType !== undefined) next.subagentType = subagentType\n const taskType = message.taskType ?? previous?.taskType\n if (taskType !== undefined) next.taskType = taskType\n const lastToolName = message.lastToolName ?? previous?.lastToolName\n if (lastToolName !== undefined) next.lastToolName = lastToolName\n const summary = message.summary ?? previous?.summary\n if (summary !== undefined) next.summary = summary\n const usage = message.usage ?? previous?.usage\n if (usage !== undefined) next.usage = usage\n if (previous?.backgrounded === true) next.backgrounded = true\n entry.tasks.set(taskId, next)\n const settled = next.status !== 'running'\n await this.#scheduleTasksSnapshot(entry, settled)\n }\n\n /** Fold the background-task level signal into the board (REPLACE semantics\n * for the backgrounded flag: only the listed tasks are detached). */\n #trackBackgroundLevel(\n entry: SupervisorEntry,\n tasks: readonly { taskId: string; taskType?: string; description: string }[],\n originTurn: number | undefined,\n ): void {\n const live = new Set(tasks.map(task => task.taskId))\n let changed = false\n for (const task of tasks) {\n const existing = entry.tasks.get(task.taskId)\n if (existing === undefined) {\n entry.tasks.set(task.taskId, {\n taskId: task.taskId,\n description: task.description,\n status: 'running',\n ...(originTurn === undefined ? {} : { originTurn }),\n ...(task.taskType === undefined ? {} : { taskType: task.taskType }),\n backgrounded: true,\n })\n changed = true\n } else if (existing.backgrounded !== true || existing.status !== 'running') {\n entry.tasks.set(task.taskId, { ...existing, status: 'running', backgrounded: true })\n changed = true\n }\n }\n for (const task of entry.tasks.values()) {\n if (task.backgrounded === true && task.status === 'running' && !live.has(task.taskId)) {\n entry.tasks.set(task.taskId, { ...task, status: 'completed' })\n changed = true\n }\n }\n if (changed) void this.#scheduleTasksSnapshot(entry, true)\n }\n\n /** Persist the task board. Settled transitions flush immediately; progress\n * ticks throttle to one snapshot per second to bound log volume. */\n async #scheduleTasksSnapshot(entry: SupervisorEntry, immediate: boolean): Promise<void> {\n const THROTTLE_MS = 1_000\n const elapsed = Date.now() - entry.taskSnapshotAt\n if (!immediate && elapsed < THROTTLE_MS) {\n if (entry.taskSnapshotTimer === undefined) {\n entry.taskSnapshotTimer = setTimeout(() => {\n entry.taskSnapshotTimer = undefined\n void this.#flushTasksSnapshot(entry)\n }, THROTTLE_MS - elapsed)\n entry.taskSnapshotTimer.unref?.()\n }\n return\n }\n await this.#flushTasksSnapshot(entry)\n }\n\n async #flushTasksSnapshot(entry: SupervisorEntry): Promise<void> {\n if (entry.taskSnapshotTimer !== undefined) {\n clearTimeout(entry.taskSnapshotTimer)\n entry.taskSnapshotTimer = undefined\n }\n entry.taskSnapshotAt = Date.now()\n // Snapshot persistence is best-effort: the in-memory board stays\n // authoritative and the next change re-flushes.\n await this.#sidecar.writeTasks(entry.sessionId, [...entry.tasks.values()]).catch(() => undefined)\n }\n\n async #completeTurn(\n entry: SupervisorEntry,\n active: ActiveTurn,\n result: Extract<NormalizedSdkMessage, { kind: 'result' }>,\n ): Promise<void> {\n if (entry.active !== active) return\n if (active.signal !== undefined && active.abortListener !== undefined) {\n active.signal.removeEventListener('abort', active.abortListener)\n }\n if (active.aborted) {\n await this.#appendSafely(active, {\n kind: 'status',\n phase: 'failed',\n title: 'Claude Code turn cancelled',\n })\n entry.active = undefined\n entry.state = 'idle'\n entry.lastUsedAt = Date.now()\n this.#armIdleTimer(entry)\n return\n }\n if (result.usage.inputTokens !== undefined || result.usage.outputTokens !== undefined || result.usage.cumulativeCostUsd !== undefined) {\n await this.#appendSafely(active, {\n kind: 'usage',\n phase: 'completed',\n title: 'Claude usage',\n summary: usageSummary(result.usage),\n usage: result.usage,\n })\n active.output.push({ type: 'usage', usage: result.usage })\n }\n const unmatchedDenials = (result.permissionDenials ?? [])\n .filter(denial => !active.deniedToolUseIds.has(denial.toolUseId))\n if (unmatchedDenials.length > 0) {\n await this.#appendSafely(active, {\n kind: 'permission',\n phase: 'denied',\n title: 'Claude Code auto-denied tool calls',\n summary: unmatchedDenials.map(denial => denial.toolName).join(', '),\n })\n }\n if (!result.success) {\n const message = result.errors?.join('\\n')\n ?? (result.terminalReason !== undefined ? `Claude Code failed the turn (${result.terminalReason})` : 'Claude Code failed the turn')\n await this.#appendSafely(active, {\n kind: 'error',\n phase: 'failed',\n title: 'Claude Code turn failed',\n summary: message,\n isError: true,\n })\n active.output.fail(new Error(message))\n } else {\n if (!active.sawTextDelta && active.text.length === 0 && result.text !== undefined) {\n active.text = result.text\n active.output.push({ type: 'text-delta', text: result.text })\n }\n await this.#appendSafely(active, {\n kind: 'status',\n phase: 'completed',\n title: 'Claude Code turn completed',\n })\n active.output.push({ type: 'complete', text: active.text })\n active.output.close()\n }\n entry.active = undefined\n entry.state = 'idle'\n entry.lastUsedAt = Date.now()\n this.#armIdleTimer(entry)\n }\n\n async #appendActivity(active: ActiveTurn, activity: ClaudeActivityInput): Promise<void> {\n const ordinal = active.cursor.nextOrdinal++\n await this.#sidecar.appendActivity(active.agent.id as string, {\n ...activity,\n turn: active.cursor.turn,\n step: active.cursor.step,\n ordinal,\n })\n }\n\n /** Persist durable activity without letting a storage failure unsettle the\n * in-memory turn or leak process ownership. Audit failure is best-effort. */\n async #appendSafely(active: ActiveTurn, activity: ClaudeActivityInput): Promise<void> {\n await this.#appendActivity(active, activity).catch(() => undefined)\n }\n\n /** Register one presenter-only mirror for a tool name the static preset\n * registry does not cover (MCP tools, newly added built-ins). Runs in the\n * agent scope so the mirror is visible only to this preset's sessions and\n * unwinds with the agent; failure keeps the generic card, never the turn. */\n #ensureDynamicPresenter(agent: Agent, name: string): void {\n if (CLAUDE_PRESENTER_NAMES.has(name)) return\n let known = this.#dynamicPresenterNames.get(agent)\n if (known === undefined) {\n known = new Set<string>()\n this.#dynamicPresenterNames.set(agent, known)\n }\n if (known.has(name)) return\n try {\n agent.ctx.tools.register(dynamicPresenterDefinition(name))\n known.add(name)\n } catch {\n // A late or disposed agent keeps the generic card; presentation must\n // never unsettle the Claude turn.\n }\n }\n\n /** Mirror one root Claude tool call into the durable native tool channel so\n * the host's tool presentation renders it exactly like a DSH-executed call.\n * Presentation duplication is best-effort and never unsettles the turn. */\n async #appendNativeToolCall(\n active: ActiveTurn,\n message: Extract<NormalizedSdkMessage, { kind: 'tool-call' }>,\n ): Promise<void> {\n try {\n await active.agent.session.append('tool/call', {\n turn: active.cursor.turn,\n step: active.cursor.step,\n callId: CallId(message.toolUseId),\n name: message.toolName,\n arguments: safeDetail(message.input) ?? '{}',\n })\n } catch {\n // Presentation duplication must never unsettle the Claude turn.\n }\n }\n\n async #appendNativeToolResult(\n active: ActiveTurn,\n message: Extract<NormalizedSdkMessage, { kind: 'tool-result' }>,\n ): Promise<void> {\n const text = typeof message.output === 'string' ? redactText(message.output) : safeDetail(message.output) ?? ''\n try {\n await active.agent.session.append('tool/result', {\n turn: active.cursor.turn,\n step: active.cursor.step,\n message: createToolResultMessage({\n callId: CallId(message.toolUseId),\n content: [{ type: 'text', text }],\n isError: message.isError,\n }),\n }, { surfaceOp: 'append' })\n } catch {\n // Presentation duplication must never unsettle the Claude turn.\n }\n }\n\n async #interrupt(entry: SupervisorEntry): Promise<void> {\n const active = entry.active\n if (active === undefined || entry.state === 'interrupting') return\n entry.state = 'interrupting'\n active.aborted = true\n active.output.fail(abortFailure())\n let interruptError: unknown\n try {\n const receipt = await withTimeout(entry.query.interrupt(), CLAUDE_INTERRUPT_TIMEOUT_MS, 'Claude Code interrupt')\n const queued = receipt?.still_queued ?? []\n if (queued.includes(active.promptUuid)) {\n throw new Error(`Claude Code interrupt left submitted prompt ${active.promptUuid} queued`)\n }\n } catch (error) {\n interruptError = error\n }\n try {\n await this.#appendActivity(active, {\n kind: 'status',\n phase: 'failed',\n title: interruptError === undefined ? 'Claude Code turn cancelled' : 'Claude Code cancelled; process entry reset',\n ...(interruptError === undefined ? {} : { summary: errorSummary(interruptError) }),\n })\n } catch {\n // The active output is already aborted; process cleanup cannot wait for audit availability.\n }\n if (this.#entries.get(entry.sessionId) === entry) this.#entries.delete(entry.sessionId)\n await this.#disposeEntry(entry)\n }\n\n async #handleDisconnect(entry: SupervisorEntry, error: unknown): Promise<void> {\n const active = entry.active\n const stderr = entry.process?.stderrTail()\n if (active !== undefined) {\n if (active.signal !== undefined && active.abortListener !== undefined) {\n active.signal.removeEventListener('abort', active.abortListener)\n }\n const unknown = active.sawActivity\n entry.state = unknown ? 'outcome-unknown' : 'disconnected'\n const failure = unknown\n ? new ClaudeOutcomeUnknownError(stderr === undefined || stderr.length === 0 ? undefined : `Claude Code exited after activity; outcome unknown. ${stderr}`)\n : new Error(stderr === undefined || stderr.length === 0 ? errorSummary(error) : stderr)\n await this.#appendSafely(active, {\n kind: 'error',\n phase: 'failed',\n title: unknown ? 'Claude Code outcome unknown' : 'Claude Code disconnected',\n summary: failure.message,\n isError: true,\n detail: error,\n })\n active.output.fail(failure)\n entry.active = undefined\n } else {\n entry.state = 'disconnected'\n }\n const waiters = entry.initWaiters.splice(0)\n const waiterError = error instanceof Error ? error : new Error(String(error))\n for (const waiter of waiters) waiter(waiterError)\n this.#entries.delete(entry.sessionId)\n await this.#disposeEntry(entry)\n }\n\n #armInitializationTimer(entry: SupervisorEntry): void {\n const timer = setTimeout(() => {\n if (entry.state !== 'starting' || entry.initialized) return\n void this.#handleDisconnect(entry, new Error('Claude Code initialization timed out'))\n }, CLAUDE_INITIALIZATION_TIMEOUT_MS)\n timer.unref?.()\n entry.initTimer = timer\n }\n\n #armIdleTimer(entry: SupervisorEntry): void {\n if (this.#config.idleTimeoutMs <= 0) return\n const timer = setTimeout(() => {\n if (entry.active !== undefined || entry.state !== 'idle') return\n this.#entries.delete(entry.sessionId)\n void this.#disposeEntry(entry)\n }, this.#config.idleTimeoutMs)\n timer.unref?.()\n entry.idleTimer = timer\n }\n\n async #disposeEntry(entry: SupervisorEntry): Promise<void> {\n if (entry.state === 'disposed') return\n if (entry.idleTimer !== undefined) clearTimeout(entry.idleTimer)\n if (entry.initTimer !== undefined) clearTimeout(entry.initTimer)\n entry.state = 'disposed'\n entry.input.discard(abortFailure())\n entry.query.close()\n entry.lifetime.abort()\n if (entry.active !== undefined) entry.active.output.fail(abortFailure())\n entry.process?.kill('SIGTERM')\n if (entry.process !== undefined) {\n try {\n await entry.process.handle.waitForExit(AbortSignal.timeout(5_000))\n } catch {\n // The DSH subprocess owner still holds the tree and will finish escalation.\n }\n }\n }\n}\n","import {\n LlmAdapter,\n ReasoningEffortId,\n type GenerateOptions,\n type LlmModelInfo,\n type LlmProviderInfo,\n type LlmResolvedModelInfo,\n type ResolvedRetryPolicy,\n type StreamChunk,\n type TokenUsage,\n} from '@deepseek-ai/dsh-llm'\nimport type { Agent, AgentRegistry } from '@deepseek-ai/dsh-agent'\nimport { CLAUDE_CODE_PRESET_ID, CLAUDE_CODE_PROVIDER, isClaudePresetId } from './constants.ts'\nimport type { ClaudeSupervisor, ClaudeThinkingMode } from './supervisor.ts'\nimport type { ClaudeUsage } from './events.ts'\n\nconst MODELS = [\n { id: 'default', name: 'Default (recommended)', description: 'Use Claude Code’s recommended default model.' },\n { id: 'opus[1m]', name: 'Opus (1M context)', description: 'Use Opus with a 1M-token context window.', contextWindow: 1_000_000 },\n { id: 'fable', name: 'Fable', description: 'Use Fable, Claude Code’s most capable coding model.' },\n { id: 'sonnet', name: 'Sonnet', description: 'Use Sonnet for efficient routine coding work.' },\n { id: 'haiku', name: 'Haiku', description: 'Use Haiku for fast, lightweight tasks.' },\n] as const\n\nconst THINKING_MODES = [\n { id: 'off', name: 'Off', description: 'No extended thinking.' },\n { id: 'low', name: 'Low', description: 'Minimal thinking, fastest responses.' },\n { id: 'medium', name: 'Medium', description: 'Moderate thinking.' },\n { id: 'high', name: 'High', description: 'Deep reasoning (Claude Code default).' },\n { id: 'xhigh', name: 'Extra High', description: 'Deeper than high; unsupported models silently downgrade to high.' },\n { id: 'max', name: 'Max', description: 'Maximum effort; unsupported models silently downgrade.' },\n { id: 'ultracode', name: 'Ultracode', description: 'Extra-high effort plus standing dynamic-workflow orchestration; requires an xhigh-capable model.' },\n] as const\n\nexport function thinkingModeFor(effort: ReasoningEffortId | undefined): ClaudeThinkingMode | undefined {\n if (effort === undefined) return undefined\n if (THINKING_MODES.some(mode => mode.id === (effort as string))) return effort as unknown as ClaudeThinkingMode\n throw new Error(`dsh-claude: unsupported reasoning effort ${JSON.stringify(effort)}`)\n}\n\nconst NO_RETRY_POLICY: ResolvedRetryPolicy = Object.freeze({\n mode: 'normal',\n maxRetries: 0,\n retryableCodes: Object.freeze([]),\n initialDelayMs: 500,\n maxDelayMs: 10_000,\n jitterRatio: 0.1,\n})\n\nexport function extractDirectUserText(messages: GenerateOptions['messages']): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (message?.role !== 'user' || message.source.kind !== 'user') continue\n const text = message.content\n .filter((block): block is Extract<typeof block, { type: 'text' }> => block.type === 'text')\n .map(block => block.text)\n .join('\\n')\n .trim()\n if (text.length > 0) return text\n if (message.content.some(block => block.type === 'image')) {\n throw new Error('dsh-claude: image-only prompts are not supported in v0.1; include a text prompt')\n }\n }\n throw new Error('dsh-claude: no direct human text was present in this model step')\n}\n\nfunction tokenUsage(usage: ClaudeUsage): TokenUsage {\n const normalized: TokenUsage = {\n inputTokens: usage.inputTokens ?? 0,\n outputTokens: usage.outputTokens ?? 0,\n }\n if (usage.cacheReadTokens !== undefined) normalized.cacheReadTokens = usage.cacheReadTokens\n if (usage.cacheCreationTokens !== undefined) normalized.cacheWriteTokens = usage.cacheCreationTokens\n return normalized\n}\n\nfunction resolveAgent(agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>, options: GenerateOptions): Agent {\n const initiator = agents.currentInitiator()\n if (initiator !== undefined) return initiator\n if (options.sessionId !== undefined) {\n const agent = agents.get(options.sessionId)\n if (agent !== undefined) return agent\n }\n throw new Error('dsh-claude: the model request has no live owning DSH agent')\n}\n\nexport class ClaudeCodeAdapter extends LlmAdapter {\n readonly #supervisor: ClaudeSupervisor\n readonly #agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>\n readonly #presetIdFor: (agent: Agent) => string | undefined\n\n constructor(\n supervisor: ClaudeSupervisor,\n agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>,\n presetIdFor: (agent: Agent) => string | undefined,\n ) {\n super()\n this.#supervisor = supervisor\n this.#agents = agents\n this.#presetIdFor = presetIdFor\n }\n\n override providerInfo(provider: string): LlmProviderInfo {\n return { id: provider, name: 'Claude Code' }\n }\n\n override providerRetryPolicy(): ResolvedRetryPolicy {\n return NO_RETRY_POLICY\n }\n\n override async listModels(): Promise<readonly LlmModelInfo[]> {\n return MODELS.map(model => ({\n provider: CLAUDE_CODE_PROVIDER,\n id: model.id,\n name: model.name,\n description: model.description,\n inputModalities: ['text'],\n }))\n }\n\n override async resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {\n const known = MODELS.find(item => item.id === model)\n const observedContextWindow = this.#supervisor.contextWindow(model)\n const contextWindow = observedContextWindow ?? (known !== undefined && 'contextWindow' in known ? known.contextWindow : undefined)\n return {\n provider,\n id: model,\n name: known?.name ?? `Claude Code ${model}`,\n ...(known === undefined ? {} : { description: known.description }),\n ...(contextWindow === undefined ? {} : { context: { contextWindow } }),\n inputModalities: ['text'],\n reasoning: {\n efforts: THINKING_MODES.map(mode => ({\n id: ReasoningEffortId(mode.id),\n name: mode.name,\n description: mode.description,\n })),\n },\n }\n }\n\n override async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {\n if (options.purpose !== undefined) {\n throw new Error(`dsh-claude: auxiliary ${options.purpose} calls are not routed into the Claude session`)\n }\n const agent = resolveAgent(this.#agents, options)\n if (!isClaudePresetId(this.#presetIdFor(agent))) {\n throw new Error(`dsh-claude: provider ${CLAUDE_CODE_PROVIDER} is available only to the ${CLAUDE_CODE_PRESET_ID} preset`)\n }\n const thinkingMode = thinkingModeFor(options.reasoningEffort)\n const prompt = extractDirectUserText(options.messages)\n const events = await this.#supervisor.runTurn({\n agent,\n prompt,\n model: options.model,\n ...(thinkingMode === undefined ? {} : { thinkingMode }),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n\n let text = ''\n let pendingUsage: TokenUsage | undefined\n let completed = false\n try {\n for await (const event of events) {\n if (event.type === 'text-delta') {\n // Buffered, not live-streamed: Claude's intermediate prose and final\n // answer settle as one block at the turn's durable position, below\n // the step's mirrored tool cards, instead of jumping there at the end.\n text += event.text\n } else if (event.type === 'usage') {\n pendingUsage = tokenUsage(event.usage)\n } else {\n completed = true\n if (text.length > 0) {\n yield { type: 'block-start', index: 0, blockType: 'text' }\n yield { type: 'text-delta', index: 0, text }\n yield { type: 'block-end', index: 0, block: { type: 'text', text } }\n }\n if (pendingUsage !== undefined) yield { type: 'usage', usage: pendingUsage }\n yield { type: 'finish', reason: { kind: 'stop' } }\n }\n }\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n completed = true\n if (text.length > 0) {\n yield { type: 'block-start', index: 0, blockType: 'text' }\n yield { type: 'text-delta', index: 0, text }\n yield { type: 'block-end', index: 0, block: { type: 'text', text } }\n }\n yield {\n type: 'finish',\n reason: {\n kind: 'aborted',\n failure: { code: 'aborted', message: error instanceof Error ? error.message : 'Claude Code turn aborted' },\n },\n }\n return\n }\n throw error\n }\n if (!completed) throw new Error('dsh-claude: Claude turn stream ended without a result')\n }\n}\n\nexport function createClaudeCodeAdapter(\n supervisor: ClaudeSupervisor,\n agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>,\n presetIdFor: (agent: Agent) => string | undefined,\n): ClaudeCodeAdapter {\n return new ClaudeCodeAdapter(supervisor, agents, presetIdFor)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\n/** Accept only loopback, same-origin browser requests to plugin-private routes. */\nexport function trustedRequest(req: IncomingMessage): boolean {\n const remote = req.socket.remoteAddress\n if (remote !== '127.0.0.1' && remote !== '::1' && remote !== '::ffff:127.0.0.1') return false\n const site = req.headers['sec-fetch-site']\n if (site === 'cross-site') return false\n const host = req.headers.host\n if (host === undefined) return false\n const authority = /^(?:127\\.0\\.0\\.1|\\[?::1\\]?|localhost)(?::\\d+)?$/i\n if (!authority.test(host)) return false\n const origin = req.headers.origin\n if (origin === undefined) return true\n try {\n const originUrl = new URL(origin)\n return originUrl.host === host && authority.test(originUrl.host)\n } catch {\n return false\n }\n}\n\n/** Send a non-cacheable JSON response with MIME sniffing disabled. */\nexport function json(res: ServerResponse, status: number, value: unknown): void {\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'x-content-type-options': 'nosniff',\n })\n res.end(JSON.stringify(value))\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-agent-presets'\nimport type {} from '@deepseek-ai/dsh-commands'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { CLAUDE_DOCTOR_PATH } from './constants.ts'\nimport { runClaudeDoctor, type ExecutableRuntime } from './executable.ts'\nimport type { ClaudeSupervisor, ClaudeSupervisorConfig } from './supervisor.ts'\nimport { redactText } from './events.ts'\nimport { json, trustedRequest } from './http.ts'\n\nexport const CLAUDE_DOCTOR_PROBE_TIMEOUT_MS = 15_000\n\n/** Live metadata-bridge state per agent, maintained by the host plugin. */\nexport interface ClaudeBridgeDiagnostic {\n attempts: number\n lastError?: string\n lastCatalog?: number\n registered?: string[]\n}\n\nexport const claudeBridgeDiagnostics = new WeakMap<Agent, ClaudeBridgeDiagnostic>()\n\nfunction safeMessage(error: unknown): string {\n return redactText(error instanceof Error ? error.message : String(error), 1_000)\n}\n\n/** Live command-bridge diagnostics: which agents exist, their presets, and how\n * many slash commands each agent's registry layer resolves. */\nfunction commandDiagnostics(ctx: Context): unknown {\n try {\n const agents = ctx.agents.list()\n return {\n total: agents.length,\n agents: agents.map(agent => {\n const info: { id: string; preset?: string; commandCount?: number; sample?: string[]; error?: string; bridge?: ClaudeBridgeDiagnostic } = { id: String(agent.id) }\n try {\n const preset = ctx.agentPresets.composedPreset(agent.ctx)\n if (preset !== undefined) info.preset = preset\n } catch (error) {\n info.error = safeMessage(error)\n }\n try {\n const list = ctx.commands.list(agent)\n info.commandCount = list.length\n info.sample = list.slice(0, 10).map(command => command.name)\n } catch (error) {\n info.error = info.error === undefined ? safeMessage(error) : `${info.error}; ${safeMessage(error)}`\n }\n const bridge = claudeBridgeDiagnostics.get(agent)\n if (bridge !== undefined) info.bridge = bridge\n return info\n }),\n }\n } catch (error) {\n return { error: safeMessage(error) }\n }\n}\n\nexport function registerClaudeDoctorRoutes(\n ctx: Context,\n runtime: ExecutableRuntime,\n supervisor: ClaudeSupervisor,\n config: ClaudeSupervisorConfig,\n resolutionError?: unknown,\n): void {\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: CLAUDE_DOCTOR_PATH,\n handler: async (req, res) => {\n if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })\n if (!trustedRequest(req)) return json(res, 403, { error: 'forbidden' })\n try {\n if (resolutionError !== undefined) {\n return json(res, 200, {\n executable: {\n status: 'missing',\n searched: config.executablePath.length > 0 ? [config.executablePath] : ['claude', '~/.local/bin/claude', '/opt/homebrew/bin/claude', '/usr/local/bin/claude'],\n },\n version: { status: 'not-run' },\n authentication: { status: 'not-run' },\n handshake: 'not-run',\n message: safeMessage(resolutionError),\n limits: {\n idleTimeoutMs: config.idleTimeoutMs,\n maxProcesses: config.maxProcesses,\n },\n processes: { count: 0, active: 0 },\n })\n }\n const report = await runClaudeDoctor(runtime, {\n configuredPath: config.executablePath,\n cwd: process.cwd(),\n signal: AbortSignal.timeout(CLAUDE_DOCTOR_PROBE_TIMEOUT_MS),\n })\n const processes = supervisor.snapshots()\n if (processes.some(process => process.claudeSessionId !== undefined)) report.handshake = 'ok'\n json(res, 200, {\n ...report,\n limits: {\n idleTimeoutMs: config.idleTimeoutMs,\n maxProcesses: config.maxProcesses,\n },\n processes: {\n count: processes.length,\n active: processes.filter(process => process.state === 'running' || process.state === 'starting').length,\n },\n commandBridge: commandDiagnostics(ctx),\n })\n } catch (error) {\n json(res, 500, { error: safeMessage(error) })\n }\n },\n }), 'dsh-claude: Doctor route')\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { CLAUDE_PROJECTION_PATH } from './constants.ts'\nimport { json, trustedRequest } from './http.ts'\nimport type { ClaudeSidecarRepository } from './sidecar.ts'\n\nconst MAX_SESSION_ID_CHARS = 1_024\n\nfunction sessionIdFromUrl(rawUrl: string | undefined): string | undefined {\n try {\n const pathname = new URL(rawUrl ?? '/', 'http://localhost').pathname\n const prefix = `${CLAUDE_PROJECTION_PATH}/`\n if (!pathname.startsWith(prefix)) return undefined\n const encoded = pathname.slice(prefix.length)\n if (encoded.length === 0 || encoded.includes('/')) return undefined\n const sessionId = decodeURIComponent(encoded)\n if (sessionId.length === 0 || sessionId.length > MAX_SESSION_ID_CHARS) return undefined\n return sessionId\n } catch {\n return undefined\n }\n}\n\n/** Register the browser-readable, credential-free sidecar projection endpoint. */\nexport function registerClaudeProjectionRoute(\n ctx: Context,\n sidecar: ClaudeSidecarRepository,\n ownsSession: (sessionId: string) => boolean,\n): void {\n ctx.effect(() => ctx.webServer.register({\n kind: 'prefix',\n path: CLAUDE_PROJECTION_PATH,\n handler: async (req, res) => {\n if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })\n if (!trustedRequest(req)) return json(res, 403, { error: 'forbidden' })\n const sessionId = sessionIdFromUrl(req.url)\n if (sessionId === undefined) return json(res, 400, { error: 'invalid session id' })\n try {\n const projection = await sidecar.read(sessionId)\n return json(res, 200, {\n schemaVersion: projection.schemaVersion,\n revision: projection.revision,\n owned: ownsSession(sessionId),\n activities: projection.activities,\n ...(projection.contextUsage === undefined ? {} : { contextUsage: projection.contextUsage }),\n ...(projection.tasks === undefined ? {} : { tasks: projection.tasks }),\n })\n } catch {\n return json(res, 500, { error: 'projection unavailable' })\n }\n },\n }), 'dsh-claude: sidecar projection route')\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-commands'\nimport { createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type {} from '@deepseek-ai/dsh-agent-presets'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport type {} from '@deepseek-ai/dsh-subprocess'\nimport type {} from '@deepseek-ai/dsh-user-approval'\nimport { CLAUDE_CODE_PRESET_ID, CLAUDE_CODE_PROVIDER_IDS, isClaudePresetId } from './constants.ts'\nimport { CLAUDE_COMMANDS_SERVICE, ClaudeCommandBridge, type ClaudeAgentCommandService } from './command-bridge.ts'\nimport { ClaudeSidecarRepository } from './sidecar.ts'\nimport { resolveClaudeExecutable } from './executable.ts'\nimport { ClaudeSupervisor } from './supervisor.ts'\nimport { createClaudeCodeAdapter } from './adapter.ts'\nimport { ensureManagedPreset } from './preset-installer.ts'\nimport { claudeBridgeDiagnostics, registerClaudeDoctorRoutes, type ClaudeBridgeDiagnostic } from './doctor-routes.ts'\nimport { registerClaudeProjectionRoute } from './projection-routes.ts'\n\nexport const name = 'llm-claude'\nexport const inject = ['llm', 'agents', 'agentPresets', 'commands', 'subprocess', 'approval']\n\nexport interface Config {\n executablePath?: string\n model?: string\n idleTimeoutMs?: number\n maxProcesses?: number\n}\n\nexport const Config: z<Config> = z.object({\n executablePath: z.string().default(''),\n model: z.string().default('default'),\n idleTimeoutMs: z.number().min(1_000).max(2_147_483_647).default(30 * 60 * 1_000),\n maxProcesses: z.number().step(1).min(1).default(4),\n})\n\nconst CLAUDE_SCOPE_UNAVAILABLE_MESSAGE = 'agent command scope unavailable (preset route not mounted?)'\nconst CATALOG_RETRY_MS = 5_000\nconst SCOPE_RETRY_MS = 500\nconst MAX_CATALOG_RETRIES = 3\nconst MAX_SCOPE_RETRIES = 24\n\nexport function mountClaudeMetadata(\n ctx: Context,\n supervisor: ClaudeSupervisor,\n agent: Agent,\n model: string,\n sidecar: ClaudeSidecarRepository,\n // IMPORTANT: call through the injected agentPresets SERVICE, never an\n // imported serviceForAgent() — a linked plugin resolves peer packages from\n // its own node_modules, which creates a second module instance with empty\n // module-level mount state. The service method runs on the app's instance.\n resolveCommands: () => ClaudeAgentCommandService | undefined =\n () => ctx.agentPresets.serviceFor(agent, CLAUDE_COMMANDS_SERVICE),\n): (() => Promise<void>) | undefined {\n if (!isClaudePresetId(ctx.agentPresets.composedPreset(agent.ctx))) return undefined\n\n let stopped = false\n let pending = Promise.resolve()\n let commandScope: ClaudeAgentCommandService | undefined\n\n // The commands service is unreachable from this host view of agent.ctx;\n // the preset route plugin provides it as an isolated per-session service.\n const scopedCommands = () => {\n const scoped = commandScope ?? resolveCommands()\n if (scoped === undefined) throw new Error(CLAUDE_SCOPE_UNAVAILABLE_MESSAGE)\n commandScope = scoped\n return scoped\n }\n\n const bridge = new ClaudeCommandBridge({\n list: () => scopedCommands().list(agent),\n register: definition => scopedCommands().register(definition),\n forward: line => {\n agent.followup(createUserMessage({\n content: [{ type: 'text', text: line }],\n source: { kind: 'user' },\n }))\n },\n })\n\n const warn = (area: string, error: unknown) => {\n ctx.logger.warn(`dsh-claude: ${area} refresh failed for ${String(agent.id)}: ${error instanceof Error ? error.message : String(error)}`)\n }\n\n const isScopeUnavailable = (error: unknown): boolean => {\n if (error instanceof Error) return error.message === CLAUDE_SCOPE_UNAVAILABLE_MESSAGE\n return String(error) === CLAUDE_SCOPE_UNAVAILABLE_MESSAGE\n }\n\n const diagnostic: ClaudeBridgeDiagnostic = claudeBridgeDiagnostics.get(agent) ?? { attempts: 0 }\n claudeBridgeDiagnostics.set(agent, diagnostic)\n\n // A fresh session's first catalog fetch races CLI startup (skills/plugins\n // can make init slow); retry with backoff so the command palette still\n // populates without waiting for the first completed turn.\n let catalogRetries = 0\n let scopeRetries = 0\n let retryTimer: ReturnType<typeof setTimeout> | undefined\n\n const scheduleRetry = (area: 'command catalog' | 'command scope', attempt: number) => {\n if (retryTimer !== undefined) clearTimeout(retryTimer)\n const delay = area === 'command catalog' ? CATALOG_RETRY_MS * attempt : Math.min(SCOPE_RETRY_MS * 2 ** attempt, 5_000)\n retryTimer = setTimeout(() => {\n if (!stopped) refresh()\n }, delay)\n retryTimer.unref?.()\n }\n\n const refresh = () => {\n pending = pending.then(async () => {\n if (stopped) return\n diagnostic.attempts += 1\n\n let catalog: Awaited<ReturnType<ClaudeSupervisor['supportedCommands']>> | undefined\n\n try {\n const result = await supervisor.supportedCommands(agent, model)\n catalog = result\n catalogRetries = 0\n scopeRetries = 0\n diagnostic.lastCatalog = catalog.length\n delete diagnostic.lastError\n } catch (error) {\n diagnostic.lastError = error instanceof Error ? error.message : String(error)\n warn('command catalog', error)\n if (!stopped && catalogRetries < MAX_CATALOG_RETRIES) {\n catalogRetries += 1\n scheduleRetry('command catalog', catalogRetries)\n }\n }\n\n if (stopped || catalog === undefined) return\n\n try {\n diagnostic.registered = bridge.refresh(catalog).map(view => view.publicName)\n if (!stopped) scopeRetries = 0\n } catch (error) {\n diagnostic.lastError = error instanceof Error ? error.message : String(error)\n warn('command catalog', error)\n if (!stopped && isScopeUnavailable(error) && scopeRetries < MAX_SCOPE_RETRIES) {\n scopeRetries += 1\n scheduleRetry('command scope', scopeRetries)\n }\n }\n\n if (stopped) return\n try {\n const usage = await supervisor.contextUsage(agent, model)\n if (!stopped) await sidecar.writeContextUsage(agent.id as string, usage)\n } catch (error) {\n warn('context usage', error)\n }\n })\n }\n\n return agent.ctx.effect(() => {\n const stopStatus = agent.ctx.on('agent/status', ({ status }) => {\n if (status === 'idle') refresh()\n })\n\n refresh()\n\n return async () => {\n stopped = true\n if (retryTimer !== undefined) clearTimeout(retryTimer)\n stopStatus()\n await pending\n bridge.dispose()\n }\n }, 'dsh-claude: agent metadata bridge')\n}\n\nexport async function apply(ctx: Context, config: Config): Promise<void> {\n await ensureManagedPreset()\n const supervisorConfig = {\n executablePath: '',\n defaultModel: config.model ?? 'default',\n idleTimeoutMs: config.idleTimeoutMs ?? 30 * 60 * 1_000,\n maxProcesses: config.maxProcesses ?? 4,\n }\n const sidecar = new ClaudeSidecarRepository()\n const supervisor = new ClaudeSupervisor({\n runtime: ctx.subprocess,\n approval: ctx.approval,\n config: supervisorConfig,\n runDetached: operation => ctx.agents.withoutInitiator(operation),\n sidecar,\n })\n let resolutionError: unknown\n try {\n const resolution = await resolveClaudeExecutable(\n ctx.subprocess,\n config.executablePath === undefined || config.executablePath.length === 0\n ? undefined\n : config.executablePath,\n )\n supervisorConfig.executablePath = resolution.path\n ctx.llm.registerAdapter(\n [...CLAUDE_CODE_PROVIDER_IDS],\n createClaudeCodeAdapter(supervisor, ctx.agents, agent => ctx.agentPresets.composedPreset(agent.ctx)),\n )\n ctx.effect(() => {\n const mounted = new Map<Agent, () => Promise<void>>()\n const pending = new Set<Agent>()\n const MOUNT_RETRY_MS = 200\n const MOUNT_RETRY_LIMIT = 50\n const mount = (agent: Agent) => {\n if (mounted.has(agent)) return\n const dispose = mountClaudeMetadata(ctx, supervisor, agent, supervisorConfig.defaultModel, sidecar)\n if (dispose !== undefined) mounted.set(agent, dispose)\n pending.delete(agent)\n }\n // The standing preset mount lands AFTER agent/created (the PresetTree is\n // applied asynchronously), so composedPreset is still undefined at that\n // point. Poll briefly until the join settles, then decide.\n const mountWhenPresetSettles = (agent: Agent) => {\n if (mounted.has(agent) || pending.has(agent)) return\n if (ctx.agentPresets.composedPreset(agent.ctx) !== undefined) {\n mount(agent)\n return\n }\n pending.add(agent)\n let attempts = 0\n const retry = () => {\n if (mounted.has(agent) || !pending.has(agent)) return\n if (ctx.agentPresets.composedPreset(agent.ctx) !== undefined) {\n mount(agent)\n return\n }\n attempts += 1\n if (attempts >= MOUNT_RETRY_LIMIT) {\n pending.delete(agent)\n return\n }\n const timer = setTimeout(retry, MOUNT_RETRY_MS)\n timer.unref?.()\n }\n const timer = setTimeout(retry, MOUNT_RETRY_MS)\n timer.unref?.()\n }\n const stopCreated = ctx.on('agent/created', ({ agent }) => { mountWhenPresetSettles(agent) })\n // Belt and suspenders: the session records its preset selection as a\n // durable event, which agent-presets republishes as agent-preset/selected.\n // agent-preset/selected is emitted by dsh-agent-presets but is not part\n // of the typed host event map yet; subscribe through a typed escape hatch.\n const onPresetSelected = ctx.on as (event: 'agent-preset/selected', handler: (sessionId: string, preset: string) => void) => () => void\n const stopSelected = onPresetSelected('agent-preset/selected', (sessionId, preset) => {\n if (!isClaudePresetId(preset)) return\n const agent = ctx.agents.get(sessionId as never)\n if (agent !== undefined) mountWhenPresetSettles(agent)\n })\n for (const agent of ctx.agents.list()) mountWhenPresetSettles(agent)\n return async () => {\n stopCreated()\n stopSelected()\n pending.clear()\n await Promise.allSettled([...mounted.values()].map(dispose => dispose()))\n mounted.clear()\n }\n }, 'dsh-claude: metadata bridges')\n } catch (error) {\n resolutionError = error\n }\n ctx.on('agent/disposed', async ({ agent }) => {\n await supervisor.disposeSession(agent.id as string)\n })\n ctx.effect(() => () => supervisor.dispose(), 'dsh-claude: process supervisor')\n ctx.inject(['webServer'], webCtx => {\n registerClaudeDoctorRoutes(webCtx, webCtx.subprocess, supervisor, supervisorConfig, resolutionError)\n registerClaudeProjectionRoute(webCtx, sidecar, sessionId => {\n const agent = webCtx.agents.get(sessionId as never)\n return agent !== undefined && isClaudePresetId(webCtx.agentPresets.composedPreset(agent.ctx))\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,MAAM,yBAAyB;AAC/B,MAAM,iBAAiB;AAgBvB,SAAS,kBAA2C;CAClD,OAAO;EAAE,eAAe;EAAwB,UAAU;EAAG,YAAY,CAAC;CAAE;AAC9E;AAEA,SAASA,SAAO,OAAqD;CACnE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACtE,QACA,KAAA;AACN;AAEA,SAAS,cAAc,OAAiC;CACtD,OAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,SAAS;AAC9E;AAEA,SAASC,SAAO,OAAgB,KAA8B;CAC5D,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,KAAK,MAAM,UAAU;AAC1E;AAEA,SAAS,QAAQ,OAAqD;CACpE,MAAM,QAAQD,SAAO,KAAK;CAC1B,IAAI,UAAU,KAAA,KACT,CAACC,SAAO,MAAM,iBAAiB,GAAG,KAClC,CAACA,SAAO,MAAM,YAAY,GAAG,KAC7B,CAACA,SAAO,MAAM,KAAK,IAAK,KACvB,MAAM,eAAe,KAAA,KAAa,CAACA,SAAO,MAAM,YAAY,GAAG,GAAI,OAAO,KAAA;CAChF,OAAO;EACL,iBAAiB,MAAM;EACvB,YAAY,MAAM;EAClB,KAAK,MAAM;EACX,GAAI,MAAM,eAAe,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY,MAAM,WAAW;CAC3E;AACF;AAEA,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAU;CAAY;CAAa;CAAe;CAAc;CAAY;CAAS;CAAW;AAAO,CAAC;AACxI,MAAM,kCAAkB,IAAI,IAAI;CAAC;CAA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B,OAAO,aAAa,eAAe,MAAM,GAAG,CAAC;EAC9F,CAAC;CACH,CAAC;AACH"}
1
+ {"version":3,"file":"index.mjs","names":["record","string","#pending","#readNow","#update","#writeNow","#path","#values","#pending","#closed","#failure","#exitCode","#signalCode","#killed","#entries","#runtime","#approval","#config","#queryFactory","#runDetached","#sidecar","#dynamicPresenterNames","#contextWindows","claudeQuery","#runMetadata","#admissionGate","#runTurnAdmitted","#disposed","#disposeEntry","#makeRoom","#createEntry","#armInitializationTimer","#syncPermissionMode","#appendActivity","#armIdleTimer","#interrupt","#metadataEntry","#whenInitialized","#pump","#handleMessage","#handleDisconnect","#flushTasksSnapshot","#trackTask","#trackBackgroundLevel","#completeTurn","#ensureDynamicPresenter","#appendNativeToolCall","#appendNativeToolResult","#scheduleTasksSnapshot","#appendSafely","#supervisor","#agents","#presetIdFor"],"sources":["../src/sidecar.ts","../src/async-queue.ts","../src/permission.ts","../src/sdk-messages.ts","../src/spawn.ts","../src/supervisor.ts","../src/adapter.ts","../src/http.ts","../src/doctor-routes.ts","../src/projection-routes.ts","../src/index.ts"],"sourcesContent":["import { randomUUID } from 'node:crypto'\nimport { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'\nimport { join } from 'node:path'\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths'\nimport type { SessionEvent } from '@deepseek-ai/dsh-session'\nimport {\n latestClaudeContextUsage,\n latestClaudeSessionBinding,\n latestClaudeTasks,\n normalizeActivity,\n normalizeContextUsage,\n normalizeTasksEvent,\n redactText,\n type ClaudeActivityEvent,\n type ClaudeActivityInput,\n type ClaudeContextUsageEvent,\n type ClaudeContextUsageInput,\n type ClaudeSessionBoundEvent,\n type ClaudeTaskInfo,\n type ClaudeTasksEvent,\n} from './events.ts'\nimport { CLAUDE_ACTIVITY_EVENT, SDK_VERSION } from './constants.ts'\n\nconst SIDECAR_SCHEMA_VERSION = 1\nconst MAX_ACTIVITIES = 10_000\n\nexport interface ClaudeSidecarProjection {\n readonly schemaVersion: typeof SIDECAR_SCHEMA_VERSION\n readonly revision: number\n readonly binding?: ClaudeSessionBoundEvent\n readonly activities: readonly ClaudeActivityEvent[]\n readonly contextUsage?: ClaudeContextUsageEvent\n readonly tasks?: ClaudeTasksEvent\n}\n\nexport interface ClaudeSidecarRepositoryOptions {\n readonly root?: string\n readonly legacyRoot?: string\n}\n\nfunction emptyProjection(): ClaudeSidecarProjection {\n return { schemaVersion: SIDECAR_SCHEMA_VERSION, revision: 0, activities: [] }\n}\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' && !Array.isArray(value)\n ? value as Record<string, unknown>\n : undefined\n}\n\nfunction finiteInteger(value: unknown): value is number {\n return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0\n}\n\nfunction string(value: unknown, max: number): value is string {\n return typeof value === 'string' && value.length > 0 && value.length <= max\n}\n\nfunction binding(value: unknown): ClaudeSessionBoundEvent | undefined {\n const input = record(value)\n if (input === undefined\n || !string(input.claudeSessionId, 512)\n || !string(input.sdkVersion, 128)\n || !string(input.cwd, 4_096)\n || (input.cliVersion !== undefined && !string(input.cliVersion, 128))) return undefined\n return {\n claudeSessionId: input.claudeSessionId,\n sdkVersion: input.sdkVersion,\n cwd: input.cwd,\n ...(input.cliVersion === undefined ? {} : { cliVersion: input.cliVersion }),\n }\n}\n\nconst ACTIVITY_KINDS = new Set(['status', 'thinking', 'tool-call', 'tool-result', 'permission', 'subagent', 'usage', 'warning', 'error'])\nconst ACTIVITY_PHASES = new Set(['started', 'updated', 'completed', 'denied', 'failed'])\n\nfunction activity(value: unknown): ClaudeActivityEvent | undefined {\n const input = record(value)\n if (input === undefined\n || !finiteInteger(input.turn)\n || !finiteInteger(input.step)\n || !finiteInteger(input.ordinal)\n || typeof input.kind !== 'string'\n || !ACTIVITY_KINDS.has(input.kind)\n || (input.phase !== undefined && (typeof input.phase !== 'string' || !ACTIVITY_PHASES.has(input.phase)))) return undefined\n return normalizeActivity(input as unknown as ClaudeActivityEvent)\n}\n\nfunction contextUsage(value: unknown): ClaudeContextUsageEvent | undefined {\n const input = record(value)\n if (input === undefined || !Array.isArray(input.categories)) return undefined\n return normalizeContextUsage(input as unknown as ClaudeContextUsageInput)\n}\n\nfunction tasks(value: unknown): ClaudeTasksEvent | undefined {\n const input = record(value)\n if (input === undefined || !Array.isArray(input.tasks)) return undefined\n return normalizeTasksEvent(input.tasks as ClaudeTaskInfo[])\n}\n\nexport function parseClaudeSidecar(value: unknown): ClaudeSidecarProjection {\n const input = record(value)\n if (input === undefined\n || input.schemaVersion !== SIDECAR_SCHEMA_VERSION\n || !finiteInteger(input.revision)\n || !Array.isArray(input.activities)\n || input.activities.length > MAX_ACTIVITIES) {\n throw new Error('dsh-claude: invalid sidecar document')\n }\n const activities = input.activities.map(activity)\n if (activities.some(item => item === undefined)) throw new Error('dsh-claude: invalid sidecar activity')\n const parsedBinding = input.binding === undefined ? undefined : binding(input.binding)\n const parsedUsage = input.contextUsage === undefined ? undefined : contextUsage(input.contextUsage)\n const parsedTasks = input.tasks === undefined ? undefined : tasks(input.tasks)\n if ((input.binding !== undefined && parsedBinding === undefined)\n || (input.contextUsage !== undefined && parsedUsage === undefined)\n || (input.tasks !== undefined && parsedTasks === undefined)) {\n throw new Error('dsh-claude: invalid sidecar projection')\n }\n return {\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n revision: input.revision,\n activities: activities as ClaudeActivityEvent[],\n ...(parsedBinding === undefined ? {} : { binding: parsedBinding }),\n ...(parsedUsage === undefined ? {} : { contextUsage: parsedUsage }),\n ...(parsedTasks === undefined ? {} : { tasks: parsedTasks }),\n }\n}\n\nfunction compareActivity(left: ClaudeActivityEvent, right: ClaudeActivityEvent): number {\n return left.turn - right.turn || left.step - right.step || left.ordinal - right.ordinal\n}\n\nfunction activityKey(value: ClaudeActivityEvent): string {\n return `${value.turn}:${value.step}:${value.ordinal}`\n}\n\nfunction mergeActivities(\n existing: readonly ClaudeActivityEvent[],\n additions: readonly ClaudeActivityEvent[],\n): ClaudeActivityEvent[] {\n const merged = new Map(existing.map(item => [activityKey(item), item]))\n for (const item of additions) merged.set(activityKey(item), item)\n return [...merged.values()].sort(compareActivity).slice(-MAX_ACTIVITIES)\n}\n\nfunction normalizeBinding(\n input: Omit<ClaudeSessionBoundEvent, 'sdkVersion'> & { sdkVersion?: string },\n): ClaudeSessionBoundEvent {\n return {\n claudeSessionId: redactText(input.claudeSessionId, 512),\n sdkVersion: redactText(input.sdkVersion ?? SDK_VERSION, 128),\n cwd: redactText(input.cwd, 4_096),\n ...(input.cliVersion === undefined ? {} : { cliVersion: redactText(input.cliVersion, 128) }),\n }\n}\n\nexport class ClaudeSidecarRepository {\n readonly root: string\n readonly legacyRoot: string | undefined\n readonly #pending = new Map<string, Promise<unknown>>()\n\n constructor(options: ClaudeSidecarRepositoryOptions = {}) {\n this.root = options.root ?? dshHomePath('plugins', 'dsh-claude', 'sessions')\n this.legacyRoot = options.legacyRoot\n ?? (options.root === undefined ? dshHomePath('plugins', 'dsh-claude-code', 'sessions') : undefined)\n }\n\n async read(sessionId: string): Promise<ClaudeSidecarProjection> {\n await this.#pending.get(sessionId)?.catch(() => undefined)\n return this.#readNow(sessionId)\n }\n\n writeBinding(\n sessionId: string,\n value: Omit<ClaudeSessionBoundEvent, 'sdkVersion'> & { sdkVersion?: string },\n ): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeBinding(value)\n return this.#update(sessionId, current => ({ ...current, binding: normalized }))\n }\n\n appendActivity(\n sessionId: string,\n value: ClaudeActivityInput & { turn: number; step: number; ordinal: number },\n ): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeActivity(value)\n return this.#update(sessionId, current => ({\n ...current,\n activities: mergeActivities(current.activities, [normalized]),\n }))\n }\n\n writeContextUsage(sessionId: string, value: ClaudeContextUsageInput): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeContextUsage(value)\n return this.#update(sessionId, current => ({ ...current, contextUsage: normalized }))\n }\n\n writeTasks(sessionId: string, value: readonly ClaudeTaskInfo[]): Promise<ClaudeSidecarProjection> {\n const normalized = normalizeTasksEvent(value)\n return this.#update(sessionId, current => ({ ...current, tasks: normalized }))\n }\n\n importLegacy(sessionId: string, events: readonly SessionEvent[]): Promise<ClaudeSidecarProjection> {\n const importedActivities = events\n .filter(event => event.type === CLAUDE_ACTIVITY_EVENT)\n .map(event => activity(event.data))\n .filter((item): item is ClaudeActivityEvent => item !== undefined)\n const importedBinding = latestClaudeSessionBinding(events)\n const importedUsage = latestClaudeContextUsage(events)\n const importedTasks = latestClaudeTasks(events)\n return this.#update(sessionId, current => ({\n ...current,\n activities: mergeActivities(importedActivities, current.activities),\n ...(current.binding !== undefined || importedBinding === undefined ? {} : { binding: normalizeBinding(importedBinding) }),\n ...(current.contextUsage !== undefined || importedUsage === undefined ? {} : { contextUsage: normalizeContextUsage(importedUsage) }),\n ...(current.tasks !== undefined || importedTasks === undefined ? {} : { tasks: normalizeTasksEvent(importedTasks.tasks) }),\n }), true)\n }\n\n #path(sessionId: string, root = this.root): string {\n if (sessionId.length === 0 || sessionId.length > 1_024) throw new Error('dsh-claude: invalid session id')\n return join(root, `${Buffer.from(sessionId).toString('base64url')}.json`)\n }\n\n #update(\n sessionId: string,\n change: (current: ClaudeSidecarProjection) => Omit<ClaudeSidecarProjection, 'revision' | 'schemaVersion'> & Partial<Pick<ClaudeSidecarProjection, 'revision' | 'schemaVersion'>>,\n skipUnchanged = false,\n ): Promise<ClaudeSidecarProjection> {\n const previous = this.#pending.get(sessionId) ?? Promise.resolve()\n const operation = previous.catch(() => undefined).then(async () => {\n const current = await this.#readNow(sessionId)\n const changed = parseClaudeSidecar({\n ...change(current),\n schemaVersion: SIDECAR_SCHEMA_VERSION,\n revision: current.revision,\n })\n if (skipUnchanged && JSON.stringify(changed) === JSON.stringify(current)) return current\n const next = { ...changed, revision: current.revision + 1 }\n await this.#writeNow(sessionId, next)\n return next\n })\n this.#pending.set(sessionId, operation)\n void operation.finally(() => {\n if (this.#pending.get(sessionId) === operation) this.#pending.delete(sessionId)\n }).catch(() => undefined)\n return operation\n }\n\n async #readNow(sessionId: string): Promise<ClaudeSidecarProjection> {\n try {\n return parseClaudeSidecar(JSON.parse(await readFile(this.#path(sessionId), 'utf8')))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n if (this.legacyRoot === undefined) return emptyProjection()\n try {\n return parseClaudeSidecar(JSON.parse(await readFile(this.#path(sessionId, this.legacyRoot), 'utf8')))\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return emptyProjection()\n throw error\n }\n }\n\n async #writeNow(sessionId: string, projection: ClaudeSidecarProjection): Promise<void> {\n await mkdir(this.root, { recursive: true, mode: 0o700 })\n await chmod(this.root, 0o700)\n const target = this.#path(sessionId)\n const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`\n try {\n await writeFile(temporary, `${JSON.stringify(projection)}\\n`, { mode: 0o600, flag: 'wx' })\n await chmod(temporary, 0o600)\n await rename(temporary, target)\n await chmod(target, 0o600)\n } finally {\n await rm(temporary, { force: true }).catch(() => undefined)\n }\n }\n}\n","export class AsyncQueueClosedError extends Error {\n constructor() {\n super('Async queue is closed')\n this.name = 'AsyncQueueClosedError'\n }\n}\n\ninterface Pending<T> {\n resolve: (result: IteratorResult<T>) => void\n reject: (error: unknown) => void\n}\n\nexport class AsyncQueue<T> implements AsyncIterable<T>, AsyncIterator<T> {\n readonly #values: T[] = []\n readonly #pending: Pending<T>[] = []\n #closed = false\n #failure: unknown\n\n get closed(): boolean {\n return this.#closed\n }\n\n push(value: T): void {\n if (this.#closed) throw new AsyncQueueClosedError()\n const waiter = this.#pending.shift()\n if (waiter !== undefined) waiter.resolve({ value, done: false })\n else this.#values.push(value)\n }\n\n close(): void {\n if (this.#closed) return\n this.#closed = true\n for (const waiter of this.#pending.splice(0)) waiter.resolve({ value: undefined, done: true })\n }\n\n fail(error: unknown): void {\n if (this.#closed) return\n this.#closed = true\n this.#failure = error\n for (const waiter of this.#pending.splice(0)) waiter.reject(error)\n }\n\n discard(error?: unknown): void {\n this.#values.splice(0)\n if (this.#closed) return\n this.#closed = true\n if (error === undefined) {\n for (const waiter of this.#pending.splice(0)) waiter.resolve({ value: undefined, done: true })\n return\n }\n this.#failure = error\n for (const waiter of this.#pending.splice(0)) waiter.resolve({ value: undefined, done: true })\n }\n\n next(): Promise<IteratorResult<T>> {\n const value = this.#values.shift()\n if (value !== undefined) return Promise.resolve({ value, done: false })\n if (this.#closed) {\n return this.#failure === undefined\n ? Promise.resolve({ value: undefined, done: true })\n : Promise.reject(this.#failure)\n }\n return new Promise<IteratorResult<T>>((resolve, reject) => {\n this.#pending.push({ resolve, reject })\n })\n }\n\n return(): Promise<IteratorResult<T>> {\n this.close()\n return Promise.resolve({ value: undefined, done: true })\n }\n\n [Symbol.asyncIterator](): AsyncIterator<T> {\n return this\n }\n}\n","import type { CanUseTool, PermissionResult } from '@anthropic-ai/claude-agent-sdk'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type { ApprovalOutcome, ApprovalService } from '@deepseek-ai/dsh-user-approval'\nimport {\n boundText,\n safeDetail,\n type ClaudeActivityInput,\n type ClaudeActivityCursor,\n} from './events.ts'\n\nexport type ApprovalRequester = Pick<ApprovalService, 'request'>\n\nexport interface ActivePermissionContext {\n agent: Agent\n cursor: ClaudeActivityCursor\n markActivity?: () => void\n recordDenial?: (toolUseId: string) => void\n appendActivity: (activity: ClaudeActivityInput) => Promise<void>\n}\n\nexport type ActivePermissionContextProvider = () => ActivePermissionContext | undefined\n\nfunction denialMessage(outcome: ApprovalOutcome): string {\n switch (outcome) {\n case 'rejected': return 'The user rejected this action in DeepSeek Harness.'\n case 'cancelled': return 'The permission request was cancelled in DeepSeek Harness.'\n case 'unavailable': return 'No DeepSeek Harness approval surface was available; the action was denied.'\n case 'allowed-once': return ''\n }\n}\n\nexport function permissionReason(\n toolName: string,\n input: Readonly<Record<string, unknown>>,\n options: Parameters<CanUseTool>[2],\n): string {\n const prompt = options.title ?? options.description ?? options.decisionReason ?? `Claude Code wants to use ${toolName}.`\n const detail = safeDetail(input)\n return boundText(detail === undefined ? prompt : `${prompt}\\nInput: ${detail}`, 1_200)\n}\n\nexport function mapApprovalOutcome(\n outcome: ApprovalOutcome,\n input: Record<string, unknown>,\n toolUseID: string,\n): PermissionResult {\n if (outcome === 'allowed-once') {\n return {\n behavior: 'allow',\n updatedInput: input,\n toolUseID,\n decisionClassification: 'user_temporary',\n }\n }\n return {\n behavior: 'deny',\n message: denialMessage(outcome),\n toolUseID,\n decisionClassification: 'user_reject',\n }\n}\n\nexport function createPermissionBridge(\n approval: ApprovalRequester,\n activeContext: ActivePermissionContextProvider,\n): CanUseTool {\n return async (toolName, input, options) => {\n const active = activeContext()\n if (active === undefined) {\n return {\n behavior: 'deny',\n message: 'No active DeepSeek Harness turn owns this Claude Code action.',\n toolUseID: options.toolUseID,\n decisionClassification: 'user_reject',\n }\n }\n\n active.markActivity?.()\n const reason = permissionReason(toolName, input, options)\n try {\n await active.appendActivity({\n kind: 'permission',\n phase: 'started',\n toolUseId: options.toolUseID,\n toolName,\n title: options.displayName ?? toolName,\n summary: options.title ?? options.description ?? reason,\n detail: input,\n })\n const outcome = await approval.request({\n agent: active.agent,\n toolName,\n reason,\n signal: options.signal,\n })\n const result = mapApprovalOutcome(outcome, input, options.toolUseID)\n if (result.behavior === 'deny') active.recordDenial?.(options.toolUseID)\n await active.appendActivity({\n kind: 'permission',\n phase: outcome === 'allowed-once' ? 'completed' : 'denied',\n toolUseId: options.toolUseID,\n toolName,\n title: options.displayName ?? toolName,\n summary: outcome === 'allowed-once' ? 'Allowed once in DeepSeek Harness' : denialMessage(outcome),\n })\n return result\n } catch (error) {\n const message = options.signal.aborted\n ? 'The permission request was cancelled in DeepSeek Harness.'\n : 'DeepSeek Harness could not record or answer the permission request; the action was denied.'\n try {\n await active.appendActivity({\n kind: 'permission',\n phase: 'failed',\n toolUseId: options.toolUseID,\n toolName,\n title: options.displayName ?? toolName,\n summary: message,\n isError: true,\n detail: error,\n })\n } catch {\n // The permission path is already fail-closed; a second audit failure cannot widen it.\n }\n return {\n behavior: 'deny',\n message,\n toolUseID: options.toolUseID,\n decisionClassification: 'user_reject',\n }\n }\n }\n}\n","import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk'\nimport type { ClaudeUsage } from './events.ts'\n\nexport type NormalizedSdkMessage =\n | { kind: 'init'; sessionId: string; cliVersion: string; cwd: string }\n | { kind: 'text-delta'; text: string; parentToolUseId?: string }\n | { kind: 'assistant-text'; text: string; parentToolUseId?: string }\n | { kind: 'thinking'; text: string; phase: 'updated' | 'completed'; parentToolUseId?: string }\n | { kind: 'tool-call'; toolUseId: string; toolName: string; input: unknown; parentToolUseId?: string }\n | { kind: 'tool-result'; toolUseId: string; output: unknown; isError: boolean; parentToolUseId?: string }\n | {\n kind: 'subagent'\n title: string\n summary?: string\n detail?: unknown\n phase: 'started' | 'updated' | 'completed' | 'failed'\n /** Structured task-board fields for task_started/progress/updated/notification. */\n taskId?: string\n taskStatus?: 'running' | 'completed' | 'failed' | 'stopped' | 'killed'\n description?: string\n subagentType?: string\n taskType?: string\n lastToolName?: string\n usage?: { totalTokens?: number; toolUses?: number; durationMs?: number }\n /** Ambient/housekeeping task: hide from chat rows, keep on the task board. */\n skipTranscript?: boolean\n }\n | {\n /** Level signal: full live background-task set (REPLACE semantics). */\n kind: 'background-tasks'\n tasks: readonly { taskId: string; taskType?: string; description: string }[]\n }\n | { kind: 'status'; title: string; summary?: string; detail?: unknown }\n | { kind: 'warning'; title: string; summary?: string; detail?: unknown }\n | { kind: 'permission-denied'; toolUseId: string; toolName: string; summary: string }\n | { kind: 'result'; success: boolean; text?: string; errors?: readonly string[]; usage: ClaudeUsage; sessionId: string; userMessageUuid?: string; terminalReason?: string; permissionDenials?: readonly { toolName: string; toolUseId: string }[] }\n | { kind: 'protocol-error'; title: string; detail: unknown }\n | { kind: 'unknown'; title: string; detail: unknown }\n\nfunction record(value: unknown): Record<string, unknown> | undefined {\n return value !== null && typeof value === 'object' ? value as Record<string, unknown> : undefined\n}\n\nfunction string(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n\nfunction contentText(content: unknown): string {\n if (typeof content === 'string') return content\n if (!Array.isArray(content)) return ''\n return content.map(item => {\n const block = record(item)\n if (block?.type === 'text') return string(block.text) ?? ''\n return ''\n }).join('')\n}\n\nfunction taskUsageOf(usage: Record<string, unknown> | undefined): { totalTokens?: number; toolUses?: number; durationMs?: number } | undefined {\n if (usage === undefined) return undefined\n const normalized: { totalTokens?: number; toolUses?: number; durationMs?: number } = {}\n if (typeof usage.total_tokens === 'number') normalized.totalTokens = usage.total_tokens\n if (typeof usage.tool_uses === 'number') normalized.toolUses = usage.tool_uses\n if (typeof usage.duration_ms === 'number') normalized.durationMs = usage.duration_ms\n return Object.keys(normalized).length === 0 ? undefined : normalized\n}\n\nfunction resultUsage(message: Record<string, unknown>): ClaudeUsage {\n const usage = record(message.usage)\n const normalized: ClaudeUsage = {}\n if (usage !== undefined) {\n if (typeof usage.input_tokens === 'number') normalized.inputTokens = usage.input_tokens\n if (typeof usage.output_tokens === 'number') normalized.outputTokens = usage.output_tokens\n if (typeof usage.cache_read_input_tokens === 'number') normalized.cacheReadTokens = usage.cache_read_input_tokens\n if (typeof usage.cache_creation_input_tokens === 'number') normalized.cacheCreationTokens = usage.cache_creation_input_tokens\n }\n if (typeof message.total_cost_usd === 'number') normalized.cumulativeCostUsd = message.total_cost_usd\n return normalized\n}\n\nfunction normalizeAssistant(message: Record<string, unknown>): NormalizedSdkMessage[] {\n const envelope = record(message.message)\n const content = envelope?.content\n if (!Array.isArray(content)) return [{ kind: 'protocol-error', title: 'Malformed Claude assistant message', detail: message }]\n const parentToolUseId = string(message.parent_tool_use_id)\n const normalized: NormalizedSdkMessage[] = []\n for (const item of content) {\n const block = record(item)\n if (block === undefined) continue\n if (block.type === 'text') {\n const text = string(block.text)\n if (text !== undefined && text.length > 0) normalized.push({ kind: 'assistant-text', text, ...(parentToolUseId === undefined ? {} : { parentToolUseId }) })\n } else if (block.type === 'thinking') {\n const text = string(block.thinking)\n if (text !== undefined && text.length > 0) normalized.push({ kind: 'thinking', text, phase: 'completed', ...(parentToolUseId === undefined ? {} : { parentToolUseId }) })\n } else if (block.type === 'tool_use') {\n const toolUseId = string(block.id)\n const toolName = string(block.name)\n if (toolUseId !== undefined && toolName !== undefined) {\n normalized.push({\n kind: 'tool-call',\n toolUseId,\n toolName,\n input: block.input,\n ...(parentToolUseId === undefined ? {} : { parentToolUseId }),\n })\n }\n }\n }\n return normalized\n}\n\nfunction normalizeUser(message: Record<string, unknown>): NormalizedSdkMessage[] {\n const envelope = record(message.message)\n const content = envelope?.content\n if (!Array.isArray(content)) return [{ kind: 'protocol-error', title: 'Malformed Claude user message', detail: message }]\n const parentToolUseId = string(message.parent_tool_use_id)\n const normalized: NormalizedSdkMessage[] = []\n for (const item of content) {\n const block = record(item)\n if (block?.type !== 'tool_result') continue\n const toolUseId = string(block.tool_use_id)\n if (toolUseId === undefined) continue\n normalized.push({\n kind: 'tool-result',\n toolUseId,\n output: message.tool_use_result ?? block.content,\n isError: block.is_error === true,\n ...(parentToolUseId === undefined ? {} : { parentToolUseId }),\n })\n }\n return normalized\n}\n\nfunction normalizeSystem(message: Record<string, unknown>): NormalizedSdkMessage[] {\n const subtype = string(message.subtype)\n if (subtype === 'init') {\n const sessionId = string(message.session_id)\n const cliVersion = string(message.claude_code_version)\n const cwd = string(message.cwd)\n return sessionId !== undefined && cliVersion !== undefined && cwd !== undefined\n ? [{ kind: 'init', sessionId, cliVersion, cwd }]\n : [{ kind: 'protocol-error', title: 'Malformed Claude initialization message', detail: message }]\n }\n if (subtype === 'status') {\n const status = message.status\n if (status === null) return [{ kind: 'status', title: 'Claude Code is ready' }]\n return [{ kind: 'status', title: `Claude Code ${String(status)}`, detail: message }]\n }\n if (subtype === 'session_state_changed') {\n return [{ kind: 'status', title: `Claude session ${String(message.state)}` }]\n }\n if (subtype === 'permission_denied') {\n const toolUseId = string(message.tool_use_id)\n const toolName = string(message.tool_name)\n if (toolUseId !== undefined && toolName !== undefined) {\n return [{\n kind: 'permission-denied',\n toolUseId,\n toolName,\n summary: string(message.message) ?? 'Claude Code denied the action',\n }]\n }\n }\n if (subtype === 'task_started') {\n const taskId = string(message.task_id)\n const description = string(message.description)\n const subagentType = string(message.subagent_type)\n const taskType = string(message.task_type)\n return [{\n kind: 'subagent',\n title: description ?? taskId ?? 'Claude subagent started',\n phase: 'started',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n taskStatus: 'running' as const,\n ...(description === undefined ? {} : { description }),\n ...(subagentType === undefined ? {} : { subagentType }),\n ...(taskType === undefined ? {} : { taskType }),\n ...(message.skip_transcript === true ? { skipTranscript: true } : {}),\n }]\n }\n if (subtype === 'task_progress') {\n const taskId = string(message.task_id)\n const description = string(message.description)\n const summary = string(message.summary)\n const subagentType = string(message.subagent_type)\n const lastToolName = string(message.last_tool_name)\n const usage = taskUsageOf(record(message.usage))\n return [{\n kind: 'subagent',\n title: summary ?? description ?? 'Claude subagent update',\n phase: 'updated',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n taskStatus: 'running' as const,\n ...(description === undefined ? {} : { description }),\n ...(subagentType === undefined ? {} : { subagentType }),\n ...(lastToolName === undefined ? {} : { lastToolName }),\n ...(summary === undefined ? {} : { summary }),\n ...(usage === undefined ? {} : { usage }),\n }]\n }\n if (subtype === 'task_updated') {\n const patch = record(message.patch)\n const status = string(patch?.status)\n const taskId = string(message.task_id)\n const description = string(patch?.description)\n const error = string(patch?.error)\n const taskStatus = status === undefined\n ? undefined\n : status === 'killed'\n ? 'killed' as const\n : status === 'completed'\n ? 'completed' as const\n : status === 'failed'\n ? 'failed' as const\n : 'running' as const\n return [{\n kind: 'subagent',\n title: description ?? 'Claude subagent update',\n phase: status === 'failed' || status === 'killed' ? 'failed' : status === 'completed' ? 'completed' : 'updated',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n ...(taskStatus === undefined ? {} : { taskStatus }),\n ...(description === undefined ? {} : { description }),\n ...(error === undefined ? {} : { summary: error }),\n }]\n }\n if (subtype === 'task_notification') {\n const failed = message.status === 'failed'\n const stopped = message.status === 'stopped' || message.status === 'cancelled'\n const taskId = string(message.task_id)\n const summary = string(message.summary)\n const taskStatus = failed ? 'failed' as const : stopped ? 'stopped' as const : 'completed' as const\n const usage = taskUsageOf(record(message.usage))\n return [{\n kind: 'subagent',\n title: summary ?? taskId ?? 'Claude subagent finished',\n phase: failed || stopped ? 'failed' : 'completed',\n detail: message,\n ...(taskId === undefined ? {} : { taskId }),\n taskStatus,\n ...(summary === undefined ? {} : { summary }),\n ...(usage === undefined ? {} : { usage }),\n }]\n }\n if (subtype === 'background_tasks_changed') {\n const tasks = Array.isArray(message.tasks) ? message.tasks : []\n return [{\n kind: 'background-tasks',\n tasks: tasks.flatMap(item => {\n const entry = record(item)\n const taskId = string(entry?.task_id)\n const description = string(entry?.description)\n const taskType = string(entry?.task_type)\n if (taskId === undefined || description === undefined) return []\n return [{\n taskId,\n description,\n ...(taskType === undefined ? {} : { taskType }),\n }]\n }),\n }]\n }\n if (subtype === 'api_retry') {\n return [{ kind: 'warning', title: 'Claude API retry', detail: message }]\n }\n if (subtype === 'informational' || subtype === 'notification' || subtype === 'local_command_output') {\n return [{\n kind: message.level === 'warning' ? 'warning' : 'status',\n title: string(message.content) ?? string(message.text) ?? 'Claude Code notice',\n detail: message,\n }]\n }\n if (subtype?.startsWith('hook_') === true || subtype === 'plugin_install') {\n return [{ kind: 'status', title: `Claude Code ${subtype.replaceAll('_', ' ')}`, detail: message }]\n }\n if (subtype !== undefined) {\n // Preserve unknown system lifecycle evidence (background tasks, resets,\n // worker/mirror lifecycle) as a bounded activity instead of silently\n // dropping it; the activity layer redacts and bounds the detail.\n return [{ kind: 'status', title: `Claude Code ${subtype.replaceAll('_', ' ')}`, detail: message }]\n }\n return []\n}\n\nconst RESULT_ERROR_SUBTYPES = new Set([\n 'error_during_execution',\n 'error_max_turns',\n 'error_max_budget_usd',\n 'error_max_structured_output_retries',\n])\n\nexport function normalizeSdkMessage(message: SDKMessage): NormalizedSdkMessage[] {\n const value = message as unknown as Record<string, unknown>\n if (value.type === 'stream_event') {\n const event = record(value.event)\n const parentToolUseId = string(value.parent_tool_use_id)\n if (event?.type === 'content_block_delta') {\n const delta = record(event.delta)\n if (delta?.type === 'text_delta') {\n const text = string(delta.text)\n return text === undefined ? [] : [{ kind: 'text-delta', text, ...(parentToolUseId === undefined ? {} : { parentToolUseId }) }]\n }\n if (delta?.type === 'thinking_delta') {\n const text = string(delta.thinking)\n return text === undefined ? [] : [{ kind: 'thinking', text, phase: 'updated', ...(parentToolUseId === undefined ? {} : { parentToolUseId }) }]\n }\n }\n return []\n }\n if (value.type === 'assistant') return normalizeAssistant(value)\n if (value.type === 'user') return normalizeUser(value)\n if (value.type === 'system') return normalizeSystem(value)\n if (value.type === 'result') {\n const sessionId = string(value.session_id)\n if (sessionId === undefined || (value.subtype !== 'success' && !RESULT_ERROR_SUBTYPES.has(String(value.subtype)))) {\n return [{ kind: 'protocol-error', title: 'Malformed Claude result message', detail: value }]\n }\n // A result is a success only when it is not flagged as an error. Local\n // 2.1.233 emits subtype:\"success\" with is_error:true for API/auth failures\n // (e.g. terminal_reason:\"api_error\"), so subtype alone is not authoritative.\n const success = value.subtype === 'success' && value.is_error !== true\n const errors = Array.isArray(value.errors)\n ? value.errors.filter((item): item is string => typeof item === 'string')\n : undefined\n const terminalReason = string(value.terminal_reason)\n const userMessageUuid = string(value.user_message_uuid)\n const permissionDenials = Array.isArray(value.permission_denials)\n ? value.permission_denials\n .map(item => record(item))\n .filter((item): item is Record<string, unknown> => item !== undefined)\n .map(item => {\n const toolName = string(item.tool_name)\n const toolUseId = string(item.tool_use_id)\n return toolName === undefined || toolUseId === undefined ? undefined : { toolName, toolUseId }\n })\n .filter((item): item is { toolName: string; toolUseId: string } => item !== undefined)\n .slice(0, 40)\n : undefined\n return [{\n kind: 'result',\n success,\n ...(success && typeof value.result === 'string' ? { text: value.result } : {}),\n ...(errors === undefined ? {} : { errors }),\n ...(terminalReason === undefined ? {} : { terminalReason }),\n ...(permissionDenials === undefined || permissionDenials.length === 0 ? {} : { permissionDenials }),\n usage: resultUsage(value),\n sessionId,\n ...(userMessageUuid === undefined ? {} : { userMessageUuid }),\n }]\n }\n if (value.type === 'auth_status') {\n return [{\n kind: value.error === undefined ? 'status' : 'warning',\n title: value.error === undefined ? 'Claude authentication status changed' : 'Claude authentication failed',\n detail: value.error ?? value.output,\n }]\n }\n if (value.type === 'rate_limit_event') {\n // The CLI pushes subscription-quota status after API activity. Only a\n // non-allowed state is a real warning; healthy updates stay audit-only.\n const info = record(value.rate_limit_info)\n const status = string(info?.status)\n const blocking = status !== undefined && status !== 'allowed'\n return [{\n kind: blocking ? 'warning' : 'status',\n title: blocking ? 'Claude rate limit is blocking requests' : 'Claude rate limit status changed',\n detail: value.rate_limit_info,\n }]\n }\n return [{ kind: 'unknown', title: `Unknown Claude SDK message: ${String(value.type)}`, detail: value }]\n}\n\nexport function extractSdkContentText(content: unknown): string {\n return contentText(content)\n}\n","import { EventEmitter } from 'node:events'\nimport type { Readable, Writable } from 'node:stream'\nimport type { SpawnOptions, SpawnedProcess } from '@anthropic-ai/claude-agent-sdk'\nimport {\n DSH_ENV_PREFIX,\n SENSITIVE_ENV_PATTERN,\n type SubprocessHandle,\n type SubprocessRuntime,\n} from '@deepseek-ai/dsh-subprocess'\n\nexport const CLAUDE_PROCESS_GRACE_MS = 2_000\nexport const CLAUDE_STDERR_TAIL_BYTES = 32 * 1024\n\nconst ADDITIONAL_SENSITIVE_ENV_PATTERN = /(?:authorization|cookie|credential|database[_-]?url|private[_-]?key|netrc)/iu\n\nexport function scrubClaudeSpawnEnv(env: Readonly<Record<string, string | undefined>>): NodeJS.ProcessEnv {\n const safe: NodeJS.ProcessEnv = {}\n for (const [key, value] of Object.entries(env)) {\n if (value === undefined) continue\n if (key.toUpperCase().startsWith(DSH_ENV_PREFIX)) continue\n if (SENSITIVE_ENV_PATTERN.test(key)) continue\n if (ADDITIONAL_SENSITIVE_ENV_PATTERN.test(key)) continue\n safe[key] = value\n }\n return safe\n}\n\nexport class ManagedClaudeProcess extends EventEmitter implements SpawnedProcess {\n readonly stdin: Writable\n readonly stdout: Readable\n readonly handle: SubprocessHandle\n #killed = false\n #exitCode: number | null = null\n #signalCode: NodeJS.Signals | null = null\n\n constructor(handle: SubprocessHandle) {\n super()\n if (handle.stdin === undefined || handle.stdout === undefined) {\n throw new Error('dsh-claude: managed Claude process requires piped stdin/stdout')\n }\n this.handle = handle\n this.stdin = handle.stdin\n this.stdout = handle.stdout\n void handle.done.then(\n outcome => {\n this.#exitCode = outcome.exitCode\n this.#signalCode = outcome.signal\n this.emit('exit', outcome.exitCode, outcome.signal)\n },\n error => {\n this.emit('error', error instanceof Error ? error : new Error(String(error)))\n },\n )\n }\n\n get killed(): boolean {\n return this.#killed\n }\n\n get exitCode(): number | null {\n return this.#exitCode\n }\n\n get signalCode(): NodeJS.Signals | null {\n return this.#signalCode\n }\n\n kill(signal: NodeJS.Signals): boolean {\n if (this.#exitCode !== null || this.#signalCode !== null) return false\n this.#killed = true\n this.handle.terminate()\n return true\n }\n\n stderrTail(): string {\n return this.handle.collected.stderr?.readFrom(0).text ?? ''\n }\n}\n\nexport type SpawnObserver = (process: ManagedClaudeProcess, options: SpawnOptions) => void\n\nexport function createManagedClaudeSpawner(\n runtime: Pick<SubprocessRuntime, 'spawn'>,\n executablePath: string,\n observe?: SpawnObserver,\n): (options: SpawnOptions) => SpawnedProcess {\n return options => {\n if (options.command !== executablePath) {\n throw new Error(`dsh-claude: SDK requested unexpected executable ${JSON.stringify(options.command)}`)\n }\n const handle = runtime.spawn({\n argv: [executablePath, ...options.args],\n cwd: options.cwd ?? process.cwd(),\n stdio: {\n stdin: 'pipe',\n stdout: 'pipe',\n stderr: { maxBytes: CLAUDE_STDERR_TAIL_BYTES },\n },\n graceMs: CLAUDE_PROCESS_GRACE_MS,\n signal: options.signal,\n env: scrubClaudeSpawnEnv(options.env),\n })\n const managed = new ManagedClaudeProcess(handle)\n observe?.(managed, options)\n return managed\n }\n}\n","import { randomUUID } from 'node:crypto'\nimport {\n query as claudeQuery,\n type EffortLevel,\n type Options as ClaudeOptions,\n type PermissionMode,\n type Query,\n type SDKControlGetContextUsageResponse,\n type SDKMessage,\n type SDKUserMessage,\n type Settings as ClaudeSettings,\n type SlashCommand,\n} from '@anthropic-ai/claude-agent-sdk'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport { CallId, createToolResultMessage } from '@deepseek-ai/dsh-llm'\nimport type { ApprovalService } from '@deepseek-ai/dsh-user-approval'\nimport type { SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'\nimport { AsyncQueue } from './async-queue.ts'\nimport { TASK_TOOL_NAMES } from './constants.ts'\nimport {\n currentClaudeActivityCursor,\n redactText,\n safeDetail,\n type ClaudeActivityCursor,\n type ClaudeActivityInput,\n type ClaudeTaskInfo,\n type ClaudeUsage,\n} from './events.ts'\nimport { createPermissionBridge } from './permission.ts'\nimport { ClaudeSidecarRepository } from './sidecar.ts'\nimport { CLAUDE_PRESENTER_NAMES, dynamicPresenterDefinition } from './presenters.ts'\nimport { normalizeSdkMessage, type NormalizedSdkMessage } from './sdk-messages.ts'\nimport { createManagedClaudeSpawner, type ManagedClaudeProcess } from './spawn.ts'\n\nexport const CLAUDE_INITIALIZATION_TIMEOUT_MS = 30_000\nexport const CLAUDE_INTERRUPT_TIMEOUT_MS = 5_000\n/** Control requests must settle; a wedged one must not clog the metadata chain. */\nexport const CLAUDE_METADATA_TIMEOUT_MS = 15_000\n\nexport type ClaudeSupervisorState =\n | 'starting'\n | 'idle'\n | 'running'\n | 'interrupting'\n | 'disconnected'\n | 'outcome-unknown'\n | 'disposed'\n\nexport interface ClaudeSupervisorConfig {\n executablePath: string\n idleTimeoutMs: number\n maxProcesses: number\n defaultModel: string\n}\n\nexport type ClaudeTurnStreamEvent =\n | { type: 'text-delta'; text: string }\n | { type: 'usage'; usage: ClaudeUsage }\n | { type: 'complete'; text: string }\n\nexport type ClaudeThinkingMode = 'off' | 'ultracode' | EffortLevel\n\nexport type DshSandboxMode = 'read-only' | 'workspace-write' | 'danger-full-access'\n\nconst CLAUDE_MODE_BY_SANDBOX: Readonly<Record<DshSandboxMode, PermissionMode>> = {\n 'read-only': 'plan',\n 'workspace-write': 'acceptEdits',\n 'danger-full-access': 'bypassPermissions',\n}\n\n/** Fold DSH's native access selector into Claude Code's closest permission mode. */\nexport function claudePermissionMode(events: readonly { type: string; data: unknown }[]): PermissionMode {\n for (let index = events.length - 1; index >= 0; index -= 1) {\n const event = events[index]\n if (event?.type !== 'sandbox/mode') continue\n const mode = (event.data as { mode?: unknown }).mode\n return typeof mode === 'string' && mode in CLAUDE_MODE_BY_SANDBOX\n ? CLAUDE_MODE_BY_SANDBOX[mode as DshSandboxMode]\n : 'plan'\n }\n return 'plan'\n}\n\nexport interface ClaudeTurnRequest {\n agent: Agent\n prompt: string\n model?: string\n thinkingMode?: ClaudeThinkingMode\n signal?: AbortSignal\n}\n\nexport interface ClaudeSupervisorSnapshot {\n sessionId: string\n claudeSessionId?: string\n state: ClaudeSupervisorState\n cwd: string\n model: string\n thinkingMode?: ClaudeThinkingMode\n lastUsedAt: number\n pid?: number\n}\n\nexport class ClaudeTurnBusyError extends Error {\n constructor(sessionId: string) {\n super(`Claude Code session ${sessionId} already has an active or interrupting turn`)\n this.name = 'ClaudeTurnBusyError'\n }\n}\n\nexport class ClaudeOutcomeUnknownError extends Error {\n constructor(message = 'Claude Code exited after activity; side-effect outcome is unknown and the prompt was not replayed') {\n super(message)\n this.name = 'ClaudeOutcomeUnknownError'\n }\n}\n\nexport class ClaudeProtocolError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ClaudeProtocolError'\n }\n}\n\nexport class ClaudeProcessLimitError extends Error {\n constructor(maxProcesses: number) {\n super(`Claude Code process limit reached (${maxProcesses}) and no idle session can be evicted`)\n this.name = 'ClaudeProcessLimitError'\n }\n}\n\nexport type ClaudeQueryFactory = (params: {\n prompt: AsyncIterable<SDKUserMessage>\n options: ClaudeOptions\n}) => Query\n\ninterface ActiveTurn {\n agent: Agent\n cursor: ClaudeActivityCursor\n output: AsyncQueue<ClaudeTurnStreamEvent>\n promptUuid: ReturnType<typeof randomUUID>\n sawActivity: boolean\n sawTextDelta: boolean\n text: string\n thinking: string\n aborted: boolean\n deniedToolUseIds: Set<string>\n /** Root call names by toolUseId; tool results carry none of their own. */\n callNames: Map<string, string>\n signal?: AbortSignal\n abortListener?: () => void\n}\n\ninterface SupervisorEntry {\n sessionId: string\n ownerAgent: Agent\n cwd: string\n model: string\n thinkingMode: ClaudeThinkingMode | undefined\n permissionMode: PermissionMode\n state: ClaudeSupervisorState\n lastUsedAt: number\n input: AsyncQueue<SDKUserMessage>\n query: Query\n lifetime: AbortController\n process: ManagedClaudeProcess | undefined\n claudeSessionId: string | undefined\n active: ActiveTurn | undefined\n idleTimer: ReturnType<typeof setTimeout> | undefined\n initTimer: ReturnType<typeof setTimeout> | undefined\n initialized: boolean\n expectedResume: string | undefined\n /** Settled when init arrives; rejected on disconnect before init. */\n initWaiters: Array<(error: unknown) => void>\n /** Uuid of the startup handshake prompt; its local-command result is never a DSH turn outcome. */\n handshakeUuid: ReturnType<typeof randomUUID>\n /** True until the handshake's settlement arrives; its output is swallowed. */\n handshakePending: boolean\n /** Live Claude task board (subagents and background tasks), keyed by task id. */\n tasks: Map<string, ClaudeTaskInfo>\n /** Last time a task snapshot was persisted (progress throttling). */\n taskSnapshotAt: number\n /** Pending throttled snapshot flush timer. */\n taskSnapshotTimer: ReturnType<typeof setTimeout> | undefined\n pump: Promise<void>\n}\n\nfunction abortFailure(): Error {\n const error = new Error('Claude Code turn aborted')\n error.name = 'AbortError'\n return error\n}\n\nfunction signalAborted(signal: AbortSignal | undefined): boolean {\n return signal?.aborted === true\n}\n\nasync function withTimeout<T>(operation: Promise<T>, timeoutMs: number, label: string): Promise<T> {\n let timer: ReturnType<typeof setTimeout> | undefined\n try {\n return await Promise.race([\n operation,\n new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => reject(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs)\n timer.unref?.()\n }),\n ])\n } finally {\n if (timer !== undefined) clearTimeout(timer)\n }\n}\n\nfunction sdkUserMessage(prompt: string, uuid: ReturnType<typeof randomUUID>): SDKUserMessage {\n return {\n type: 'user',\n message: { role: 'user', content: prompt },\n parent_tool_use_id: null,\n uuid,\n }\n}\n\n/** CLI ≥ 2.1.235 emits system/init only after its first stdin input, while\n * the supervisor must see init before submitting any real turn. A local\n * slash command nudges startup without costing a model call; its lifecycle\n * messages are ignored because no DSH turn is active while they arrive. */\nconst CLAUDE_HANDSHAKE_PROMPT = '/status'\n\nfunction usageSummary(usage: ClaudeUsage): string {\n const input = usage.inputTokens ?? 0\n const output = usage.outputTokens ?? 0\n const cost = usage.cumulativeCostUsd === undefined\n ? ''\n : ` · $${usage.cumulativeCostUsd.toFixed(4)} cumulative`\n return `${input} input / ${output} output tokens${cost}`\n}\n\nfunction errorSummary(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Root-call activity summary; subagent dispatches lead with Claude's own task description. */\nfunction rootCallSummary(toolName: string, input: unknown): string {\n if (TASK_TOOL_NAMES.has(toolName)) {\n const description = input !== null && typeof input === 'object'\n ? (input as Record<string, unknown>).description\n : undefined\n if (typeof description === 'string' && description.length > 0) return description\n return 'Claude dispatched a subagent'\n }\n return `Claude called ${toolName}`\n}\n\nexport class ClaudeSupervisor {\n readonly #entries = new Map<string, SupervisorEntry>()\n readonly #runtime: Pick<SubprocessRuntime, 'spawn'>\n readonly #approval: Pick<ApprovalService, 'request'>\n readonly #config: ClaudeSupervisorConfig\n readonly #queryFactory: ClaudeQueryFactory\n readonly #runDetached: <T>(operation: () => T) => T\n readonly #sidecar: ClaudeSidecarRepository\n readonly #dynamicPresenterNames = new WeakMap<Agent, Set<string>>()\n readonly #contextWindows = new Map<string, number>()\n #disposed = false\n #admissionGate: Promise<void> = Promise.resolve()\n\n constructor(dependencies: {\n runtime: Pick<SubprocessRuntime, 'spawn'>\n approval: Pick<ApprovalService, 'request'>\n config: ClaudeSupervisorConfig\n queryFactory?: ClaudeQueryFactory\n runDetached?: <T>(operation: () => T) => T\n sidecar?: ClaudeSidecarRepository\n }) {\n this.#runtime = dependencies.runtime\n this.#approval = dependencies.approval\n this.#config = dependencies.config\n this.#queryFactory = dependencies.queryFactory ?? (params => claudeQuery(params))\n this.#runDetached = dependencies.runDetached ?? (operation => operation())\n this.#sidecar = dependencies.sidecar ?? new ClaudeSidecarRepository()\n }\n\n snapshots(): ClaudeSupervisorSnapshot[] {\n return [...this.#entries.values()].map(entry => ({\n sessionId: entry.sessionId,\n ...(entry.claudeSessionId === undefined ? {} : { claudeSessionId: entry.claudeSessionId }),\n state: entry.state,\n cwd: entry.cwd,\n model: entry.model,\n ...(entry.thinkingMode === undefined ? {} : { thinkingMode: entry.thinkingMode }),\n lastUsedAt: entry.lastUsedAt,\n ...(entry.process === undefined ? {} : { pid: entry.process.handle.pid }),\n }))\n }\n\n supportedCommands(agent: Agent, model = this.#config.defaultModel): Promise<readonly SlashCommand[]> {\n return this.#runMetadata(agent, model, query => query.supportedCommands())\n }\n\n async contextUsage(agent: Agent, model = this.#config.defaultModel): Promise<SDKControlGetContextUsageResponse> {\n const usage = await this.#runMetadata(agent, model, query => query.getContextUsage())\n const contextWindow = usage.rawMaxTokens > 0 ? usage.rawMaxTokens : usage.maxTokens\n if (contextWindow > 0) {\n this.#contextWindows.set(model, contextWindow)\n this.#contextWindows.set(usage.model, contextWindow)\n }\n return usage\n }\n\n contextWindow(model: string): number | undefined {\n return this.#contextWindows.get(model)\n }\n\n runTurn(request: ClaudeTurnRequest): Promise<AsyncIterable<ClaudeTurnStreamEvent>> {\n const operation = this.#admissionGate.then(() => this.#runTurnAdmitted(request))\n this.#admissionGate = operation.then(() => undefined, () => undefined)\n return operation\n }\n\n async #runTurnAdmitted(request: ClaudeTurnRequest): Promise<AsyncIterable<ClaudeTurnStreamEvent>> {\n if (this.#disposed) throw new Error('dsh-claude: supervisor is disposed')\n if (signalAborted(request.signal)) throw abortFailure()\n const sessionId = request.agent.id as string\n let entry = this.#entries.get(sessionId)\n if (entry?.state === 'disposed' || entry?.state === 'disconnected' || entry?.state === 'outcome-unknown') {\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n entry = undefined\n }\n if (entry === undefined) {\n await this.#makeRoom()\n entry = await this.#createEntry(request.agent, request.model ?? this.#config.defaultModel, request.thinkingMode)\n this.#entries.set(sessionId, entry)\n this.#armInitializationTimer(entry)\n }\n if (entry.ownerAgent !== request.agent) {\n throw new Error(`dsh-claude: live agent identity changed for session ${sessionId}`)\n }\n if (entry.active !== undefined || entry.state === 'interrupting') throw new ClaudeTurnBusyError(sessionId)\n\n if (entry.idleTimer !== undefined) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = undefined\n }\n const model = request.model ?? this.#config.defaultModel\n if (request.thinkingMode !== entry.thinkingMode) {\n // The SDK only accepts effort/thinking at query start, so rebuild the\n // query; the persisted Claude session binding keeps the context.\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n entry = await this.#createEntry(request.agent, model, request.thinkingMode)\n this.#entries.set(sessionId, entry)\n this.#armInitializationTimer(entry)\n } else {\n await this.#syncPermissionMode(entry)\n if (model !== entry.model) {\n await entry.query.setModel(model)\n entry.model = model\n }\n }\n\n const promptUuid = randomUUID()\n const cursor = currentClaudeActivityCursor(request.agent.session.events)\n const projection = await this.#sidecar.read(sessionId)\n cursor.nextOrdinal = projection.activities.reduce((next, activity) => (\n activity.turn === cursor.turn && activity.step === cursor.step\n ? Math.max(next, activity.ordinal + 1)\n : next\n ), 0)\n const active: ActiveTurn = {\n agent: request.agent,\n cursor,\n output: new AsyncQueue<ClaudeTurnStreamEvent>(),\n promptUuid,\n sawActivity: false,\n sawTextDelta: false,\n text: '',\n thinking: '',\n aborted: false,\n deniedToolUseIds: new Set(),\n callNames: new Map(),\n ...(request.signal === undefined ? {} : { signal: request.signal }),\n }\n entry.active = active\n entry.state = 'running'\n entry.lastUsedAt = Date.now()\n try {\n await this.#appendActivity(active, {\n kind: 'status',\n phase: 'started',\n title: 'Claude Code turn started',\n })\n } catch (error) {\n active.output.fail(error)\n entry.active = undefined\n if (this.#entries.get(sessionId) === entry) this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n throw error\n }\n if (signalAborted(request.signal)) {\n active.aborted = true\n active.output.fail(abortFailure())\n await this.#appendActivity(active, {\n kind: 'status',\n phase: 'failed',\n title: 'Claude Code turn cancelled before submission',\n })\n entry.active = undefined\n entry.state = 'idle'\n entry.lastUsedAt = Date.now()\n this.#armIdleTimer(entry)\n return active.output\n }\n if (request.signal !== undefined) {\n const abortListener = () => { void this.#interrupt(entry as SupervisorEntry) }\n active.abortListener = abortListener\n request.signal.addEventListener('abort', abortListener, { once: true })\n }\n entry.input.push(sdkUserMessage(request.prompt, promptUuid))\n return active.output\n }\n\n #runMetadata<T>(\n agent: Agent,\n model: string,\n operation: (query: Query, entry: SupervisorEntry) => Promise<T>,\n ): Promise<T> {\n const admitted = this.#admissionGate.then(async () => {\n if (this.#disposed) throw new Error('dsh-claude: supervisor is disposed')\n const entry = await this.#metadataEntry(agent, model)\n try {\n // Control requests go out only after the CLI finishes initializing;\n // issued earlier they can wedge and clog the caller's refresh chain.\n await withTimeout(this.#whenInitialized(entry), CLAUDE_INITIALIZATION_TIMEOUT_MS, 'Claude metadata initialization')\n return await withTimeout(operation(entry.query, entry), CLAUDE_METADATA_TIMEOUT_MS, 'Claude metadata request')\n } finally {\n entry.lastUsedAt = Date.now()\n if (entry.active === undefined && entry.state === 'idle') this.#armIdleTimer(entry)\n }\n })\n this.#admissionGate = admitted.then(() => undefined, () => undefined)\n return admitted\n }\n\n #whenInitialized(entry: SupervisorEntry): Promise<void> {\n if (entry.initialized) return Promise.resolve()\n if (entry.state === 'disposed' || entry.state === 'disconnected' || entry.state === 'outcome-unknown') {\n return Promise.reject(new Error(`dsh-claude: session ${entry.sessionId} is ${entry.state}`))\n }\n return new Promise<void>((resolve, reject) => {\n entry.initWaiters.push(error => (error === undefined ? resolve() : reject(error instanceof Error ? error : new Error(String(error)))))\n })\n }\n\n async #metadataEntry(agent: Agent, model: string): Promise<SupervisorEntry> {\n const sessionId = agent.id as string\n let entry = this.#entries.get(sessionId)\n if (entry?.state === 'disposed' || entry?.state === 'disconnected' || entry?.state === 'outcome-unknown') {\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n entry = undefined\n }\n if (entry === undefined) {\n await this.#makeRoom()\n entry = await this.#createEntry(agent, model)\n this.#entries.set(sessionId, entry)\n this.#armInitializationTimer(entry)\n }\n if (entry.ownerAgent !== agent) {\n throw new Error(`dsh-claude: live agent identity changed for session ${sessionId}`)\n }\n if (entry.active !== undefined || entry.state === 'interrupting') throw new ClaudeTurnBusyError(sessionId)\n if (entry.idleTimer !== undefined) {\n clearTimeout(entry.idleTimer)\n entry.idleTimer = undefined\n }\n await this.#syncPermissionMode(entry)\n if (model !== entry.model) {\n await entry.query.setModel(model)\n entry.model = model\n }\n return entry\n }\n\n async #syncPermissionMode(entry: SupervisorEntry): Promise<void> {\n const mode = claudePermissionMode(entry.ownerAgent.session.events)\n if (mode === entry.permissionMode) return\n await entry.query.setPermissionMode(mode)\n entry.permissionMode = mode\n }\n\n async disposeSession(sessionId: string): Promise<void> {\n const entry = this.#entries.get(sessionId)\n if (entry === undefined) return\n this.#entries.delete(sessionId)\n await this.#disposeEntry(entry)\n }\n\n async dispose(): Promise<void> {\n if (this.#disposed) return\n this.#disposed = true\n const entries = [...this.#entries.values()]\n this.#entries.clear()\n await Promise.allSettled(entries.map(entry => this.#disposeEntry(entry)))\n }\n\n async #makeRoom(): Promise<void> {\n if (this.#entries.size < this.#config.maxProcesses) return\n const idle = [...this.#entries.values()]\n .filter(entry => entry.active === undefined && entry.state === 'idle')\n .sort((left, right) => left.lastUsedAt - right.lastUsedAt)[0]\n if (idle === undefined) throw new ClaudeProcessLimitError(this.#config.maxProcesses)\n this.#entries.delete(idle.sessionId)\n await this.#disposeEntry(idle)\n }\n\n async #createEntry(agent: Agent, model: string, thinkingMode?: ClaudeThinkingMode): Promise<SupervisorEntry> {\n const sessionId = agent.id as string\n const cwd = agent.session.header.cwd ?? process.cwd()\n const input = new AsyncQueue<SDKUserMessage>()\n const lifetime = new AbortController()\n const projection = await this.#sidecar.importLegacy(sessionId, agent.session.events)\n const binding = projection.binding\n const permissionMode = claudePermissionMode(agent.session.events)\n const entry = {\n sessionId,\n ownerAgent: agent,\n cwd,\n model,\n thinkingMode,\n permissionMode,\n state: 'starting' as ClaudeSupervisorState,\n lastUsedAt: Date.now(),\n input,\n lifetime,\n claudeSessionId: binding?.claudeSessionId,\n expectedResume: binding?.claudeSessionId,\n handshakeUuid: randomUUID(),\n handshakePending: true,\n initialized: false,\n initWaiters: [] as Array<(error: unknown) => void>,\n initTimer: undefined,\n idleTimer: undefined,\n tasks: new Map<string, ClaudeTaskInfo>(),\n taskSnapshotAt: 0,\n taskSnapshotTimer: undefined,\n } as SupervisorEntry\n\n const canUseTool = createPermissionBridge(this.#approval, () => {\n const active = entry.active\n return active === undefined ? undefined : {\n agent: active.agent,\n cursor: active.cursor,\n markActivity: () => { active.sawActivity = true },\n recordDenial: toolUseId => { active.deniedToolUseIds.add(toolUseId) },\n appendActivity: activity => this.#appendActivity(active, activity),\n }\n })\n const options: ClaudeOptions = {\n pathToClaudeCodeExecutable: this.#config.executablePath,\n cwd,\n settingSources: ['user', 'project', 'local'],\n systemPrompt: { type: 'preset', preset: 'claude_code' },\n tools: { type: 'preset', preset: 'claude_code' },\n includePartialMessages: true,\n permissionMode,\n allowDangerouslySkipPermissions: true,\n canUseTool,\n abortController: lifetime,\n spawnClaudeCodeProcess: createManagedClaudeSpawner(this.#runtime, this.#config.executablePath, process => {\n entry.process = process\n }),\n ...(binding === undefined ? {} : { resume: binding.claudeSessionId }),\n model,\n ...(thinkingMode === undefined\n ? {}\n : thinkingMode === 'off'\n ? { thinking: { type: 'disabled' } as const }\n : thinkingMode === 'ultracode'\n ? { settings: { ultracode: true } satisfies ClaudeSettings }\n : { effort: thinkingMode }),\n }\n entry.query = this.#queryFactory({ prompt: input, options })\n entry.input.push(sdkUserMessage(CLAUDE_HANDSHAKE_PROMPT, entry.handshakeUuid))\n entry.pump = this.#runDetached(() => this.#pump(entry))\n return entry\n }\n\n async #pump(entry: SupervisorEntry): Promise<void> {\n try {\n for await (const sdkMessage of entry.query) {\n for (const message of normalizeSdkMessage(sdkMessage as SDKMessage)) {\n await this.#handleMessage(entry, message)\n }\n }\n if (entry.state !== 'disposed') await this.#handleDisconnect(entry, new Error('Claude Code stream ended'))\n } catch (error) {\n if (entry.state !== 'disposed') await this.#handleDisconnect(entry, error)\n }\n }\n\n async #handleMessage(entry: SupervisorEntry, message: NormalizedSdkMessage): Promise<void> {\n if (message.kind === 'init') {\n // Claude Code can re-emit system/init across turns in long-lived\n // streaming-input mode (e.g. the auth-error path). Treat it idempotently:\n // refresh the session id/version and negotiated state, and only reject a\n // genuine identity/cwd mismatch.\n if (entry.expectedResume !== undefined && message.sessionId !== entry.expectedResume) {\n throw new ClaudeProtocolError(`Claude Code resumed unexpected session ${message.sessionId}; expected ${entry.expectedResume}`)\n }\n if (message.cwd !== entry.cwd) {\n throw new ClaudeProtocolError(`Claude Code initialized in unexpected cwd ${message.cwd}; expected ${entry.cwd}`)\n }\n if (entry.initTimer !== undefined) {\n clearTimeout(entry.initTimer)\n entry.initTimer = undefined\n }\n entry.initialized = true\n entry.claudeSessionId = message.sessionId\n entry.state = entry.active === undefined ? 'idle' : 'running'\n for (const waiter of entry.initWaiters.splice(0)) waiter(undefined)\n // The SDK emits no background-task level at startup; reset the board on\n // every (re)start and let membership changes repopulate it.\n if (entry.tasks.size > 0) {\n entry.tasks.clear()\n await this.#flushTasksSnapshot(entry)\n }\n await this.#sidecar.writeBinding(entry.sessionId, {\n claudeSessionId: message.sessionId,\n cliVersion: message.cliVersion,\n cwd: message.cwd,\n })\n return\n }\n\n // Task lifecycle is session-scoped, not turn-scoped: background tasks and\n // subagents settle while no DSH turn is active, and their notifications\n // must still reach the task board instead of being dropped with turn-less\n // messages below.\n const taskId = message.kind === 'subagent' ? message.taskId : undefined\n if (message.kind === 'subagent' && taskId !== undefined) {\n await this.#trackTask(entry, message, taskId, entry.active?.cursor.turn)\n } else if (message.kind === 'background-tasks') {\n this.#trackBackgroundLevel(entry, message.tasks, entry.active?.cursor.turn)\n }\n\n if (entry.handshakePending) {\n // Startup-handshake output of the local `/status` nudge: never part of\n // any DSH turn. Protocol failures stay loud; the settlement clears the\n // phase so subsequent messages belong to real turns.\n if (message.kind === 'protocol-error') {\n throw new ClaudeProtocolError(`${message.title}: ${JSON.stringify(message.detail).slice(0, 1_000)}`)\n }\n if (message.kind === 'result') entry.handshakePending = false\n return\n }\n\n const active = entry.active\n if (active === undefined) return\n if (message.kind === 'result') {\n if (message.userMessageUuid !== undefined && message.userMessageUuid === entry.handshakeUuid) {\n // Startup handshake settlement; never a DSH turn outcome.\n return\n }\n if (entry.claudeSessionId === undefined) {\n throw new ClaudeProtocolError('Claude Code sent a result before initialization')\n }\n if (message.sessionId !== entry.claudeSessionId) {\n throw new ClaudeProtocolError(`Claude Code result session ${message.sessionId} does not match ${entry.claudeSessionId}`)\n }\n if (message.userMessageUuid !== undefined && message.userMessageUuid !== active.promptUuid) {\n throw new ClaudeProtocolError(`Claude Code result for user message ${message.userMessageUuid} does not match active request ${active.promptUuid}`)\n }\n await this.#completeTurn(entry, active, message)\n return\n }\n if (message.kind === 'protocol-error') {\n throw new ClaudeProtocolError(`${message.title}: ${JSON.stringify(message.detail).slice(0, 1_000)}`)\n }\n active.sawActivity = true\n\n switch (message.kind) {\n case 'text-delta':\n if (message.parentToolUseId !== undefined) return\n active.sawTextDelta = true\n active.text += message.text\n active.output.push({ type: 'text-delta', text: message.text })\n return\n case 'assistant-text':\n if (message.parentToolUseId !== undefined) return\n if (!active.sawTextDelta) {\n // Complete assistant text is the fallback when no partial text delta\n // streamed. Mark text-delta seen so that additional complete\n // assistant records sharing the same message.id (one per completed\n // content block) do not duplicate the text.\n active.sawTextDelta = true\n active.text += message.text\n active.output.push({ type: 'text-delta', text: message.text })\n }\n return\n case 'thinking':\n if (message.parentToolUseId !== undefined) return\n if (message.phase === 'updated') {\n active.thinking += message.text\n return\n }\n active.thinking = message.text\n await this.#appendActivity(active, {\n kind: 'thinking',\n phase: 'completed',\n title: 'Claude thinking',\n summary: message.text,\n })\n return\n case 'tool-call':\n await this.#appendActivity(active, {\n kind: message.parentToolUseId === undefined ? 'tool-call' : 'subagent',\n phase: 'started',\n toolUseId: message.toolUseId,\n ...(message.parentToolUseId === undefined ? {} : { parentToolUseId: message.parentToolUseId }),\n toolName: message.toolName,\n title: message.toolName,\n summary: message.parentToolUseId === undefined ? rootCallSummary(message.toolName, message.input) : `Subagent called ${message.toolName}`,\n detail: message.input,\n })\n if (message.parentToolUseId === undefined) {\n active.callNames.set(message.toolUseId, message.toolName)\n this.#ensureDynamicPresenter(active.agent, message.toolName)\n // Task dispatches render as plugin-owned group cards gathering the\n // subagents' nested work; only ordinary tools mirror natively.\n if (!TASK_TOOL_NAMES.has(message.toolName)) await this.#appendNativeToolCall(active, message)\n }\n return\n case 'tool-result':\n await this.#appendActivity(active, {\n kind: message.parentToolUseId === undefined ? 'tool-result' : 'subagent',\n phase: message.isError ? 'failed' : 'completed',\n toolUseId: message.toolUseId,\n ...(message.parentToolUseId === undefined ? {} : { parentToolUseId: message.parentToolUseId }),\n title: message.isError ? 'Tool failed' : 'Tool completed',\n detail: message.output,\n isError: message.isError,\n })\n if (message.parentToolUseId === undefined\n && !TASK_TOOL_NAMES.has(active.callNames.get(message.toolUseId) ?? '')) {\n await this.#appendNativeToolResult(active, message)\n }\n return\n case 'subagent':\n await this.#appendActivity(active, {\n kind: 'subagent',\n phase: message.phase,\n ...(message.taskId === undefined ? {} : { taskId: message.taskId }),\n title: message.title,\n summary: message.summary,\n detail: message.detail,\n isError: message.phase === 'failed',\n })\n return\n case 'status':\n case 'warning':\n case 'unknown':\n await this.#appendActivity(active, {\n kind: message.kind === 'status' ? 'status' : 'warning',\n phase: 'updated',\n title: message.title,\n ...('summary' in message ? { summary: message.summary } : {}),\n ...('detail' in message ? { detail: message.detail } : {}),\n })\n return\n case 'permission-denied':\n await this.#appendActivity(active, {\n kind: 'permission',\n phase: 'denied',\n toolUseId: message.toolUseId,\n toolName: message.toolName,\n title: message.toolName,\n summary: message.summary,\n })\n return\n }\n }\n\n /** Merge one task lifecycle message into the session's task board. */\n async #trackTask(\n entry: SupervisorEntry,\n message: Extract<NormalizedSdkMessage, { kind: 'subagent' }>,\n taskId: string,\n originTurn: number | undefined,\n ): Promise<void> {\n const previous = entry.tasks.get(taskId)\n const next: ClaudeTaskInfo = {\n taskId,\n description: message.description ?? previous?.description ?? message.title,\n status: message.taskStatus ?? previous?.status ?? 'running',\n }\n const resolvedOriginTurn = previous?.originTurn ?? originTurn\n if (resolvedOriginTurn !== undefined) next.originTurn = resolvedOriginTurn\n const subagentType = message.subagentType ?? previous?.subagentType\n if (subagentType !== undefined) next.subagentType = subagentType\n const taskType = message.taskType ?? previous?.taskType\n if (taskType !== undefined) next.taskType = taskType\n const lastToolName = message.lastToolName ?? previous?.lastToolName\n if (lastToolName !== undefined) next.lastToolName = lastToolName\n const summary = message.summary ?? previous?.summary\n if (summary !== undefined) next.summary = summary\n const usage = message.usage ?? previous?.usage\n if (usage !== undefined) next.usage = usage\n if (previous?.backgrounded === true) next.backgrounded = true\n entry.tasks.set(taskId, next)\n const settled = next.status !== 'running'\n await this.#scheduleTasksSnapshot(entry, settled)\n }\n\n /** Fold the background-task level signal into the board (REPLACE semantics\n * for the backgrounded flag: only the listed tasks are detached). */\n #trackBackgroundLevel(\n entry: SupervisorEntry,\n tasks: readonly { taskId: string; taskType?: string; description: string }[],\n originTurn: number | undefined,\n ): void {\n const live = new Set(tasks.map(task => task.taskId))\n let changed = false\n for (const task of tasks) {\n const existing = entry.tasks.get(task.taskId)\n if (existing === undefined) {\n entry.tasks.set(task.taskId, {\n taskId: task.taskId,\n description: task.description,\n status: 'running',\n ...(originTurn === undefined ? {} : { originTurn }),\n ...(task.taskType === undefined ? {} : { taskType: task.taskType }),\n backgrounded: true,\n })\n changed = true\n } else if (existing.backgrounded !== true || existing.status !== 'running') {\n entry.tasks.set(task.taskId, { ...existing, status: 'running', backgrounded: true })\n changed = true\n }\n }\n for (const task of entry.tasks.values()) {\n if (task.backgrounded === true && task.status === 'running' && !live.has(task.taskId)) {\n entry.tasks.set(task.taskId, { ...task, status: 'completed' })\n changed = true\n }\n }\n if (changed) void this.#scheduleTasksSnapshot(entry, true)\n }\n\n /** Persist the task board. Settled transitions flush immediately; progress\n * ticks throttle to one snapshot per second to bound log volume. */\n async #scheduleTasksSnapshot(entry: SupervisorEntry, immediate: boolean): Promise<void> {\n const THROTTLE_MS = 1_000\n const elapsed = Date.now() - entry.taskSnapshotAt\n if (!immediate && elapsed < THROTTLE_MS) {\n if (entry.taskSnapshotTimer === undefined) {\n entry.taskSnapshotTimer = setTimeout(() => {\n entry.taskSnapshotTimer = undefined\n void this.#flushTasksSnapshot(entry)\n }, THROTTLE_MS - elapsed)\n entry.taskSnapshotTimer.unref?.()\n }\n return\n }\n await this.#flushTasksSnapshot(entry)\n }\n\n async #flushTasksSnapshot(entry: SupervisorEntry): Promise<void> {\n if (entry.taskSnapshotTimer !== undefined) {\n clearTimeout(entry.taskSnapshotTimer)\n entry.taskSnapshotTimer = undefined\n }\n entry.taskSnapshotAt = Date.now()\n // Snapshot persistence is best-effort: the in-memory board stays\n // authoritative and the next change re-flushes.\n await this.#sidecar.writeTasks(entry.sessionId, [...entry.tasks.values()]).catch(() => undefined)\n }\n\n async #completeTurn(\n entry: SupervisorEntry,\n active: ActiveTurn,\n result: Extract<NormalizedSdkMessage, { kind: 'result' }>,\n ): Promise<void> {\n if (entry.active !== active) return\n if (active.signal !== undefined && active.abortListener !== undefined) {\n active.signal.removeEventListener('abort', active.abortListener)\n }\n if (active.aborted) {\n await this.#appendSafely(active, {\n kind: 'status',\n phase: 'failed',\n title: 'Claude Code turn cancelled',\n })\n entry.active = undefined\n entry.state = 'idle'\n entry.lastUsedAt = Date.now()\n this.#armIdleTimer(entry)\n return\n }\n if (result.usage.inputTokens !== undefined || result.usage.outputTokens !== undefined || result.usage.cumulativeCostUsd !== undefined) {\n await this.#appendSafely(active, {\n kind: 'usage',\n phase: 'completed',\n title: 'Claude usage',\n summary: usageSummary(result.usage),\n usage: result.usage,\n })\n active.output.push({ type: 'usage', usage: result.usage })\n }\n const unmatchedDenials = (result.permissionDenials ?? [])\n .filter(denial => !active.deniedToolUseIds.has(denial.toolUseId))\n if (unmatchedDenials.length > 0) {\n await this.#appendSafely(active, {\n kind: 'permission',\n phase: 'denied',\n title: 'Claude Code auto-denied tool calls',\n summary: unmatchedDenials.map(denial => denial.toolName).join(', '),\n })\n }\n if (!result.success) {\n const message = result.errors?.join('\\n')\n ?? (result.terminalReason !== undefined ? `Claude Code failed the turn (${result.terminalReason})` : 'Claude Code failed the turn')\n await this.#appendSafely(active, {\n kind: 'error',\n phase: 'failed',\n title: 'Claude Code turn failed',\n summary: message,\n isError: true,\n })\n active.output.fail(new Error(message))\n } else {\n if (!active.sawTextDelta && active.text.length === 0 && result.text !== undefined) {\n active.text = result.text\n active.output.push({ type: 'text-delta', text: result.text })\n }\n await this.#appendSafely(active, {\n kind: 'status',\n phase: 'completed',\n title: 'Claude Code turn completed',\n })\n active.output.push({ type: 'complete', text: active.text })\n active.output.close()\n }\n entry.active = undefined\n entry.state = 'idle'\n entry.lastUsedAt = Date.now()\n this.#armIdleTimer(entry)\n }\n\n async #appendActivity(active: ActiveTurn, activity: ClaudeActivityInput): Promise<void> {\n const ordinal = active.cursor.nextOrdinal++\n await this.#sidecar.appendActivity(active.agent.id as string, {\n ...activity,\n turn: active.cursor.turn,\n step: active.cursor.step,\n ordinal,\n })\n }\n\n /** Persist durable activity without letting a storage failure unsettle the\n * in-memory turn or leak process ownership. Audit failure is best-effort. */\n async #appendSafely(active: ActiveTurn, activity: ClaudeActivityInput): Promise<void> {\n await this.#appendActivity(active, activity).catch(() => undefined)\n }\n\n /** Register one presenter-only mirror for a tool name the static preset\n * registry does not cover (MCP tools, newly added built-ins). Runs in the\n * agent scope so the mirror is visible only to this preset's sessions and\n * unwinds with the agent; failure keeps the generic card, never the turn. */\n #ensureDynamicPresenter(agent: Agent, name: string): void {\n if (CLAUDE_PRESENTER_NAMES.has(name)) return\n let known = this.#dynamicPresenterNames.get(agent)\n if (known === undefined) {\n known = new Set<string>()\n this.#dynamicPresenterNames.set(agent, known)\n }\n if (known.has(name)) return\n try {\n agent.ctx.tools.register(dynamicPresenterDefinition(name))\n known.add(name)\n } catch {\n // A late or disposed agent keeps the generic card; presentation must\n // never unsettle the Claude turn.\n }\n }\n\n /** Mirror one root Claude tool call into the durable native tool channel so\n * the host's tool presentation renders it exactly like a DSH-executed call.\n * Presentation duplication is best-effort and never unsettles the turn. */\n async #appendNativeToolCall(\n active: ActiveTurn,\n message: Extract<NormalizedSdkMessage, { kind: 'tool-call' }>,\n ): Promise<void> {\n try {\n await active.agent.session.append('tool/call', {\n turn: active.cursor.turn,\n step: active.cursor.step,\n callId: CallId(message.toolUseId),\n name: message.toolName,\n arguments: safeDetail(message.input) ?? '{}',\n })\n } catch {\n // Presentation duplication must never unsettle the Claude turn.\n }\n }\n\n async #appendNativeToolResult(\n active: ActiveTurn,\n message: Extract<NormalizedSdkMessage, { kind: 'tool-result' }>,\n ): Promise<void> {\n const text = typeof message.output === 'string' ? redactText(message.output) : safeDetail(message.output) ?? ''\n try {\n await active.agent.session.append('tool/result', {\n turn: active.cursor.turn,\n step: active.cursor.step,\n message: createToolResultMessage({\n callId: CallId(message.toolUseId),\n content: [{ type: 'text', text }],\n isError: message.isError,\n }),\n }, { surfaceOp: 'append' })\n } catch {\n // Presentation duplication must never unsettle the Claude turn.\n }\n }\n\n async #interrupt(entry: SupervisorEntry): Promise<void> {\n const active = entry.active\n if (active === undefined || entry.state === 'interrupting') return\n entry.state = 'interrupting'\n active.aborted = true\n active.output.fail(abortFailure())\n let interruptError: unknown\n try {\n const receipt = await withTimeout(entry.query.interrupt(), CLAUDE_INTERRUPT_TIMEOUT_MS, 'Claude Code interrupt')\n const queued = receipt?.still_queued ?? []\n if (queued.includes(active.promptUuid)) {\n throw new Error(`Claude Code interrupt left submitted prompt ${active.promptUuid} queued`)\n }\n } catch (error) {\n interruptError = error\n }\n try {\n await this.#appendActivity(active, {\n kind: 'status',\n phase: 'failed',\n title: interruptError === undefined ? 'Claude Code turn cancelled' : 'Claude Code cancelled; process entry reset',\n ...(interruptError === undefined ? {} : { summary: errorSummary(interruptError) }),\n })\n } catch {\n // The active output is already aborted; process cleanup cannot wait for audit availability.\n }\n if (this.#entries.get(entry.sessionId) === entry) this.#entries.delete(entry.sessionId)\n await this.#disposeEntry(entry)\n }\n\n async #handleDisconnect(entry: SupervisorEntry, error: unknown): Promise<void> {\n const active = entry.active\n const stderr = entry.process?.stderrTail()\n if (active !== undefined) {\n if (active.signal !== undefined && active.abortListener !== undefined) {\n active.signal.removeEventListener('abort', active.abortListener)\n }\n const unknown = active.sawActivity\n entry.state = unknown ? 'outcome-unknown' : 'disconnected'\n const failure = unknown\n ? new ClaudeOutcomeUnknownError(stderr === undefined || stderr.length === 0 ? undefined : `Claude Code exited after activity; outcome unknown. ${stderr}`)\n : new Error(stderr === undefined || stderr.length === 0 ? errorSummary(error) : stderr)\n await this.#appendSafely(active, {\n kind: 'error',\n phase: 'failed',\n title: unknown ? 'Claude Code outcome unknown' : 'Claude Code disconnected',\n summary: failure.message,\n isError: true,\n detail: error,\n })\n active.output.fail(failure)\n entry.active = undefined\n } else {\n entry.state = 'disconnected'\n }\n const waiters = entry.initWaiters.splice(0)\n const waiterError = error instanceof Error ? error : new Error(String(error))\n for (const waiter of waiters) waiter(waiterError)\n this.#entries.delete(entry.sessionId)\n await this.#disposeEntry(entry)\n }\n\n #armInitializationTimer(entry: SupervisorEntry): void {\n const timer = setTimeout(() => {\n if (entry.state !== 'starting' || entry.initialized) return\n void this.#handleDisconnect(entry, new Error('Claude Code initialization timed out'))\n }, CLAUDE_INITIALIZATION_TIMEOUT_MS)\n timer.unref?.()\n entry.initTimer = timer\n }\n\n #armIdleTimer(entry: SupervisorEntry): void {\n if (this.#config.idleTimeoutMs <= 0) return\n const timer = setTimeout(() => {\n if (entry.active !== undefined || entry.state !== 'idle') return\n this.#entries.delete(entry.sessionId)\n void this.#disposeEntry(entry)\n }, this.#config.idleTimeoutMs)\n timer.unref?.()\n entry.idleTimer = timer\n }\n\n async #disposeEntry(entry: SupervisorEntry): Promise<void> {\n if (entry.state === 'disposed') return\n if (entry.idleTimer !== undefined) clearTimeout(entry.idleTimer)\n if (entry.initTimer !== undefined) clearTimeout(entry.initTimer)\n entry.state = 'disposed'\n entry.input.discard(abortFailure())\n entry.query.close()\n entry.lifetime.abort()\n if (entry.active !== undefined) entry.active.output.fail(abortFailure())\n entry.process?.kill('SIGTERM')\n if (entry.process !== undefined) {\n try {\n await entry.process.handle.waitForExit(AbortSignal.timeout(5_000))\n } catch {\n // The DSH subprocess owner still holds the tree and will finish escalation.\n }\n }\n }\n}\n","import {\n LlmAdapter,\n ReasoningEffortId,\n type GenerateOptions,\n type LlmModelInfo,\n type LlmProviderInfo,\n type LlmResolvedModelInfo,\n type ResolvedRetryPolicy,\n type StreamChunk,\n type TokenUsage,\n} from '@deepseek-ai/dsh-llm'\nimport type { Agent, AgentRegistry } from '@deepseek-ai/dsh-agent'\nimport { CLAUDE_CODE_PRESET_ID, CLAUDE_CODE_PROVIDER, isClaudePresetId } from './constants.ts'\nimport type { ClaudeSupervisor, ClaudeThinkingMode } from './supervisor.ts'\nimport type { ClaudeUsage } from './events.ts'\n\nconst MODELS = [\n { id: 'default', name: 'Default (recommended)', description: 'Use Claude Code’s recommended default model.' },\n { id: 'opus[1m]', name: 'Opus (1M context)', description: 'Use Opus with a 1M-token context window.', contextWindow: 1_000_000 },\n { id: 'fable', name: 'Fable', description: 'Use Fable, Claude Code’s most capable coding model.' },\n { id: 'sonnet', name: 'Sonnet', description: 'Use Sonnet for efficient routine coding work.' },\n { id: 'haiku', name: 'Haiku', description: 'Use Haiku for fast, lightweight tasks.' },\n] as const\n\nconst THINKING_MODES = [\n { id: 'off', name: 'Off', description: 'No extended thinking.' },\n { id: 'low', name: 'Low', description: 'Minimal thinking, fastest responses.' },\n { id: 'medium', name: 'Medium', description: 'Moderate thinking.' },\n { id: 'high', name: 'High', description: 'Deep reasoning (Claude Code default).' },\n { id: 'xhigh', name: 'Extra High', description: 'Deeper than high; unsupported models silently downgrade to high.' },\n { id: 'max', name: 'Max', description: 'Maximum effort; unsupported models silently downgrade.' },\n { id: 'ultracode', name: 'Ultracode', description: 'Extra-high effort plus standing dynamic-workflow orchestration; requires an xhigh-capable model.' },\n] as const\n\nexport function thinkingModeFor(effort: ReasoningEffortId | undefined): ClaudeThinkingMode | undefined {\n if (effort === undefined) return undefined\n if (THINKING_MODES.some(mode => mode.id === (effort as string))) return effort as unknown as ClaudeThinkingMode\n throw new Error(`dsh-claude: unsupported reasoning effort ${JSON.stringify(effort)}`)\n}\n\nconst NO_RETRY_POLICY: ResolvedRetryPolicy = Object.freeze({\n mode: 'normal',\n maxRetries: 0,\n retryableCodes: Object.freeze([]),\n initialDelayMs: 500,\n maxDelayMs: 10_000,\n jitterRatio: 0.1,\n})\n\nexport function extractDirectUserText(messages: GenerateOptions['messages']): string {\n for (let index = messages.length - 1; index >= 0; index -= 1) {\n const message = messages[index]\n if (message?.role !== 'user' || message.source.kind !== 'user') continue\n const text = message.content\n .filter((block): block is Extract<typeof block, { type: 'text' }> => block.type === 'text')\n .map(block => block.text)\n .join('\\n')\n .trim()\n if (text.length > 0) return text\n if (message.content.some(block => block.type === 'image')) {\n throw new Error('dsh-claude: image-only prompts are not supported in v0.1; include a text prompt')\n }\n }\n throw new Error('dsh-claude: no direct human text was present in this model step')\n}\n\nfunction tokenUsage(usage: ClaudeUsage): TokenUsage {\n const normalized: TokenUsage = {\n inputTokens: usage.inputTokens ?? 0,\n outputTokens: usage.outputTokens ?? 0,\n }\n if (usage.cacheReadTokens !== undefined) normalized.cacheReadTokens = usage.cacheReadTokens\n if (usage.cacheCreationTokens !== undefined) normalized.cacheWriteTokens = usage.cacheCreationTokens\n return normalized\n}\n\nfunction resolveAgent(agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>, options: GenerateOptions): Agent {\n const initiator = agents.currentInitiator()\n if (initiator !== undefined) return initiator\n if (options.sessionId !== undefined) {\n const agent = agents.get(options.sessionId)\n if (agent !== undefined) return agent\n }\n throw new Error('dsh-claude: the model request has no live owning DSH agent')\n}\n\nexport class ClaudeCodeAdapter extends LlmAdapter {\n readonly #supervisor: ClaudeSupervisor\n readonly #agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>\n readonly #presetIdFor: (agent: Agent) => string | undefined\n\n constructor(\n supervisor: ClaudeSupervisor,\n agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>,\n presetIdFor: (agent: Agent) => string | undefined,\n ) {\n super()\n this.#supervisor = supervisor\n this.#agents = agents\n this.#presetIdFor = presetIdFor\n }\n\n override providerInfo(provider: string): LlmProviderInfo {\n return { id: provider, name: 'Claude Code' }\n }\n\n override providerRetryPolicy(): ResolvedRetryPolicy {\n return NO_RETRY_POLICY\n }\n\n override async listModels(): Promise<readonly LlmModelInfo[]> {\n return MODELS.map(model => ({\n provider: CLAUDE_CODE_PROVIDER,\n id: model.id,\n name: model.name,\n description: model.description,\n inputModalities: ['text'],\n }))\n }\n\n override async resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {\n const known = MODELS.find(item => item.id === model)\n const observedContextWindow = this.#supervisor.contextWindow(model)\n const contextWindow = observedContextWindow ?? (known !== undefined && 'contextWindow' in known ? known.contextWindow : undefined)\n return {\n provider,\n id: model,\n name: known?.name ?? `Claude Code ${model}`,\n ...(known === undefined ? {} : { description: known.description }),\n ...(contextWindow === undefined ? {} : { context: { contextWindow } }),\n inputModalities: ['text'],\n reasoning: {\n efforts: THINKING_MODES.map(mode => ({\n id: ReasoningEffortId(mode.id),\n name: mode.name,\n description: mode.description,\n })),\n },\n }\n }\n\n override async *stream(options: GenerateOptions): AsyncIterable<StreamChunk> {\n if (options.purpose !== undefined) {\n throw new Error(`dsh-claude: auxiliary ${options.purpose} calls are not routed into the Claude session`)\n }\n const agent = resolveAgent(this.#agents, options)\n if (!isClaudePresetId(this.#presetIdFor(agent))) {\n throw new Error(`dsh-claude: provider ${CLAUDE_CODE_PROVIDER} is available only to the ${CLAUDE_CODE_PRESET_ID} preset`)\n }\n const thinkingMode = thinkingModeFor(options.reasoningEffort)\n const prompt = extractDirectUserText(options.messages)\n const events = await this.#supervisor.runTurn({\n agent,\n prompt,\n model: options.model,\n ...(thinkingMode === undefined ? {} : { thinkingMode }),\n ...(options.signal === undefined ? {} : { signal: options.signal }),\n })\n\n let text = ''\n let pendingUsage: TokenUsage | undefined\n let completed = false\n try {\n for await (const event of events) {\n if (event.type === 'text-delta') {\n // Buffered, not live-streamed: Claude's intermediate prose and final\n // answer settle as one block at the turn's durable position, below\n // the step's mirrored tool cards, instead of jumping there at the end.\n text += event.text\n } else if (event.type === 'usage') {\n pendingUsage = tokenUsage(event.usage)\n } else {\n completed = true\n if (text.length > 0) {\n yield { type: 'block-start', index: 0, blockType: 'text' }\n yield { type: 'text-delta', index: 0, text }\n yield { type: 'block-end', index: 0, block: { type: 'text', text } }\n }\n if (pendingUsage !== undefined) yield { type: 'usage', usage: pendingUsage }\n yield { type: 'finish', reason: { kind: 'stop' } }\n }\n }\n } catch (error) {\n if ((error as Error).name === 'AbortError') {\n completed = true\n if (text.length > 0) {\n yield { type: 'block-start', index: 0, blockType: 'text' }\n yield { type: 'text-delta', index: 0, text }\n yield { type: 'block-end', index: 0, block: { type: 'text', text } }\n }\n yield {\n type: 'finish',\n reason: {\n kind: 'aborted',\n failure: { code: 'aborted', message: error instanceof Error ? error.message : 'Claude Code turn aborted' },\n },\n }\n return\n }\n throw error\n }\n if (!completed) throw new Error('dsh-claude: Claude turn stream ended without a result')\n }\n}\n\nexport function createClaudeCodeAdapter(\n supervisor: ClaudeSupervisor,\n agents: Pick<AgentRegistry, 'currentInitiator' | 'get'>,\n presetIdFor: (agent: Agent) => string | undefined,\n): ClaudeCodeAdapter {\n return new ClaudeCodeAdapter(supervisor, agents, presetIdFor)\n}\n","import type { IncomingMessage, ServerResponse } from 'node:http'\n\n/** Accept only loopback, same-origin browser requests to plugin-private routes. */\nexport function trustedRequest(req: IncomingMessage): boolean {\n const remote = req.socket.remoteAddress\n if (remote !== '127.0.0.1' && remote !== '::1' && remote !== '::ffff:127.0.0.1') return false\n const site = req.headers['sec-fetch-site']\n if (site === 'cross-site') return false\n const host = req.headers.host\n if (host === undefined) return false\n const authority = /^(?:127\\.0\\.0\\.1|\\[?::1\\]?|localhost)(?::\\d+)?$/i\n if (!authority.test(host)) return false\n const origin = req.headers.origin\n if (origin === undefined) return true\n try {\n const originUrl = new URL(origin)\n return originUrl.host === host && authority.test(originUrl.host)\n } catch {\n return false\n }\n}\n\n/** Send a non-cacheable JSON response with MIME sniffing disabled. */\nexport function json(res: ServerResponse, status: number, value: unknown): void {\n res.writeHead(status, {\n 'content-type': 'application/json; charset=utf-8',\n 'cache-control': 'no-store',\n 'x-content-type-options': 'nosniff',\n })\n res.end(JSON.stringify(value))\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-agent-presets'\nimport type {} from '@deepseek-ai/dsh-commands'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { CLAUDE_DOCTOR_PATH } from './constants.ts'\nimport { runClaudeDoctor, type ExecutableRuntime } from './executable.ts'\nimport type { ClaudeSupervisor, ClaudeSupervisorConfig } from './supervisor.ts'\nimport { redactText } from './events.ts'\nimport { json, trustedRequest } from './http.ts'\n\nexport const CLAUDE_DOCTOR_PROBE_TIMEOUT_MS = 15_000\n\n/** Live metadata-bridge state per agent, maintained by the host plugin. */\nexport interface ClaudeBridgeDiagnostic {\n attempts: number\n lastError?: string\n lastCatalog?: number\n registered?: string[]\n}\n\nexport const claudeBridgeDiagnostics = new WeakMap<Agent, ClaudeBridgeDiagnostic>()\n\nfunction safeMessage(error: unknown): string {\n return redactText(error instanceof Error ? error.message : String(error), 1_000)\n}\n\n/** Live command-bridge diagnostics: which agents exist, their presets, and how\n * many slash commands each agent's registry layer resolves. */\nfunction commandDiagnostics(ctx: Context): unknown {\n try {\n const agents = ctx.agents.list()\n return {\n total: agents.length,\n agents: agents.map(agent => {\n const info: { id: string; preset?: string; commandCount?: number; sample?: string[]; error?: string; bridge?: ClaudeBridgeDiagnostic } = { id: String(agent.id) }\n try {\n const preset = ctx.agentPresets.composedPreset(agent.ctx)\n if (preset !== undefined) info.preset = preset\n } catch (error) {\n info.error = safeMessage(error)\n }\n try {\n const list = ctx.commands.list(agent)\n info.commandCount = list.length\n info.sample = list.slice(0, 10).map(command => command.name)\n } catch (error) {\n info.error = info.error === undefined ? safeMessage(error) : `${info.error}; ${safeMessage(error)}`\n }\n const bridge = claudeBridgeDiagnostics.get(agent)\n if (bridge !== undefined) info.bridge = bridge\n return info\n }),\n }\n } catch (error) {\n return { error: safeMessage(error) }\n }\n}\n\nexport function registerClaudeDoctorRoutes(\n ctx: Context,\n runtime: ExecutableRuntime,\n supervisor: ClaudeSupervisor,\n config: ClaudeSupervisorConfig,\n resolutionError?: unknown,\n): void {\n ctx.effect(() => ctx.webServer.register({\n kind: 'exact',\n path: CLAUDE_DOCTOR_PATH,\n handler: async (req, res) => {\n if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })\n if (!trustedRequest(req)) return json(res, 403, { error: 'forbidden' })\n try {\n if (resolutionError !== undefined) {\n return json(res, 200, {\n executable: {\n status: 'missing',\n searched: config.executablePath.length > 0 ? [config.executablePath] : ['claude', '~/.local/bin/claude', '/opt/homebrew/bin/claude', '/usr/local/bin/claude'],\n },\n version: { status: 'not-run' },\n authentication: { status: 'not-run' },\n handshake: 'not-run',\n message: safeMessage(resolutionError),\n limits: {\n idleTimeoutMs: config.idleTimeoutMs,\n maxProcesses: config.maxProcesses,\n },\n processes: { count: 0, active: 0 },\n })\n }\n const report = await runClaudeDoctor(runtime, {\n configuredPath: config.executablePath,\n cwd: process.cwd(),\n signal: AbortSignal.timeout(CLAUDE_DOCTOR_PROBE_TIMEOUT_MS),\n })\n const processes = supervisor.snapshots()\n if (processes.some(process => process.claudeSessionId !== undefined)) report.handshake = 'ok'\n json(res, 200, {\n ...report,\n limits: {\n idleTimeoutMs: config.idleTimeoutMs,\n maxProcesses: config.maxProcesses,\n },\n processes: {\n count: processes.length,\n active: processes.filter(process => process.state === 'running' || process.state === 'starting').length,\n },\n commandBridge: commandDiagnostics(ctx),\n })\n } catch (error) {\n json(res, 500, { error: safeMessage(error) })\n }\n },\n }), 'dsh-claude: Doctor route')\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport { CLAUDE_PROJECTION_PATH } from './constants.ts'\nimport { json, trustedRequest } from './http.ts'\nimport type { ClaudeSidecarRepository } from './sidecar.ts'\n\nconst MAX_SESSION_ID_CHARS = 1_024\n\nfunction sessionIdFromUrl(rawUrl: string | undefined): string | undefined {\n try {\n const pathname = new URL(rawUrl ?? '/', 'http://localhost').pathname\n const prefix = `${CLAUDE_PROJECTION_PATH}/`\n if (!pathname.startsWith(prefix)) return undefined\n const encoded = pathname.slice(prefix.length)\n if (encoded.length === 0 || encoded.includes('/')) return undefined\n const sessionId = decodeURIComponent(encoded)\n if (sessionId.length === 0 || sessionId.length > MAX_SESSION_ID_CHARS) return undefined\n return sessionId\n } catch {\n return undefined\n }\n}\n\n/** Register the browser-readable, credential-free sidecar projection endpoint. */\nexport function registerClaudeProjectionRoute(\n ctx: Context,\n sidecar: ClaudeSidecarRepository,\n ownsSession: (sessionId: string) => boolean,\n): void {\n ctx.effect(() => ctx.webServer.register({\n kind: 'prefix',\n path: CLAUDE_PROJECTION_PATH,\n handler: async (req, res) => {\n if (req.method !== 'GET') return json(res, 405, { error: 'method not allowed' })\n if (!trustedRequest(req)) return json(res, 403, { error: 'forbidden' })\n const sessionId = sessionIdFromUrl(req.url)\n if (sessionId === undefined) return json(res, 400, { error: 'invalid session id' })\n try {\n const projection = await sidecar.read(sessionId)\n return json(res, 200, {\n schemaVersion: projection.schemaVersion,\n revision: projection.revision,\n owned: ownsSession(sessionId),\n activities: projection.activities,\n ...(projection.contextUsage === undefined ? {} : { contextUsage: projection.contextUsage }),\n ...(projection.tasks === undefined ? {} : { tasks: projection.tasks }),\n })\n } catch {\n return json(res, 500, { error: 'projection unavailable' })\n }\n },\n }), 'dsh-claude: sidecar projection route')\n}\n","import type { Context } from '@deepseek-ai/cordis'\nimport z from '@deepseek-ai/schemastery'\nimport type { Agent } from '@deepseek-ai/dsh-agent'\nimport type {} from '@deepseek-ai/dsh-commands'\nimport { createUserMessage } from '@deepseek-ai/dsh-llm'\nimport type {} from '@deepseek-ai/dsh-agent-presets'\nimport type {} from '@deepseek-ai/dsh-host-webserver'\nimport type {} from '@deepseek-ai/dsh-subprocess'\nimport type {} from '@deepseek-ai/dsh-user-approval'\nimport { CLAUDE_CODE_PRESET_ID, CLAUDE_CODE_PROVIDER_IDS, isClaudePresetId } from './constants.ts'\nimport { CLAUDE_COMMANDS_SERVICE, ClaudeCommandBridge, type ClaudeAgentCommandService } from './command-bridge.ts'\nimport { ClaudeSidecarRepository } from './sidecar.ts'\nimport { resolveClaudeExecutable } from './executable.ts'\nimport { ClaudeSupervisor } from './supervisor.ts'\nimport { createClaudeCodeAdapter } from './adapter.ts'\nimport { ManagedPresetConflictError, removeManagedPreset } from './preset-installer.ts'\nimport { claudeBridgeDiagnostics, registerClaudeDoctorRoutes, type ClaudeBridgeDiagnostic } from './doctor-routes.ts'\nimport { registerClaudeProjectionRoute } from './projection-routes.ts'\n\nexport const name = 'llm-claude'\nexport const inject = ['llm', 'agents', 'agentPresets', 'commands', 'subprocess', 'approval']\n\nexport interface Config {\n executablePath?: string\n model?: string\n idleTimeoutMs?: number\n maxProcesses?: number\n}\n\nexport const Config: z<Config> = z.object({\n executablePath: z.string().default(''),\n model: z.string().default('default'),\n idleTimeoutMs: z.number().min(1_000).max(2_147_483_647).default(30 * 60 * 1_000),\n maxProcesses: z.number().step(1).min(1).default(4),\n})\n\nconst CLAUDE_SCOPE_UNAVAILABLE_MESSAGE = 'agent command scope unavailable (preset route not mounted?)'\nconst CATALOG_RETRY_MS = 5_000\nconst SCOPE_RETRY_MS = 500\nconst MAX_CATALOG_RETRIES = 3\nconst MAX_SCOPE_RETRIES = 24\n\nexport function mountClaudeMetadata(\n ctx: Context,\n supervisor: ClaudeSupervisor,\n agent: Agent,\n model: string,\n sidecar: ClaudeSidecarRepository,\n // IMPORTANT: call through the injected agentPresets SERVICE, never an\n // imported serviceForAgent() — a linked plugin resolves peer packages from\n // its own node_modules, which creates a second module instance with empty\n // module-level mount state. The service method runs on the app's instance.\n resolveCommands: () => ClaudeAgentCommandService | undefined =\n () => ctx.agentPresets.serviceFor(agent, CLAUDE_COMMANDS_SERVICE),\n): (() => Promise<void>) | undefined {\n if (!isClaudePresetId(ctx.agentPresets.composedPreset(agent.ctx))) return undefined\n\n let stopped = false\n let pending = Promise.resolve()\n let commandScope: ClaudeAgentCommandService | undefined\n\n // The commands service is unreachable from this host view of agent.ctx;\n // the preset route plugin provides it as an isolated per-session service.\n const scopedCommands = () => {\n const scoped = commandScope ?? resolveCommands()\n if (scoped === undefined) throw new Error(CLAUDE_SCOPE_UNAVAILABLE_MESSAGE)\n commandScope = scoped\n return scoped\n }\n\n const bridge = new ClaudeCommandBridge({\n list: () => scopedCommands().list(agent),\n register: definition => scopedCommands().register(definition),\n forward: line => {\n agent.followup(createUserMessage({\n content: [{ type: 'text', text: line }],\n source: { kind: 'user' },\n }))\n },\n })\n\n const warn = (area: string, error: unknown) => {\n ctx.logger.warn(`dsh-claude: ${area} refresh failed for ${String(agent.id)}: ${error instanceof Error ? error.message : String(error)}`)\n }\n\n const isScopeUnavailable = (error: unknown): boolean => {\n if (error instanceof Error) return error.message === CLAUDE_SCOPE_UNAVAILABLE_MESSAGE\n return String(error) === CLAUDE_SCOPE_UNAVAILABLE_MESSAGE\n }\n\n const diagnostic: ClaudeBridgeDiagnostic = claudeBridgeDiagnostics.get(agent) ?? { attempts: 0 }\n claudeBridgeDiagnostics.set(agent, diagnostic)\n\n // A fresh session's first catalog fetch races CLI startup (skills/plugins\n // can make init slow); retry with backoff so the command palette still\n // populates without waiting for the first completed turn.\n let catalogRetries = 0\n let scopeRetries = 0\n let retryTimer: ReturnType<typeof setTimeout> | undefined\n\n const scheduleRetry = (area: 'command catalog' | 'command scope', attempt: number) => {\n if (retryTimer !== undefined) clearTimeout(retryTimer)\n const delay = area === 'command catalog' ? CATALOG_RETRY_MS * attempt : Math.min(SCOPE_RETRY_MS * 2 ** attempt, 5_000)\n retryTimer = setTimeout(() => {\n if (!stopped) refresh()\n }, delay)\n retryTimer.unref?.()\n }\n\n const refresh = () => {\n pending = pending.then(async () => {\n if (stopped) return\n diagnostic.attempts += 1\n\n let catalog: Awaited<ReturnType<ClaudeSupervisor['supportedCommands']>> | undefined\n\n try {\n const result = await supervisor.supportedCommands(agent, model)\n catalog = result\n catalogRetries = 0\n scopeRetries = 0\n diagnostic.lastCatalog = catalog.length\n delete diagnostic.lastError\n } catch (error) {\n diagnostic.lastError = error instanceof Error ? error.message : String(error)\n warn('command catalog', error)\n if (!stopped && catalogRetries < MAX_CATALOG_RETRIES) {\n catalogRetries += 1\n scheduleRetry('command catalog', catalogRetries)\n }\n }\n\n if (stopped || catalog === undefined) return\n\n try {\n diagnostic.registered = bridge.refresh(catalog).map(view => view.publicName)\n if (!stopped) scopeRetries = 0\n } catch (error) {\n diagnostic.lastError = error instanceof Error ? error.message : String(error)\n warn('command catalog', error)\n if (!stopped && isScopeUnavailable(error) && scopeRetries < MAX_SCOPE_RETRIES) {\n scopeRetries += 1\n scheduleRetry('command scope', scopeRetries)\n }\n }\n\n if (stopped) return\n try {\n const usage = await supervisor.contextUsage(agent, model)\n if (!stopped) await sidecar.writeContextUsage(agent.id as string, usage)\n } catch (error) {\n warn('context usage', error)\n }\n })\n }\n\n return agent.ctx.effect(() => {\n const stopStatus = agent.ctx.on('agent/status', ({ status }) => {\n if (status === 'idle') refresh()\n })\n\n refresh()\n\n return async () => {\n stopped = true\n if (retryTimer !== undefined) clearTimeout(retryTimer)\n stopStatus()\n await pending\n bridge.dispose()\n }\n }, 'dsh-claude: agent metadata bridge')\n}\n\nexport async function apply(ctx: Context, config: Config): Promise<void> {\n // Versions before 0.1.2 copied the packaged preset into the user preset root.\n // The bundle now registers its package directory as a system root, so remove\n // only an exact legacy copy during upgrade and preserve any user-modified one.\n try {\n await removeManagedPreset()\n } catch (error) {\n if (!(error instanceof ManagedPresetConflictError)) throw error\n ctx.logger.warn(`dsh-claude: preserving user-modified legacy preset at ${error.path}`)\n }\n const supervisorConfig = {\n executablePath: '',\n defaultModel: config.model ?? 'default',\n idleTimeoutMs: config.idleTimeoutMs ?? 30 * 60 * 1_000,\n maxProcesses: config.maxProcesses ?? 4,\n }\n const sidecar = new ClaudeSidecarRepository()\n const supervisor = new ClaudeSupervisor({\n runtime: ctx.subprocess,\n approval: ctx.approval,\n config: supervisorConfig,\n runDetached: operation => ctx.agents.withoutInitiator(operation),\n sidecar,\n })\n let resolutionError: unknown\n try {\n const resolution = await resolveClaudeExecutable(\n ctx.subprocess,\n config.executablePath === undefined || config.executablePath.length === 0\n ? undefined\n : config.executablePath,\n )\n supervisorConfig.executablePath = resolution.path\n ctx.llm.registerAdapter(\n [...CLAUDE_CODE_PROVIDER_IDS],\n createClaudeCodeAdapter(supervisor, ctx.agents, agent => ctx.agentPresets.composedPreset(agent.ctx)),\n )\n ctx.effect(() => {\n const mounted = new Map<Agent, () => Promise<void>>()\n const pending = new Set<Agent>()\n const MOUNT_RETRY_MS = 200\n const MOUNT_RETRY_LIMIT = 50\n const mount = (agent: Agent) => {\n if (mounted.has(agent)) return\n const dispose = mountClaudeMetadata(ctx, supervisor, agent, supervisorConfig.defaultModel, sidecar)\n if (dispose !== undefined) mounted.set(agent, dispose)\n pending.delete(agent)\n }\n // The standing preset mount lands AFTER agent/created (the PresetTree is\n // applied asynchronously), so composedPreset is still undefined at that\n // point. Poll briefly until the join settles, then decide.\n const mountWhenPresetSettles = (agent: Agent) => {\n if (mounted.has(agent) || pending.has(agent)) return\n if (ctx.agentPresets.composedPreset(agent.ctx) !== undefined) {\n mount(agent)\n return\n }\n pending.add(agent)\n let attempts = 0\n const retry = () => {\n if (mounted.has(agent) || !pending.has(agent)) return\n if (ctx.agentPresets.composedPreset(agent.ctx) !== undefined) {\n mount(agent)\n return\n }\n attempts += 1\n if (attempts >= MOUNT_RETRY_LIMIT) {\n pending.delete(agent)\n return\n }\n const timer = setTimeout(retry, MOUNT_RETRY_MS)\n timer.unref?.()\n }\n const timer = setTimeout(retry, MOUNT_RETRY_MS)\n timer.unref?.()\n }\n const stopCreated = ctx.on('agent/created', ({ agent }) => { mountWhenPresetSettles(agent) })\n // Belt and suspenders: the session records its preset selection as a\n // durable event, which agent-presets republishes as agent-preset/selected.\n // agent-preset/selected is emitted by dsh-agent-presets but is not part\n // of the typed host event map yet; subscribe through a typed escape hatch.\n const onPresetSelected = ctx.on as (event: 'agent-preset/selected', handler: (sessionId: string, preset: string) => void) => () => void\n const stopSelected = onPresetSelected('agent-preset/selected', (sessionId, preset) => {\n if (!isClaudePresetId(preset)) return\n const agent = ctx.agents.get(sessionId as never)\n if (agent !== undefined) mountWhenPresetSettles(agent)\n })\n for (const agent of ctx.agents.list()) mountWhenPresetSettles(agent)\n return async () => {\n stopCreated()\n stopSelected()\n pending.clear()\n await Promise.allSettled([...mounted.values()].map(dispose => dispose()))\n mounted.clear()\n }\n }, 'dsh-claude: metadata bridges')\n } catch (error) {\n resolutionError = error\n }\n ctx.on('agent/disposed', async ({ agent }) => {\n await supervisor.disposeSession(agent.id as string)\n })\n ctx.effect(() => () => supervisor.dispose(), 'dsh-claude: process supervisor')\n ctx.inject(['webServer'], webCtx => {\n registerClaudeDoctorRoutes(webCtx, webCtx.subprocess, supervisor, supervisorConfig, resolutionError)\n registerClaudeProjectionRoute(webCtx, sidecar, sessionId => {\n const agent = webCtx.agents.get(sessionId as never)\n return agent !== undefined && isClaudePresetId(webCtx.agentPresets.composedPreset(agent.ctx))\n })\n })\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,MAAM,yBAAyB;AAC/B,MAAM,iBAAiB;AAgBvB,SAAS,kBAA2C;CAClD,OAAO;EAAE,eAAe;EAAwB,UAAU;EAAG,YAAY,CAAC;CAAE;AAC9E;AAEA,SAASA,SAAO,OAAqD;CACnE,OAAO,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,KAAK,IACtE,QACA,KAAA;AACN;AAEA,SAAS,cAAc,OAAiC;CACtD,OAAO,OAAO,UAAU,YAAY,OAAO,cAAc,KAAK,KAAK,SAAS;AAC9E;AAEA,SAASC,SAAO,OAAgB,KAA8B;CAC5D,OAAO,OAAO,UAAU,YAAY,MAAM,SAAS,KAAK,MAAM,UAAU;AAC1E;AAEA,SAAS,QAAQ,OAAqD;CACpE,MAAM,QAAQD,SAAO,KAAK;CAC1B,IAAI,UAAU,KAAA,KACT,CAACC,SAAO,MAAM,iBAAiB,GAAG,KAClC,CAACA,SAAO,MAAM,YAAY,GAAG,KAC7B,CAACA,SAAO,MAAM,KAAK,IAAK,KACvB,MAAM,eAAe,KAAA,KAAa,CAACA,SAAO,MAAM,YAAY,GAAG,GAAI,OAAO,K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;GAChB;EACF,GAAG,8BAA8B;CACnC,SAAS,OAAO;EACd,kBAAkB;CACpB;CACA,IAAI,GAAG,kBAAkB,OAAO,EAAE,YAAY;EAC5C,MAAM,WAAW,eAAe,MAAM,EAAY;CACpD,CAAC;CACD,IAAI,mBAAmB,WAAW,QAAQ,GAAG,gCAAgC;CAC7E,IAAI,OAAO,CAAC,WAAW,IAAG,WAAU;EAClC,2BAA2B,QAAQ,OAAO,YAAY,YAAY,kBAAkB,eAAe;EACnG,8BAA8B,QAAQ,UAAS,cAAa;GAC1D,MAAM,QAAQ,OAAO,OAAO,IAAI,SAAkB;GAClD,OAAO,UAAU,KAAA,KAAa,iBAAiB,OAAO,aAAa,eAAe,MAAM,GAAG,CAAC;EAC9F,CAAC;CACH,CAAC;AACH"}
@@ -181,7 +181,8 @@ async function managedContents(paths) {
181
181
  const routeEntry = join(paths.sourceDir, "..", "lib", "preset-route.mjs");
182
182
  return await Promise.all(MANAGED_PRESET_FILES.map(async (file) => {
183
183
  const source = await readFile(join(paths.sourceDir, file), "utf8");
184
- const nameRow = `name: ${PRESET_ROUTE_PACKAGE_SPECIFIER}`;
184
+ const nameRow = `name: '${PRESET_ROUTE_PACKAGE_SPECIFIER}'`;
185
+ const legacyNameRow = `name: ${PRESET_ROUTE_PACKAGE_SPECIFIER}`;
185
186
  if (file !== "agent.cordis.yml" || !source.includes(nameRow)) return {
186
187
  file,
187
188
  content: source,
@@ -190,9 +191,9 @@ async function managedContents(paths) {
190
191
  };
191
192
  return {
192
193
  file,
193
- content: source.replace(nameRow, `name: ${routeEntry}`),
194
+ content: source.replace(nameRow, `name: '${routeEntry}'`),
194
195
  legacy: [source],
195
- isLegacy: (current) => current.includes("id: claude-code-route") && (current.includes(nameRow) || current.includes("lib/preset-route.mjs"))
196
+ isLegacy: (current) => current.includes("id: claude-code-route") && (current.includes(nameRow) || current.includes(legacyNameRow) || current.includes("lib/preset-route.mjs"))
196
197
  };
197
198
  }));
198
199
  }
@@ -269,23 +270,23 @@ async function assertSafeTargetDirectory(targetDir) {
269
270
  async function removeManagedPreset(paths = defaultManagedPresetPaths()) {
270
271
  await assertSafeTargetDirectory(paths.targetDir);
271
272
  const expected = await managedContents(paths);
272
- let removed = false;
273
+ const managedTargets = [];
273
274
  for (const { file, content, legacy, isLegacy } of expected) {
274
275
  const target = join(paths.targetDir, file);
275
276
  const current = await readIfPresent(target);
276
277
  if (current === void 0) continue;
277
278
  if (current !== content && !legacy.includes(current) && !isLegacy(current)) throw new ManagedPresetConflictError(target);
278
- await rm(target);
279
- removed = true;
279
+ managedTargets.push(target);
280
280
  }
281
+ for (const target of managedTargets) await rm(target);
281
282
  try {
282
283
  if ((await readdir(paths.targetDir)).length === 0) await rmdir(paths.targetDir);
283
284
  } catch (error) {
284
285
  if (error.code !== "ENOENT") throw error;
285
286
  }
286
- return removed ? "removed" : "absent";
287
+ return managedTargets.length > 0 ? "removed" : "absent";
287
288
  }
288
289
  //#endregion
289
- export { runClaudeDoctor as a, resolveClaudeExecutable as i, removeManagedPreset as n, parseClaudeVersion as r, ensureManagedPreset as t };
290
+ export { resolveClaudeExecutable as a, parseClaudeVersion as i, ensureManagedPreset as n, runClaudeDoctor as o, removeManagedPreset as r, ManagedPresetConflictError as t };
290
291
 
291
- //# sourceMappingURL=preset-installer-DUVN1J6P.mjs.map
292
+ //# sourceMappingURL=preset-installer-XBN9ywDk.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preset-installer-XBN9ywDk.mjs","names":[],"sources":["../src/executable.ts","../src/preset-installer.ts"],"sourcesContent":["import { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'\nimport { redactText } from './events.ts'\n\nconst VERSION_PATTERN = /(?:Claude Code\\s+)?v?(\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?)/i\nconst MAX_PROBE_STDOUT = 64 * 1024\nconst MAX_PROBE_STDERR = 8 * 1024\n\nexport type ExecutableRuntime = Pick<SubprocessRuntime, 'resolveExecutable' | 'spawn'>\n\nexport class ClaudeExecutableNotFoundError extends Error {\n readonly searched: readonly string[]\n\n constructor(searched: readonly string[], options?: ErrorOptions) {\n super(`Claude Code executable not found. Searched: ${searched.join(', ')}`, options)\n this.name = 'ClaudeExecutableNotFoundError'\n this.searched = [...searched]\n }\n}\n\nexport interface ClaudeExecutableResolution {\n path: string\n searched: readonly string[]\n}\n\nexport interface ClaudeDoctorReport {\n executable: {\n status: 'found' | 'missing'\n path?: string\n searched: readonly string[]\n }\n version: {\n status: 'ok' | 'error' | 'not-run'\n value?: string\n message?: string\n }\n authentication: {\n status: 'signed-in' | 'signed-out' | 'unknown' | 'not-run'\n method?: string\n provider?: string\n subscription?: string\n message?: string\n }\n handshake: 'not-run' | 'ok' | 'error'\n}\n\nfunction fallbackCandidates(): string[] {\n if (process.platform !== 'darwin') return []\n return [\n join(homedir(), '.local', 'bin', 'claude'),\n '/opt/homebrew/bin/claude',\n '/usr/local/bin/claude',\n ]\n}\n\nfunction abortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')\n}\n\nexport async function resolveClaudeExecutable(\n runtime: ExecutableRuntime,\n configuredPath?: string,\n signal?: AbortSignal,\n): Promise<ClaudeExecutableResolution> {\n const searched: string[] = []\n const candidates = configuredPath === undefined\n ? ['claude', ...fallbackCandidates()]\n : [configuredPath]\n if (configuredPath !== undefined && !configuredPath.startsWith('/')) {\n throw new Error(`Claude Code executable path must be absolute: ${configuredPath}`)\n }\n\n let lastError: unknown\n for (const candidate of candidates) {\n if (searched.includes(candidate)) continue\n searched.push(candidate)\n try {\n const path = await runtime.resolveExecutable(candidate, undefined, signal)\n return { path, searched }\n } catch (error) {\n if (abortError(error) || signal?.aborted === true) throw error\n lastError = error\n }\n }\n throw new ClaudeExecutableNotFoundError(searched, lastError === undefined ? undefined : { cause: lastError })\n}\n\ninterface CollectedCommand {\n exitCode: number | null\n signal: NodeJS.Signals | null\n stdout: string\n stderr: string\n}\n\nasync function collect(handle: SubprocessHandle): Promise<CollectedCommand> {\n const outcome = await handle.done\n const stdout = handle.collected.stdout?.readFrom(0).text ?? ''\n const stderr = handle.collected.stderr?.readFrom(0).text ?? ''\n return { ...outcome, stdout, stderr }\n}\n\nasync function runProbe(\n runtime: ExecutableRuntime,\n executable: string,\n args: readonly string[],\n cwd: string,\n signal?: AbortSignal,\n): Promise<CollectedCommand> {\n return collect(runtime.spawn({\n argv: [executable, ...args],\n cwd,\n stdio: {\n stdin: 'ignore',\n stdout: { maxBytes: MAX_PROBE_STDOUT },\n stderr: { maxBytes: MAX_PROBE_STDERR },\n },\n graceMs: 2_000,\n ...(signal === undefined ? {} : { signal }),\n env: {},\n }))\n}\n\nexport function parseClaudeVersion(output: string): string | undefined {\n return VERSION_PATTERN.exec(output)?.[1]\n}\n\nexport async function probeClaudeVersion(\n runtime: ExecutableRuntime,\n executable: string,\n cwd: string,\n signal?: AbortSignal,\n): Promise<string> {\n const result = await runProbe(runtime, executable, ['--version'], cwd, signal)\n const version = parseClaudeVersion(`${result.stdout}\\n${result.stderr}`)\n if (result.exitCode !== 0 || version === undefined) {\n throw new Error(`Claude Code version probe failed (${result.exitCode ?? result.signal ?? 'unknown exit'})`)\n }\n return version\n}\n\nexport async function probeClaudeAuthentication(\n runtime: ExecutableRuntime,\n executable: string,\n cwd: string,\n signal?: AbortSignal,\n): Promise<ClaudeDoctorReport['authentication']> {\n const result = await runProbe(runtime, executable, ['auth', 'status', '--json'], cwd, signal)\n if (result.exitCode !== 0) {\n return { status: 'unknown', message: 'Claude authentication status command failed' }\n }\n try {\n const value = JSON.parse(result.stdout) as Record<string, unknown>\n const report: ClaudeDoctorReport['authentication'] = {\n status: value.loggedIn === true ? 'signed-in' : value.loggedIn === false ? 'signed-out' : 'unknown',\n }\n if (typeof value.authMethod === 'string') report.method = redactText(value.authMethod, 100)\n if (typeof value.apiProvider === 'string') report.provider = redactText(value.apiProvider, 100)\n if (typeof value.subscriptionType === 'string') report.subscription = redactText(value.subscriptionType, 100)\n return report\n } catch {\n return { status: 'unknown', message: 'Claude authentication status was not valid JSON' }\n }\n}\n\nexport async function runClaudeDoctor(\n runtime: ExecutableRuntime,\n options: { configuredPath?: string; cwd: string; signal?: AbortSignal },\n): Promise<ClaudeDoctorReport> {\n let resolution: ClaudeExecutableResolution\n try {\n resolution = await resolveClaudeExecutable(runtime, options.configuredPath, options.signal)\n } catch (error) {\n if (error instanceof ClaudeExecutableNotFoundError) {\n return {\n executable: { status: 'missing', searched: error.searched },\n version: { status: 'not-run' },\n authentication: { status: 'not-run' },\n handshake: 'not-run',\n }\n }\n throw error\n }\n\n const report: ClaudeDoctorReport = {\n executable: { status: 'found', path: resolution.path, searched: resolution.searched },\n version: { status: 'not-run' },\n authentication: { status: 'not-run' },\n handshake: 'not-run',\n }\n try {\n report.version = {\n status: 'ok',\n value: await probeClaudeVersion(runtime, resolution.path, options.cwd, options.signal),\n }\n } catch (error) {\n report.version = {\n status: 'error',\n message: error instanceof Error ? error.message : 'Version probe failed',\n }\n }\n try {\n report.authentication = await probeClaudeAuthentication(runtime, resolution.path, options.cwd, options.signal)\n } catch (error) {\n report.authentication = {\n status: 'unknown',\n message: error instanceof Error ? error.message : 'Authentication probe failed',\n }\n }\n return report\n}\n","import { randomUUID } from 'node:crypto'\nimport { link, lstat, mkdir, readFile, readdir, rm, rmdir, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths'\nimport { CLAUDE_CODE_PRESET_ID, LEGACY_CLAUDE_CODE_PRESET_ID } from './constants.ts'\n\nexport const MANAGED_PRESET_FILES = ['agent.cordis.yml', 'preset.yml'] as const\n\n/** Package specifier kept in the shipped template. DSH Desktop's resolver hook\n * only rewrites bare specifiers issued by the root include; preset subtrees\n * resolve through Node's internal loader with an unrelated base and cannot\n * find linked packages. The installer therefore substitutes the absolute\n * built entry path, which the preset tree imports directly as a file URL. */\nconst PRESET_ROUTE_PACKAGE_SPECIFIER = '@norman-else/dsh-claude/preset-route'\n\nexport class ManagedPresetConflictError extends Error {\n readonly path: string\n\n constructor(path: string) {\n super(`dsh-claude: refusing to overwrite user-modified preset file ${path}`)\n this.name = 'ManagedPresetConflictError'\n this.path = path\n }\n}\n\nexport interface ManagedPresetPaths {\n sourceDir: string\n targetDir: string\n legacyTargetDir?: string\n}\n\nexport function defaultManagedPresetPaths(dshHome?: string): ManagedPresetPaths {\n const packageRoot = fileURLToPath(new URL('../', import.meta.url))\n return {\n sourceDir: join(packageRoot, 'preset'),\n targetDir: dshHome === undefined\n ? dshHomePath('.agent-presets', CLAUDE_CODE_PRESET_ID)\n : join(dshHome, '.agent-presets', CLAUDE_CODE_PRESET_ID),\n legacyTargetDir: dshHome === undefined\n ? dshHomePath('.agent-presets', LEGACY_CLAUDE_CODE_PRESET_ID)\n : join(dshHome, '.agent-presets', LEGACY_CLAUDE_CODE_PRESET_ID),\n }\n}\n\ninterface ManagedContent {\n file: string\n /** Content this installer version writes. */\n content: string\n /** Older installer-written contents that may be silently upgraded/removed. */\n legacy: readonly string[]\n /** Legacy detection for contents that predate the current template. */\n isLegacy(current: string): boolean\n}\n\nasync function managedContents(paths: ManagedPresetPaths): Promise<ManagedContent[]> {\n const routeEntry = join(paths.sourceDir, '..', 'lib', 'preset-route.mjs')\n return await Promise.all(MANAGED_PRESET_FILES.map(async (file): Promise<ManagedContent> => {\n const source = await readFile(join(paths.sourceDir, file), 'utf8')\n const nameRow = `name: '${PRESET_ROUTE_PACKAGE_SPECIFIER}'`\n const legacyNameRow = `name: ${PRESET_ROUTE_PACKAGE_SPECIFIER}`\n if (file !== 'agent.cordis.yml' || !source.includes(nameRow)) {\n return { file, content: source, legacy: [], isLegacy: () => false }\n }\n return {\n file,\n content: source.replace(nameRow, `name: '${routeEntry}'`),\n legacy: [source],\n // Any earlier installer generation wrote this same entry id with the\n // route reference in either supported form (bare package specifier or\n // absolute built-module path); treat those as safe to upgrade regardless\n // of comment or field drift in the template.\n isLegacy: current =>\n current.includes('id: claude-code-route')\n && (current.includes(nameRow)\n || current.includes(legacyNameRow)\n || current.includes('lib/preset-route.mjs')),\n }\n }))\n}\n\nasync function readIfPresent(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\nasync function atomicWrite(path: string, content: string): Promise<boolean> {\n await mkdir(dirname(path), { recursive: true })\n const temporary = `${path}.${randomUUID()}.tmp`\n try {\n await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n try {\n await link(temporary, path)\n return true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n if (await readIfPresent(path) === content) return false\n throw new ManagedPresetConflictError(path)\n }\n } finally {\n await rm(temporary, { force: true })\n }\n}\n\nexport async function ensureManagedPreset(paths = defaultManagedPresetPaths()): Promise<'installed' | 'unchanged'> {\n await assertSafeTargetDirectory(paths.targetDir)\n const expected = await managedContents(paths)\n let changed = false\n for (const { file, content, legacy, isLegacy } of expected) {\n const target = join(paths.targetDir, file)\n const current = await readIfPresent(target)\n if (current === content) continue\n if (current !== undefined) {\n // Upgrade installer-written legacy content in place; never touch user edits.\n if (!legacy.includes(current) && !isLegacy(current)) throw new ManagedPresetConflictError(target)\n await rm(target)\n }\n changed = await atomicWrite(target, content) || changed\n }\n if (paths.legacyTargetDir !== undefined) {\n changed = await removeLegacyManagedPreset(paths.legacyTargetDir) || changed\n }\n return changed ? 'installed' : 'unchanged'\n}\n\nasync function removeLegacyManagedPreset(targetDir: string): Promise<boolean> {\n await assertSafeTargetDirectory(targetDir)\n const agent = await readIfPresent(join(targetDir, 'agent.cordis.yml'))\n const preset = await readIfPresent(join(targetDir, 'preset.yml'))\n if (agent === undefined && preset === undefined) return false\n\n // Only migrate the prior installer-owned template. Any user edit leaves the\n // complete legacy preset untouched so existing sessions remain recoverable.\n const managedAgent = agent !== undefined\n && agent.includes('id: claude-code-route')\n && (agent.includes('dsh-claude-code/preset-route') || agent.includes('lib/preset-route.mjs'))\n const managedPreset = preset !== undefined\n && preset.includes('Managed by dsh-claude-code')\n && preset.includes('name: Claude Code')\n if (!managedAgent || !managedPreset) return false\n\n await rm(join(targetDir, 'agent.cordis.yml'))\n await rm(join(targetDir, 'preset.yml'))\n if ((await readdir(targetDir)).length === 0) await rmdir(targetDir)\n return true\n}\n\n/** Reject a target directory that is a symlink (or occupies the path as a file)\n * so the managed preset never writes through an attacker-controlled link. */\nasync function assertSafeTargetDirectory(targetDir: string): Promise<void> {\n try {\n const stat = await lstat(targetDir)\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new ManagedPresetConflictError(targetDir)\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n}\n\nexport async function removeManagedPreset(paths = defaultManagedPresetPaths()): Promise<'removed' | 'absent'> {\n await assertSafeTargetDirectory(paths.targetDir)\n const expected = await managedContents(paths)\n const managedTargets: string[] = []\n for (const { file, content, legacy, isLegacy } of expected) {\n const target = join(paths.targetDir, file)\n const current = await readIfPresent(target)\n if (current === undefined) continue\n if (current !== content && !legacy.includes(current) && !isLegacy(current)) throw new ManagedPresetConflictError(target)\n managedTargets.push(target)\n }\n for (const target of managedTargets) await rm(target)\n try {\n if ((await readdir(paths.targetDir)).length === 0) await rmdir(paths.targetDir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n return managedTargets.length > 0 ? 'removed' : 'absent'\n}\n"],"mappings":";;;;;;;;AAKA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAIzB,IAAa,gCAAb,cAAmD,MAAM;CACvD;CAEA,YAAY,UAA6B,SAAwB;EAC/D,MAAM,+CAA+C,SAAS,KAAK,IAAI,KAAK,OAAO;EACnF,KAAK,OAAO;EACZ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AAY;AACjD"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@norman-else/dsh-claude",
3
3
  "description": "Run the local Claude Code CLI as a first-class main conversation inside DeepSeek Harness",
4
- "version": "0.1.1",
4
+ "version": "0.1.2",
5
5
  "type": "module",
6
6
  "main": "lib/index.mjs",
7
7
  "types": "lib/index.d.mts",
@@ -1,11 +1,8 @@
1
- # Managed by dsh-claude. Claude Code owns the inner agent loop and tools;
2
- # this preset contributes only the request-route override.
3
- # Template: the installer rewrites `name` to the absolute path of the built
4
- # lib/preset-route.mjs, because preset subtrees cannot resolve bare package
5
- # specifiers for linked profiles (DSH Desktop's resolver hook only covers the
6
- # root include).
1
+ # Shipped by dsh-claude. Claude Code owns the inner agent loop and tools;
2
+ # this system preset contributes only the request-route override. DSH resolves
3
+ # the bare package specifier from the host profile when mounting system roots.
7
4
  - id: claude-code-route
8
- name: @norman-else/dsh-claude/preset-route
5
+ name: '@norman-else/dsh-claude/preset-route'
9
6
  # Entry-local isolate realm: each session's preset mount gets its own
10
7
  # claudeCommands service instance (keeps mountPreset's leaked-service check
11
8
  # happy and prevents cross-session collisions). The host reads it through
package/preset/preset.yml CHANGED
@@ -1,4 +1,4 @@
1
- # Managed by dsh-claude. Do not edit; copy this preset under a new id to customize it.
1
+ # Shipped by dsh-claude. Copy this system preset under a new id to customize it.
2
2
  name: Claude
3
3
  description: Use the local Claude Code as the complete agent runtime inside DSH.
4
4
  order: 10
@@ -1 +0,0 @@
1
- {"version":3,"file":"preset-installer-DUVN1J6P.mjs","names":[],"sources":["../src/executable.ts","../src/preset-installer.ts"],"sourcesContent":["import { homedir } from 'node:os'\nimport { join } from 'node:path'\nimport type { SubprocessHandle, SubprocessRuntime } from '@deepseek-ai/dsh-subprocess'\nimport { redactText } from './events.ts'\n\nconst VERSION_PATTERN = /(?:Claude Code\\s+)?v?(\\d+\\.\\d+\\.\\d+(?:[-+][\\w.-]+)?)/i\nconst MAX_PROBE_STDOUT = 64 * 1024\nconst MAX_PROBE_STDERR = 8 * 1024\n\nexport type ExecutableRuntime = Pick<SubprocessRuntime, 'resolveExecutable' | 'spawn'>\n\nexport class ClaudeExecutableNotFoundError extends Error {\n readonly searched: readonly string[]\n\n constructor(searched: readonly string[], options?: ErrorOptions) {\n super(`Claude Code executable not found. Searched: ${searched.join(', ')}`, options)\n this.name = 'ClaudeExecutableNotFoundError'\n this.searched = [...searched]\n }\n}\n\nexport interface ClaudeExecutableResolution {\n path: string\n searched: readonly string[]\n}\n\nexport interface ClaudeDoctorReport {\n executable: {\n status: 'found' | 'missing'\n path?: string\n searched: readonly string[]\n }\n version: {\n status: 'ok' | 'error' | 'not-run'\n value?: string\n message?: string\n }\n authentication: {\n status: 'signed-in' | 'signed-out' | 'unknown' | 'not-run'\n method?: string\n provider?: string\n subscription?: string\n message?: string\n }\n handshake: 'not-run' | 'ok' | 'error'\n}\n\nfunction fallbackCandidates(): string[] {\n if (process.platform !== 'darwin') return []\n return [\n join(homedir(), '.local', 'bin', 'claude'),\n '/opt/homebrew/bin/claude',\n '/usr/local/bin/claude',\n ]\n}\n\nfunction abortError(error: unknown): boolean {\n return error instanceof Error && (error.name === 'AbortError' || error.name === 'TimeoutError')\n}\n\nexport async function resolveClaudeExecutable(\n runtime: ExecutableRuntime,\n configuredPath?: string,\n signal?: AbortSignal,\n): Promise<ClaudeExecutableResolution> {\n const searched: string[] = []\n const candidates = configuredPath === undefined\n ? ['claude', ...fallbackCandidates()]\n : [configuredPath]\n if (configuredPath !== undefined && !configuredPath.startsWith('/')) {\n throw new Error(`Claude Code executable path must be absolute: ${configuredPath}`)\n }\n\n let lastError: unknown\n for (const candidate of candidates) {\n if (searched.includes(candidate)) continue\n searched.push(candidate)\n try {\n const path = await runtime.resolveExecutable(candidate, undefined, signal)\n return { path, searched }\n } catch (error) {\n if (abortError(error) || signal?.aborted === true) throw error\n lastError = error\n }\n }\n throw new ClaudeExecutableNotFoundError(searched, lastError === undefined ? undefined : { cause: lastError })\n}\n\ninterface CollectedCommand {\n exitCode: number | null\n signal: NodeJS.Signals | null\n stdout: string\n stderr: string\n}\n\nasync function collect(handle: SubprocessHandle): Promise<CollectedCommand> {\n const outcome = await handle.done\n const stdout = handle.collected.stdout?.readFrom(0).text ?? ''\n const stderr = handle.collected.stderr?.readFrom(0).text ?? ''\n return { ...outcome, stdout, stderr }\n}\n\nasync function runProbe(\n runtime: ExecutableRuntime,\n executable: string,\n args: readonly string[],\n cwd: string,\n signal?: AbortSignal,\n): Promise<CollectedCommand> {\n return collect(runtime.spawn({\n argv: [executable, ...args],\n cwd,\n stdio: {\n stdin: 'ignore',\n stdout: { maxBytes: MAX_PROBE_STDOUT },\n stderr: { maxBytes: MAX_PROBE_STDERR },\n },\n graceMs: 2_000,\n ...(signal === undefined ? {} : { signal }),\n env: {},\n }))\n}\n\nexport function parseClaudeVersion(output: string): string | undefined {\n return VERSION_PATTERN.exec(output)?.[1]\n}\n\nexport async function probeClaudeVersion(\n runtime: ExecutableRuntime,\n executable: string,\n cwd: string,\n signal?: AbortSignal,\n): Promise<string> {\n const result = await runProbe(runtime, executable, ['--version'], cwd, signal)\n const version = parseClaudeVersion(`${result.stdout}\\n${result.stderr}`)\n if (result.exitCode !== 0 || version === undefined) {\n throw new Error(`Claude Code version probe failed (${result.exitCode ?? result.signal ?? 'unknown exit'})`)\n }\n return version\n}\n\nexport async function probeClaudeAuthentication(\n runtime: ExecutableRuntime,\n executable: string,\n cwd: string,\n signal?: AbortSignal,\n): Promise<ClaudeDoctorReport['authentication']> {\n const result = await runProbe(runtime, executable, ['auth', 'status', '--json'], cwd, signal)\n if (result.exitCode !== 0) {\n return { status: 'unknown', message: 'Claude authentication status command failed' }\n }\n try {\n const value = JSON.parse(result.stdout) as Record<string, unknown>\n const report: ClaudeDoctorReport['authentication'] = {\n status: value.loggedIn === true ? 'signed-in' : value.loggedIn === false ? 'signed-out' : 'unknown',\n }\n if (typeof value.authMethod === 'string') report.method = redactText(value.authMethod, 100)\n if (typeof value.apiProvider === 'string') report.provider = redactText(value.apiProvider, 100)\n if (typeof value.subscriptionType === 'string') report.subscription = redactText(value.subscriptionType, 100)\n return report\n } catch {\n return { status: 'unknown', message: 'Claude authentication status was not valid JSON' }\n }\n}\n\nexport async function runClaudeDoctor(\n runtime: ExecutableRuntime,\n options: { configuredPath?: string; cwd: string; signal?: AbortSignal },\n): Promise<ClaudeDoctorReport> {\n let resolution: ClaudeExecutableResolution\n try {\n resolution = await resolveClaudeExecutable(runtime, options.configuredPath, options.signal)\n } catch (error) {\n if (error instanceof ClaudeExecutableNotFoundError) {\n return {\n executable: { status: 'missing', searched: error.searched },\n version: { status: 'not-run' },\n authentication: { status: 'not-run' },\n handshake: 'not-run',\n }\n }\n throw error\n }\n\n const report: ClaudeDoctorReport = {\n executable: { status: 'found', path: resolution.path, searched: resolution.searched },\n version: { status: 'not-run' },\n authentication: { status: 'not-run' },\n handshake: 'not-run',\n }\n try {\n report.version = {\n status: 'ok',\n value: await probeClaudeVersion(runtime, resolution.path, options.cwd, options.signal),\n }\n } catch (error) {\n report.version = {\n status: 'error',\n message: error instanceof Error ? error.message : 'Version probe failed',\n }\n }\n try {\n report.authentication = await probeClaudeAuthentication(runtime, resolution.path, options.cwd, options.signal)\n } catch (error) {\n report.authentication = {\n status: 'unknown',\n message: error instanceof Error ? error.message : 'Authentication probe failed',\n }\n }\n return report\n}\n","import { randomUUID } from 'node:crypto'\nimport { link, lstat, mkdir, readFile, readdir, rm, rmdir, writeFile } from 'node:fs/promises'\nimport { dirname, join } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { dshHomePath } from '@deepseek-ai/dsh-home-paths'\nimport { CLAUDE_CODE_PRESET_ID, LEGACY_CLAUDE_CODE_PRESET_ID } from './constants.ts'\n\nexport const MANAGED_PRESET_FILES = ['agent.cordis.yml', 'preset.yml'] as const\n\n/** Package specifier kept in the shipped template. DSH Desktop's resolver hook\n * only rewrites bare specifiers issued by the root include; preset subtrees\n * resolve through Node's internal loader with an unrelated base and cannot\n * find linked packages. The installer therefore substitutes the absolute\n * built entry path, which the preset tree imports directly as a file URL. */\nconst PRESET_ROUTE_PACKAGE_SPECIFIER = '@norman-else/dsh-claude/preset-route'\n\nexport class ManagedPresetConflictError extends Error {\n readonly path: string\n\n constructor(path: string) {\n super(`dsh-claude: refusing to overwrite user-modified preset file ${path}`)\n this.name = 'ManagedPresetConflictError'\n this.path = path\n }\n}\n\nexport interface ManagedPresetPaths {\n sourceDir: string\n targetDir: string\n legacyTargetDir?: string\n}\n\nexport function defaultManagedPresetPaths(dshHome?: string): ManagedPresetPaths {\n const packageRoot = fileURLToPath(new URL('../', import.meta.url))\n return {\n sourceDir: join(packageRoot, 'preset'),\n targetDir: dshHome === undefined\n ? dshHomePath('.agent-presets', CLAUDE_CODE_PRESET_ID)\n : join(dshHome, '.agent-presets', CLAUDE_CODE_PRESET_ID),\n legacyTargetDir: dshHome === undefined\n ? dshHomePath('.agent-presets', LEGACY_CLAUDE_CODE_PRESET_ID)\n : join(dshHome, '.agent-presets', LEGACY_CLAUDE_CODE_PRESET_ID),\n }\n}\n\ninterface ManagedContent {\n file: string\n /** Content this installer version writes. */\n content: string\n /** Older installer-written contents that may be silently upgraded/removed. */\n legacy: readonly string[]\n /** Legacy detection for contents that predate the current template. */\n isLegacy(current: string): boolean\n}\n\nasync function managedContents(paths: ManagedPresetPaths): Promise<ManagedContent[]> {\n const routeEntry = join(paths.sourceDir, '..', 'lib', 'preset-route.mjs')\n return await Promise.all(MANAGED_PRESET_FILES.map(async (file): Promise<ManagedContent> => {\n const source = await readFile(join(paths.sourceDir, file), 'utf8')\n const nameRow = `name: ${PRESET_ROUTE_PACKAGE_SPECIFIER}`\n if (file !== 'agent.cordis.yml' || !source.includes(nameRow)) {\n return { file, content: source, legacy: [], isLegacy: () => false }\n }\n return {\n file,\n content: source.replace(nameRow, `name: ${routeEntry}`),\n legacy: [source],\n // Any earlier installer generation wrote this same entry id with the\n // route reference in either supported form (bare package specifier or\n // absolute built-module path); treat those as safe to upgrade regardless\n // of comment or field drift in the template.\n isLegacy: current =>\n current.includes('id: claude-code-route')\n && (current.includes(nameRow) || current.includes('lib/preset-route.mjs')),\n }\n }))\n}\n\nasync function readIfPresent(path: string): Promise<string | undefined> {\n try {\n return await readFile(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined\n throw error\n }\n}\n\nasync function atomicWrite(path: string, content: string): Promise<boolean> {\n await mkdir(dirname(path), { recursive: true })\n const temporary = `${path}.${randomUUID()}.tmp`\n try {\n await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' })\n try {\n await link(temporary, path)\n return true\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error\n if (await readIfPresent(path) === content) return false\n throw new ManagedPresetConflictError(path)\n }\n } finally {\n await rm(temporary, { force: true })\n }\n}\n\nexport async function ensureManagedPreset(paths = defaultManagedPresetPaths()): Promise<'installed' | 'unchanged'> {\n await assertSafeTargetDirectory(paths.targetDir)\n const expected = await managedContents(paths)\n let changed = false\n for (const { file, content, legacy, isLegacy } of expected) {\n const target = join(paths.targetDir, file)\n const current = await readIfPresent(target)\n if (current === content) continue\n if (current !== undefined) {\n // Upgrade installer-written legacy content in place; never touch user edits.\n if (!legacy.includes(current) && !isLegacy(current)) throw new ManagedPresetConflictError(target)\n await rm(target)\n }\n changed = await atomicWrite(target, content) || changed\n }\n if (paths.legacyTargetDir !== undefined) {\n changed = await removeLegacyManagedPreset(paths.legacyTargetDir) || changed\n }\n return changed ? 'installed' : 'unchanged'\n}\n\nasync function removeLegacyManagedPreset(targetDir: string): Promise<boolean> {\n await assertSafeTargetDirectory(targetDir)\n const agent = await readIfPresent(join(targetDir, 'agent.cordis.yml'))\n const preset = await readIfPresent(join(targetDir, 'preset.yml'))\n if (agent === undefined && preset === undefined) return false\n\n // Only migrate the prior installer-owned template. Any user edit leaves the\n // complete legacy preset untouched so existing sessions remain recoverable.\n const managedAgent = agent !== undefined\n && agent.includes('id: claude-code-route')\n && (agent.includes('dsh-claude-code/preset-route') || agent.includes('lib/preset-route.mjs'))\n const managedPreset = preset !== undefined\n && preset.includes('Managed by dsh-claude-code')\n && preset.includes('name: Claude Code')\n if (!managedAgent || !managedPreset) return false\n\n await rm(join(targetDir, 'agent.cordis.yml'))\n await rm(join(targetDir, 'preset.yml'))\n if ((await readdir(targetDir)).length === 0) await rmdir(targetDir)\n return true\n}\n\n/** Reject a target directory that is a symlink (or occupies the path as a file)\n * so the managed preset never writes through an attacker-controlled link. */\nasync function assertSafeTargetDirectory(targetDir: string): Promise<void> {\n try {\n const stat = await lstat(targetDir)\n if (!stat.isDirectory() || stat.isSymbolicLink()) {\n throw new ManagedPresetConflictError(targetDir)\n }\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw error\n }\n}\n\nexport async function removeManagedPreset(paths = defaultManagedPresetPaths()): Promise<'removed' | 'absent'> {\n await assertSafeTargetDirectory(paths.targetDir)\n const expected = await managedContents(paths)\n let removed = false\n for (const { file, content, legacy, isLegacy } of expected) {\n const target = join(paths.targetDir, file)\n const current = await readIfPresent(target)\n if (current === undefined) continue\n if (current !== content && !legacy.includes(current) && !isLegacy(current)) throw new ManagedPresetConflictError(target)\n await rm(target)\n removed = true\n }\n try {\n if ((await readdir(paths.targetDir)).length === 0) await rmdir(paths.targetDir)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error\n }\n return removed ? 'removed' : 'absent'\n}\n"],"mappings":";;;;;;;;AAKA,MAAM,kBAAkB;AACxB,MAAM,mBAAmB;AACzB,MAAM,mBAAmB;AAIzB,IAAa,gCAAb,cAAmD,MAAM;CACvD;CAEA,YAAY,UAA6B,SAAwB;EAC/D,MAAM,+CAA+C,SAAS,KAAK,IAAI,KAAK,OAAO;EACnF,KAAK,OAAO;EACZ,KAAK,WAAW,CAAC,GAAG,QAAQ;CAC9B;AACF;AA4BA,SAAS,qBAA+B;CAC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