Merge remote-tracking branch 'origin/master' into codex/agent-session-jsonl-location

# Conflicts:
#	docs/config-catalog.md
#	docs/cordis-catalog/services.md
#	docs/core-data-structures/bash.md
#	docs/module-graph.md
#	docs/rfc/INDEX.md
#	docs/rfc/implemented/architecture/2026-06-30-bash-stdin-env-trusted-plugin-surface.md
#	docs/rfc/implemented/feature/2026-06-30-hook-bridges.md
#	examples/acp-agent/tests/snapshots/advanced-toolchain/session.1.jsonl
#	examples/acp-agent/tests/snapshots/advanced-toolchain/session.2.jsonl
#	examples/acp-agent/tests/snapshots/advanced-toolchain/session.jsonl
#	examples/acp-agent/tests/snapshots/advanced-toolchain/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/both-mode-turn/session.jsonl
#	examples/acp-agent/tests/snapshots/both-mode-turn/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/code-mode-turn/system-prompt.golden.md
#	examples/acp-agent/tests/snapshots/skill-load/session.jsonl
#	examples/acp-agent/tests/snapshots/text-turn/session.jsonl
#	examples/sandbox-acp-agent/tests/snapshots/mode-switching/session.jsonl
#	packages/bash/bash-local/README.md
#	packages/bash/bash-local/src/run.ts
#	packages/bash/bash-local/tests/run.spec.ts
#	packages/bash/bash/README.md
#	packages/bash/tool-bash/README.md
#	packages/bash/tool-bash/src/index.ts
#	packages/bash/tool-bash/tests/tools.spec.ts
#	packages/cordis/tool-cordis/src/api-catalog.ts
#	packages/core/agent-core/src/index.ts
#	packages/session-persistence/session-persistence-jsonl/src/index.ts
#	packages/session-persistence/session-persistence-sqlite/src/index.ts
#	packages/session-persistence/session-persistence/README.md
#	packages/session-persistence/session-persistence/src/index.ts
#	packages/ui/acp-agent/README.md
#	packages/ui/stdio-agent/README.md
This commit is contained in:
Yichen Jiang
2026-07-14 18:04:05 +08:00
672 changed files with 10233 additions and 14251 deletions
+12 -16
View File
@@ -1,13 +1,8 @@
/**
* Parse a Claude Code hook config file into the shared {@link MatcherGroup}
* shape, faithfully to CC's `hooks.json` / settings `hooks` key format.
*
* A CC config maps each event name to an array of matcher groups, each holding
* an array of typed hooks. Only `type: 'command'` hooks run here; other types
* (`prompt`/`agent`/`http`) are PARSED but skipped with a warning (faithful-but-
* degraded — the same stance Codex takes). The `command` string undergoes
* `${CLAUDE_PLUGIN_ROOT}` substitution at parse time so the runner sees a literal.
*
* Parse Claude Code's event-to-matcher-group hook format into shared {@link MatcherGroup}s.
* Only command hooks run; other hook types are returned as skipped so the
* bridge can warn. Plugin-root and project-directory substitutions are applied
* to commands at parse time.
* @module @deepseek-ai/dsh-hooks-claude/config
*/
@@ -57,13 +52,14 @@ export function substituteCommand(command: string, vars: SubstitutionVars): stri
}
/**
* Parse a raw Claude Code config object (the value under the `hooks` key, or a
* `hooks.json` whose top level IS that map) into runnable {@link MatcherGroup}s.
* Non-command hooks and malformed entries are dropped (recorded in `skipped` /
* silently ignored) rather than throwing — a bad hook config must not crash boot.
* `vars` are substituted into every surviving `command`.
* @param raw - the parsed JSON config: a settings object with a `hooks` key, or the bare event map.
* @param vars - substitution values applied to every surviving `command` (defaults to none).
* Parse either a settings `hooks` value or a bare `hooks.json` event map. Malformed entries are
* ignored rather than failing boot; non-command hooks are returned in `skipped`, and substitutions
* are applied to every surviving command.
*
* @param raw - the parsed JSON config: a settings object with a `hooks` key, or the bare
* event map.
* @param vars - substitution values applied to every surviving `command` (defaults to
* none).
* @returns the runnable per-event groups plus the skipped non-command hooks.
*/
export function parseClaudeConfig(raw: unknown, vars: SubstitutionVars = {}): ParsedClaudeConfig {
+31 -99
View File
@@ -1,24 +1,11 @@
/**
* `dsh-hooks-claude` — a bridge plugin that runs a user's existing Claude Code
* hook config (`hooks.json` / a settings file's `hooks` key) on the harness's
* canonical interception seams. It is the CC DIALECT half of the hooks
* subsystem: it owns CC's per-event stdin payloads, CC's env +
* `${CLAUDE_PLUGIN_ROOT}` substitution, and the mapping from a hook's neutral
* outcome onto the harness's typed Decisions. The dialect-agnostic primitives
* (matcher, exit-code/stdout codec, `ctx.bash` execution, most-restrictive
* merge, the `hook/*` events) come from `@deepseek-ai/dsh-hook-protocol`.
*
* A native cordis plugin could do everything this bridge does — more powerfully,
* with typed returns and no serialization boundary. The bridge exists only to
* run UNMODIFIED external CC hooks faithfully; anything bespoke should be a
* native plugin on the same seams.
*
* Scope: the seven in-scope hook points (`SessionStart`, `UserPromptSubmit`,
* `PreToolUse`, `PostToolUse`, `Stop`, `SubagentStart`, `SubagentStop`). Only
* `type: 'command'` hooks run; the matcher group config + exit-code/stdout
* protocol are byte-faithful to CC. `updatedInput` (tool-input rewrite) is
* logged + warned, not honored (deferred — see the interception-seams RFC).
*
* Bridge for unmodified Claude Code command hooks on harness interception
* seams. It supports SessionStart, prompt/tool pre/post, Stop, and subagent
* start/stop. It owns Claude payloads, environment, substitution, and decision
* mapping; shared execution and parsing live in `dsh-hook-protocol`.
* `updatedInput` is logged and warned but not honored. Bespoke behavior should
* use typed native plugins on the same seams; see the
* [hook-bridges RFC](../../../../docs/rfc/implemented/feature/2026-06-30-hook-bridges.md).
* @module @deepseek-ai/dsh-hooks-claude
*/
@@ -57,7 +44,7 @@ export const inject = ['bash']
export interface Config {
/**
* Path to a `hooks.json` or a settings file whose `hooks` key holds the config.
* PROCESS-LEVEL: read once at load, a relative path resolves against the process
* Process-level: read once at load, a relative path resolves against the process
* launch cwd, so one config applies to the whole process.
* TODO(per-session-hook-config): per-session discovery of a project-local
* `hooks.json` from each `session/new.cwd` is not yet implemented.
@@ -106,14 +93,11 @@ function assertPositiveInteger(name: string, value: number): void {
}
export function apply(ctx: Context, config: Config): void {
// Validate the cap BEFORE the config-file parse: a bad value must fail the
// load loudly, not be skipped by the parse-failure early return.
// Validate before config parsing so a bad value cannot be hidden by its early return.
const stderrSummaryMaxChars = config.stderrSummaryMaxChars ?? DEFAULT_STDERR_SUMMARY_MAX_CHARS
assertPositiveInteger('stderrSummaryMaxChars', stderrSummaryMaxChars)
const defaultTimeoutMs = config.defaultTimeoutMs ?? DEFAULT_HOOK_TIMEOUT_MS
// --- Parse the config ONCE at load. A read/parse failure is contained: the
// bridge logs and registers nothing rather than crashing boot (a typo'd path
// must not take the agent down). ---
// Parse once at load. A read or parse failure logs and registers nothing.
let parsed: ClaudeHookConfig = {}
try {
const raw: unknown = JSON.parse(readFileSync(config.configPath, 'utf8'))
@@ -130,11 +114,8 @@ export function apply(ctx: Context, config: Config): void {
return
}
// --- The emit-shaped points (SessionStart, SubagentStart, SubagentStop) run
// detached — no seam awaits them — so every run chain is tracked and disposal
// aborts still-running hook processes, then drains the continuations
// (docs/defensive-patterns.md: dispose must reach quiescence). After the parse
// gate: a bridge that registered nothing has nothing to drain. ---
// Emit-shaped points run detached, so track their chains; disposal aborts
// active hooks and drains continuations before resolving.
const detached = createDetachedRuns()
ctx.effect(() => () => detached.drain(), 'hooks-claude: drain detached hook runs')
@@ -155,19 +136,11 @@ export function apply(ctx: Context, config: Config): void {
): Promise<MergedHookOutcome> {
const groups: MatcherGroup[] = parsed[point] ?? []
const outputs: HookOutput[] = []
// Run the hook in the AGENT'S session workspace (the `session/new` cwd on the
// session header), not the executor default (the ACP server's launch dir).
// A hook that does `pwd`, reads a relative file, or writes a marker must
// operate in the user's project tree. Absent for a no-agent run (falls back
// to the executor default).
// Run the hook in the agent's session workspace (the `session/new` cwd on the session
// header), not the executor default (the ACP server's launch dir).
const workdir = opts.agent?.session.header.cwd
// CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to
// the session workspace (the same dir the hook RUNS in). Claude Code always
// exports this var, and common unmodified hooks reference `$CLAUDE_PROJECT_DIR`
// (shell expansion at run time) for project-relative paths — leaving it empty
// in the default ACP wiring (no `projectDir` configured) would break them even
// though the bridge already knows the workspace. Absent only for a no-agent run
// with no configured projectDir (nothing to point at).
// CLAUDE_PROJECT_DIR: an explicit config value wins; otherwise default it to the session
// workspace (the same dir the hook runs in).
const projectDir = config.projectDir ?? workdir
const hookEnv = projectDir !== undefined ? { CLAUDE_PROJECT_DIR: projectDir } : undefined
for (const group of groups) {
@@ -207,13 +180,7 @@ export function apply(ctx: Context, config: Config): void {
return mergeHookOutputs(outputs)
}
// TODO(hook-continue-false): the merge computes `merged.stop`/`stopReason` from
// a hook's `continue:false`, but no seam below honors it — there is no
// "hard-halt the whole agent" primitive on the interception seams yet (a
// Decision can block/deny/steer a single point, not stop the run). Honoring it
// needs that primitive; deferred with the loop-guard work. Until then a
// `continue:false` hook still has its per-point effect (its decision/context),
// and the halt request is recorded in the `hook/result` log but not acted on.
// TODO(hook-continue-false): `merged.stop` is logged but needs a run-level halt seam.
/** Build a HookContext from accumulated additionalContext strings, or undefined when none. */
function contextFrom(merged: MergedHookOutcome): HookContext | undefined {
@@ -222,30 +189,15 @@ export function apply(ctx: Context, config: Config): void {
return { content, source: PLUGIN_SOURCE }
}
/**
* Concatenate this bridge's {@link HookContext} (`ours`, always present at the
* call sites) with a downstream listener's optional one, so folding our
* additionalContext onto a delegated decision drops neither. The merged block
* carries a single `source` — this bridge's — because a `HookContext` holds one
* `MessageSource` and the seam cannot represent mixed provenance; the rendered
* `context/message` only distinguishes by `source.kind` ('plugin'), so a
* downstream plugin's text is still correctly framed as plugin context, not a
* user prompt.
*/
/** Merge hook context while retaining this bridge's plugin-level source. */
function concatContext(ours: HookContext, theirs: HookContext | undefined): HookContext {
if (!theirs) return ours
return { content: [...ours.content, ...theirs.content], source: ours.source }
}
// --- SessionStart: emit (cannot block). Inject any additionalContext into the
// agent. The matcher subject is the source.
// TODO(session-start-gating): `agent/session-start` is a SYNCHRONOUS emit and
// this hook runs on a detached `.then`, so the injected context is BEST-EFFORT
// — it is not guaranteed to land before the first turn reaches the model. A
// slow hook can miss the first request (the context then arrives as a later
// injection turn). Gating startup on the hook is a loop-level change deferred
// to the interception seams; today the contract is "injected as soon as the
// hook resolves", not "before the first request". ---
// SessionStart injects context when its detached hook resolves; a slow hook
// may miss the first request.
// TODO(session-start-gating): add a startup gate before promising first-turn delivery.
ctx.on('agent/session-start', (agent, source) => {
detached.track(runPoint('SessionStart', source, sessionStartPayload(ctx, agent, source), { agent, signal: detached.signal })
.then((merged) => {
@@ -265,10 +217,8 @@ export function apply(ctx: Context, config: Config): void {
if (merged.decision === 'deny') {
return { kind: 'block', reason: merged.reason ?? 'blocked by UserPromptSubmit hook' }
}
// Our hooks did not block. DELEGATE (attaching context alone is not a veto):
// a later `agent/prompt-submit` listener must still get to block or rewrite.
// Then fold our additionalContext onto its decision — a downstream block wins
// (a dropped prompt makes the context moot; `block` carries no context field).
// Delegate so later listeners may still rewrite or block, then prepend our
// context only to a downstream allow decision.
const downstream = await next()
const ours = contextFrom(merged)
if (!ours || downstream.kind !== 'allow') return downstream
@@ -310,34 +260,20 @@ export function apply(ctx: Context, config: Config): void {
}
})
// --- Stop → ContinuationDecision. CC's Stop hook can force the conversation to
// CONTINUE (block the stop) with stderr/reason as the continuation. No matcher.
// TODO(stop-loop-guard): CC breaks an infinite force-continue with
// `stop_hook_active` (set true once a Stop hook has already fired this run) plus
// a max-consecutive cap; both are deferred. Today `stop_hook_active` is always
// false, so a Stop hook that unconditionally blocks would force-continue every
// step — a hook author must self-limit until the guard lands. ---
// A blocking Stop hook forces continuation with its reason.
// TODO(stop-loop-guard): cap consecutive forced continuations; hooks must self-limit meanwhile.
ctx.on('agent/turn-continuation', async (agent, turn, _default, next): Promise<ContinuationDecision> => {
const merged = await runPoint('Stop', '', stopPayload(ctx, agent), { agent, turn })
if (merged.decision === 'deny') {
// A blocking Stop hook forces continuation. It carries its reason as
// next-step steering; a blocking hook that emitted no reason (exit 2, empty
// stderr) still forces the turn to continue — the block is what matters, so
// fall back to a generic steering line rather than letting the turn stop.
// A blocking Stop hook forces continuation.
const text = merged.reason ?? 'continue: blocked by Stop hook'
return { action: 'continue', reason: { content: [{ type: 'text', text }], source: PLUGIN_SOURCE } }
}
return next()
})
// --- SubagentStart / SubagentStop: observe-only emits (the subagent seam is
// observe-only this cut). A SubagentStart hook's additionalContext is injected
// into the live child; SubagentStop only observes. Both look the live child up
// so the hook runs in the child's session workspace and the payload carries
// the child's session_id/cwd (see subagentPayload). The matcher subject is the
// CC-default `agent_type` (SUBAGENT_TYPE) — the harness seam carries no
// per-kind label, so a config's default/`*`/empty agent_type matcher fires and
// a specific-kind matcher does not (documented in the RFC). ---
// SubagentStart may inject child context; SubagentStop only observes. Both
// use the live child's workspace and the generic agent-type matcher subject.
ctx.on('subagent/start', (info) => {
const child = ctx.get('agents')?.get(info.id)
detached.track(runPoint('SubagentStart', SUBAGENT_TYPE, subagentPayload(ctx, 'SubagentStart', info, child), { ...child ? { agent: child } : {}, signal: detached.signal })
@@ -348,13 +284,9 @@ export function apply(ctx: Context, config: Config): void {
.catch((error: unknown) => { ctx.logger.warn(`hooks-claude: SubagentStart hook failed: ${String(error)}`) }))
})
ctx.on('subagent/end', (info) => {
// Look up the child (still recoverable: `subagent/end` fires from the
// service's detached `.then` BEFORE the tool caller's `await run.result`
// disposes it) so the hook runs in the child's cwd, not the server default.
// No `.then`/inject follows (SubagentStop only observes), and no `turn` is
// passed (so no `hook/*` log records), so runPoint has nothing that can
// reject — no `.catch` is needed (the tracker's settlement bookkeeping
// would absorb one anyway).
// Look up the child (still recoverable: `subagent/end` fires from the service's detached
// `.then` before the tool caller's `await run.result` disposes it) so the hook runs in the
// child's cwd, not the server default.
const child = ctx.get('agents')?.get(info.id)
detached.track(runPoint('SubagentStop', SUBAGENT_TYPE, subagentPayload(ctx, 'SubagentStop', info, child), { ...child ? { agent: child } : {}, signal: detached.signal }))
})