@khorsheed/dsh-local-agent-claude-code 0.1.0-rc.6

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.
Files changed (38) hide show
  1. package/README.en.md +120 -0
  2. package/README.i18n.yaml +6 -0
  3. package/README.md +120 -0
  4. package/cordis.patch.yml +42 -0
  5. package/lib/client.js +1065 -0
  6. package/lib/index.js +3771 -0
  7. package/lib/invariant.js +31 -0
  8. package/lib/types/claude-cli-provider.d.ts +389 -0
  9. package/lib/types/claude-cli-provider.js +1509 -0
  10. package/lib/types/client/SettingsCard.d.ts +78 -0
  11. package/lib/types/client/SettingsCard.js +198 -0
  12. package/lib/types/client/icons.d.ts +18 -0
  13. package/lib/types/client/icons.js +2 -0
  14. package/lib/types/client/index.d.ts +36 -0
  15. package/lib/types/client/index.js +87 -0
  16. package/lib/types/client/locales.d.ts +64 -0
  17. package/lib/types/client/locales.js +55 -0
  18. package/lib/types/control-requests.d.ts +15 -0
  19. package/lib/types/control-requests.js +62 -0
  20. package/lib/types/index.d.ts +81 -0
  21. package/lib/types/index.js +300 -0
  22. package/lib/types/invariant.d.ts +16 -0
  23. package/lib/types/invariant.js +33 -0
  24. package/lib/types/live-driver.d.ts +172 -0
  25. package/lib/types/live-driver.js +1057 -0
  26. package/lib/types/live-switch.d.ts +67 -0
  27. package/lib/types/live-switch.js +85 -0
  28. package/lib/types/model-broker.d.ts +131 -0
  29. package/lib/types/model-broker.js +248 -0
  30. package/lib/types/model-catalog.d.ts +27 -0
  31. package/lib/types/model-catalog.js +118 -0
  32. package/lib/types/provision.d.ts +63 -0
  33. package/lib/types/provision.js +132 -0
  34. package/lib/types/records.d.ts +120 -0
  35. package/lib/types/records.js +687 -0
  36. package/locale/en.json +6 -0
  37. package/locale/zh.json +6 -0
  38. package/package.json +106 -0
package/README.en.md ADDED
@@ -0,0 +1,120 @@
1
+ # `@khorsheed/dsh-local-agent-claude-code`
2
+
3
+ English | [中文](README.md)
4
+
5
+ **Live output migration.** Live runs always consume incremental output. The old `liveMirrorGranularity: event | token` key is accepted for existing profiles but ignored; changing it never changes a running process. Exec remains available for evaluation. Final provider items remain authoritative, including tool history and usage.
6
+
7
+ Delegate coding tasks to a locally installed Claude Code from any dsh agent preset — answers stream back live, and your personal `~/.claude` is never touched. The Claude Code harness of the [local-agent family](../local-agent/README.md).
8
+
9
+ ## Features
10
+
11
+ - **Delegate from any preset** — the tool mounts once at the profile root; no per-preset variants.
12
+ - **Scoped home** — every Claude process runs with `CLAUDE_CONFIG_DIR` under `$DSH_HOME/local-agent/claude-code`; your personal `~/.claude` stays out of it.
13
+ - **Guided login, one command** — `/claude-code login` answers with the exact command to run in your own terminal (claude ≥2.1 prints its OAuth URL only on a TTY, so the host no longer spawns and scrapes) and watches the scoped home for the credential; `sessions`/`status`/`logout` and a Settings → 本地 Agent panel complete the family.
14
+ - **Resume a delegation** — pass back the result's `resume` handle to continue the same Claude session, with per-round accounting.
15
+ - **Live stream mirror** — the child session mirrors Claude's thinking, tool calls, and replies live; aborting keeps the partial transcript and real token usage.
16
+ - **Model readback and per-cell working directory** — every settled round reads back the model from stream-json’s system/init into the delegation record; orchestrators pass a `cwd` per cell, and a resume in a different directory is rejected.
17
+ ## Install
18
+
19
+ Prerequisites: a running dsh profile, and the Claude Code CLI (`claude`) on `PATH` — the plugin does not install it. Install the family core together with this bundle (`dsh plugin add` reconciles only *direct* dependencies, so name both):
20
+
21
+ ```sh
22
+ dsh plugin --profile web add @khorsheed/dsh-local-agent @khorsheed/dsh-local-agent-claude-code
23
+ ```
24
+
25
+ Restart the profile, then run `/claude-code login` once from a session. Uninstall:
26
+
27
+ ```sh
28
+ dsh plugin --profile web remove @khorsheed/dsh-local-agent-claude-code
29
+ ```
30
+
31
+ The scoped home is kept on uninstall so a reinstall needs no fresh login; delete `$DSH_HOME/local-agent/claude-code` to remove every trace.
32
+
33
+ ## Config
34
+
35
+ Optional fields on the bundle row:
36
+
37
+ - `permissionMode` — `skip` (default) passes `--dangerously-skip-permissions` so the child can write files without an approval prompt; `normal` runs without it, so approval-requiring actions (e.g. writing files) are denied.
38
+ - `model` — every delegation round starts the CLI with it (`claude -p --model <model>`); absent passes no model flag at all. See below.
39
+ - `baseUrl` — sets `ANTHROPIC_BASE_URL` for the child CLI (e.g. a self-hosted router or proxy); absent, the child inherits the host process environment. Config wins over environment.
40
+ - `live` — live driver: one resident stream-json process per member (`--input-format stream-json`), one stdin message per round (runtime-level graceful control interrupt, same-shape push stream); off — or a channel that cannot come up — means the one-shot `claude -p` path.
41
+ - `liveIdleMs` — idle lifetime of a resident runtime before reclaim (default 30 min).
42
+
43
+ ### Default model (`model`)
44
+
45
+ **Absent = today's behavior.** Without this key the plugin adds no model flag to the argv at all: the scoped `settings.json`'s `model` decides which model runs, and claude's own default decides when that is missing too (the plugin never guesses what it is).
46
+
47
+ **Set = every delegation round starts the CLI with it.** All four argv variants — fresh and resume, one-shot and resident (`live: true`) — carry `--model <model>`, placed before the member channel's `--allowedTools … --`: that flag is variadic and everything after its `--` is the task text.
48
+
49
+ One-shot (exec) rounds never rewrite the scoped `settings.json`: `--model` overrules it per round and the file stays exactly as you edited it. A resident (live) spawn scratches the member's effective model into that file (a `--resume` reattach honors the file's model over the `--model` flag) and restores the previous value before a spawn that binds none; the "CLI config" layer that status and the settings card report is always the value you configured, never a member's scratch.
50
+
51
+ The settings card’s "Default model" writes the provider setting for subsequent rounds. Its shared picker displays the scoped model directory, discovery source and completeness, plus an explicit model-ID input when needed. Clearing the selection follows the effective configuration/default chain. Saving does not interrupt an active round and requires no reload. If the shared picker is unavailable, the card retains its text-input fallback. Per-member model and effort changes use the durable controls described below.
52
+
53
+ The model surface now also reads Claude's native `initialize` directory, preserving selection aliases, display labels, resolved names and supported effort levels. It shares the core cache and refresh subscription, retains successful data after a failed refresh, and labels historical suggestions separately. This scoped control probe sends no user task and writes no model settings. An older CLI without this directory reports unsupported; native candidates do not establish account entitlement. The shared model picker and member effort controls are connected. Busy selections apply at the next complete turn boundary, including tool continuations; core owns current/pending state, cancellation and retry, while frozen evaluation members reject changes.
54
+
55
+ **A delegation's own model outranks this key.** An orchestrator may name the model for ONE delegation through the facade's `DelegationCallOptions.model`, which sits above this key (the layer order is in the family core README). The first round's request is recorded and every resume round re-requests it — `resume` takes no model of its own. In resident mode a fresh delegation's model binds as the member's start model at the runtime's spawn: a runtime bound to a different model retires first, and the same CLI session resumes on the new process.
56
+
57
+ **Session-level member switching.** The member composer's model picker writes a **session-level override** through the family gateway's `setMemberModel` — it outranks the delegation model and this key, lives in memory only, and deliberately neither survives a host restart nor enters the settings. A switch is refused while the member has a round in flight; with the live driver on, switching to a different model retires the member's resident runtime so the next round respawns onto the new model while resuming the SAME CLI session (the conversation carries over), and a same-model switch is a no-op.
58
+
59
+ **This is not an evaluation gap.** A run freezes its condition at setup: change the key mid-run and the next round's model read-back sees declared ≠ observed and fails the run as misattributed (frozen decision 5). "A new run follows the new value, a running one is never switched underneath you" is the design, not an oversight.
60
+
61
+ ⚠️ `skip` has no OS-level sandbox — the child can write anywhere the host user can, including outside the workspace — and the scoped login's OAuth token is sent to whatever `baseUrl` points at. Prefer `normal` when a delegation needs confinement; point `baseUrl` only at endpoints you trust.
62
+
63
+ **Evaluation snapshot (`effectiveSettings`).** The harness declares a live-read snapshot of its fairness-relevant settings for the evaluation condition hash: drive (exec/live), the permission mode (`skip`/`normal`, plugin config), whether a non-default endpoint is in force (following the provider's own resolution order — the config item wins over the host environment's `ANTHROPIC_BASE_URL`; hostname only), and the configured model (the plugin config's `model` key first — it overrules the file on every argv — then the scoped `settings.json`'s `model`; the CLI's own default model stays the CLI's business and is never guessed — neither key, no field), and the CLI version (`claude --version`, cached against the executable's path + mtime; absent when the CLI cannot be asked). `/claude-code status` and the `LocalAgentStatus` Remote attach the same snapshot.
64
+
65
+ ## Compatibility
66
+
67
+ - npm release line (`@deepseek-ai/dsh@0.1.5-rc.1`): ✅ public API compatible. Live generation uses the local-agent transient Remote and public Conversation nodes; suffix checkpoints provide recovery, and native final messages retain transcript and usage semantics. Browser P95 acceptance is tracked separately in the room coordinator proposal. Older hosts stay on the previous release line.
68
+ - source line (deepseek-harness master): ✅ (verifiedHost: 0.1.5-rc.1)
69
+
70
+ ## Known Limitations
71
+
72
+ - **macOS logout is config-only** — the keychain entry is left for the CLI's own `claude auth logout`; a fresh login rewrites the same slot, so the stale entry is harmless.
73
+ - **One grant cannot be shared between a host round and a container round** — the two use different stores on macOS, and a rotation on either side invalidates the other's token family. A containerized condition takes its own named scope; see Container delegation.
74
+ - **Linux credentials are not isolated** (upstream bug #47661) — claude reads the default `~/.claude/.credentials.json` even when the scoped home has none.
75
+ - **Interactive-session records may be missing** — under a custom `CLAUDE_CONFIG_DIR` the CLI may not write transcripts (upstream behavior).
76
+ - **Headless caveat** — `/claude-code` commands need a Web session; `--profile headless` delegates through a composition that mounts the tool row.
77
+
78
+ ## How it works
79
+
80
+ <details>
81
+ <summary>Internals (click to expand)</summary>
82
+
83
+ **Model readback and the cwd override.** After every settled round the provider reports the actual model from the stream-json `system` (init) event's `model` field (e.g. `claude-opus-5[1m]`, verbatim — context-variant suffixes included) through the `settled` run-progress event, and merges it into the delegation record's `observedModel` field; absence is recorded, never guessed. When no layer and no record names a model, the 默认 surface's last-observed hint reads the member's OWN transcript (`projects/<cwd-slug>/<sessionId>.jsonl`, or the tree's newest for the memberless card) — the history backstop for rounds that predate the settle channel; read-only, never a write into `delegations.jsonl`. An orchestrator may also pass a per-round working directory through the facade's `DelegationCallOptions.cwd` (recorded as the record's `cwd`); when a resume round resolves to a different directory than the recorded first round, it fails loud before any process spawns — a CLI session continues in the directory its first round ran in.
84
+
85
+ **Tool-call accounting.** Every settled round also reports how many tool calls it made, on the `settled` run-progress event (`toolCalls: { count, byName }`). The count is taken in the `tool_use` branch the stream fold ALREADY walks, and `byName` keys are the block's own `name` (`Bash`, `Read`, `TodoWrite`, or an MCP tool's full `mcp__server__tool`), carried verbatim and never normalized across harnesses. `TodoWrite` counts too: the fold diverts it into the todo snapshot instead of the transcript, but the CLI still called it. One accounting per round, never cumulative; a round that called nothing carries no field at all (absent is not zero). Measured: a "read two files, then list the directory" round reads back `{count: 3, byName: {Read: 2, Bash: 1}}`, matching the mirrored tool cards one for one.
86
+
87
+ **Named scopes.** `/claude-code login --scope <name>` opens a second `CLAUDE_CONFIG_DIR` at `<homesRoot>/claude-code@<name>`, and the login argv is built from the directory BEING logged in (`env CLAUDE_CONFIG_DIR=… claude auth login` — that assignment outranks the spawn env, so a hard-coded default would authorize the wrong directory under `--scope`). claude's keychain item is keyed by the config directory's path, so a named scope gets its own keychain item for free — the one credential store among the four harnesses that is path-isolated by nature. A scoped delegation runs `claude -p` against that directory, reconciles keychain↔file there, and reads back from there; exec-only.
88
+
89
+ **Container delegation.** An orchestrator may run the round inside an **already-acquired container** through the facade's `DelegationCallOptions.exec` (`{ container, workdir, env? }`): the argv becomes `docker exec -w <workdir> [-e NAME…] <container> claude -p …` and everything else (stream-json parse, settle, recording) is byte-for-byte unchanged. `env` must name the in-container `CLAUDE_CONFIG_DIR`, and the caller bind-mounts the host scoped home read-write onto that path. Measured on claude 2.1.272 inside the evaluation image, the in-container CLI reads AND writes `<CLAUDE_CONFIG_DIR>/.credentials.json`, and its whole state tree (`projects/`, `sessions/`, …) lands there too; the older upstream-#47661 behavior (Linux writes the scoped dir but reads the default home) does not describe that version. The credential reconcile before every spawn still runs against the **host** scoped home, so a refreshed grant reaches the container through the mount — and it is **newer-wins, not a mirror**, because the unit is a SECOND WRITER to that same file. The CLI inside a unit has no keychain, so it rotates the grant in the mounted file; an unconditional keychain→file mirror would then hand the next run a refresh token the unit already spent, the endpoint rejects it, and the CLI answers by CLEARING the file — which logs the whole instance out, because that file is the instance's credential. The reconcile therefore writes the keychain blob only when it is not older than the file's (access-token expiry decides; an undefined expiry on either side keeps the keychain writing, and an unusable file never wins). The mount stays read-write for a second reason as well: the round's transcripts land in `projects/` under the same directory, and the evaluation's model read-back parses them from the host side of that mount. A container round always takes the exec one-shot and declares no member bridge.
90
+
91
+ **A container round needs its OWN scope, and the discipline is not optional.** claude is the only harness here with two credential stores, and measured on macOS 2.1.274 they do not have one reader: the HOST CLI reads and writes the KEYCHAIN, while the CLI inside a unit — Linux, no keychain — reads and writes the mounted file. One grant refreshed from both is one grant refreshed twice, and the endpoint rotates single-use refresh tokens by invalidating the whole token FAMILY: whichever side did not refresh last is left holding a dead token. Measured end to end — a container round rotated the file, and the next host round answered `OAuth session expired and could not be refreshed` although the file's own access token was still hours from expiry, recoverable only by a fresh login. Newer-wins keeps the FILE side correct, which is what the unit and every status probe read, but nothing can write the unit's rotation back into the keychain (`security add-generic-password` would put the secret in argv, so it is refused). So the container side and the host side must be two INDEPENDENT grants: give every containerized claude condition its own named scope, authorize it once with `/claude-code login --scope <name>`, and never run a host-side claude round in that scope. The evaluation refuses a plan that breaks this before it acquires a unit. **Mind the host-only entries in the scoped `settings.json`**: measured, the `https_proxy` there — meant for the host daemon — points at nothing inside the unit and the round dies with `Connection refused`. The caller stages what it mounts.
92
+
93
+ ```
94
+ src/index.ts harness registration, /claude-code command family, config schema
95
+ src/claude-cli-provider.ts one-shot provider: spawn, stream mirror, turn/token accounting
96
+ src/provision.ts scoped-home provisioning and file-based logout
97
+ src/records.ts auth probe and session-record listing from the scoped home
98
+ ```
99
+
100
+ The bundle patch registers the `claude-code` harness into the family core (`@khorsheed/dsh-local-agent`, declared as a dependency — the claude bundle deliberately does not re-insert the core row, which would mount it twice) and mounts the `claude-local` provider, which spawns `claude -p --verbose --output-format stream-json` under the harness's scoped home. The `subagent_claude_code` tool is the family-owned tool (`@khorsheed/dsh-local-agent-tool-subagent`): the official subset (`description`/`prompt`) plus an optional `resume` parameter.
101
+
102
+ **Scope isolation.** On macOS the real credential lives in the OS keychain under a hashed entry (`Claude Code-credentials-<sha256(configDir)[:8]>`) keyed to the scoped home path — file-based logout cannot reach it, but a fresh login rewrites the same slot. Which store the CLI itself uses is VERSION-dependent and was measured, not assumed: 2.1.236 wrote the keychain and read the file (the split this mirror exists for), while 2.1.274 on macOS reads and writes the keychain, and 2.1.272 on Linux reads and writes the scoped file. The file therefore stays authoritative for this package's own probes and for a container round; the keychain is what a host CLI on current macOS actually uses. Auth detection is a light file check of the scoped `.claude.json`'s `oauthAccount` — the CLI is never spawned just to probe. The probe also reconciles the two stores, so it obeys the same newer-wins rule as the spawn sites: it runs on every status read and every readiness check, and an unconditional mirror there would undo a containerized round's refresh just as surely.
103
+
104
+ **Session records.** `/claude-code sessions` lists the scoped home's `projects/<cwd-slug>/<uuid>.jsonl` session files — this agent's delegations, never your personal sessions. The slug is a lossy encoding of the workspace path, so the listed `workDir` comes from the file content (the first `user` event's `cwd` field), never the directory name. The Settings panel shows the same listing narrowed to the current workspace.
105
+
106
+ **Resume security.** The handle never rides the prompt: it is read only from the `resume` parameter, and the localAgent registry resolves it only for the same parent session and provider that recorded the delegation — a forged handle (unknown child session, another parent's session, or the wrong provider) is rejected before any CLI process starts.
107
+
108
+ **Stream mirror & accounting.** `thinking` blocks fold to `reasoning` blocks, `tool_use`/`tool_result` to tool lines (`[工具 Bash] <command> → output`), reply `text` to assistant text; resumed rounds append their own turn without duplication. Edit-family calls (Edit/Write/MultiEdit/NotebookEdit) fold into ApplyPatch-style cards — the path on the args line, the actual edit (old/new strings or the whole file body) as the card body, the same shape codex's fileChange mirror uses; server-side tools (`server_tool_use` web_search/web_fetch) pair with their results by id into visible WebSearch/WebFetch cards; a `redacted_thinking` block folds to a visible placeholder think line (the content is server-encrypted by design — the line says so); every other tool's input keeps its one-scalar summary, with a truncated JSON summary as the fallback instead of dropping. Every mirrored step is wrapped in a `step/start`–`step/end` pair at its own (turn, step) — the host's live conversation view registers steps only on those boundaries, so a boundary-less assistant message stays unrendered until a full rebuild. The provider opens `turn/start` at spawn and closes `turn/end` on settle — including failure and cancellation — so `subagentTiming` duration equals actual CLI runtime and no window stays open; the final `assistant/message` carries token usage parsed from the JSON result (`input_tokens`, `output_tokens`, `cache_read_input_tokens`, `cache_creation_input_tokens` — Anthropic reports each separately).
109
+
110
+ **Model experience.** The child is a fresh one-shot `claude -p` in the delegating session's workspace; the parent submits only the standalone task text and sees only the final answer or the exact error, plus the resume self-description on a fresh delegation — Claude commentary, tool activity, and workspace diffs are not copied over. Child tokens never enter the parent's context; the child pays for its own Claude context and turn (cache reuse depends only on the scoped installation's provider, model, and history); the parent's KV cache is unaffected.
111
+
112
+ **Live driver (`live: true`).** Replaces the per-round spawn: the member's first delegation brings up one resident stream-json process (`claude -p --verbose --input-format stream-json --output-format stream-json`), the first stdin `user` message triggers `system/init` (the server-assigned session id becomes the delegation record's `cliSessionId`), and every later round is one stdin message. The event stream is byte-identical in shape to exec's stream-json, so each turn folds through the same `ClaudeStreamParser` (the last line held back until `result` carries usage, as in exec), and `cancel` lands as a `control_request interrupt` — the process survives and the session stays continuable. Reclaim is stdin EOF → SIGTERM; after a crash the next round reattaches with `--resume <session_id>`. A runtime binds the member's effective model at spawn (session-level override → delegation model → settings key) and scratches it into the scoped `settings.json` (a `--resume` reattach honors the file over the flag); a runtime whose bound model no longer matches the round's resolution retires before the respawn. A `permissionMode: normal` spawn omits `--dangerously-skip-permissions`, so the CLI's server→client control requests (the `can_use_tool` approval surface) are auto-answered with allow by the driver — a subagent has no approval surface, matching exec's effective behavior under skip; any other subtype gets an error answer instead of a silent hang. The auth discipline is byte-identical to exec: only the scoped `CLAUDE_CONFIG_DIR` (plus an optional `baseUrl` override) is injected — the global `~/.claude` is never touched and no `auth` verb ever runs.
113
+
114
+ **Config notes.** The host environment is a startup-time snapshot — a later `export ANTHROPIC_BASE_URL` in another shell has no effect until the host restarts; check the host's environment, not your current shell, when diagnosing routing. Every delegation logs the effective endpoint at info level (`subagent-claude: delegating via <endpoint>`), and a failed run's error text names it. `skip` is the default because a one-shot CLI subagent has no approval surface; scope the host's own sandbox (e.g. run the host inside a sandboxed workspace) when a delegation needs confinement.
115
+
116
+ </details>
117
+
118
+ ## Development
119
+
120
+ Part of the [dsh-plugins](https://github.com/Khorsheed/dsh-plugins) monorepo (`packages/local-agent-claude-code`). Issues and contributions welcome there.
@@ -0,0 +1,6 @@
1
+ # Bilingual-pair consistency record: the git blob hash of each side as of the
2
+ # last confirmed-consistent state. Both languages carry equal authority; after
3
+ # editing either side, bring the other along and re-record with:
4
+ # pnpm run verify-translation-pairing --write packages/local-agent-claude-code/README.en.md
5
+ packages/local-agent-claude-code/README.en.md: 29705c09a8af61a023bbfdaed0b38c62a28f9787
6
+ packages/local-agent-claude-code/README.md: 5c74d6c22db916f8b2852271a8d7cb57ddc0b11a
package/README.md ADDED
@@ -0,0 +1,120 @@
1
+ # `@khorsheed/dsh-local-agent-claude-code`
2
+
3
+ [English](README.en.md) | 中文
4
+
5
+ **实时输出迁移。** live 轮次统一消费增量输出。旧 `liveMirrorGranularity: event | token` 配置继续兼容读取,但不再影响行为,也不会改变运行中的进程。评测继续保留 exec。最终内容仍以 provider 完成项为准,包括工具记录和用量。
6
+
7
+ 把编码任务委派给本地安装的 Claude Code,任意 dsh agent preset 都能用——答案实时流回,你的个人 `~/.claude` 绝不被动到。[local-agent 家族](../local-agent/README.md) 的 Claude Code harness。
8
+
9
+ ## 特性
10
+
11
+ - **任意 preset 都能委派**——工具只在 profile 根挂载一次,无需逐 preset 变体。
12
+ - **作用域隔离**——每个 Claude 进程都以 `$DSH_HOME/local-agent/claude-code` 为 `CLAUDE_CONFIG_DIR` 运行;你的个人 `~/.claude` 置身事外。
13
+ - **一条命令完成登录指引**——`/claude-code login` 在会话中给出需要在你自己终端运行的完整命令(claude ≥2.1 只在 TTY 打印 OAuth URL,宿主不再 spawn 抓取),并监听作用域目录识别登录完成;`sessions`/`status`/`logout` 与 设置 → 本地 Agent 面板构成完整一族。
14
+ - **续聊委派**——把结果自述的 `resume` 句柄传回,即可继续同一个 Claude 会话,并按轮记账。
15
+ - **实时流镜像**——子会话实时镜像 Claude 的思考、工具调用与回复;中止会保留部分转写与真实 token 用量。
16
+ - **模型回读与独立工作目录**——每轮从 stream-json 的 system/init 回读实际模型,写进委派记录;编排器可用 `cwd` 选项给每格独立目录,resume 换目录即拒绝。
17
+ ## 安装
18
+
19
+ 前置依赖:一个可运行的 dsh profile,以及 `PATH` 上的 Claude Code CLI(`claude`)——插件不负责安装。家族 core 与本包一起安装(`dsh plugin add` 只调和**直接**依赖,所以两个包都点名):
20
+
21
+ ```sh
22
+ dsh plugin --profile web add @khorsheed/dsh-local-agent @khorsheed/dsh-local-agent-claude-code
23
+ ```
24
+
25
+ 重启 profile,然后在会话里运行一次 `/claude-code login`。卸载:
26
+
27
+ ```sh
28
+ dsh plugin --profile web remove @khorsheed/dsh-local-agent-claude-code
29
+ ```
30
+
31
+ 作用域目录在卸载时刻意保留,重装无需重新登录;删除 `$DSH_HOME/local-agent/claude-code` 即可清除全部痕迹。
32
+
33
+ ## 配置
34
+
35
+ bundle 行接受这些可选字段:
36
+
37
+ - `permissionMode`——`skip`(默认)传 `--dangerously-skip-permissions`,子代理写文件无需审批;`normal` 不传,需审批的动作(如写文件)被拒绝。
38
+ - `model`——每轮委派以它起 CLI(`claude -p --model <模型>`);不写就一个模型参数都不传。见下。
39
+ - `baseUrl`——为子 CLI 设置 `ANTHROPIC_BASE_URL`(例如自部署路由器或代理);缺省继承宿主进程环境。配置优先于环境。
40
+ - `live`——长驻驱动:每成员常驻一个 stream-json 进程(`--input-format stream-json`),按轮发 stdin 消息(runtime 级优雅中断 control interrupt、同形推送流);关闭或通道不可用即回一次性 `claude -p`。
41
+ - `liveIdleMs`——长驻 runtime 空闲回收时限(默认 30 分钟)。
42
+
43
+ ### 默认模型(`model`)
44
+
45
+ **不写 = 今天的表现。**没有这个键时,本插件在 argv 上一个模型参数都不加:跑哪个模型由作用域 `settings.json` 的 `model` 决定,它也没有时由 claude 自己的默认决定(本插件从不猜它是什么)。
46
+
47
+ **写了 = 每轮委派以它起 CLI。**新起一轮与续接(resume)、一次性与常驻(`live: true`)四种 argv 都带上 `--model <模型>`,位置在成员通道的 `--allowedTools …--` 之前——那个旗标是变长的,`--` 之后就是任务文本。
48
+
49
+ 一次性(exec)轮不改写作用域 `settings.json`——`--model` 每轮覆盖它,文件仍是你编辑的样子。常驻(live)spawn 会把成员的生效模型暂写进该文件(`--resume` 重挂时 CLI 认文件里的模型而不认 `--model` 旗标),绑定空模型的 spawn 前再还原;状态页与设置卡读到的「CLI 配置」层永远是你自己配的值,不会读到某个成员留下的暂写。
50
+
51
+ 设置卡「默认模型」修改后续轮次使用的 provider 配置。共享选择器展示当前作用域的模型目录、发现来源和完整性,并保留按需填写模型 ID 的入口。清空选择后跟随有效配置及默认值链。保存不会打断当前轮次,也无需重载;共享选择器不可用时,卡片保留文本输入兜底。成员级模型和推理强度修改使用下文的持久控制面。
52
+
53
+ 模型读面现已读取 Claude 原生 `initialize` 目录,保留选择别名、显示名、解析名称和支持的 effort 值。目录共用 core 缓存和刷新订阅,刷新失败保留成功数据,并独立标识历史建议。此 scoped 控制查询不发送用户任务、不写模型设置。旧 CLI 缺少目录时显示不支持;原生候选不证明账号权限。共用模型菜单和成员 effort 控制已接入。运行中选择排到下一完整轮次(含工具续跑);core 统一持有当前/待生效配置、撤销与重试,冻结评测成员禁止变更。
54
+
55
+ **委派级的模型优先。**编排器可以经门面 `DelegationCallOptions.model` 给**某一次委派**点名模型,它排在这个键之前(顺序见家族核心 README 的层序)。首轮请求的值记进委派记录,resume 轮照它重发——resume 不接受 model 参数。常驻模式下,首轮点名的模型作为该成员的起始模型在 runtime spawn 时绑定:已绑定不同模型的 runtime 先退役,同一个 CLI 会话经 `--resume` 在新进程上续起。
56
+
57
+ **成员会话级切换。**成员会话的 composer 模型选择器经家族网关 `setMemberModel` 写入一个**会话级覆盖**——它排在委派模型与这个键之前,只存内存、刻意不跨宿主重启、也不写进设置。切换进行中轮次的成员会被拒绝;live 下换到不同模型会退役该成员的常驻 runtime,下一轮以新模型重挂**同一个** CLI 会话(对话不丢),换成相同模型则什么都不发生。
58
+
59
+ **这不是评测的缺口。**评测 run 的条件在建立时冻结:run 跑到一半改这个键,下一轮的模型回读会发现声明模型 ≠ 实测模型,run 直接判为 misattributed 而失败(冻结决策 5)。「切了新 run 照新走、进行中的 run 不被悄悄换掉」是设计出来的,不是漏掉的。
60
+
61
+ ⚠️ `skip` 没有 OS 级沙箱——子进程可以写宿主用户能写的任何地方,包括工作区之外;作用域登录的 OAuth token 会发送给 `baseUrl` 指向的端点。委派需要限制时改用 `normal`;`baseUrl` 只指向你信任的地址。
62
+
63
+ **评测快照(effectiveSettings)。** 本 harness 向注册表声明一份实时读取的公平性设置快照,供评测条件哈希使用:drive(exec/live)、permissionMode(skip/normal,插件配置)、端点是否固定(按 provider 的解析顺序——配置项优先于宿主进程环境的 `ANTHROPIC_BASE_URL`,只报主机名)、已配置模型(先看插件配置的 `model` 键——它每轮覆盖文件;没有才读作用域 `settings.json` 的 `model`;CLI 自身的默认模型由 CLI 决定,绝不猜值,都没有就不给字段)、CLI 版本(`claude --version`,按可执行文件路径+mtime 缓存;探测不到即字段缺位)。`/claude-code status` 与 `LocalAgentStatus` Remote 附带同一份快照。
64
+
65
+ ## Compatibility
66
+
67
+ - npm 发布线(`@deepseek-ai/dsh@0.1.5-rc.1`):✅ 公开 API 兼容。生成中的内容走 local-agent 瞬时 Remote 与公开 Conversation 节点;后缀检查点负责恢复,最终原生消息保留转写与用量语义。浏览器 P95 另在 room 协调者提案中验收。更旧宿主留在前一发布线。
68
+ - 源码线(deepseek-harness master):✅(verifiedHost: 0.1.5-rc.1)
69
+
70
+ ## 已知限制
71
+
72
+ - **macOS logout 只删配置**——keychain 条目留给 CLI 自己的 `claude auth logout`;下次登录会重写同一槽位,残留无害。
73
+ - **同一次授权不能被宿主轮与容器轮共用**——macOS 上两者用的是不同存储,任一侧轮换都会作废另一侧的 token family。容器化的条件用自己的命名 scope,见「容器内委派」。
74
+ - **Linux 凭据不隔离**(上游 bug #47661)——即使作用域目录没有凭据,claude 也会读默认 `~/.claude/.credentials.json`。
75
+ - **交互会话记录可能缺失**——自定义 `CLAUDE_CONFIG_DIR` 下 CLI 可能不写转写(上游行为)。
76
+ - **headless 注意**——`/claude-code` 命令需要 Web 会话;`--profile headless` 可通过挂载工具行的组合委派。
77
+
78
+ ## 实现原理
79
+
80
+ <details>
81
+ <summary>内部结构(点击展开)</summary>
82
+
83
+ **模型回读与 cwd 覆盖。** 每轮 settle 后,provider 把 stream-json `system`(init)事件 `model` 字段里的实际模型(如 `claude-opus-5[1m]`,原样回读,上下文变体后缀照留)随 `settled` 进度事件上报,并合并进 `delegations.jsonl` 的 `observedModel` 字段;取不到即缺位,绝不猜测。当任何一层、任何记录都没有模型时,「默认」面的最近观测提示读成员**自己的**转录(`projects/<cwd-slug>/<sessionId>.jsonl`;无成员面读全树最新的那份)——这是为 settle 通道之前的旧轮次准备的历史兜底;只读,绝不回写 `delegations.jsonl`。编排器还可以经门面 `DelegationCallOptions.cwd` 给本轮指定工作目录(记录进 `cwd` 字段);resume 轮解析出的目录若与首轮记录不一致,进程启动前即 fail loud——CLI 会话延续的是首轮所在目录的上下文。
84
+
85
+ **工具调用计数。** 每轮 settle 时,provider 顺带数出本轮的工具调用,随 `settled` 进度事件上报(`toolCalls: { count, byName }`)。计数就在流解析**已经走过**的 `tool_use` 分支里,`byName` 的键是该块自己的 `name`(`Bash`、`Read`、`TodoWrite`,MCP 工具则是 `mcp__server__tool` 全名),原样保留、不跨家归一。`TodoWrite` 也计——折叠逻辑把它挪去了 todo 快照、不进 transcript,但 CLI 确实调了它。本轮一份,绝不累计;一次都没调用就整个字段缺位(缺席 ≠ 0)。实测:一轮「先 Read 两个文件再 Bash 列目录」回读 `{count: 3, byName: {Read: 2, Bash: 1}}`,与镜像出的工具卡片逐个对得上。
86
+
87
+ **命名 scope。** `/claude-code login --scope <名>` 在 `<homesRoot>/claude-code@<名>` 里另开一份 `CLAUDE_CONFIG_DIR`:登录的 argv 由**被登录的那份目录**现算(`env CLAUDE_CONFIG_DIR=… claude auth login` 的赋值压过 spawn env,写死缺省目录会让 `--scope` 登错地方)。claude 的 keychain 项按配置目录路径哈希,命名 scope 因此自动拿到自己的 keychain 项——四家里唯一天然按路径隔离的凭据。带 scope 的委派用该目录跑 `claude -p`、按它做 keychain↔文件协调、从它回读;只走 exec。
88
+
89
+ **容器内委派。** 编排器可以经门面 `DelegationCallOptions.exec`(`{ container, workdir, env? }`)让本轮跑在一个**已取得的容器**里:argv 变成 `docker exec -w <workdir> [-e NAME…] <container> claude -p …`,其余(stream-json 解析、settle、记录)逐字节不变。`env` 必须给出容器内的 `CLAUDE_CONFIG_DIR`,调用方把宿主作用域目录 rw bind 到那条路径上。实测评测镜像里的 claude 2.1.272:容器内的 CLI **读写 `<CLAUDE_CONFIG_DIR>/.credentials.json`**,它整棵状态树(`projects/`、`sessions/` 等)也落在那里;上游 #47661 那种「Linux 写作用域目录、读默认 home」的老行为不描述这个版本。每次 spawn 前的凭据协调照常在**宿主**作用域目录上跑,续期结果因此经挂载对容器可见——而且它是**新者胜,不是单向镜像**,因为单元是同一个文件的**第二个写者**。单元里的 CLI 没有 keychain,只能在挂进去的文件里就地轮换凭证;此时若无条件地把 keychain 盖到文件上,下一轮拿到的就是单元已经用掉的 refresh token,端点拒绝,CLI 随即**清空该文件**——整台实例随之登出,因为那个文件就是实例的凭据。所以协调只在 keychain 那份不比文件旧时才写(以 access token 过期时间为准;任一侧没有过期时间就仍由 keychain 写,不可用的文件永远不会赢)。挂载保持读写还有第二个理由:本轮的会话记录落在同一目录的 `projects/` 下,评测的模型回读正是从这条挂载的宿主侧解析它们。容器轮固定走 exec 一次性驱动,且不声明成员桥。
90
+
91
+ **容器轮必须用自己的 scope,这条纪律不是可选项。** claude 是这几家里唯一有两个凭据存储的,而实测 macOS 2.1.274 它们并没有同一个读者:**宿主 CLI 读写 keychain**,而单元里的 CLI——Linux、没有 keychain——读写挂进去的文件。同一次授权被两个存储各续一次,就是被续了两次;服务端轮换一次性 refresh token 的做法是把整个 **token family 作废**,于是没有最后续到的那一侧手里就是一个死 token。端到端实测过:容器轮轮换了文件,紧接着的宿主轮报 `OAuth session expired and could not be refreshed`,而文件自己的 access token 离过期还有好几个小时,只能重登才能恢复。新者胜保住的是**文件那一侧**(单元与所有状态探针读的就是它),但没有任何东西能把单元的轮换写回 keychain(`security add-generic-password` 只能把密文放进 argv,因此否决)。所以容器侧与宿主侧必须是**两次独立授权**:每个容器化的 claude 条件用自己的命名 scope,用 `/claude-code login --scope <名>` 授权一次,且**永不**在该 scope 上跑宿主轮。评测会在取单元之前就拒绝违反这条的计划。**注意作用域 `settings.json` 里的宿主专用项**:实测那里给宿主守护进程用的 `https_proxy` 在容器内指向不存在的地址,本轮当场 `Connection refused`——挂进去的目录要由调用方备好。
92
+
93
+ ```
94
+ src/index.ts harness 注册、/claude-code 命令族、config schema
95
+ src/claude-cli-provider.ts 一次性 provider:spawn、流镜像、turn/token 记账
96
+ src/provision.ts 作用域目录 provisioning 与基于文件的 logout
97
+ src/records.ts 认证探测与作用域目录的会话记录列表
98
+ ```
99
+
100
+ bundle patch 把 `claude-code` harness 注册进家族 core(`@khorsheed/dsh-local-agent`,声明为依赖——claude 包刻意不重复插入 core 行,重复会挂载两次),并挂载 `claude-local` provider,后者在 harness 作用域目录下 spawn `claude -p --verbose --output-format stream-json`。`subagent_claude_code` 工具是家族自有工具(`@khorsheed/dsh-local-agent-tool-subagent`):官方子集(`description`/`prompt`)加一个可选 `resume` 参数。
101
+
102
+ **作用域隔离。** macOS 上真实凭据在系统 keychain 的哈希条目里(`Claude Code-credentials-<sha256(configDir)[:8]>`,以作用域目录路径为键)——基于文件的 logout 够不到它,但下次登录会重写同一个槽位。**CLI 自己用哪个存储是随版本变的,且由实测而非假定确定**:2.1.236 写 keychain、读文件(这个镜像正是为那条分裂而存在),而 2.1.274 在 macOS 上读写 keychain,2.1.272 在 Linux 上读写作用域文件。因此文件对本包自己的探针与容器轮仍是权威;keychain 才是当前 macOS 上宿主 CLI 真正用的那个。认证探测只做轻量文件检查——看作用域 `.claude.json` 的 `oauthAccount`,绝不为了探测而 spawn CLI。该探测同样会协调两个存储,因此遵守与 spawn 点一致的新者胜规则:它在每次状态读与每次就绪检查时都会跑,那里若是无条件镜像,同样会把容器轮的续期抹掉。
103
+
104
+ **会话记录。** `/claude-code sessions` 列出作用域目录下的 `projects/<cwd-slug>/<uuid>.jsonl` 会话文件——即本 agent 的委派,绝不是你的私人会话。slug 是工作区路径的有损编码,所以列出的 `workDir` 取自文件内容(第一条 `user` 事件的 `cwd` 字段),绝不取自目录名。设置面板呈现同一份列表并收窄到当前工作区。
105
+
106
+ **续聊安全。** 句柄绝不进 prompt:它只从 `resume` 参数读取,localAgent registry 只对记录该委派的同一 parent 会话与 provider 解析句柄——伪造的句柄(未知子会话、他人 parent 的会话、或错误的 provider)在任何 CLI 进程启动前就被拒绝。
107
+
108
+ **流镜像与记账。** `thinking` 块折叠为 `reasoning` 块、`tool_use`/`tool_result` 为工具行(`[工具 Bash] <command> → output`)、回复 `text` 为 assistant 文本;续聊轮各自追加自己的 turn,不会重复。编辑类调用(Edit/Write/MultiEdit/NotebookEdit)折叠为 ApplyPatch 式卡片——路径在参数行,真正的改动(旧/新串或整个文件体)在卡身,与 codex 的 fileChange 镜像同一形态;服务端工具(`server_tool_use` 的 web_search/web_fetch)与其结果按 id 配对成可见的 WebSearch/WebFetch 卡;`redacted_thinking` 折叠为一行可见的占位思考(内容按设计由服务端加密,不可见——行内注明);其余工具的输入取单一标量摘要,取不到就给一份截断的 JSON 摘要而不是丢空。每个镜像 step 都包在同 (turn, step) 的 `step/start`–`step/end` 边界对内——宿主实时会话视图只在边界上登记 step,缺了边界 assistant 消息要等整页重建才渲染。provider 在 spawn 时开 `turn/start`、settle 时关 `turn/end`——失败与被取消同样关闭——因此 `subagentTiming` 时长等于实际 CLI 运行时长,不会留下未闭合窗口;最终 `assistant/message` 携带从 JSON 结果解析的 token 用量(`input_tokens`、`output_tokens`、`cache_read_input_tokens`、`cache_creation_input_tokens`——Anthropic 各桶独立上报)。
109
+
110
+ **模型体验。** 子会话是委派会话工作区内一个全新的一次性 `claude -p`;父级只提交独立的任务文本,只看到最终回答或精确错误,以及首次委派时的续聊自述——Claude 的评论、工具活动、工作区 diff 不会复制进父级。子会话 token 永不进入父级上下文;子会话为独立的 Claude 上下文与回合付费(缓存复用只取决于作用域安装自身的 provider、模型与历史);父级 KV cache 不受影响。
111
+
112
+ **长驻驱动(`live: true`)。** 替代每轮 spawn:成员首轮委派拉起一个常驻 stream-json 进程(`claude -p --verbose --input-format stream-json --output-format stream-json`),第一条 stdin `user` 消息触发 `system/init`(server 分配 session id,即委派记录的 `cliSessionId`),之后每轮 = 一条 stdin 消息;事件流与 exec 的 stream-json **完全同形**,逐轮过同一个 `ClaudeStreamParser` 折叠(末行留置到 `result` 挂用量,与 exec 一致),`cancel` 落地为 `control_request interrupt`——进程不死、会话可续。回收阶梯是 stdin EOF → SIGTERM;崩溃后下一轮以 `--resume <session_id>` 重挂盘上会话。runtime 在 spawn 时绑定成员的生效模型(会话级覆盖 → 委派模型 → 设置键),并把它暂写进作用域 `settings.json`(`--resume` 重挂认文件不认旗标);绑定模型与新一轮解析不一致的 runtime 先退役再重挂。`permissionMode: normal` 的 spawn 不带 `--dangerously-skip-permissions`,CLI 的 server→client 控制请求(`can_use_tool` 审批面)由驱动自动应答 allow——子代理没有审批面,与 exec 在 skip 下的有效行为一致;其余子类型应答 error 而不是沉默挂起。授权纪律与 exec 逐字一致:只注入作用域 `CLAUDE_CONFIG_DIR`(与可选的 `baseUrl` 覆盖),绝不碰全局 `~/.claude`,绝不执行任何 `auth` 命令。
113
+
114
+ **配置注意。** 宿主环境是启动时的快照——之后在别的 shell 里 `export ANTHROPIC_BASE_URL` 对运行中的进程无效,除非重启宿主;排查路由异常时检查宿主的实际环境而非你当前的 shell。每次委派在 info 级别记录有效端点(`subagent-claude: delegating via <endpoint>`),失败运行的报错文本会点名它。`skip` 作为默认是因为一次性 CLI 子代理没有审批面;委派需要被限制时,给宿主自身套沙箱(例如在沙箱化工作区内运行 dsh 宿主)。
115
+
116
+ </details>
117
+
118
+ ## 开发
119
+
120
+ 隶属 [dsh-plugins](https://github.com/Khorsheed/dsh-plugins) monorepo(`packages/local-agent-claude-code`)。问题与贡献请移步该仓库。
@@ -0,0 +1,42 @@
1
+ # The dsh-local-agent-claude-code bundle patch: delegate dsh agents to the
2
+ # local Claude Code CLI under a scoped CLAUDE_CONFIG_DIR, and surface its
3
+ # session records. The family core row (`local-agent`, shared scoped-homes
4
+ # root) lives in the framework bundle @khorsheed/dsh-local-agent's own patch.
5
+ # This bundle declares that package as an npm dependency, which makes the
6
+ # core's module resolvable — it does NOT mount the core row: `dsh plugin add`
7
+ # reconciles only the profile's direct dependencies, so the core must be
8
+ # installed explicitly alongside this bundle, or this provider stays pending.
9
+ # No other patch inserts the core row id.
10
+ #
11
+ # Two rows are inserted:
12
+ # - local-agent-claude-code: this bundle's plugin registers the
13
+ # `claude-code` harness (CLAUDE_CONFIG_DIR scoped home,
14
+ # `claude auth login` browser flow, project-file session records).
15
+ # - tool-subagent-claude-code-local: the family-owned delegation tool
16
+ # (schema description/prompt plus optional resume) over the `claude-local`
17
+ # provider. The toolName is `subagent_claude_code` — the family takes the
18
+ # model-facing name: the official preset row of that name ships
19
+ # `disabled: true`, and this patch disables it too (below) so a community
20
+ # install can never register two `subagent_claude_code` tools. A user who
21
+ # deliberately re-enables the official row in their own preset layer gets
22
+ # a loud duplicate-name conflict — by design, they must choose one. The
23
+ # family tool adds continuation: a later round may pass the dsh child
24
+ # session id returned by the first delegation to continue the same claude
25
+ # conversation.
26
+ #
27
+ # The tool mounts at the profile root, so every agent preset can delegate
28
+ # without per-preset variants. The provider starts no claude process until a
29
+ # tool call or /claude-code login.
30
+
31
+ - id: tool-subagent-claude-code
32
+ disabled: true
33
+
34
+ - insert:
35
+ - id: local-agent-claude-code
36
+ name: '@khorsheed/dsh-local-agent-claude-code'
37
+
38
+ - id: tool-subagent-claude-code-local
39
+ name: '@khorsheed/dsh-local-agent-tool-subagent'
40
+ config:
41
+ provider: claude-local
42
+ toolName: subagent_claude_code