From 4f3f59ad7c499377871a8ee9c2ced686d1b1bb61 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:09:40 +0800 Subject: [PATCH 1/7] refactor: share the claude-shaped hook factories and install the duplicates gate First slice of #308: the hook dialects that follow Claude Code's convention build their shapes from the new harness spi factories (claudeShapedHookOutput, claudeShapedField/Fields/SessionId/TurnId, claudeShapedSessionStartLifecycle, the gate/permission field lists, the seconds timeout) instead of copying them, and seven providers' dialects plus their hook test fixtures build through hookSampleFactory / hookEventSampleFactory in @rivus/agent-kit-testing. Usage scans share usageWindowKey. pnpm duplicates lands as the gate script (conventions only: *.test.*, test support and fixture trees), tracking the remaining provider mirrors for the follow-up slices. knip keeps its staged excludes in this slice. --- package.json | 1 + .../src/domain/lifecycle/spi/claude-shaped.ts | 77 +++++++++++++++++++ packages/harness/src/spi.ts | 12 +++ packages/providers/claude-code/src/hooks.ts | 33 ++++---- .../claude-code/test/fixtures/hooks.ts | 20 ++--- packages/providers/codex/src/hooks.ts | 36 ++++----- .../providers/cursor/test/fixtures/hooks.ts | 19 ++--- packages/providers/dim/src/hooks.ts | 32 ++++---- .../gemini-cli/test/fixtures/hooks.ts | 20 ++--- packages/providers/grok/src/hooks.ts | 10 +-- packages/providers/kimi/src/hooks.ts | 49 ++++-------- .../providers/kimi/test/fixtures/hooks.ts | 20 ++--- packages/providers/opencode/src/usage.ts | 8 +- packages/providers/qoder/src/hooks.ts | 58 +++++--------- .../providers/qoder/test/fixtures/hooks.ts | 19 ++--- packages/providers/zcode/src/usage.ts | 8 +- packages/sessions/src/spi.ts | 11 ++- .../testing/src/hook-dialect-conformance.ts | 46 +++++++++++ packages/testing/src/public.ts | 2 + 19 files changed, 261 insertions(+), 220 deletions(-) create mode 100644 packages/harness/src/domain/lifecycle/spi/claude-shaped.ts diff --git a/package.json b/package.json index f5599ba3..31dfe6d9 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ "changeset": "changeset", "check": "pnpm run format:check && pnpm run build && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run check:package", "check:package": "pnpm -r run check:package", + "duplicates": "jscpd --config node_modules/@perfectpan/lint-config/jscpd.json packages apps infra scripts tests --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/*.json,**/*.test.ts,**/*.test.tsx,**/test/support/**,**/test/fixtures/**' --format 'typescript'", "duplicates:audit": "jscpd --config node_modules/@perfectpan/lint-config/jscpd-audit.json packages apps infra scripts tests --absolute --output tmp/duplicates-audit --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/*.json' --format 'typescript'", "format": "pnpm -r run format", "format:check": "pnpm -r run format:check", diff --git a/packages/harness/src/domain/lifecycle/spi/claude-shaped.ts b/packages/harness/src/domain/lifecycle/spi/claude-shaped.ts new file mode 100644 index 00000000..1e078feb --- /dev/null +++ b/packages/harness/src/domain/lifecycle/spi/claude-shaped.ts @@ -0,0 +1,77 @@ +import type { FieldSource, HookOutput, LifecycleSwitch, PayloadFields } from "./hook-dialect.js"; + +/** + * The hook shapes the agents that follow Claude Code's convention share, as + * factories instead of copies: a dialect declares "Claude-shaped" and names + * only its own differences, so a drift in the shared shape is one edit. The + * per-agent facts — event sets, timeouts, exit-code deviations — stay in each + * provider's dialect, with their documentation. + */ + +/** The exit-code table Claude Code documents and its followers copy. */ +export const claudeShapedHookOutput: HookOutput = { + emptyStdout: "proceed", + invalidStdout: "proceed", + exitCode2: "block", + otherExitCodes: "hook-failed", + passThrough: "{}" +}; + +/** The output table with the plain-text stdout a start-of-turn or session event turns into context. */ +export const withPlainStdoutContext = (output: HookOutput): HookOutput => ({ ...output, plainStdout: "context" }); + +/** One Claude-shaped payload field: the JSON path the value is read from. */ +export const claudeShapedField = (path: string): FieldSource => ({ paths: [[path]] }); + +/** The session id field with the agent's environment variable as a fallback. */ +export const claudeShapedSessionId = (env: readonly string[]): FieldSource => ({ + paths: [["session_id"]], + env +}); + +/** The turn id field when the payload names one (Claude Code's `prompt_id`, or the agent's own). */ +export const claudeShapedTurnId = (path = "prompt_id"): FieldSource => claudeShapedField(path); + +/** The payload fields every Claude-shaped stdin payload carries, keyed as the dialect spells them. */ +export const claudeShapedFields: PayloadFields & Record = { + event: { paths: [["hook_event_name"]] }, + sessionId: { paths: [["session_id"]] }, + cwd: { paths: [["cwd"]] }, + transcriptPath: { paths: [["transcript_path"]] }, + toolName: { paths: [["tool_name"]] }, + toolCallId: { paths: [["tool_use_id"]] }, + subagentId: { paths: [["agent_id"]] }, + subagentType: { paths: [["agent_type"]] } +}; + +/** How a SessionStart carrying a `source` splits compaction from a fresh session start. */ +export const claudeShapedSessionStartLifecycle: LifecycleSwitch = { + field: ["source"], + cases: { compact: { phase: "activity" } }, + otherwise: { phase: "start", scope: "session" } +}; + +/** The stdout JSON keys a gate decision (PreToolUse) may carry. */ +export const claudeShapedGateFields: readonly string[] = [ + "continue", + "stopReason", + "suppressOutput", + "systemMessage", + "hookSpecificOutput", + "decision", + "reason" +]; + +/** The stdout JSON keys a permission decision may carry. */ +export const claudeShapedPermissionFields: readonly string[] = [ + "continue", + "stopReason", + "systemMessage", + "hookSpecificOutput" +]; + +/** Command-hook timeouts measured in seconds, as Claude Code's settings carry them. */ +export const claudeShapedSecondsTimeout: { unit: "seconds"; default: number } = { + unit: "seconds", + default: 600 +}; diff --git a/packages/harness/src/spi.ts b/packages/harness/src/spi.ts index 4f14c0f7..cf58a0a7 100644 --- a/packages/harness/src/spi.ts +++ b/packages/harness/src/spi.ts @@ -47,6 +47,18 @@ export { aliasesOf, finishSelectorsOf } from "./domain/lifecycle/spi/hook-dialect.js"; +export { + claudeShapedField, + claudeShapedFields, + claudeShapedGateFields, + claudeShapedHookOutput, + claudeShapedPermissionFields, + claudeShapedSecondsTimeout, + claudeShapedSessionId, + claudeShapedSessionStartLifecycle, + claudeShapedTurnId, + withPlainStdoutContext +} from "./domain/lifecycle/spi/claude-shaped.js"; export { type LifecycleMapping } from "./domain/lifecycle/value-objects/lifecycle-event.js"; export { canonicalContent, type ContentHash } from "./domain/ledger/value-objects/content-hash.js"; diff --git a/packages/providers/claude-code/src/hooks.ts b/packages/providers/claude-code/src/hooks.ts index f1d3ba79..35e72a47 100644 --- a/packages/providers/claude-code/src/hooks.ts +++ b/packages/providers/claude-code/src/hooks.ts @@ -1,5 +1,13 @@ import { CLAUDE_CODE_ID, CLAUDE_CODE_SESSION_ENV } from "./facts.js"; -import type { HookDialect, HookOutput } from "@rivus/agent-kit-harness/spi"; +import { + claudeShapedFields, + claudeShapedHookOutput, + claudeShapedSecondsTimeout, + claudeShapedSessionId, + claudeShapedTurnId, + type HookDialect, + type HookOutput +} from "@rivus/agent-kit-harness/spi"; // https://code.claude.com/docs/en/hooks (events, input fields, exit codes, JSON output, timeouts) and // https://code.claude.com/docs/en/env-vars (CLAUDE_CODE_SESSION_ID). Hooks also live in a skills-dir plugin's @@ -10,13 +18,7 @@ import type { HookDialect, HookOutput } from "@rivus/agent-kit-harness/spi"; * and ends with `}`, otherwise plain text. Exit 2 blocks the events that can block. Any other code is a * non-blocking error. `{}` is valid output for every event, and for the agents that run these hooks too. */ -const OUTPUT: HookOutput = { - emptyStdout: "proceed", - invalidStdout: "proceed", - exitCode2: "block", - otherExitCodes: "hook-failed", - passThrough: "{}" -}; +const OUTPUT: HookOutput = { ...claudeShapedHookOutput }; export const claudeCodeHookDialect: HookDialect = { specificationVersion: "harness-v1", @@ -24,23 +26,16 @@ export const claudeCodeHookDialect: HookDialect = { delivery: "command", // Seconds; 600 for command hooks, 30 on UserPromptSubmit. All SessionEnd hooks share 1.5 s, raised to the // highest timeout in the settings files, at most 60 s. - timeout: { unit: "seconds", default: 600 }, + timeout: claudeShapedSecondsTimeout, // Interactive sessions hold back every settings hook until the folder's trust dialog is accepted; there is no // per-hook review. trust: { review: "workspace" }, output: OUTPUT, fields: { - event: { paths: [["hook_event_name"]] }, - sessionId: { paths: [["session_id"]], env: [CLAUDE_CODE_SESSION_ENV] }, - cwd: { paths: [["cwd"]] }, - transcriptPath: { paths: [["transcript_path"]] }, + ...claudeShapedFields, + sessionId: claudeShapedSessionId([CLAUDE_CODE_SESSION_ENV]), // The user prompt being processed, absent until the first input; it is the turn. - turnId: { paths: [["prompt_id"]] }, - // agent_type alone also appears on a main session started with --agent; agent_id only inside a subagent. - subagentId: { paths: [["agent_id"]] }, - subagentType: { paths: [["agent_type"]] }, - toolName: { paths: [["tool_name"]] }, - toolCallId: { paths: [["tool_use_id"]] } + turnId: claudeShapedTurnId() }, events: { SessionStart: { diff --git a/packages/providers/claude-code/test/fixtures/hooks.ts b/packages/providers/claude-code/test/fixtures/hooks.ts index cf6d6685..a9ffd265 100644 --- a/packages/providers/claude-code/test/fixtures/hooks.ts +++ b/packages/providers/claude-code/test/fixtures/hooks.ts @@ -1,6 +1,5 @@ -import type { LifecycleEvent } from "@rivus/agent-kit-harness/public/events"; -import type { HookDialectSample } from "@rivus/agent-kit-testing/public"; +import { hookSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Scrubbed Claude Code hook payloads (https://code.claude.com/docs/en/hooks), one or more per event. @@ -19,22 +18,15 @@ const identity = { turnId: common.prompt_id } as const; -function sample( - name: string, - event: string, - extra: Record, - expected: Omit -): HookDialectSample { - return { - name, - payload: { ...common, hook_event_name: event, ...extra }, - expected: { ...identity, nativeEvent: event, ...expected } - }; -} const bash = { tool_name: "Bash", tool_input: { command: "npm test", description: "Run tests" } }; const inSubagent = { agent_id: "a91c", agent_type: "Explore" }; +const sample = hookSampleFactory({ + payload: common, + expected: identity +}); + export const claudeCodeSamples: readonly HookDialectSample[] = [ { name: "SessionStart before the first prompt has no prompt id", diff --git a/packages/providers/codex/src/hooks.ts b/packages/providers/codex/src/hooks.ts index 8655e22a..cfa0a938 100644 --- a/packages/providers/codex/src/hooks.ts +++ b/packages/providers/codex/src/hooks.ts @@ -1,5 +1,13 @@ import { CODEX_ID } from "./facts.js"; -import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi"; +import { + claudeShapedFields, + claudeShapedHookOutput, + claudeShapedSessionStartLifecycle, + claudeShapedSecondsTimeout, + claudeShapedTurnId, + type HookDialect, + type HookOutput +} from "@rivus/agent-kit-harness/spi"; // https://developers.openai.com/codex/hooks (redirects to https://learn.chatgpt.com/docs/hooks): events, input and // output fields, exit codes, trust. Plugin-bundled hooks: https://developers.openai.com/plugins/build/plugins. @@ -15,11 +23,8 @@ const COMMON_FIELDS = ["continue", "stopReason", "systemMessage", "suppressOutpu * fields an event accepts, and what plain text does, differ per event. */ const OUTPUT: HookOutput = { - emptyStdout: "proceed", - invalidStdout: "hook-failed", - exitCode2: "block", - otherExitCodes: "hook-failed", - passThrough: "{}" + ...claudeShapedHookOutput, + invalidStdout: "hook-failed" }; /** Plain text on stdout becomes developer context here, so an observer prints nothing. */ @@ -30,31 +35,20 @@ export const codexHookDialect: HookDialect = { agent: CODEX_ID, delivery: "command", // Seconds, default 600, at least 1. SessionEnd and Interrupt default to 1 s and are clamped to 1–3 s. - timeout: { unit: "seconds", default: 600 }, + timeout: claudeShapedSecondsTimeout, // Trust is recorded against a hash of the normalized hook definition (event, matcher, handler with its command // and timeout), so changing the command asks again; the script it points to is not hashed. trust: { review: "content-hash" }, output: OUTPUT, fields: { - event: { paths: [["hook_event_name"]] }, // Subagent hooks get the parent's session id. Codex sets no session variable for hooks. - sessionId: { paths: [["session_id"]] }, - cwd: { paths: [["cwd"]] }, - transcriptPath: { paths: [["transcript_path"]] }, + ...claudeShapedFields, // On every turn-scoped event; a time-ordered UUIDv7 in the source, opaque per the docs. - turnId: { paths: [["turn_id"]] }, - subagentId: { paths: [["agent_id"]] }, - subagentType: { paths: [["agent_type"]] }, - toolName: { paths: [["tool_name"]] }, - toolCallId: { paths: [["tool_use_id"]] } + turnId: claudeShapedTurnId("turn_id") }, events: { SessionStart: { - lifecycle: { - field: ["source"], - cases: { compact: { phase: "activity" } }, - otherwise: { phase: "start", scope: "session" } - }, + lifecycle: claudeShapedSessionStartLifecycle, output: { ...CONTEXT_OUTPUT, fields: [...COMMON_FIELDS, "hookSpecificOutput"] } }, UserPromptSubmit: { diff --git a/packages/providers/cursor/test/fixtures/hooks.ts b/packages/providers/cursor/test/fixtures/hooks.ts index 7d9104f5..4e2548bc 100644 --- a/packages/providers/cursor/test/fixtures/hooks.ts +++ b/packages/providers/cursor/test/fixtures/hooks.ts @@ -1,4 +1,4 @@ -import type { HookDialectSample } from "@rivus/agent-kit-testing/public"; +import { hookSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Scrubbed Cursor hook payloads (https://cursor.com/docs/hooks), one or more per event. @@ -19,22 +19,15 @@ const identity = { transcriptPath: common.transcript_path } as const; -function sample( - name: string, - event: string, - extra: Record, - expected: Omit -): HookDialectSample { - return { - name, - payload: { ...common, hook_event_name: event, ...extra }, - expected: { ...identity, nativeEvent: event, ...expected } - }; -} const shell = { command: "npm test", cwd: "/u/me/work/app", sandbox: false }; const tool = { tool_name: "Shell", tool_input: { command: "npm test" }, tool_use_id: "tool-1" }; +const sample = hookSampleFactory({ + payload: common, + expected: identity +}); + export const cursorSamples: readonly HookDialectSample[] = [ sample( "sessionStart", diff --git a/packages/providers/dim/src/hooks.ts b/packages/providers/dim/src/hooks.ts index c29519e6..9905bb2e 100644 --- a/packages/providers/dim/src/hooks.ts +++ b/packages/providers/dim/src/hooks.ts @@ -1,5 +1,12 @@ import { DIM_ID } from "./facts.js"; -import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi"; +import { + claudeShapedField, + claudeShapedHookOutput, + claudeShapedPermissionFields, + claudeShapedSessionStartLifecycle, + type HookDialect, + type HookOutput +} from "@rivus/agent-kit-harness/spi"; // Hook facts from the CLI itself (0.5.27): `hooks.json` in the data root or project `.dimcode/` holds the Claude // Code grouped shape under a `hooks` key, the command events are the ten SUPPORTED_COMMAND_HOOK_EVENTS, the stdin @@ -7,11 +14,8 @@ import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi" // code 2 blocks (BLOCK_EXIT_CODE). Hooks must be trusted through `dim hooks`, which reviews the file's content. const OUTPUT: HookOutput = { - emptyStdout: "proceed", - invalidStdout: "proceed", - exitCode2: "block", + ...claudeShapedHookOutput, otherExitCodes: "proceed", - passThrough: "{}", unverified: "what stdout JSON the CLI accepts, and what other exit codes do, is not documented" }; @@ -25,26 +29,20 @@ export const dimHookDialect: HookDialect = { trust: { review: "content-hash" }, output: OUTPUT, fields: { - event: { paths: [["hook_event_name"]] }, - sessionId: { paths: [["session_id"]] }, - cwd: { paths: [["cwd"]] }, - transcriptPath: { paths: [["transcript_path"]] } + event: claudeShapedField("hook_event_name"), + sessionId: claudeShapedField("session_id"), + cwd: claudeShapedField("cwd"), + transcriptPath: claudeShapedField("transcript_path") // The per-event tool fields are not documented; the guide's matcher subjects (tool, agenttype, trigger, // toolcall) say the payload names them, so they are mapped once a capture confirms the keys. }, events: { - SessionStart: { - lifecycle: { - field: ["source"], - cases: { compact: { phase: "activity" } }, - otherwise: { phase: "start", scope: "session" } - } - }, + SessionStart: { lifecycle: claudeShapedSessionStartLifecycle }, UserPromptSubmit: { lifecycle: { phase: "start", scope: "turn" } }, PreToolUse: { lifecycle: { phase: "activity" }, gate: true, - output: { ...OUTPUT, fields: ["continue", "stopReason", "systemMessage", "hookSpecificOutput"] } + output: { ...OUTPUT, fields: claudeShapedPermissionFields } }, PermissionRequest: { lifecycle: { phase: "blocked", blocker: "permission" } }, PostToolUse: { lifecycle: { phase: "activity" } }, diff --git a/packages/providers/gemini-cli/test/fixtures/hooks.ts b/packages/providers/gemini-cli/test/fixtures/hooks.ts index f98998d7..23476ce1 100644 --- a/packages/providers/gemini-cli/test/fixtures/hooks.ts +++ b/packages/providers/gemini-cli/test/fixtures/hooks.ts @@ -1,6 +1,5 @@ -import type { LifecycleEvent } from "@rivus/agent-kit-harness/public/events"; -import type { HookDialectSample } from "@rivus/agent-kit-testing/public"; +import { hookSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Scrubbed Gemini CLI hook payloads (docs/hooks/reference.md in google-gemini/gemini-cli), one per event. @@ -17,22 +16,15 @@ const identity = { cwd: common.cwd } as const; -function sample( - name: string, - event: string, - extra: Record, - expected: Omit -): HookDialectSample { - return { - name, - payload: { ...common, hook_event_name: event, ...extra }, - expected: { ...identity, nativeEvent: event, ...expected } - }; -} const shell = { tool_name: "run_shell_command", tool_input: { command: "npm test" } }; const request = { llm_request: { model: "gemini-3-pro", messages: [] } }; +const sample = hookSampleFactory({ + payload: common, + expected: identity +}); + export const geminiCliSamples: readonly HookDialectSample[] = [ sample("SessionStart", "SessionStart", { source: "startup" }, { phase: "start", scope: "session" }), sample("BeforeAgent", "BeforeAgent", { prompt: "explain this file" }, { phase: "start", scope: "turn" }), diff --git a/packages/providers/grok/src/hooks.ts b/packages/providers/grok/src/hooks.ts index ddb9e8bc..4c4cc193 100644 --- a/packages/providers/grok/src/hooks.ts +++ b/packages/providers/grok/src/hooks.ts @@ -8,7 +8,7 @@ import { GROK_ID, GROK_SESSION_ENV } from "./facts.js"; -import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi"; +import { claudeShapedHookOutput, type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi"; // https://docs.x.ai/build/features/hooks and the fuller user guide in the source, // https://github.com/xai-org/grok-build/blob/2bdd1d6/crates/codegen/xai-grok-pager/docs/user-guide/10-hooks.md @@ -16,13 +16,7 @@ import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi" // src/discovery.rs (which files load). /** Observe-only events ignore stdout; failures, timeouts and malformed output fail open. */ -const OUTPUT: HookOutput = { - emptyStdout: "proceed", - invalidStdout: "proceed", - exitCode2: "block", - otherExitCodes: "hook-failed", - passThrough: "{}" -}; +const OUTPUT: HookOutput = { ...claudeShapedHookOutput }; const camel = (name: string) => name.charAt(0).toLowerCase() + name.slice(1); diff --git a/packages/providers/kimi/src/hooks.ts b/packages/providers/kimi/src/hooks.ts index e0295078..3b50e41f 100644 --- a/packages/providers/kimi/src/hooks.ts +++ b/packages/providers/kimi/src/hooks.ts @@ -1,22 +1,28 @@ import { KIMI_CLIENT_TYPE_FIELD, KIMI_ID } from "./facts.js"; -import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi"; +import { + claudeShapedFields, + claudeShapedGateFields, + claudeShapedHookOutput, + claudeShapedSessionStartLifecycle, + claudeShapedTurnId, + withPlainStdoutContext, + type HookDialect, + type HookOutput +} from "@rivus/agent-kit-harness/spi"; // https://www.kimi.com/code/docs/en/kimi-code-cli/customization/hooks.html (events, payload, exit codes, timeouts). // The payload is Claude Code-shaped (snake_case fields on stdin); exit 0 allows, 2 blocks the blockable events, and // every other outcome fails open — the CLI logs a failed hook and moves on. const OUTPUT: HookOutput = { - emptyStdout: "proceed", - invalidStdout: "proceed", - exitCode2: "block", + ...claudeShapedHookOutput, // Fail-open: a script that errors, times out or exits with another code never blocks. otherExitCodes: "proceed", - passThrough: "{}", unverified: "whether stdout JSON the event does not accept keeps the flow unchanged is not documented" }; /** Events whose stdout may become context, per the guide's allow-continues-with-stdout rule. */ -const OUTPUT_WITH_CONTEXT: HookOutput = { ...OUTPUT, plainStdout: "context" }; +const OUTPUT_WITH_CONTEXT: HookOutput = withPlainStdoutContext(OUTPUT); export const kimiHookDialect: HookDialect = { specificationVersion: "harness-v1", @@ -27,24 +33,10 @@ export const kimiHookDialect: HookDialect = { timeout: { unit: "seconds", default: 30 }, // Hook rules live only in the user config and local plugins, which the CLI runs without a review prompt. output: OUTPUT, - fields: { - event: { paths: [["hook_event_name"]] }, - sessionId: { paths: [["session_id"]] }, - turnId: { paths: [["turn_id"]] }, - cwd: { paths: [["cwd"]] }, - transcriptPath: { paths: [["transcript_path"]] }, - toolName: { paths: [["tool_name"]] }, - toolCallId: { paths: [["tool_use_id"]] }, - subagentId: { paths: [["agent_id"]] }, - subagentType: { paths: [["agent_type"]] } - }, + fields: { ...claudeShapedFields, turnId: claudeShapedTurnId("turn_id") }, events: { SessionStart: { - lifecycle: { - field: ["source"], - cases: { compact: { phase: "activity" } }, - otherwise: { phase: "start", scope: "session" } - }, + lifecycle: claudeShapedSessionStartLifecycle, output: OUTPUT_WITH_CONTEXT }, // A message queued while a turn runs; the payload carries prompt_id and prompt. @@ -55,18 +47,7 @@ export const kimiHookDialect: HookDialect = { PreToolUse: { lifecycle: { phase: "activity" }, gate: true, - output: { - ...OUTPUT, - fields: [ - "continue", - "stopReason", - "suppressOutput", - "systemMessage", - "hookSpecificOutput", - "decision", - "reason" - ] - } + output: { ...OUTPUT, fields: claudeShapedGateFields } }, PostToolUse: { lifecycle: { phase: "activity" } }, PostToolUseFailure: { lifecycle: { phase: "activity" } }, diff --git a/packages/providers/kimi/test/fixtures/hooks.ts b/packages/providers/kimi/test/fixtures/hooks.ts index a20dc6c9..5dbe80f9 100644 --- a/packages/providers/kimi/test/fixtures/hooks.ts +++ b/packages/providers/kimi/test/fixtures/hooks.ts @@ -1,6 +1,4 @@ -import type { LifecycleEvent } from "@rivus/agent-kit-harness/public/events"; - -import type { HookDialectSample } from "@rivus/agent-kit-testing/public"; +import { hookEventSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Synthetic Kimi Code hook payloads (customization/hooks.html), passed on stdin as JSON: the base fields every event // carries, plus the per-event ones the guide documents. @@ -9,17 +7,11 @@ const sessionId = "session_abc123"; const cwd = "/u/me/work"; const identity = { agent: "kimi", sessionId, cwd } as const; -function sample( - event: string, - fields: Record, - expected: Omit -): HookDialectSample { - return { - name: event, - payload: { hook_event_name: event, session_id: sessionId, session_title: "Fix the login page", client_type: "kimi_code_cli", cwd, ...fields }, - expected: { ...identity, nativeEvent: event, ...expected } - }; -} + +const sample = hookEventSampleFactory({ + payload: { hook_event_name: "", session_id: sessionId, session_title: "Fix the login page", client_type: "kimi_code_cli", cwd }, + expected: identity +}); export const kimiSamples: readonly HookDialectSample[] = [ sample("SessionStart", { source: "startup", model: "kimi-for-coding" }, { phase: "start", scope: "session" }), diff --git a/packages/providers/opencode/src/usage.ts b/packages/providers/opencode/src/usage.ts index 7ae3ce99..857622a0 100644 --- a/packages/providers/opencode/src/usage.ts +++ b/packages/providers/opencode/src/usage.ts @@ -26,6 +26,7 @@ import { type UsageRecord, type UsageSource, type UsageSourceFailure, + usageWindowKey, type UsageStream } from "@rivus/agent-kit-sessions/spi"; import { @@ -122,11 +123,6 @@ export function opencodeMessageUsage(value: unknown, row: SqliteMessageRow): Usa return record; } -/** The key under which a scan counts a record once in its window: the session and the message id. */ -function opencodeUsageKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} - /** A message runs far shorter than this, so a row created this long before `since` holds no record to keep. */ export const LONGEST_MESSAGE_MS: number = SQLITE_LONGEST_MESSAGE_MS; @@ -271,7 +267,7 @@ function decodeLegacySession(platform: UsagePlatform, dir: string, options: Deco export const opencodeUsageDecoder: UsageDecoder = { specificationVersion: "usage-v1", agent: AGENT, - usageKey: opencodeUsageKey, + usageKey: usageWindowKey, async *sources(platform, home, options = {}) { const { since, signal } = options; signal?.throwIfAborted(); diff --git a/packages/providers/qoder/src/hooks.ts b/packages/providers/qoder/src/hooks.ts index 7fb5c174..1300774b 100644 --- a/packages/providers/qoder/src/hooks.ts +++ b/packages/providers/qoder/src/hooks.ts @@ -1,5 +1,15 @@ import { QODER_ID } from "./facts.js"; -import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi"; +import { + claudeShapedFields, + claudeShapedGateFields, + claudeShapedHookOutput, + claudeShapedPermissionFields, + claudeShapedSecondsTimeout, + claudeShapedSessionStartLifecycle, + withPlainStdoutContext, + type HookDialect, + type HookOutput +} from "@rivus/agent-kit-harness/spi"; // Hook facts from the agent SDK's protocol types (npm `@qoder-ai/qoder-agent-sdk`, dist/types/hooks.d.ts): the // Claude-Code-shaped snake_case payload (`hook_event_name`, `session_id`, `cwd`, `transcript_path`, `tool_name`, @@ -7,40 +17,23 @@ import { type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi" // the SDK's event list. Exit-code semantics follow Claude Code's, which the CLI's hooks migrate command targets. const OUTPUT: HookOutput = { - emptyStdout: "proceed", - invalidStdout: "proceed", - exitCode2: "block", - otherExitCodes: "hook-failed", - passThrough: "{}", + ...claudeShapedHookOutput, unverified: "the CLI's exit-code table is not published; these follow the Claude Code shapes it migrates from" }; -const OUTPUT_WITH_CONTEXT: HookOutput = { ...OUTPUT, plainStdout: "context" }; +const OUTPUT_WITH_CONTEXT: HookOutput = withPlainStdoutContext(OUTPUT); export const qoderHookDialect: HookDialect = { specificationVersion: "harness-v1", agent: QODER_ID, delivery: "command", // Seconds, as Claude Code's settings carry them. - timeout: { unit: "seconds", default: 600 }, + timeout: claudeShapedSecondsTimeout, output: OUTPUT, - fields: { - event: { paths: [["hook_event_name"]] }, - sessionId: { paths: [["session_id"]] }, - cwd: { paths: [["cwd"]] }, - transcriptPath: { paths: [["transcript_path"]] }, - toolName: { paths: [["tool_name"]] }, - toolCallId: { paths: [["tool_use_id"]] }, - subagentId: { paths: [["agent_id"]] }, - subagentType: { paths: [["agent_type"]] } - }, + fields: { ...claudeShapedFields }, events: { SessionStart: { - lifecycle: { - field: ["source"], - cases: { compact: { phase: "activity" } }, - otherwise: { phase: "start", scope: "session" } - }, + lifecycle: claudeShapedSessionStartLifecycle, output: OUTPUT_WITH_CONTEXT }, SessionEnd: { lifecycle: { phase: "finish", scope: "session" } }, @@ -48,27 +41,12 @@ export const qoderHookDialect: HookDialect = { PreToolUse: { lifecycle: { phase: "activity" }, gate: true, - output: { - ...OUTPUT, - fields: [ - "continue", - "stopReason", - "suppressOutput", - "systemMessage", - "hookSpecificOutput", - "decision", - "reason" - ] - } + output: { ...OUTPUT, fields: claudeShapedGateFields } }, PermissionRequest: { lifecycle: { phase: "blocked", blocker: "permission" }, gate: true, - output: { - ...OUTPUT, - exitCode2: "proceed", - fields: ["continue", "stopReason", "systemMessage", "hookSpecificOutput"] - } + output: { ...OUTPUT, exitCode2: "proceed", fields: claudeShapedPermissionFields } }, PermissionDenied: { lifecycle: { phase: "activity" } }, PostToolUse: { lifecycle: { phase: "activity" } }, diff --git a/packages/providers/qoder/test/fixtures/hooks.ts b/packages/providers/qoder/test/fixtures/hooks.ts index 5d7b7631..c5790334 100644 --- a/packages/providers/qoder/test/fixtures/hooks.ts +++ b/packages/providers/qoder/test/fixtures/hooks.ts @@ -1,6 +1,5 @@ -import type { LifecycleEvent } from "@rivus/agent-kit-harness/public/events"; -import type { HookDialectSample } from "@rivus/agent-kit-testing/public"; +import { hookEventSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Synthetic Qoder CLI hook payloads, per the agent SDK's protocol hook types: the Claude-Code-shaped snake_case base // fields, plus the per-event fields the SDK types name. @@ -10,20 +9,14 @@ const cwd = "/u/me/work"; const transcriptPath = `${cwd}/.qoder/t.jsonl`; const identity = { agent: "qoder", sessionId, cwd, transcriptPath } as const; -function sample( - event: string, - fields: Record, - expected: Omit -): HookDialectSample { - return { - name: event, - payload: { hook_event_name: event, session_id: sessionId, cwd, transcript_path: transcriptPath, ...fields }, - expected: { ...identity, nativeEvent: event, ...expected } - }; -} const tool = { tool_name: "Bash", tool_use_id: "tc_3", tool_input: { command: "ls" } }; +const sample = hookEventSampleFactory({ + payload: { hook_event_name: "", session_id: sessionId, cwd, transcript_path: transcriptPath }, + expected: identity +}); + export const qoderSamples: readonly HookDialectSample[] = [ sample("SessionStart", { source: "startup" }, { phase: "start", scope: "session" }), sample("SessionStart", { source: "compact" }, { phase: "activity" }), diff --git a/packages/providers/zcode/src/usage.ts b/packages/providers/zcode/src/usage.ts index 4b898e77..cc6537ff 100644 --- a/packages/providers/zcode/src/usage.ts +++ b/packages/providers/zcode/src/usage.ts @@ -20,6 +20,7 @@ import { type UsageRecord, type UsageSource, type UsageSourceFailure, + usageWindowKey, type UsageStream } from "@rivus/agent-kit-sessions/spi"; import { ZCODE_ID as AGENT, ZCODE_WAL_SUFFIX } from "./facts.js"; @@ -120,11 +121,6 @@ export function zcodeMessageUsage(value: unknown, row: SqliteMessageRow): UsageR return record; } -/** The key under which a scan counts a record once in its window: the session and the message id. */ -function zcodeUsageKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} - /** A message runs far shorter than this, so a row created this long before `since` holds no record to keep. */ export const LONGEST_MESSAGE_MS: number = SQLITE_LONGEST_MESSAGE_MS; @@ -185,7 +181,7 @@ function decodeDatabase(platform: UsagePlatform, path: string, options: DecodeUs export const zcodeUsageDecoder: UsageDecoder = { specificationVersion: "usage-v1", agent: AGENT, - usageKey: zcodeUsageKey, + usageKey: usageWindowKey, async *sources(platform, home, options = {}) { const { since, signal } = options; signal?.throwIfAborted(); diff --git a/packages/sessions/src/spi.ts b/packages/sessions/src/spi.ts index 95d9736e..bf5e8830 100644 --- a/packages/sessions/src/spi.ts +++ b/packages/sessions/src/spi.ts @@ -164,4 +164,13 @@ export { decodeIsFinal } from "./domain/usage/services/quiet.js"; export { shortHash } from "./lib/short-hash.js"; export { type UsageCursor } from "./domain/usage/value-objects/usage-cursor.js"; export { type ModelUsage, type UsageRecord } from "./domain/usage/value-objects/usage-record.js"; -export { type Usage, compactUsage } from "./domain/usage/value-objects/usage.js"; +import type { UsageRecord } from "./domain/usage/value-objects/usage-record.js"; + +/** + * The key under which a usage scan counts a record once in its window: the + * session and the request id, when the record carries one. + */ +export function usageWindowKey(record: UsageRecord): string | undefined { + return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; +} +export { type Usage, compactUsage } from "./domain/usage/value-objects/usage.js"; \ No newline at end of file diff --git a/packages/testing/src/hook-dialect-conformance.ts b/packages/testing/src/hook-dialect-conformance.ts index 86130a43..95fa9092 100644 --- a/packages/testing/src/hook-dialect-conformance.ts +++ b/packages/testing/src/hook-dialect-conformance.ts @@ -27,6 +27,52 @@ export interface HookDialectFixtures { readonly samples: readonly HookDialectSample[]; } +/** + * The scrubbed base fields and identity every sample of one agent shares. The base's `expected` carries the + * identity fields; per-event fields (the phase onward) come from each sample. + */ +export interface HookSampleBase { + readonly payload: Readonly>; + readonly expected: Partial>; +} + +/** + * The sample builder every agent's hook fixtures share: the agent's base payload and identity are + * captured once, and each sample names its event and the per-event fields. + */ +export function hookSampleFactory(base: { + readonly payload: Readonly>; + readonly expected: Partial>; +}): ( + name: string, + event: string, + fields: Readonly>, + expected: Omit +) => HookDialectSample { + return (name, event, fields, expected) => + ({ + name, + payload: { ...base.payload, hook_event_name: event, ...fields }, + expected: { ...base.expected, nativeEvent: event, ...expected } + }) as HookDialectSample; +} + +/** + * The sample builder for agents whose samples are named by their event: the + * name is the wire event, so each call is `(event, fields, expected)`. + */ +export function hookEventSampleFactory(base: { + readonly payload: Readonly>; + readonly expected: Partial>; +}): ( + event: string, + fields?: Readonly>, + expected?: Partial> +) => HookDialectSample { + const byName = hookSampleFactory(base); + return (event, fields = {}, expected = {}) => byName(event, event, fields, expected as never); +} + const PHASES = new Set(["start", "activity", "blocked", "finish", "unknown"]); const SCOPES = new Set(["session", "turn"]); const OUTCOMES = new Set(["completed", "failed", "cancelled"]); diff --git a/packages/testing/src/public.ts b/packages/testing/src/public.ts index 4032b9e1..20487765 100644 --- a/packages/testing/src/public.ts +++ b/packages/testing/src/public.ts @@ -1,6 +1,8 @@ export { type HookDialectFixtures, hookDialectConformance, + hookEventSampleFactory, + hookSampleFactory, type HookDialectSample } from "./hook-dialect-conformance.js"; export { From ae77d8bb04f1aee3b393c1dc2f630e7b0ec7ece2 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:13:55 +0800 Subject: [PATCH 2/7] style: format the sessions spi --- packages/sessions/src/spi.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/sessions/src/spi.ts b/packages/sessions/src/spi.ts index bf5e8830..49ca39d4 100644 --- a/packages/sessions/src/spi.ts +++ b/packages/sessions/src/spi.ts @@ -173,4 +173,4 @@ import type { UsageRecord } from "./domain/usage/value-objects/usage-record.js"; export function usageWindowKey(record: UsageRecord): string | undefined { return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; } -export { type Usage, compactUsage } from "./domain/usage/value-objects/usage.js"; \ No newline at end of file +export { type Usage, compactUsage } from "./domain/usage/value-objects/usage.js"; From ea168e8f0ba65c152d74f90f1088eece77c2e4a5 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:18:41 +0800 Subject: [PATCH 3/7] style: format the provider packages --- packages/providers/cursor/test/fixtures/hooks.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/providers/cursor/test/fixtures/hooks.ts b/packages/providers/cursor/test/fixtures/hooks.ts index 4e2548bc..32a5dfaf 100644 --- a/packages/providers/cursor/test/fixtures/hooks.ts +++ b/packages/providers/cursor/test/fixtures/hooks.ts @@ -19,7 +19,6 @@ const identity = { transcriptPath: common.transcript_path } as const; - const shell = { command: "npm test", cwd: "/u/me/work/app", sandbox: false }; const tool = { tool_name: "Shell", tool_input: { command: "npm test" }, tool_use_id: "tool-1" }; From 753190fbfd30dfbcbc1c47e0b4a2637887c8057c Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:41:52 +0800 Subject: [PATCH 4/7] refactor: drop the knip export/type/duplicates staging knip runs without exclude: ['exports', 'types', 'duplicates']: - 29 dead declarations are gone (dead wrappers, schemas and dead functions the conformance migrations left behind); 93 internally-used exports lost their export keyword - the two dynamic-read surfaces stay exported with @public tags: the facts.ts constants (the architecture checker reads agentMarkers and its same-file const references by name) and the hook factories exported by the harness spi - the CODEX_ID/CODEX_COMMAND duplicate is resolved: its consumers use CODEX_ID, since the command name equals the agent id by definition - the two GateRings in sub-lane draw through a plain ring() helper; the LayerRule interface is file-internal now The 119 remaining duplicates are the per-provider install/sessions/events/ usage mirrors the issue tracks for the follow-up slices. --- apps/website-api/src/api-markdown.ts | 4 +-- apps/website/src/features/demo/snippets.ts | 6 ++-- apps/website/src/features/docs/guide-paths.ts | 2 +- .../website/src/features/layer/layer-paths.ts | 2 +- infra/architecture/boundaries.ts | 2 +- knip.ts | 5 ++- packages/acp/src/application/services/wire.ts | 4 +-- .../acp-session/events/acp-session-events.ts | 8 ++--- packages/acp/test/support.ts | 2 +- .../application/use-cases/create-lanes.ts | 6 ++-- .../lanes/domain/lane/events/lane-events.ts | 12 +++---- .../lane/value-objects/lane-snapshot.ts | 2 +- .../application/use-cases/lease-manager.ts | 2 +- .../lease/domain/lease/events/lease-events.ts | 6 ++-- .../agent-kit-collab/test/support/workers.ts | 2 +- packages/agent-kit/src/providers/acp.ts | 2 +- packages/agent-kit/src/providers/discovery.ts | 2 +- packages/agent-kit/src/providers/identity.ts | 2 +- packages/agent-kit/src/providers/install.ts | 2 +- packages/agent-kit/src/providers/sessions.ts | 2 +- .../src/application/services/host-paths.ts | 2 +- .../src/application/services/run-probe.ts | 2 +- .../application/services/ledger-session.ts | 2 +- .../src/application/use-cases/plan-install.ts | 2 +- .../factories/plan-evidence-scope.ts | 2 +- .../install-plan/services/legacy-ownership.ts | 2 +- .../services/registration-commands.ts | 2 +- .../src/infra/services/config-entries.ts | 2 +- .../harness/src/infra/services/read-text.ts | 2 +- packages/harness/test/support/workers.ts | 2 +- packages/providers/claude-code/src/facts.ts | 31 ++++++++++++++++ .../claude-code/src/records/record.ts | 2 +- packages/providers/codex/src/discovery.ts | 3 +- packages/providers/codex/src/facts.ts | 29 ++++++++++++++- packages/providers/codex/src/install.ts | 11 +++--- .../providers/codex/src/records/record.ts | 19 +++------- packages/providers/codex/src/records/usage.ts | 9 ++--- .../codex/src/sessions/translation.ts | 8 ++--- packages/providers/cursor/src/facts.ts | 19 +++++++++- packages/providers/dim/src/facts.ts | 22 ++++++++++++ packages/providers/dim/src/layout.ts | 3 -- packages/providers/dsh/src/facts.ts | 12 +++++++ packages/providers/dsh/src/layout.ts | 2 +- packages/providers/dsh/src/records.ts | 17 +-------- packages/providers/dsh/src/records/zstd.ts | 4 +-- packages/providers/gemini-cli/src/facts.ts | 24 +++++++++++++ packages/providers/gemini-cli/test/support.ts | 5 --- packages/providers/grok/src/facts.ts | 30 ++++++++++++++++ packages/providers/grok/src/records.ts | 4 +-- .../grok/src/sessions/translation.ts | 6 ++-- packages/providers/kimi/src/facts.ts | 23 ++++++++++++ packages/providers/kimi/src/records.ts | 33 ++--------------- .../providers/kimi/src/sessions/events.ts | 3 +- packages/providers/opencode/src/facts.ts | 18 ++++++++++ packages/providers/pi/src/facts.ts | 16 +++++++++ packages/providers/pi/src/records.ts | 36 ++----------------- packages/providers/qoder/src/facts.ts | 17 +++++++++ packages/providers/zcode/src/facts.ts | 18 ++++++++++ packages/providers/zcode/src/layout.ts | 4 +-- .../src/application/services/files/edges.ts | 2 +- packages/sessions/src/application/spi.ts | 3 -- .../src/application/use-cases/scan-usage.ts | 2 +- .../transcript/services/fold-transcript.ts | 6 ++-- .../value-objects/source-pointer.ts | 2 +- .../testing/src/hook-dialect-conformance.ts | 9 ----- packages/testing/src/ledger-fixture.ts | 4 +-- packages/testing/test/memory-support.ts | 2 +- packages/testing/test/support.ts | 10 +----- scripts/lib/litellm-snapshot.ts | 2 +- 69 files changed, 350 insertions(+), 215 deletions(-) diff --git a/apps/website-api/src/api-markdown.ts b/apps/website-api/src/api-markdown.ts index 3e22bc75..0d4a6e4e 100644 --- a/apps/website-api/src/api-markdown.ts +++ b/apps/website-api/src/api-markdown.ts @@ -1,5 +1,5 @@ /** Frontmatter descriptions render as plain text, so a code mark would show as a character. */ -export function plainDescription(description: string): string { +function plainDescription(description: string): string { return description.replaceAll("`", ""); } @@ -27,7 +27,7 @@ export function rewriteApiLinks(markdown: string): string { }); } -export interface IndexEntry { +interface IndexEntry { readonly specifier: string; readonly slug: string; readonly blurb: string; diff --git a/apps/website/src/features/demo/snippets.ts b/apps/website/src/features/demo/snippets.ts index 5390477f..c677e48e 100644 --- a/apps/website/src/features/demo/snippets.ts +++ b/apps/website/src/features/demo/snippets.ts @@ -18,7 +18,7 @@ export interface Token { readonly swap?: boolean; } -export interface DemoAgent { +interface DemoAgent { readonly id: string; readonly mine: boolean; readonly enabled: boolean; @@ -112,7 +112,7 @@ export function taskLabel(task: TaskKey): CopyKey { return taskSpec(task).label; } -export function agentSupports(row: SupportRow, task: TaskKey): boolean { +function agentSupports(row: SupportRow, task: TaskKey): boolean { const capability = taskSpec(task).capability; if (capability === null) { return true; @@ -120,7 +120,7 @@ export function agentSupports(row: SupportRow, task: TaskKey): boolean { return row[capability]; } -export function isSelectable(agentId: string, task: TaskKey, rows: readonly SupportRow[]): boolean { +function isSelectable(agentId: string, task: TaskKey, rows: readonly SupportRow[]): boolean { if (agentId === MY_AGENT) { return true; } diff --git a/apps/website/src/features/docs/guide-paths.ts b/apps/website/src/features/docs/guide-paths.ts index 9978e2db..ab3cc59e 100644 --- a/apps/website/src/features/docs/guide-paths.ts +++ b/apps/website/src/features/docs/guide-paths.ts @@ -15,7 +15,7 @@ export const ENTRY_GUIDE_SLUG = { "/lanes": "coordination/lanes" } as const; -export type GuideEntry = keyof typeof ENTRY_GUIDE_SLUG; +type GuideEntry = keyof typeof ENTRY_GUIDE_SLUG; export function docsIndex(): "/docs" { return "/docs"; diff --git a/apps/website/src/features/layer/layer-paths.ts b/apps/website/src/features/layer/layer-paths.ts index e1508853..18e0028f 100644 --- a/apps/website/src/features/layer/layer-paths.ts +++ b/apps/website/src/features/layer/layer-paths.ts @@ -59,7 +59,7 @@ function isLayerFn(name: string): name is LayerFn { return (CONNECTION_FNS as readonly string[]).includes(name) || (COORDINATION_FNS as readonly string[]).includes(name); } -export function isCoordinationFn(name: LayerFn): boolean { +function isCoordinationFn(name: LayerFn): boolean { return (COORDINATION_FNS as readonly string[]).includes(name); } diff --git a/infra/architecture/boundaries.ts b/infra/architecture/boundaries.ts index a4a9bac0..0dbf3e68 100644 --- a/infra/architecture/boundaries.ts +++ b/infra/architecture/boundaries.ts @@ -55,7 +55,7 @@ export interface PackageRule { readonly publicImports?: Readonly>; } -export interface LayerRule { +interface LayerRule { /** Layers of the same package this layer may import. */ readonly layers: readonly Layer[]; /** diff --git a/knip.ts b/knip.ts index bd649027..1027da90 100644 --- a/knip.ts +++ b/knip.ts @@ -19,11 +19,10 @@ function sourceEntries( .map(sourcePath => `${sourcePath}!`); } -// The inline *.test.ts files are discovered by vitest. Unused exports/types are staged for a -// dedicated cleanup pass; configuration and tag hints still fail the run. +// The inline *.test.ts files are discovered by vitest. Configuration and tag hints fail the run. const config: KnipConfig = { ...knip, - exclude: ['exports', 'types', 'duplicates'], + // eslint-plugin-boundaries and oxlint-plugin-eslint are declared in infra/architecture and load // through withBoundaryLint in every package's vite.config.ts; eslint-import-resolver-typescript // is referenced by name inside the boundaries resolver options; @effect/language-service is a diff --git a/packages/acp/src/application/services/wire.ts b/packages/acp/src/application/services/wire.ts index 41a87a92..cf198940 100644 --- a/packages/acp/src/application/services/wire.ts +++ b/packages/acp/src/application/services/wire.ts @@ -67,14 +67,14 @@ export interface AgentInfo { readonly title?: string; } -export interface Handshake { +interface Handshake { readonly protocolVersion: number; readonly features: AgentFeatures; readonly authMethods: readonly AuthMethodInfo[]; readonly agentInfo?: AgentInfo; } -export interface SessionParams { +interface SessionParams { readonly cwd: string; readonly mcpServers: readonly McpServerConfig[]; readonly meta?: Record; diff --git a/packages/acp/src/domain/acp-session/events/acp-session-events.ts b/packages/acp/src/domain/acp-session/events/acp-session-events.ts index 7c31682c..2f1d637f 100644 --- a/packages/acp/src/domain/acp-session/events/acp-session-events.ts +++ b/packages/acp/src/domain/acp-session/events/acp-session-events.ts @@ -1,21 +1,21 @@ -export interface SessionOpened { +interface SessionOpened { readonly _tag: "SessionOpened"; readonly sessionId: string; } -export interface TurnStarted { +interface TurnStarted { readonly _tag: "TurnStarted"; readonly sessionId: string; readonly turn: number; } -export interface CancelRequested { +interface CancelRequested { readonly _tag: "CancelRequested"; readonly sessionId: string; readonly turn: number; } -export interface TurnFinished { +interface TurnFinished { readonly _tag: "TurnFinished"; readonly sessionId: string; readonly turn: number; diff --git a/packages/acp/test/support.ts b/packages/acp/test/support.ts index b471207f..b584e4bd 100644 --- a/packages/acp/test/support.ts +++ b/packages/acp/test/support.ts @@ -16,7 +16,7 @@ import { type PromptBlock } from "../src/public.js"; -export const FAKE_AGENT: string = fileURLToPath(new URL("fixtures/fake-agent.ts", import.meta.url)); +const FAKE_AGENT: string = fileURLToPath(new URL("fixtures/fake-agent.ts", import.meta.url)); /** The fake agent as a profile: Node runs the fixture, and the system prompt goes to `_meta.systemPrompt`. */ export function fakeProfile(overrides: Partial = {}): AcpProfile { diff --git a/packages/agent-kit-collab/src/lanes/application/use-cases/create-lanes.ts b/packages/agent-kit-collab/src/lanes/application/use-cases/create-lanes.ts index 0173e866..b45f805f 100644 --- a/packages/agent-kit-collab/src/lanes/application/use-cases/create-lanes.ts +++ b/packages/agent-kit-collab/src/lanes/application/use-cases/create-lanes.ts @@ -35,7 +35,7 @@ export interface LanesConfig { } /** Why the lanes interrupted an activation. */ -export type ActivationInterruptReason = "cancel" | "close" | "timeout"; +type ActivationInterruptReason = "cancel" | "close" | "timeout"; /** * How an activation ended. An activation that succeeded or failed by itself is reported so even when a cancel, close @@ -48,12 +48,12 @@ export type ActivationExit = | { readonly _tag: "ActivationInterrupted"; readonly key: string; readonly reason: ActivationInterruptReason }; /** `close` ran, or the Scope that created the lanes closed. */ -export interface LanesClosed { +interface LanesClosed { readonly _tag: "LanesClosed"; readonly key: string; } -export interface LanesStatus { +interface LanesStatus { readonly running: number; readonly queued: number; readonly closed: boolean; diff --git a/packages/agent-kit-collab/src/lanes/domain/lane/events/lane-events.ts b/packages/agent-kit-collab/src/lanes/domain/lane/events/lane-events.ts index 8151b097..4edd802c 100644 --- a/packages/agent-kit-collab/src/lanes/domain/lane/events/lane-events.ts +++ b/packages/agent-kit-collab/src/lanes/domain/lane/events/lane-events.ts @@ -1,33 +1,33 @@ /** The wake joined an activation that has not started yet: the queued one, or the one after the running one. */ -export interface WakeCoalesced { +interface WakeCoalesced { readonly _tag: "WakeCoalesced"; readonly key: string; } /** The lane joined the end of the queue to wait for a free slot. */ -export interface LaneQueued { +interface LaneQueued { readonly _tag: "LaneQueued"; readonly key: string; } /** The lane left the queue, because it got a slot or was cancelled. */ -export interface LaneDequeued { +interface LaneDequeued { readonly _tag: "LaneDequeued"; readonly key: string; } -export interface ActivationStarted { +interface ActivationStarted { readonly _tag: "ActivationStarted"; readonly key: string; } -export interface ActivationEnded { +interface ActivationEnded { readonly _tag: "ActivationEnded"; readonly key: string; } /** A cancel dropped the wake a running lane owed, so no activation follows the running one. */ -export interface PendingDropped { +interface PendingDropped { readonly _tag: "PendingDropped"; readonly key: string; } diff --git a/packages/agent-kit-collab/src/lanes/domain/lane/value-objects/lane-snapshot.ts b/packages/agent-kit-collab/src/lanes/domain/lane/value-objects/lane-snapshot.ts index f81c029a..0bc23060 100644 --- a/packages/agent-kit-collab/src/lanes/domain/lane/value-objects/lane-snapshot.ts +++ b/packages/agent-kit-collab/src/lanes/domain/lane/value-objects/lane-snapshot.ts @@ -2,7 +2,7 @@ * `idle`: nothing runs and nothing is owed. `queued`: woken while every slot was taken, waiting for one. `running`: one * activation runs. */ -export type LaneState = "idle" | "queued" | "running"; +type LaneState = "idle" | "queued" | "running"; export interface LaneSnapshot { readonly key: string; diff --git a/packages/agent-kit-collab/src/lease/application/use-cases/lease-manager.ts b/packages/agent-kit-collab/src/lease/application/use-cases/lease-manager.ts index 3ac3e4de..60cb30fb 100644 --- a/packages/agent-kit-collab/src/lease/application/use-cases/lease-manager.ts +++ b/packages/agent-kit-collab/src/lease/application/use-cases/lease-manager.ts @@ -31,7 +31,7 @@ export interface LeaseConfig { readonly retryMs?: number; } -export interface AcquireOptions { +interface AcquireOptions { /** * Keep trying every `retryMs` while the lease is held or the repository is busy (a guard that stays locked), * instead of failing with `LeaseHeld` or a `busy` `LeaseRepositoryFailure`. The wait ends when the lease is taken, diff --git a/packages/agent-kit-collab/src/lease/domain/lease/events/lease-events.ts b/packages/agent-kit-collab/src/lease/domain/lease/events/lease-events.ts index 8dab6fe5..b9bbb48f 100644 --- a/packages/agent-kit-collab/src/lease/domain/lease/events/lease-events.ts +++ b/packages/agent-kit-collab/src/lease/domain/lease/events/lease-events.ts @@ -1,4 +1,4 @@ -export interface LeaseAcquired { +interface LeaseAcquired { readonly _tag: "LeaseAcquired"; readonly key: string; readonly generation: number; @@ -7,14 +7,14 @@ export interface LeaseAcquired { readonly previousHolderId: string | null; } -export interface LeaseRenewed { +interface LeaseRenewed { readonly _tag: "LeaseRenewed"; readonly key: string; readonly generation: number; readonly revision: number; } -export interface LeaseReleased { +interface LeaseReleased { readonly _tag: "LeaseReleased"; readonly key: string; readonly generation: number; diff --git a/packages/agent-kit-collab/test/support/workers.ts b/packages/agent-kit-collab/test/support/workers.ts index 2efaa81f..dc186848 100644 --- a/packages/agent-kit-collab/test/support/workers.ts +++ b/packages/agent-kit-collab/test/support/workers.ts @@ -15,7 +15,7 @@ export const WORKER_TEST_TIMEOUT_MS = 30_000; const workerLine = z.looseObject({ event: z.string() }); /** One JSON line a worker printed. */ -export type WorkerLine = Readonly>; +type WorkerLine = Readonly>; export interface Worker { readonly pid: number; diff --git a/packages/agent-kit/src/providers/acp.ts b/packages/agent-kit/src/providers/acp.ts index 1cf8889d..a629605d 100644 --- a/packages/agent-kit/src/providers/acp.ts +++ b/packages/agent-kit/src/providers/acp.ts @@ -12,7 +12,7 @@ import { dimAcpProfile } from "@rivus/agent-kit-provider-dim/acp"; import { mergeService } from "./merge.js"; import type { Provider } from "./types.js"; -export const builtinAcpProfiles: AcpProfiles = { +const builtinAcpProfiles: AcpProfiles = { "claude-code": claudeCodeAcpProfile, codex: codexAcpProfile, dsh: dshAcpProfile, diff --git a/packages/agent-kit/src/providers/discovery.ts b/packages/agent-kit/src/providers/discovery.ts index a133c42b..18bb1b80 100644 --- a/packages/agent-kit/src/providers/discovery.ts +++ b/packages/agent-kit/src/providers/discovery.ts @@ -13,7 +13,7 @@ import { kimiProbe } from "@rivus/agent-kit-provider-kimi/discovery"; import { mergeService } from "./merge.js"; import type { Provider } from "./types.js"; -export const builtinProbeRecipes: { +const builtinProbeRecipes: { readonly codex: typeof codexProbe; readonly "claude-code": typeof claudeCodeProbe; readonly grok: typeof grokProbe; diff --git a/packages/agent-kit/src/providers/identity.ts b/packages/agent-kit/src/providers/identity.ts index cb9e5682..78d2df9c 100644 --- a/packages/agent-kit/src/providers/identity.ts +++ b/packages/agent-kit/src/providers/identity.ts @@ -14,7 +14,7 @@ import { dim } from "@rivus/agent-kit-provider-dim/identity"; import { mergeService } from "./merge.js"; import type { Provider } from "./types.js"; -export const builtinCodingAgents: { +const builtinCodingAgents: { readonly codex: typeof codex; readonly dsh: typeof dsh; readonly "claude-code": typeof claudeCode; diff --git a/packages/agent-kit/src/providers/install.ts b/packages/agent-kit/src/providers/install.ts index a02fd712..34fab9a5 100644 --- a/packages/agent-kit/src/providers/install.ts +++ b/packages/agent-kit/src/providers/install.ts @@ -12,7 +12,7 @@ import { zcodeInstallAdapter } from "@rivus/agent-kit-provider-zcode/install"; import { mergeService } from "./merge.js"; import type { Provider } from "./types.js"; -export const builtinInstallAdapters: { +const builtinInstallAdapters: { readonly codex: typeof codexInstallAdapter; readonly "claude-code": typeof claudeCodeInstallAdapter; readonly grok: typeof grokInstallAdapter; diff --git a/packages/agent-kit/src/providers/sessions.ts b/packages/agent-kit/src/providers/sessions.ts index 0e530eca..a00f7c98 100644 --- a/packages/agent-kit/src/providers/sessions.ts +++ b/packages/agent-kit/src/providers/sessions.ts @@ -11,7 +11,7 @@ import { geminiCliSessionAdapter } from "@rivus/agent-kit-provider-gemini-cli/se import { mergeService } from "./merge.js"; import type { Provider } from "./types.js"; -export const builtinSessionAdapters: { +const builtinSessionAdapters: { readonly codex: typeof codexSessionAdapter; readonly dsh: typeof dshSessionAdapter; readonly opencode: typeof opencodeSessionAdapter; diff --git a/packages/discovery/src/application/services/host-paths.ts b/packages/discovery/src/application/services/host-paths.ts index 1a7cb589..5a6d568f 100644 --- a/packages/discovery/src/application/services/host-paths.ts +++ b/packages/discovery/src/application/services/host-paths.ts @@ -72,7 +72,7 @@ function recipeHomeRule( } /** Every path a recipe checks, including its credential files. */ -export function recipePaths(recipe: ProbeRecipe): ProbePath[] { +function recipePaths(recipe: ProbeRecipe): ProbePath[] { return [ ...recipe.appPaths, ...recipe.configPaths, diff --git a/packages/discovery/src/application/services/run-probe.ts b/packages/discovery/src/application/services/run-probe.ts index 6c7ecc42..01c3cef0 100644 --- a/packages/discovery/src/application/services/run-probe.ts +++ b/packages/discovery/src/application/services/run-probe.ts @@ -15,7 +15,7 @@ const OutputLimit = z.looseObject({ code: z.literal(OUTPUT_LIMIT_CODE) }); * Windows runs `.cmd` and `.bat` files only through `cmd.exe`, and Node refuses to spawn them without a shell. npm * installs agents as such shims, so on Windows they are found but never run. */ -export function isShellShim(platform: Pick, path: string): boolean { +function isShellShim(platform: Pick, path: string): boolean { return platform.os === "win32" && /\.(?:cmd|bat)$/i.test(path); } diff --git a/packages/harness/src/application/services/ledger-session.ts b/packages/harness/src/application/services/ledger-session.ts index 80a4672d..5d01b319 100644 --- a/packages/harness/src/application/services/ledger-session.ts +++ b/packages/harness/src/application/services/ledger-session.ts @@ -91,7 +91,7 @@ export function saveLedger( * Resolves the operations an interrupted modification left pending from probes of their targets, never by * replaying them, and saves the result. Must run under the LedgerLock. */ -export function recoverPending( +function recoverPending( scope: LedgerScope, loaded: LoadedLedger, registrations?: RegistrationLookup diff --git a/packages/harness/src/application/use-cases/plan-install.ts b/packages/harness/src/application/use-cases/plan-install.ts index ff4efd59..ef0ec07e 100644 --- a/packages/harness/src/application/use-cases/plan-install.ts +++ b/packages/harness/src/application/use-cases/plan-install.ts @@ -350,7 +350,7 @@ export interface PlanInput { * The content a step leaves at its target, or `undefined` when it leaves nothing or does not write there. * The executor resolves a restored pre-image from its blob reference. */ -export function contentAfter( +function contentAfter( scope: LedgerScope, step: PlanStep, ledger: Ledger diff --git a/packages/harness/src/domain/install-plan/factories/plan-evidence-scope.ts b/packages/harness/src/domain/install-plan/factories/plan-evidence-scope.ts index 62818ab5..f2a1f6e0 100644 --- a/packages/harness/src/domain/install-plan/factories/plan-evidence-scope.ts +++ b/packages/harness/src/domain/install-plan/factories/plan-evidence-scope.ts @@ -65,7 +65,7 @@ function foreignSource(file: ForeignHookFile, runner: CodingAgentId): LegacyHook * files the selected runners execute (see `foreignHookFiles`). A grouped file is one source under `/hooks`; a flat * file is one source per runner event, its pointer naming the JSON-escaped event. */ -export function legacyHookSources( +function legacyHookSources( owner: OwnerSnapshot, agents: readonly CodingAgentId[], adapters: InstallAdapters, diff --git a/packages/harness/src/domain/install-plan/services/legacy-ownership.ts b/packages/harness/src/domain/install-plan/services/legacy-ownership.ts index a14a6faf..c31d0e1c 100644 --- a/packages/harness/src/domain/install-plan/services/legacy-ownership.ts +++ b/packages/harness/src/domain/install-plan/services/legacy-ownership.ts @@ -131,7 +131,7 @@ function bundleFiresEvent( * runner; the owner tracks it in its ledger; and the plan leaves it where it is (no step, or a removal other than a * delete). Replacing the file would silently drop that consumer's hook, so this is an unresolvable conflict. */ -export function retainsForeignHook( +function retainsForeignHook( item: ForeignHookObservation, context: { readonly bundle: BundleSnapshot; diff --git a/packages/harness/src/domain/install-plan/services/registration-commands.ts b/packages/harness/src/domain/install-plan/services/registration-commands.ts index 0a391e4c..afdf3ada 100644 --- a/packages/harness/src/domain/install-plan/services/registration-commands.ts +++ b/packages/harness/src/domain/install-plan/services/registration-commands.ts @@ -3,7 +3,7 @@ import type { CodingAgentId } from "@rivus/agent-kit-catalog/public"; import type { LedgerEntry } from "../../ledger/entities/ledger-entry.js"; import type { PlanStepSnapshot } from "../value-objects/plan-step.js"; -export type RegistrationPurpose = "register" | "unregister"; +type RegistrationPurpose = "register" | "unregister"; export interface RegistrationCommands { /** The agent whose command line acts: the step's first, falling back to the ledger entry's first. */ diff --git a/packages/harness/src/infra/services/config-entries.ts b/packages/harness/src/infra/services/config-entries.ts index 036aeab4..5486b705 100644 --- a/packages/harness/src/infra/services/config-entries.ts +++ b/packages/harness/src/infra/services/config-entries.ts @@ -26,7 +26,7 @@ export interface EntryEdit { type Container = { readonly [key: string]: Document } | readonly Document[]; /** The keys of a JSON pointer such as `/hooks/Stop`, unescaped (`~1` is `/`, `~0` is `~`). */ -export function pointerKeys(pointer: string): readonly string[] { +function pointerKeys(pointer: string): readonly string[] { return pointer .split("/") .slice(1) diff --git a/packages/harness/src/infra/services/read-text.ts b/packages/harness/src/infra/services/read-text.ts index 398caff7..8d85eb9b 100644 --- a/packages/harness/src/infra/services/read-text.ts +++ b/packages/harness/src/infra/services/read-text.ts @@ -6,7 +6,7 @@ import type { Platform } from "@rivus/agent-kit-platform/public"; const Missing = z.looseObject({ code: z.union([z.literal("ENOENT"), z.literal("ENOTDIR")]) }); /** Whether `cause` says that nothing is at the path (or a parent is not a directory). */ -export function isMissing(cause: unknown): boolean { +function isMissing(cause: unknown): boolean { return Missing.safeParse(cause).success; } diff --git a/packages/harness/test/support/workers.ts b/packages/harness/test/support/workers.ts index 7b20b7da..dbf9b2fd 100644 --- a/packages/harness/test/support/workers.ts +++ b/packages/harness/test/support/workers.ts @@ -5,7 +5,7 @@ import { fileURLToPath } from "node:url"; const hook = fileURLToPath(new URL("resolve-ts.ts", import.meta.url)); /** One JSON line a worker printed. */ -export interface WorkerLine { +interface WorkerLine { readonly event: string; readonly at: number; readonly [field: string]: unknown; diff --git a/packages/providers/claude-code/src/facts.ts b/packages/providers/claude-code/src/facts.ts index ae02afbc..52c74d1f 100644 --- a/packages/providers/claude-code/src/facts.ts +++ b/packages/providers/claude-code/src/facts.ts @@ -1,38 +1,68 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; +/** @public */ export const CLAUDE_CODE_ID = "claude-code"; +/** @public */ export const CLAUDE_CODE_DISPLAY_NAME = "Claude Code"; +/** @public */ export const CLAUDE_CODE_COMMAND = "claude"; +/** @public */ export const CLAUDE_CODE_HOME_DIR = ".claude"; +/** @public */ export const HOME_ENV = "CLAUDE_CONFIG_DIR"; // The override names the configuration directory itself. +/** @public */ export const CLAUDE_CODE_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [CLAUDE_CODE_HOME_DIR] }; +/** @public */ export const CLAUDE_CODE_PROJECTS_DIR = "projects"; +/** @public */ export const CLAUDE_CODE_CREDENTIALS_FILE = ".credentials.json"; +/** @public */ export const CLAUDE_CODE_GLOBAL_CONFIG = "~/.claude.json"; +/** @public */ export const CLAUDE_CODE_AUTH_ARGS: readonly string[] = ["auth", "status", "--json"]; +/** @public */ export const CLAUDE_CODE_AUTH_TOKEN_ENV = "ANTHROPIC_AUTH_TOKEN"; +/** @public */ export const CLAUDE_CODE_API_KEY_ENV = "ANTHROPIC_API_KEY"; +/** @public */ export const CLAUDE_CODE_OAUTH_TOKEN_ENV = "CLAUDE_CODE_OAUTH_TOKEN"; +/** @public */ export const CLAUDE_CODE_SESSION_ENV = "CLAUDE_CODE_SESSION_ID"; +/** @public */ export const CLAUDE_CODE_SETTINGS_FILE = "settings.json"; +/** @public */ export const CLAUDE_CODE_SKILLS_DIR = "skills"; +/** @public */ export const CLAUDE_CODE_PLUGIN_MANIFEST = ".claude-plugin/plugin.json"; +/** @public */ export const CLAUDE_CODE_PLUGIN_HOOKS = "hooks/hooks.json"; +/** @public */ export const CLAUDE_CODE_HOOKS_POINTER = "/hooks"; +/** @public */ export const CLAUDE_CODE_HOOK_FORMAT = "json"; +/** @public */ export const CLAUDE_CODE_HOOK_LAYOUT = "grouped"; +/** @public */ export const CLAUDE_CODE_SETTINGS_PATH: string = `~/${CLAUDE_CODE_HOME_DIR}/${CLAUDE_CODE_SETTINGS_FILE}`; +/** @public */ export const CLAUDE_CODE_SUBAGENTS_DIR = "subagents"; +/** @public */ export const CLAUDE_CODE_SESSION_SUFFIX = ".jsonl"; +/** @public */ export const CLAUDE_CODE_SESSION_SUFFIX_PATTERN: RegExp = /\.jsonl$/; +/** @public */ export const CLAUDE_CODE_META_SUFFIX = ".meta.json"; +/** @public */ export const CLAUDE_CODE_AGENT_FILE_START = "agent"; +/** @public */ export const CLAUDE_CODE_AGENT_FILE_PREFIX: string = `${CLAUDE_CODE_AGENT_FILE_START}-`; +/** @public */ export const CLAUDE_CODE_ACP_COMMAND = "claude-agent-acp"; +/** @public */ export const CLAUDE_CODE_ACP_ENV: readonly string[] = [ "ANTHROPIC_*", "CLAUDE_*", @@ -41,4 +71,5 @@ export const CLAUDE_CODE_ACP_ENV: readonly string[] = [ "GOOGLE_APPLICATION_CREDENTIALS" ]; +/** @public */ export const agentMarkers: readonly string[] = [CLAUDE_CODE_ID, CLAUDE_CODE_COMMAND, CLAUDE_CODE_HOME_DIR, HOME_ENV]; diff --git a/packages/providers/claude-code/src/records/record.ts b/packages/providers/claude-code/src/records/record.ts index 7619283c..0938d64e 100644 --- a/packages/providers/claude-code/src/records/record.ts +++ b/packages/providers/claude-code/src/records/record.ts @@ -36,7 +36,7 @@ export interface ClaudeCodeContentBlockValue { } /** The `message` of a `user` or `assistant` record. */ -export interface ClaudeCodeMessageValue { +interface ClaudeCodeMessageValue { id?: string; model?: string; stop_reason?: string; diff --git a/packages/providers/codex/src/discovery.ts b/packages/providers/codex/src/discovery.ts index 30c8968f..f66ed60b 100644 --- a/packages/providers/codex/src/discovery.ts +++ b/packages/providers/codex/src/discovery.ts @@ -1,7 +1,6 @@ import { CODEX_ID, CODEX_DISPLAY_NAME, - CODEX_COMMAND, CODEX_SESSIONS_DIR, CODEX_ARCHIVED_SESSIONS_DIR, CODEX_AUTH_FILE, @@ -78,7 +77,7 @@ export const codexProbe: ProbeRecipe = { agent: CODEX_ID, displayName: CODEX_DISPLAY_NAME, kind: "cli", - commands: [CODEX_COMMAND], + commands: [CODEX_ID], appPaths: [], configPaths: [ { agentHome: CODEX_ID, path: CODEX_SESSIONS_DIR }, diff --git a/packages/providers/codex/src/facts.ts b/packages/providers/codex/src/facts.ts index dab8710f..d8c52675 100644 --- a/packages/providers/codex/src/facts.ts +++ b/packages/providers/codex/src/facts.ts @@ -1,36 +1,63 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; +/** @public */ export const CODEX_ID = "codex"; +/** @public */ export const CODEX_DISPLAY_NAME = "Codex"; -export const CODEX_COMMAND: string = CODEX_ID; +/** @public */ export const CODEX_HOME_DIR = ".codex"; +/** @public */ export const HOME_ENV = "CODEX_HOME"; // The override names the Codex home itself. +/** @public */ export const CODEX_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [CODEX_HOME_DIR] }; +/** @public */ export const CODEX_SESSIONS_DIR = "sessions"; +/** @public */ export const CODEX_ARCHIVED_SESSIONS_DIR = "archived_sessions"; +/** @public */ export const CODEX_AUTH_FILE = "auth.json"; +/** @public */ export const CODEX_AUTH_ARGS: readonly string[] = ["login", "status"]; +/** @public */ export const CODEX_CONFIG_FILE = "config.toml"; +/** @public */ export const CODEX_CONFIG_PATTERN: RegExp = /[\\/]config\.toml$/; +/** @public */ export const CODEX_HOOKS_FILE = "hooks.json"; +/** @public */ export const CODEX_PLUGINS_DIR = "plugins"; +/** @public */ export const CODEX_PLUGINS_POINTER = "/plugins"; +/** @public */ export const CODEX_PLUGIN_CACHE_DIR: string = `${CODEX_PLUGINS_DIR}/cache`; +/** @public */ export const CODEX_PLUGIN_MANIFEST = ".codex-plugin/plugin.json"; +/** @public */ export const CODEX_PLUGIN_HOOKS: string = `hooks/${CODEX_HOOKS_FILE}`; +/** @public */ export const CODEX_MARKETPLACE_MANIFEST = ".agents/plugins/marketplace.json"; +/** @public */ export const CODEX_HOOKS_POINTER = "/hooks"; +/** @public */ export const CODEX_HOOK_LAYOUT = "grouped"; +/** @public */ export const CODEX_CONFIG_FORMAT = "toml"; +/** @public */ export const CODEX_HOOK_FORMAT = "json"; +/** @public */ export const CODEX_ROLLOUT_PREFIX = "rollout-"; +/** @public */ export const CODEX_SESSION_SUFFIX = ".jsonl"; +/** @public */ export const CODEX_SESSION_SUFFIX_PATTERN: RegExp = /\.jsonl$/; +/** @public */ export const CODEX_ACP_COMMAND = "codex-acp"; +/** @public */ export const CODEX_ACP_ENV: readonly string[] = ["OPENAI_*", "CODEX_*", "AZURE_OPENAI_*"]; +/** @public */ export const agentMarkers: readonly string[] = [CODEX_ID, CODEX_HOME_DIR, HOME_ENV]; diff --git a/packages/providers/codex/src/install.ts b/packages/providers/codex/src/install.ts index e007659e..bb5e6120 100644 --- a/packages/providers/codex/src/install.ts +++ b/packages/providers/codex/src/install.ts @@ -1,6 +1,5 @@ import { CODEX_ID, - CODEX_COMMAND, CODEX_HOME, CODEX_PLUGINS_DIR, CODEX_PLUGINS_POINTER, @@ -100,8 +99,8 @@ function cliRegistration(locator: ArtifactLocator, context: InstallContext): Cli if (marketplace !== undefined) { const dir = `${codexHome(context)}/${CODEX_PLUGINS_DIR}/${marketplace}`; return { - register: { command: CODEX_COMMAND, args: ["plugin", "marketplace", "add", dir] }, - unregister: { command: CODEX_COMMAND, args: ["plugin", "marketplace", "remove", marketplace] }, + register: { command: CODEX_ID, args: ["plugin", "marketplace", "add", dir] }, + unregister: { command: CODEX_ID, args: ["plugin", "marketplace", "remove", marketplace] }, recorded: { entries: [record(`/marketplaces/${marketplace}`)], copies: [] } }; } @@ -114,8 +113,8 @@ function cliRegistration(locator: ArtifactLocator, context: InstallContext): Cli const [plugin = "", market = ""] = id.slice(1); const cache = codexPluginCache(context, plugin, market); return { - register: { command: CODEX_COMMAND, args: ["plugin", "add", `${plugin}@${market}`] }, - unregister: { command: CODEX_COMMAND, args: ["plugin", "remove", `${plugin}@${market}`] }, + register: { command: CODEX_ID, args: ["plugin", "add", `${plugin}@${market}`] }, + unregister: { command: CODEX_ID, args: ["plugin", "remove", `${plugin}@${market}`] }, installedCopy: `${cache}/local/${CODEX_PLUGIN_HOOKS}`, recorded: { entries: [record(`${CODEX_PLUGINS_POINTER}/${plugin}@${market}`)], copies: [cache] } }; @@ -135,7 +134,7 @@ export const codexInstallAdapter: InstallAdapter = { agent: CODEX_ID, hookStrategies: ["native-plugin", "shared-config"], skillStrategies: ["scan-directory"], - requires: { "native-plugin": CODEX_COMMAND }, + requires: { "native-plugin": CODEX_ID }, roots: (context) => [codexHome(context), sharedAgentsDir(context)], hookFile: (strategy, bundle) => strategy === "native-plugin" diff --git a/packages/providers/codex/src/records/record.ts b/packages/providers/codex/src/records/record.ts index bed40964..c11eb08b 100644 --- a/packages/providers/codex/src/records/record.ts +++ b/packages/providers/codex/src/records/record.ts @@ -216,20 +216,11 @@ export type CodexPayloadValue = CodexPayload & Record; type CodexTokenCountsValue = CodexTokenCounts & Record; export type CodexHistoryItemValue = CodexHistoryItem & Record; -const _codexRecordKeys: true = true satisfies KeysExact; -const _codexPayloadKeys: true = true satisfies KeysExact; -const _codexHistoryItemKeys: true = true satisfies KeysExact; -const _codexTokenCountsKeys: true = true satisfies KeysExact; - -// Compiled: every schema names exactly the keys of its interface, in both directions. The checks stay exported so -// they are never unused, and typeof a `true satisfies` check is just `true`, which drags no schema type into the -// declaration file. -export type CodexKeysExact = [ - typeof _codexRecordKeys, - typeof _codexPayloadKeys, - typeof _codexHistoryItemKeys, - typeof _codexTokenCountsKeys -]; +// Compile-time key checks: the schemas' keys must match the domain types exactly. +void (true satisfies KeysExact); +void (true satisfies KeysExact); +void (true satisfies KeysExact); +void (true satisfies KeysExact); /** The rollout record `value`, or `undefined` when it is not a record. */ export function codexRecord(value: unknown): CodexRecordValue | undefined { diff --git a/packages/providers/codex/src/records/usage.ts b/packages/providers/codex/src/records/usage.ts index b4d2441c..5380f954 100644 --- a/packages/providers/codex/src/records/usage.ts +++ b/packages/providers/codex/src/records/usage.ts @@ -65,10 +65,7 @@ const CodexUsagePayloadSchema = z.looseObject({ thread_settings: lenient(z.looseObject({ service_tier: lenient(z.string()) })) }); -const _codexUsagePayloadKeys: true = true satisfies KeysExact; - -/** Compiled: the decoder's payload schema names exactly the keys of its interface. */ -export type CodexUsageKeysExact = [typeof _codexUsagePayloadKeys]; +void (true satisfies KeysExact); /** * One rollout record for the usage rule: the envelope every codex reader parses, and the payload fields above. One @@ -108,7 +105,7 @@ const COUNT_KEYS = [ * The Usage of the model call between two cumulative `total_token_usage` objects, for a `token_count` that has no * `last_token_usage`: each count's increase, never below 0. A count that `total` does not report stays absent. */ -export function codexUsageDelta(total: unknown, previous: unknown): Usage | undefined { +function codexUsageDelta(total: unknown, previous: unknown): Usage | undefined { const current = codexTokenCounts(total); if (!current) { return undefined; @@ -195,7 +192,7 @@ export function codexRecordUsage( * The price factor of a Codex service tier, as presence and ccusage bill it: priority processing (`priority`, which * the CLI's configuration also calls `fast`) costs twice the standard rate. Any other tier is standard. */ -export function codexPricingMultiplier(serviceTier: string | undefined): number | undefined { +function codexPricingMultiplier(serviceTier: string | undefined): number | undefined { return serviceTier === "priority" || serviceTier === "fast" ? 2 : undefined; } diff --git a/packages/providers/codex/src/sessions/translation.ts b/packages/providers/codex/src/sessions/translation.ts index 07a562e5..c26e9f20 100644 --- a/packages/providers/codex/src/sessions/translation.ts +++ b/packages/providers/codex/src/sessions/translation.ts @@ -53,7 +53,7 @@ const lineKey = (record: SourcedRecord): string => `L${record.line}`; * `replacement_history` of a compacted record. `id` is the event id the translation gives it, `ts` the record's time * or, for a placed request, the output's, and `requestId` the window tag `placeRequest` writes. */ -export type CodexPart = TranscriptEventBody & CodexPartFields; +type CodexPart = TranscriptEventBody & CodexPartFields; /** What a `CodexPart` carries beside its kind and payload. */ interface CodexPartFields { @@ -70,7 +70,7 @@ interface CodexPartFields { } /** Where a record sits in its replay, as the batch rule (`scanForkReplay`) and the streaming passes see it. */ -export interface CodexReplayView { +interface CodexReplayView { /** Whether the record is a copy of the rollout's parent: `index < end` in the batch rule. */ readonly replayed: boolean; /** Whether this record is the first one after the replay, which resets the request window. */ @@ -78,7 +78,7 @@ export interface CodexReplayView { } /** What one stepped record becomes, beside the parsed values the translation's own extraction reads. */ -export interface CodexStep { +interface CodexStep { /** `false` when the record is of a format generation this adapter does not know. */ ok: boolean; rec: CodexRecordValue | undefined; @@ -91,7 +91,7 @@ export interface CodexStep { } /** Why a record became no event, as the translation's skipped records report it. */ -export interface CodexSkip { +interface CodexSkip { reason: string; record: SourcedRecord; } diff --git a/packages/providers/cursor/src/facts.ts b/packages/providers/cursor/src/facts.ts index 865ec27d..1ff69be4 100644 --- a/packages/providers/cursor/src/facts.ts +++ b/packages/providers/cursor/src/facts.ts @@ -1,32 +1,49 @@ +/** @public */ export const CURSOR_ID = "cursor"; +/** @public */ export const CURSOR_DISPLAY_NAME = "Cursor"; +/** @public */ export const CURSOR_AGENT_COMMAND = "cursor-agent"; +/** @public */ export const CURSOR_APP_PATH = "/Applications/Cursor.app"; +/** @public */ export const CURSOR_CREDENTIAL_PATHS: readonly string[] = [ "~/.config/cursor/auth.json", "~/AppData/Roaming/Cursor/auth.json" ]; +/** @public */ export const CURSOR_CONFIG_PATHS: readonly string[] = [ "~/Library/Application Support/Cursor/User/globalStorage", "~/.config/Cursor/User/globalStorage", "~/AppData/Roaming/Cursor/User/globalStorage", ...CURSOR_CREDENTIAL_PATHS ]; +/** @public */ export const CURSOR_PLUGIN_HOME = ".cursor"; +/** @public */ export const CURSOR_LOCAL_PLUGINS = "plugins/local"; +/** @public */ export const CURSOR_PLUGIN_MANIFEST = ".cursor-plugin/plugin.json"; +/** @public */ export const CURSOR_PLUGIN_HOOKS = "hooks/hooks.json"; +/** @public */ export const CURSOR_HOOKS_FILE = "hooks.json"; -export const CURSOR_VERSION_FIELD = "cursor_version"; +/** @public */ export const CURSOR_VERSION_ENV = "CURSOR_VERSION"; +/** @public */ +export const CURSOR_VERSION_FIELD = "cursor_version"; +/** @public */ export const CURSOR_TRANSCRIPT_ENV = "CURSOR_TRANSCRIPT_PATH"; +/** @public */ export const CURSOR_FOREIGN_AGENT = "claude-code"; +/** @public */ export const CURSOR_FOREIGN_HOOK_FILES: readonly string[] = [ "~/.claude/settings.json", ".claude/settings.json", ".claude/settings.local.json" ]; +/** @public */ export const agentMarkers: readonly string[] = [ CURSOR_ID, CURSOR_AGENT_COMMAND, diff --git a/packages/providers/dim/src/facts.ts b/packages/providers/dim/src/facts.ts index fbb651ac..a504cab5 100644 --- a/packages/providers/dim/src/facts.ts +++ b/packages/providers/dim/src/facts.ts @@ -3,26 +3,45 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; // DimCode (DimAgent, npm `dimcode`, binary `dim`, https://dimagent.com). Verified on 0.5.27 by installing and // inspecting the CLI: `dim acp` serves ACP v1, `dim exec` runs headless, and the v2 data root is a SQLite database. +/** @public */ export const DIM_ID = "dim"; +/** @public */ export const DIM_DISPLAY_NAME = "DimCode"; +/** @public */ export const DIM_COMMAND = "dim"; +/** @public */ export const HOME_DIR = ".dimcode"; +/** @public */ export const HOME_SUBDIR = "v2"; // The override names a base directory under which DimCode appends `v2`, like GEMINI_CLI_HOME does for Gemini. +/** @public */ export const HOME_ENV = "DIMCODE_HOME"; +/** @public */ export const DIM_HOME: HomeRule = { envVar: HOME_ENV, envSubpath: [HOME_SUBDIR], defaultPath: [HOME_DIR, HOME_SUBDIR] }; +/** @public */ export const DIM_DATABASE = "dimcode.sqlite"; +/** @public */ export const DIM_WAL_SUFFIX = "-wal"; +/** @public */ export const DIM_CONFIG_FILE = "config.json"; +/** @public */ export const DIM_PROVIDERS_FILE = "providers.json"; +/** @public */ export const DIM_AUTH_FILE = "auth.json"; +/** @public */ export const DIM_HOOKS_FILE = "hooks.json"; +/** @public */ export const DIM_HOOKS_POINTER = "/hooks"; +/** @public */ export const DIM_HOOK_FORMAT = "json"; +/** @public */ export const DIM_HOOK_LAYOUT = "grouped"; +/** @public */ export const DIM_SKILLS_DIR = "skills"; +/** @public */ export const DIM_DATABASE_BELOW_HOME: string = `${DIM_DATABASE}`; // The provider catalog's `environmentVariableName`s the CLI reads beside its stored credentials. +/** @public */ export const DIM_API_KEY_ENVS: readonly string[] = [ "ANTHROPIC_API_KEY", "OPENAI_API_KEY", @@ -33,7 +52,10 @@ export const DIM_API_KEY_ENVS: readonly string[] = [ "AZURE_API_KEY", "AIHUBMIX_API_KEY" ]; +/** @public */ export const DIM_ACP_ARGS: readonly string[] = ["acp"]; +/** @public */ export const DIM_ACP_ENV: readonly string[] = ["DIMCODE_*", ...DIM_API_KEY_ENVS]; +/** @public */ export const agentMarkers: readonly string[] = [DIM_ID, DIM_COMMAND, HOME_DIR, HOME_ENV]; diff --git a/packages/providers/dim/src/layout.ts b/packages/providers/dim/src/layout.ts index bc6ee324..271573ac 100644 --- a/packages/providers/dim/src/layout.ts +++ b/packages/providers/dim/src/layout.ts @@ -9,6 +9,3 @@ import { DIM_DATABASE } from "./facts.js"; export function dimDatabasePath(home: AgentHome): string { return joinPath(home.path, DIM_DATABASE); } - -/** The database below the home, as a probe path names it. */ -export const dimDatabaseBelowHome: string = DIM_DATABASE; diff --git a/packages/providers/dsh/src/facts.ts b/packages/providers/dsh/src/facts.ts index 00601eb1..5d4a3f03 100644 --- a/packages/providers/dsh/src/facts.ts +++ b/packages/providers/dsh/src/facts.ts @@ -1,23 +1,32 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; +/** @public */ export const DSH_ID = "dsh"; +/** @public */ export const DSH_DISPLAY_NAME = "DeepSeek Harness"; +/** @public */ export const HOME_ENV = "DSH_HOME"; // The override names the harness home itself, not a parent directory. +/** @public */ export const DSH_HOME: HomeRule = { envVar: HOME_ENV, expandsTilde: true, defaultPath: [".dsh"] }; +/** @public */ export const DSH_SESSIONS_DIR = "sessions"; /** The session format generation this adapter reads. */ +/** @public */ export const DSH_SESSION_VERSION = 4; /** The npm package `@deepseek-ai/dsh` installs this command. */ +/** @public */ export const DSH_COMMAND = "dsh"; /** The profile that serves ACP v1 over stdio. */ +/** @public */ export const DSH_ACP_ARGS: readonly string[] = ["--profile", "acp"]; /** * Known launch settings for the built-in ACP profile and DeepSeek API. Internal subprocess markers and the * speech worker's generated token are excluded. User-configured pi-ai `apiKeyEnv` names are not enumerable; * callers must explicitly forward a referenced key only when it is available solely in their own environment. */ +/** @public */ export const DSH_ACP_ENV: readonly string[] = [ HOME_ENV, "DSH_AGENTS_HOME", @@ -31,8 +40,11 @@ export const DSH_ACP_ENV: readonly string[] = [ "DEEPSEEK_*" ]; /** Where `dsh` stores the API key a login saves, under `refs.DEEPSEEK_API_KEY`; YAML, so never parsed here. */ +/** @public */ export const DSH_CREDENTIAL_FILE = ".credentials.yaml"; /** The variable the stored credential is named after; the launch environment's value is a fallback to the file. */ +/** @public */ export const DSH_API_KEY_ENV = "DEEPSEEK_API_KEY"; +/** @public */ export const agentMarkers: readonly string[] = [DSH_ID, ".dsh", HOME_ENV]; diff --git a/packages/providers/dsh/src/layout.ts b/packages/providers/dsh/src/layout.ts index 5b63f6da..1197a319 100644 --- a/packages/providers/dsh/src/layout.ts +++ b/packages/providers/dsh/src/layout.ts @@ -22,7 +22,7 @@ export function dshIsCompressed(path: string): boolean { } /** The generation the file name names: `session.vN.…` is N, the unsuffixed `session.jsonl` was v0. */ -export function dshVersionOf(path: string): number | undefined { +function dshVersionOf(path: string): number | undefined { const match = /^session(?:\.v(\d+))?\.jsonl(?:\.zstd)?$/.exec(basenamePath(path)); if (match === null) { return undefined; diff --git a/packages/providers/dsh/src/records.ts b/packages/providers/dsh/src/records.ts index 1da4146d..b96a8754 100644 --- a/packages/providers/dsh/src/records.ts +++ b/packages/providers/dsh/src/records.ts @@ -73,7 +73,7 @@ const DshUsage = z.looseObject({ reasoningTokens: lenient(z.number()) }); -export interface DshUsageValue { +interface DshUsageValue { inputTokens?: number; outputTokens?: number; totalTokens?: number; @@ -174,10 +174,6 @@ export interface DshMessageValue { id?: string; } -export function dshMessageOf(value: unknown): DshMessageValue | undefined { - return z.safeParse(DshMessage, value).data; -} - /** A `user/message` event's `data` is the message itself, not a wrapper. */ export function dshUserMessageOf(value: unknown): DshMessageValue | undefined { return z.safeParse(DshMessage, value).data; @@ -201,17 +197,6 @@ export function dshAssistantOf(value: unknown): DshAssistantValue | undefined { return z.safeParse(DshAssistant, value).data; } -const DshToolCall = z.looseObject({ callId: z.string(), name: z.string(), arguments: z.string() }); - -export interface DshToolCallValue { - callId: string; - name: string; - arguments: string; -} - -export function dshToolCallOf(value: unknown): DshToolCallValue | undefined { - return z.safeParse(DshToolCall, value).data; -} const DshRequestHeader = z.looseObject({ header: lenient( diff --git a/packages/providers/dsh/src/records/zstd.ts b/packages/providers/dsh/src/records/zstd.ts index f7626d66..d4c33508 100644 --- a/packages/providers/dsh/src/records/zstd.ts +++ b/packages/providers/dsh/src/records/zstd.ts @@ -12,13 +12,13 @@ export interface DshFrame { end: number; } -export interface DshText { +interface DshText { text: string; codec?: "zstd"; } /** Why a compressed source cannot be read: the host has no decompressor, or the bytes do not decode. */ -export type DshUndecodable = "no-decompressor" | "decode-failed"; +type DshUndecodable = "no-decompressor" | "decode-failed"; /** A whole-file read: the decoded text, or why a compressed file cannot be read. */ export type DshTextRead = DshText | { readonly undecodable: DshUndecodable } | undefined; diff --git a/packages/providers/gemini-cli/src/facts.ts b/packages/providers/gemini-cli/src/facts.ts index 8fb1b2e9..ac96f0c8 100644 --- a/packages/providers/gemini-cli/src/facts.ts +++ b/packages/providers/gemini-cli/src/facts.ts @@ -1,28 +1,52 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; +/** @public */ export const GEMINI_CLI_ID = "gemini-cli"; +/** @public */ export const GEMINI_CLI_DISPLAY_NAME = "Gemini CLI"; +/** @public */ export const GEMINI_CLI_COMMAND = "gemini"; +/** @public */ export const HOME_DIR = ".gemini"; +/** @public */ export const HOME_ENV = "GEMINI_CLI_HOME"; // The override names the user's home directory; the CLI appends its own directory. +/** @public */ export const GEMINI_CLI_HOME: HomeRule = { envVar: HOME_ENV, envSubpath: [HOME_DIR], defaultPath: [HOME_DIR] }; +/** @public */ export const GEMINI_CLI_SETTINGS_FILE = "settings.json"; +/** @public */ export const GEMINI_CLI_CREDENTIAL_FILE = "oauth_creds.json"; +/** @public */ export const GEMINI_CLI_API_KEY_ENV = "GEMINI_API_KEY"; +/** @public */ export const GEMINI_CLI_SESSION_ENV = "GEMINI_SESSION_ID"; +/** @public */ export const GEMINI_CLI_CWD_ENV = "GEMINI_CWD"; +/** @public */ export const GEMINI_CLI_TMP_DIR = "tmp"; +/** @public */ export const GEMINI_CLI_CHATS_DIR = "chats"; +/** @public */ export const GEMINI_CLI_EXTENSIONS_DIR = "extensions"; +/** @public */ export const GEMINI_CLI_EXTENSION_FILE = "gemini-extension.json"; +/** @public */ export const GEMINI_CLI_HOOKS_FILE = "hooks/hooks.json"; +/** @public */ export const GEMINI_CLI_HOOKS_POINTER = "/hooks"; +/** @public */ export const GEMINI_CLI_JSONL_SUFFIX = ".jsonl"; +/** @public */ export const GEMINI_CLI_JSON_SUFFIX = ".json"; +/** @public */ export const GEMINI_CLI_CHAT_SUFFIX_PATTERN: RegExp = /\.jsonl?$/; +/** @public */ export const GEMINI_CLI_MESSAGE_TYPE = "gemini"; +/** @public */ export const GEMINI_CLI_ACP_ARGS: readonly string[] = ["--experimental-acp"]; +/** @public */ export const GEMINI_CLI_ACP_ENV: readonly string[] = ["GEMINI_*", "GOOGLE_*"]; +/** @public */ export const agentMarkers: readonly string[] = [GEMINI_CLI_ID, GEMINI_CLI_COMMAND, HOME_DIR, HOME_ENV]; diff --git a/packages/providers/gemini-cli/test/support.ts b/packages/providers/gemini-cli/test/support.ts index f0cc0fe8..398e7162 100644 --- a/packages/providers/gemini-cli/test/support.ts +++ b/packages/providers/gemini-cli/test/support.ts @@ -34,8 +34,3 @@ export function geminiSessions(root: string): ConformanceSession[] { { path: at("conformance/unknown-type/chats/session-1.jsonl"), records: 2, capabilities: [] } ]; } - -/** The fixtures directory this package's sessions tests read into a memory platform. */ -export function geminiFixtures(): string { - return fileURLToPath(new URL("fixtures/sessions", import.meta.url)); -} diff --git a/packages/providers/grok/src/facts.ts b/packages/providers/grok/src/facts.ts index bc92af97..f44b7985 100644 --- a/packages/providers/grok/src/facts.ts +++ b/packages/providers/grok/src/facts.ts @@ -1,47 +1,77 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; +/** @public */ export const GROK_ID = "grok"; +/** @public */ export const GROK_DISPLAY_NAME = "Grok"; +/** @public */ export const HOME_DIR = ".grok"; +/** @public */ export const HOME_ENV = "GROK_HOME"; // The override names the Grok home itself. +/** @public */ export const GROK_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [HOME_DIR] }; +/** @public */ export const GROK_SESSIONS_DIR = "sessions"; +/** @public */ export const GROK_AUTH_FILE = "auth.json"; +/** @public */ export const GROK_API_KEY_ENV = "XAI_API_KEY"; +/** @public */ export const GROK_HOOKS_DIR = "hooks"; +/** @public */ export const GROK_HOOK_SUFFIX = ".json"; +/** @public */ export const GROK_UPDATES_FILE = "updates.jsonl"; +/** @public */ export const GROK_EVENTS_FILE = "events.jsonl"; +/** @public */ export const GROK_CHAT_HISTORY_FILE = "chat_history.jsonl"; +/** @public */ export const GROK_SUMMARY_FILE = "summary.json"; /** * The join files read for per-call requests (`events.jsonl` and `chat_history.jsonl`) are context echoes, not * transcripts: a session past this size joins no calls and the translation keeps its turn-level request. */ +/** @public */ export const GROK_CALLS_FILE_BYTES: number = 32 * 1024 * 1024; +/** @public */ export const GROK_SYSTEM_PROMPT_FILE = "system_prompt.txt"; +/** @public */ export const GROK_TOOLS_FILE = "tool_definitions.json"; +/** @public */ export const GROK_SUBAGENTS_DIR = "subagents"; +/** @public */ export const GROK_SUBAGENT_META_FILE = "meta.json"; +/** @public */ export const GROK_EVENT_FIELD = "hookEventName"; +/** @public */ export const GROK_EVENT_ENV = "GROK_HOOK_EVENT"; +/** @public */ export const GROK_SESSION_ENV = "GROK_SESSION_ID"; +/** @public */ export const GROK_CLAUDE_AGENT = "claude-code"; +/** @public */ export const GROK_CLAUDE_HOOK_FILES: readonly string[] = [ "~/.claude/settings.json", "~/.claude/settings.local.json", ".claude/settings.json", ".claude/settings.local.json" ]; +/** @public */ export const GROK_CURSOR_AGENT = "cursor"; +/** @public */ export const GROK_CURSOR_HOOK_FILES: readonly string[] = ["~/.cursor/hooks.json", ".cursor/hooks.json"]; +/** @public */ export const GROK_ACP_ARGS: readonly string[] = ["agent", "stdio"]; +/** @public */ export const GROK_ACP_ENV: readonly string[] = ["GROK_*", "XAI_*"]; +/** @public */ export const GROK_VERSION_SIDE_EFFECT = "Creates ~/.grok, or $GROK_HOME, when it does not exist, as every grok run does."; +/** @public */ export const agentMarkers: readonly string[] = [GROK_ID, HOME_DIR, HOME_ENV]; diff --git a/packages/providers/grok/src/records.ts b/packages/providers/grok/src/records.ts index eec4b2a0..495f8d51 100644 --- a/packages/providers/grok/src/records.ts +++ b/packages/providers/grok/src/records.ts @@ -132,7 +132,7 @@ export function grokUsageByModel( * defines the unit as 10^10 ticks per USD: `total_cost_usd_ticks` 126890500 is `total_cost_usd` 0.01268905. The count * arrives parsed, so the price is one division. */ -export function grokCostUsd(ticks: number | undefined): number | undefined { +function grokCostUsd(ticks: number | undefined): number | undefined { return ticks === undefined ? undefined : ticks / 1e10; } @@ -167,7 +167,7 @@ const GrokHookRun = z.looseObject({ * The fields Grok adds to a recorded `session/update`, as this module's readers read them. `usage` stays on the * record, for `grokTurnUsage` to parse where a turn completes. */ -export interface GrokFieldsValue { +interface GrokFieldsValue { _meta?: GrokMetaValue; formatVersion?: unknown; schema_version?: number; diff --git a/packages/providers/grok/src/sessions/translation.ts b/packages/providers/grok/src/sessions/translation.ts index 585dda37..da1f2c4d 100644 --- a/packages/providers/grok/src/sessions/translation.ts +++ b/packages/providers/grok/src/sessions/translation.ts @@ -226,16 +226,16 @@ export function applyGrokSubagents(agents: Lane[], subagents: ReadonlyMap { - const first = records[0]; - if (first === undefined) { - return err(unknownFormatGeneration(PI_ID, file)); - } - const header = piHeaderOf(first.value); - if (header === undefined || header.version !== PI_SESSION_VERSION) { - return err(unknownFormatGeneration(PI_ID, first)); - } - return ok(header); -} export type PiContentPart = | { kind: "text"; text: string } diff --git a/packages/providers/qoder/src/facts.ts b/packages/providers/qoder/src/facts.ts index 42c9098e..2f354228 100644 --- a/packages/providers/qoder/src/facts.ts +++ b/packages/providers/qoder/src/facts.ts @@ -5,25 +5,42 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; // ships `qodercli hooks migrate` from Claude Code), per its agent SDK's protocol types // (npm `@qoder-ai/qoder-agent-sdk`, dist/types/{hooks,settings}.d.ts) and the binary strings. +/** @public */ export const QODER_ID = "qoder"; +/** @public */ export const QODER_DISPLAY_NAME = "Qoder CLI"; // The entry point the installer puts on PATH; the versioned binary lives under `~/.qoder/bin/qodercli/`. +/** @public */ export const QODER_COMMAND = "qodercli"; +/** @public */ export const HOME_DIR = ".qoder"; // QODER_CONFIG_DIR relocates the user-level config root (verified against the binary strings; `QODER_USER_CONFIG_DIR` // also appears there). +/** @public */ export const HOME_ENV = "QODER_CONFIG_DIR"; +/** @public */ export const QODER_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [HOME_DIR] }; +/** @public */ export const QODER_SETTINGS_FILE = "settings.json"; +/** @public */ export const QODER_SETTINGS_PATH: string = `~/${HOME_DIR}/${QODER_SETTINGS_FILE}`; +/** @public */ export const QODER_HOOKS_POINTER = "/hooks"; +/** @public */ export const QODER_HOOK_FORMAT = "json"; +/** @public */ export const QODER_HOOK_LAYOUT = "grouped"; // Project settings live in the workspace under `.qoder/`, beside `settings.local.json`. +/** @public */ export const QODER_PROJECT_SETTINGS_DIR = ".qoder"; +/** @public */ export const QODER_OAUTH_FILE = "oauth_creds.json"; +/** @public */ export const QODER_PAT_ENV = "QODER_PERSONAL_ACCESS_TOKEN"; +/** @public */ export const QODER_ACP_ARGS: readonly string[] = ["--acp"]; +/** @public */ export const QODER_ACP_ENV: readonly string[] = ["QODER_*", "DASHSCOPE_API_KEY"]; +/** @public */ export const agentMarkers: readonly string[] = [QODER_ID, QODER_COMMAND, HOME_DIR, HOME_ENV]; diff --git a/packages/providers/zcode/src/facts.ts b/packages/providers/zcode/src/facts.ts index 7649667d..de45e033 100644 --- a/packages/providers/zcode/src/facts.ts +++ b/packages/providers/zcode/src/facts.ts @@ -1,22 +1,37 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; +/** @public */ export const ZCODE_ID = "zcode"; +/** @public */ export const ZCODE_DISPLAY_NAME = "ZCode"; +/** @public */ export const HOME_DIR = ".zcode"; +/** @public */ export const HOME_ENV = "ZCODE_STORAGE_DIR"; +/** @public */ export const ZCODE_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [HOME_DIR] }; +/** @public */ export const ZCODE_DB_DIR = "cli/db"; +/** @public */ export const ZCODE_DATABASE = "db.sqlite"; +/** @public */ export const ZCODE_WAL_SUFFIX = "-wal"; +/** @public */ export const ZCODE_CONFIG_FILE = "cli/config.json"; +/** @public */ export const ZCODE_KIT_PLUGINS = "agent-kit/zcode"; +/** @public */ export const ZCODE_PLUGIN_MANIFEST = ".zcode-plugin/plugin.json"; +/** @public */ export const ZCODE_PLUGIN_HOOKS = "hooks/hooks.json"; +/** @public */ export const ZCODE_PLUGIN_DIRS_POINTER = "/plugins/dirs"; // The login the CLI shares with the app sits under ZCODE_DATA_BASE_DIR (default the home directory), not under // ZCODE_STORAGE_DIR; the variable-named base is what a probe path cannot express. +/** @public */ export const ZCODE_CREDENTIAL_FILE = "~/.zcode/v2/credentials.json"; /** Keys whose non-empty string value means a login is stored; checked by name only, never read out. */ +/** @public */ export const ZCODE_CREDENTIAL_KEYS: readonly string[] = [ "oauth:bigmodel:access_token", "oauth:zai:access_token", @@ -24,8 +39,11 @@ export const ZCODE_CREDENTIAL_KEYS: readonly string[] = [ ]; /** The session id ZCode exports to every hook process, beside Claude Code's `CLAUDE_CODE_SESSION_ID`. */ +/** @public */ export const ZCODE_SESSION_ENV = "ZCODE_SESSION_ID"; /** A payload field only ZCode's hook input carries; see the hook dialect. */ +/** @public */ export const ZCODE_HOST_FIELD = "traceId"; +/** @public */ export const agentMarkers: readonly string[] = [ZCODE_ID, HOME_DIR, HOME_ENV]; diff --git a/packages/providers/zcode/src/layout.ts b/packages/providers/zcode/src/layout.ts index 9ab1edc6..7458c63f 100644 --- a/packages/providers/zcode/src/layout.ts +++ b/packages/providers/zcode/src/layout.ts @@ -2,8 +2,8 @@ import type { AgentHome } from "@rivus/agent-kit-catalog/spi"; import { joinPath } from "@rivus/agent-kit-sessions/spi"; import { ZCODE_DATABASE, ZCODE_DB_DIR } from "./facts.js"; -export const zcodeDatabaseDirectory: string = ZCODE_DB_DIR; -export const zcodeDatabaseFile: string = ZCODE_DATABASE; +const zcodeDatabaseDirectory: string = ZCODE_DB_DIR; +const zcodeDatabaseFile: string = ZCODE_DATABASE; /** The database below the home, as a probe path names it. */ export const zcodeDatabaseBelowHome: string = `${zcodeDatabaseDirectory}/${zcodeDatabaseFile}`; diff --git a/packages/sessions/src/application/services/files/edges.ts b/packages/sessions/src/application/services/files/edges.ts index 9f192cf6..98b50e2e 100644 --- a/packages/sessions/src/application/services/files/edges.ts +++ b/packages/sessions/src/application/services/files/edges.ts @@ -58,7 +58,7 @@ export async function readEdges( * Complete lines from both ends. The head keeps lines up to its last newline. When the ranges overlap, the tail * starts right after that newline, so no line is lost; otherwise the tail drops its first, partial line. */ -export function edgeLines(edges: FileEdges): string[] { +function edgeLines(edges: FileEdges): string[] { if (edges.whole) { return textLines(edges.headBytes); } diff --git a/packages/sessions/src/application/spi.ts b/packages/sessions/src/application/spi.ts index 68ea45e0..e617595c 100644 --- a/packages/sessions/src/application/spi.ts +++ b/packages/sessions/src/application/spi.ts @@ -226,6 +226,3 @@ export interface UsageDecoder { */ usageKey(record: UsageRecord): string | undefined; } - -/** Usage decoders by agent id. */ -export type UsageDecoders = ServiceTable; diff --git a/packages/sessions/src/application/use-cases/scan-usage.ts b/packages/sessions/src/application/use-cases/scan-usage.ts index 1a628128..469cea29 100644 --- a/packages/sessions/src/application/use-cases/scan-usage.ts +++ b/packages/sessions/src/application/use-cases/scan-usage.ts @@ -30,7 +30,7 @@ import type { UsageStream } from "../spi.js"; -export type { UsageScanMark, UsageScanSource, UsageScanState }; +export type { UsageScanSource, UsageScanState }; interface ScanUsageCommon { readonly providers: UsageProviders; diff --git a/packages/sessions/src/domain/transcript/services/fold-transcript.ts b/packages/sessions/src/domain/transcript/services/fold-transcript.ts index 032efac5..22fa9338 100644 --- a/packages/sessions/src/domain/transcript/services/fold-transcript.ts +++ b/packages/sessions/src/domain/transcript/services/fold-transcript.ts @@ -11,7 +11,7 @@ import { PayloadText } from "../../../lib/payload-text.js"; const CONTEXT_SHAPE_POINTS = 120; /** The capabilities whose absence leaves a summary number out. The others are counted regardless. */ -export interface SummaryGates { +interface SummaryGates { readonly requests: boolean; readonly usage: boolean; readonly durations: boolean; @@ -55,7 +55,7 @@ export function addTurnDuration(totals: SummaryTotals, durationMs?: number): voi } /** Counts a request's own duration, the fallback `durationMs` uses when no turn names one. */ -export function addRequestDuration(totals: SummaryTotals, durationMs?: number): void { +function addRequestDuration(totals: SummaryTotals, durationMs?: number): void { if (durationMs !== undefined && Number.isFinite(durationMs)) { totals.requestDurations.push(durationMs); } @@ -73,7 +73,7 @@ function inputPointsOf(totals: SummaryTotals): number[] { } /** Input tokens of each request in order, downsampled to at most 120 points. */ -export function downsampleContextShape(values: readonly number[]): number[] { +function downsampleContextShape(values: readonly number[]): number[] { if (values.length <= CONTEXT_SHAPE_POINTS) { return values.slice(); } diff --git a/packages/sessions/src/domain/transcript/value-objects/source-pointer.ts b/packages/sessions/src/domain/transcript/value-objects/source-pointer.ts index 1d29e72f..2840a78d 100644 --- a/packages/sessions/src/domain/transcript/value-objects/source-pointer.ts +++ b/packages/sessions/src/domain/transcript/value-objects/source-pointer.ts @@ -1,7 +1,7 @@ import { definedFields } from "@rivus/agent-kit-catalog/public"; /** The SQLite row an event's original is, when the session lives in a database. */ -export interface SqliteSourcePointer { +interface SqliteSourcePointer { /** Table and column names; the reader validates both as SQL identifiers. */ readonly table: string; readonly column: string; diff --git a/packages/testing/src/hook-dialect-conformance.ts b/packages/testing/src/hook-dialect-conformance.ts index 95fa9092..413b12f3 100644 --- a/packages/testing/src/hook-dialect-conformance.ts +++ b/packages/testing/src/hook-dialect-conformance.ts @@ -27,15 +27,6 @@ export interface HookDialectFixtures { readonly samples: readonly HookDialectSample[]; } -/** - * The scrubbed base fields and identity every sample of one agent shares. The base's `expected` carries the - * identity fields; per-event fields (the phase onward) come from each sample. - */ -export interface HookSampleBase { - readonly payload: Readonly>; - readonly expected: Partial>; -} - /** * The sample builder every agent's hook fixtures share: the agent's base payload and identity are * captured once, and each sample names its event and the per-event fields. diff --git a/packages/testing/src/ledger-fixture.ts b/packages/testing/src/ledger-fixture.ts index 39fe6274..8499b293 100644 --- a/packages/testing/src/ledger-fixture.ts +++ b/packages/testing/src/ledger-fixture.ts @@ -28,7 +28,7 @@ export function fixtureHash(text: string): ContentHash { } /** `fixtureHash` of the canonical form of an Artifact's content, as a real caller would hash it with SHA-256. */ -export function fixtureContentHash(locator: ArtifactLocator, content: ArtifactContent): ContentHash { +function fixtureContentHash(locator: ArtifactLocator, content: ArtifactContent): ContentHash { return fixtureHash(canonicalContent(locator.kind, content)); } @@ -49,7 +49,7 @@ export interface LedgerFixture { const FIXTURE_OWNER = "fixture-owner"; -export function ledgerEntryFixture(fixture: LedgerEntryFixture): LedgerEntry { +function ledgerEntryFixture(fixture: LedgerEntryFixture): LedgerEntry { const { content, ...entry } = fixture; const owners = entry.owners ?? [entry.activeOwner ?? FIXTURE_OWNER]; return { diff --git a/packages/testing/test/memory-support.ts b/packages/testing/test/memory-support.ts index 778da220..e3bd78ff 100644 --- a/packages/testing/test/memory-support.ts +++ b/packages/testing/test/memory-support.ts @@ -4,7 +4,7 @@ import type { SessionPlatform } from "@rivus/agent-kit-sessions/public"; // A session whose turns are one 40 KB prompt, one request and one turn duration: memory-hungry for a reader that // materializes the transcript, while the summary pass's own state — the numbers per request — stays a few bytes a // turn. The big session is ~16 MB, the small one ~2 MB. -export const TURN_TEXT_BYTES = 40 * 1024; +const TURN_TEXT_BYTES = 40 * 1024; export const SMALL_TURNS = 48; export const LARGE_TURNS = 384; diff --git a/packages/testing/test/support.ts b/packages/testing/test/support.ts index 9437cb68..a4bfb909 100644 --- a/packages/testing/test/support.ts +++ b/packages/testing/test/support.ts @@ -3,7 +3,7 @@ import { lstat, readdir, readFile, realpath, stat } from "node:fs/promises"; import { join, relative, sep } from "node:path"; import { fileURLToPath } from "node:url"; -import type { FileKind, PlatformFs, PlatformSqlite } from "@rivus/agent-kit-platform/public"; +import type { FileKind, PlatformFs } from "@rivus/agent-kit-platform/public"; /** Every file under `dir`, keyed by `/`, for `createMemoryPlatform({ files })`. */ export async function readTree(dir: string, prefix: string): Promise> { @@ -89,11 +89,3 @@ export function nodeReadFs(): Pick new sqlite.DatabaseSync(path, { readOnly: options?.readonly ?? false }) - }; -} diff --git a/scripts/lib/litellm-snapshot.ts b/scripts/lib/litellm-snapshot.ts index 5b587c99..b14fafbb 100644 --- a/scripts/lib/litellm-snapshot.ts +++ b/scripts/lib/litellm-snapshot.ts @@ -56,7 +56,7 @@ const Current = z.object({ version: z.string() }); * priority, ultrafast and decisions variants of a price, and the tiers of another cache lifetime (`_above_12hr_…`), * are not kept. */ -export interface SnapshotLongContext { +interface SnapshotLongContext { /** The threshold, from the `k` of the field names: 272000 for `_above_272k_tokens`. */ above_tokens: number; input_cost_per_token?: number; From be50a2f18081a1fc05e4c11bbd019152d39722e7 Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:47:37 +0800 Subject: [PATCH 5/7] style: format the sessions spi --- packages/providers/dsh/src/records.ts | 1 - packages/providers/kimi/src/records.ts | 1 - packages/providers/kimi/src/sessions/events.ts | 2 +- packages/providers/pi/src/records.ts | 3 --- packages/sessions/src/application/use-cases/scan-usage.ts | 2 +- 5 files changed, 2 insertions(+), 7 deletions(-) diff --git a/packages/providers/dsh/src/records.ts b/packages/providers/dsh/src/records.ts index b96a8754..3eec0bb8 100644 --- a/packages/providers/dsh/src/records.ts +++ b/packages/providers/dsh/src/records.ts @@ -197,7 +197,6 @@ export function dshAssistantOf(value: unknown): DshAssistantValue | undefined { return z.safeParse(DshAssistant, value).data; } - const DshRequestHeader = z.looseObject({ header: lenient( z.looseObject({ diff --git a/packages/providers/kimi/src/records.ts b/packages/providers/kimi/src/records.ts index 7e953678..e5283e2a 100644 --- a/packages/providers/kimi/src/records.ts +++ b/packages/providers/kimi/src/records.ts @@ -111,7 +111,6 @@ export function kimiLoopEventOf(value: unknown): KimiLoopEventValue | undefined return z.safeParse(KimiLoopEvent, value).data; } - export interface KimiTurnEndedValue { durationMs?: number; reason?: string; diff --git a/packages/providers/kimi/src/sessions/events.ts b/packages/providers/kimi/src/sessions/events.ts index b7e8e99b..c0e336de 100644 --- a/packages/providers/kimi/src/sessions/events.ts +++ b/packages/providers/kimi/src/sessions/events.ts @@ -321,4 +321,4 @@ export function createKimiTranslation(options: { readonly retain: boolean }): }; } -export { KIMI_CAPABILITIES, }; +export { KIMI_CAPABILITIES }; diff --git a/packages/providers/pi/src/records.ts b/packages/providers/pi/src/records.ts index 4aefa6a1..d561bea6 100644 --- a/packages/providers/pi/src/records.ts +++ b/packages/providers/pi/src/records.ts @@ -1,7 +1,6 @@ import { compactUsage, lenient, logTimestamp, type Usage } from "@rivus/agent-kit-sessions/spi"; import * as z from "zod/mini"; - /** The `version` of the session file this adapter reads. Pi migrates older files before it appends to them. */ export const PI_SESSION_VERSION = 3; @@ -41,7 +40,6 @@ export function piUsageOf(usage: PiUsageValue | undefined): Usage | undefined { }); } - const PiMessage = z.looseObject({ role: z.string(), content: lenient(z.union([z.string(), z.array(z.unknown())])), @@ -146,7 +144,6 @@ export function piEntryOf(value: unknown): PiEntryValue | undefined { return z.safeParse(PiEntry, value).data; } - export type PiContentPart = | { kind: "text"; text: string } | { kind: "thinking"; text: string; redacted?: boolean } diff --git a/packages/sessions/src/application/use-cases/scan-usage.ts b/packages/sessions/src/application/use-cases/scan-usage.ts index 469cea29..7de26add 100644 --- a/packages/sessions/src/application/use-cases/scan-usage.ts +++ b/packages/sessions/src/application/use-cases/scan-usage.ts @@ -30,7 +30,7 @@ import type { UsageStream } from "../spi.js"; -export type { UsageScanSource, UsageScanState }; +export type { UsageScanSource, UsageScanState }; interface ScanUsageCommon { readonly providers: UsageProviders; From 3feb995dd0ed68d03507969f4225a47f4cd9656a Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Tue, 17 Nov 2026 12:05:12 +0800 Subject: [PATCH 6/7] refactor: tighten hook sample types, facts tags and duplicates scan --- package.json | 4 +-- .../src/domain/lifecycle/spi/claude-shaped.ts | 8 ++--- packages/providers/claude-code/src/facts.ts | 29 --------------- packages/providers/claude-code/src/hooks.ts | 26 +++++--------- .../claude-code/test/fixtures/hooks.ts | 2 -- packages/providers/codex/src/facts.ts | 26 -------------- packages/providers/cursor/src/facts.ts | 15 -------- packages/providers/dim/src/facts.ts | 21 +---------- packages/providers/dim/src/usage.ts | 10 ++---- packages/providers/dim/test/fixtures/hooks.ts | 35 +++++++------------ packages/providers/dsh/src/facts.ts | 10 ------ packages/providers/dsh/src/usage.ts | 10 ++---- packages/providers/gemini-cli/src/facts.ts | 21 ----------- packages/providers/gemini-cli/src/usage.ts | 10 ++---- .../gemini-cli/test/fixtures/hooks.ts | 2 -- packages/providers/grok/src/facts.ts | 27 -------------- packages/providers/grok/src/records.ts | 5 --- packages/providers/grok/src/usage.ts | 7 ++-- packages/providers/kimi/src/facts.ts | 22 ------------ packages/providers/kimi/src/install.ts | 3 +- packages/providers/kimi/src/records.ts | 6 ++++ .../providers/kimi/test/fixtures/hooks.ts | 3 +- packages/providers/opencode/src/facts.ts | 17 --------- packages/providers/pi/src/facts.ts | 13 ------- packages/providers/pi/src/usage.ts | 10 ++---- packages/providers/qoder/src/facts.ts | 16 --------- .../providers/qoder/test/fixtures/hooks.ts | 4 +-- packages/providers/zcode/src/facts.ts | 16 --------- packages/providers/zcode/src/hooks.ts | 29 +++++++-------- .../usage/services/usage-window.test.ts | 10 +++++- .../src/domain/usage/services/usage-window.ts | 8 +++++ packages/sessions/src/spi.ts | 10 +----- .../testing/src/hook-dialect-conformance.ts | 30 ++++++++-------- 33 files changed, 102 insertions(+), 363 deletions(-) diff --git a/package.json b/package.json index 31dfe6d9..aa74059f 100644 --- a/package.json +++ b/package.json @@ -8,8 +8,8 @@ "changeset": "changeset", "check": "pnpm run format:check && pnpm run build && pnpm run lint && pnpm run typecheck && pnpm run test && pnpm run check:package", "check:package": "pnpm -r run check:package", - "duplicates": "jscpd --config node_modules/@perfectpan/lint-config/jscpd.json packages apps infra scripts tests --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/*.json,**/*.test.ts,**/*.test.tsx,**/test/support/**,**/test/fixtures/**' --format 'typescript'", - "duplicates:audit": "jscpd --config node_modules/@perfectpan/lint-config/jscpd-audit.json packages apps infra scripts tests --absolute --output tmp/duplicates-audit --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/*.json' --format 'typescript'", + "duplicates": "jscpd --config node_modules/@perfectpan/lint-config/jscpd.json packages apps infra scripts tests --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/.source/**,**/.tanstack/**,**/routeTree.gen.ts,**/*.json,**/*.test.ts,**/*.test.tsx,**/test/support/**,**/test/fixtures/**' --format 'typescript,tsx'", + "duplicates:audit": "jscpd --config node_modules/@perfectpan/lint-config/jscpd-audit.json packages apps infra scripts tests --absolute --output tmp/duplicates-audit --ignore '**/node_modules/**,**/dist/**,**/coverage/**,**/.vite/**,**/.source/**,**/.tanstack/**,**/routeTree.gen.ts,**/*.json' --format 'typescript,tsx'", "format": "pnpm -r run format", "format:check": "pnpm -r run format:check", "knip": "knip", diff --git a/packages/harness/src/domain/lifecycle/spi/claude-shaped.ts b/packages/harness/src/domain/lifecycle/spi/claude-shaped.ts index 1e078feb..855b55df 100644 --- a/packages/harness/src/domain/lifecycle/spi/claude-shaped.ts +++ b/packages/harness/src/domain/lifecycle/spi/claude-shaped.ts @@ -1,4 +1,4 @@ -import type { FieldSource, HookOutput, LifecycleSwitch, PayloadFields } from "./hook-dialect.js"; +import type { FieldSource, HookOutput, HookTimeout, LifecycleSwitch, PayloadFields } from "./hook-dialect.js"; /** * The hook shapes the agents that follow Claude Code's convention share, as @@ -30,10 +30,10 @@ export const claudeShapedSessionId = (env: readonly string[]): FieldSource => ({ }); /** The turn id field when the payload names one (Claude Code's `prompt_id`, or the agent's own). */ -export const claudeShapedTurnId = (path = "prompt_id"): FieldSource => claudeShapedField(path); +export const claudeShapedTurnId = (path: string = "prompt_id"): FieldSource => claudeShapedField(path); /** The payload fields every Claude-shaped stdin payload carries, keyed as the dialect spells them. */ -export const claudeShapedFields: PayloadFields & Record = { +export const claudeShapedFields: PayloadFields = { event: { paths: [["hook_event_name"]] }, sessionId: { paths: [["session_id"]] }, cwd: { paths: [["cwd"]] }, @@ -71,7 +71,7 @@ export const claudeShapedPermissionFields: readonly string[] = [ ]; /** Command-hook timeouts measured in seconds, as Claude Code's settings carry them. */ -export const claudeShapedSecondsTimeout: { unit: "seconds"; default: number } = { +export const claudeShapedSecondsTimeout: HookTimeout = { unit: "seconds", default: 600 }; diff --git a/packages/providers/claude-code/src/facts.ts b/packages/providers/claude-code/src/facts.ts index 52c74d1f..08b7447b 100644 --- a/packages/providers/claude-code/src/facts.ts +++ b/packages/providers/claude-code/src/facts.ts @@ -1,68 +1,39 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const CLAUDE_CODE_ID = "claude-code"; -/** @public */ export const CLAUDE_CODE_DISPLAY_NAME = "Claude Code"; -/** @public */ export const CLAUDE_CODE_COMMAND = "claude"; -/** @public */ export const CLAUDE_CODE_HOME_DIR = ".claude"; /** @public */ export const HOME_ENV = "CLAUDE_CONFIG_DIR"; // The override names the configuration directory itself. -/** @public */ export const CLAUDE_CODE_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [CLAUDE_CODE_HOME_DIR] }; -/** @public */ export const CLAUDE_CODE_PROJECTS_DIR = "projects"; -/** @public */ export const CLAUDE_CODE_CREDENTIALS_FILE = ".credentials.json"; -/** @public */ export const CLAUDE_CODE_GLOBAL_CONFIG = "~/.claude.json"; -/** @public */ export const CLAUDE_CODE_AUTH_ARGS: readonly string[] = ["auth", "status", "--json"]; -/** @public */ export const CLAUDE_CODE_AUTH_TOKEN_ENV = "ANTHROPIC_AUTH_TOKEN"; -/** @public */ export const CLAUDE_CODE_API_KEY_ENV = "ANTHROPIC_API_KEY"; -/** @public */ export const CLAUDE_CODE_OAUTH_TOKEN_ENV = "CLAUDE_CODE_OAUTH_TOKEN"; -/** @public */ export const CLAUDE_CODE_SESSION_ENV = "CLAUDE_CODE_SESSION_ID"; -/** @public */ export const CLAUDE_CODE_SETTINGS_FILE = "settings.json"; -/** @public */ export const CLAUDE_CODE_SKILLS_DIR = "skills"; -/** @public */ export const CLAUDE_CODE_PLUGIN_MANIFEST = ".claude-plugin/plugin.json"; -/** @public */ export const CLAUDE_CODE_PLUGIN_HOOKS = "hooks/hooks.json"; -/** @public */ export const CLAUDE_CODE_HOOKS_POINTER = "/hooks"; -/** @public */ export const CLAUDE_CODE_HOOK_FORMAT = "json"; -/** @public */ export const CLAUDE_CODE_HOOK_LAYOUT = "grouped"; -/** @public */ export const CLAUDE_CODE_SETTINGS_PATH: string = `~/${CLAUDE_CODE_HOME_DIR}/${CLAUDE_CODE_SETTINGS_FILE}`; -/** @public */ export const CLAUDE_CODE_SUBAGENTS_DIR = "subagents"; -/** @public */ export const CLAUDE_CODE_SESSION_SUFFIX = ".jsonl"; -/** @public */ export const CLAUDE_CODE_SESSION_SUFFIX_PATTERN: RegExp = /\.jsonl$/; -/** @public */ export const CLAUDE_CODE_META_SUFFIX = ".meta.json"; -/** @public */ export const CLAUDE_CODE_AGENT_FILE_START = "agent"; -/** @public */ export const CLAUDE_CODE_AGENT_FILE_PREFIX: string = `${CLAUDE_CODE_AGENT_FILE_START}-`; -/** @public */ export const CLAUDE_CODE_ACP_COMMAND = "claude-agent-acp"; -/** @public */ export const CLAUDE_CODE_ACP_ENV: readonly string[] = [ "ANTHROPIC_*", "CLAUDE_*", diff --git a/packages/providers/claude-code/src/hooks.ts b/packages/providers/claude-code/src/hooks.ts index 35e72a47..e648410f 100644 --- a/packages/providers/claude-code/src/hooks.ts +++ b/packages/providers/claude-code/src/hooks.ts @@ -1,10 +1,14 @@ import { CLAUDE_CODE_ID, CLAUDE_CODE_SESSION_ENV } from "./facts.js"; import { claudeShapedFields, + claudeShapedGateFields, claudeShapedHookOutput, + claudeShapedPermissionFields, claudeShapedSecondsTimeout, claudeShapedSessionId, + claudeShapedSessionStartLifecycle, claudeShapedTurnId, + withPlainStdoutContext, type HookDialect, type HookOutput } from "@rivus/agent-kit-harness/spi"; @@ -40,30 +44,18 @@ export const claudeCodeHookDialect: HookDialect = { events: { SessionStart: { // `compact` fires after a compaction inside a running session. - lifecycle: { - field: ["source"], - cases: { compact: { phase: "activity" } }, - otherwise: { phase: "start", scope: "session" } - }, + lifecycle: claudeShapedSessionStartLifecycle, // Plain-text stdout becomes context for Claude here; `{}` is JSON and adds nothing. - output: { ...OUTPUT, plainStdout: "context" } + output: withPlainStdoutContext(OUTPUT) }, - UserPromptSubmit: { lifecycle: { phase: "start", scope: "turn" }, output: { ...OUTPUT, plainStdout: "context" } }, + UserPromptSubmit: { lifecycle: { phase: "start", scope: "turn" }, output: withPlainStdoutContext(OUTPUT) }, PreToolUse: { lifecycle: { phase: "activity" }, gate: true, // Silence decides nothing ("staying silent doesn't approve it"); the permission flow continues. output: { ...OUTPUT, - fields: [ - "continue", - "stopReason", - "suppressOutput", - "systemMessage", - "hookSpecificOutput", - "decision", - "reason" - ] + fields: claudeShapedGateFields } }, PermissionRequest: { @@ -73,7 +65,7 @@ export const claudeCodeHookDialect: HookDialect = { output: { ...OUTPUT, exitCode2: "proceed", - fields: ["continue", "stopReason", "systemMessage", "hookSpecificOutput"] + fields: claudeShapedPermissionFields } }, PermissionDenied: { lifecycle: { phase: "activity" } }, diff --git a/packages/providers/claude-code/test/fixtures/hooks.ts b/packages/providers/claude-code/test/fixtures/hooks.ts index a9ffd265..3a5d5aae 100644 --- a/packages/providers/claude-code/test/fixtures/hooks.ts +++ b/packages/providers/claude-code/test/fixtures/hooks.ts @@ -1,4 +1,3 @@ - import { hookSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Scrubbed Claude Code hook payloads (https://code.claude.com/docs/en/hooks), one or more per event. @@ -18,7 +17,6 @@ const identity = { turnId: common.prompt_id } as const; - const bash = { tool_name: "Bash", tool_input: { command: "npm test", description: "Run tests" } }; const inSubagent = { agent_id: "a91c", agent_type: "Explore" }; diff --git a/packages/providers/codex/src/facts.ts b/packages/providers/codex/src/facts.ts index d8c52675..638e68bc 100644 --- a/packages/providers/codex/src/facts.ts +++ b/packages/providers/codex/src/facts.ts @@ -1,62 +1,36 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const CODEX_ID = "codex"; -/** @public */ export const CODEX_DISPLAY_NAME = "Codex"; -/** @public */ export const CODEX_HOME_DIR = ".codex"; /** @public */ export const HOME_ENV = "CODEX_HOME"; // The override names the Codex home itself. -/** @public */ export const CODEX_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [CODEX_HOME_DIR] }; -/** @public */ export const CODEX_SESSIONS_DIR = "sessions"; -/** @public */ export const CODEX_ARCHIVED_SESSIONS_DIR = "archived_sessions"; -/** @public */ export const CODEX_AUTH_FILE = "auth.json"; -/** @public */ export const CODEX_AUTH_ARGS: readonly string[] = ["login", "status"]; -/** @public */ export const CODEX_CONFIG_FILE = "config.toml"; -/** @public */ export const CODEX_CONFIG_PATTERN: RegExp = /[\\/]config\.toml$/; -/** @public */ export const CODEX_HOOKS_FILE = "hooks.json"; -/** @public */ export const CODEX_PLUGINS_DIR = "plugins"; -/** @public */ export const CODEX_PLUGINS_POINTER = "/plugins"; -/** @public */ export const CODEX_PLUGIN_CACHE_DIR: string = `${CODEX_PLUGINS_DIR}/cache`; -/** @public */ export const CODEX_PLUGIN_MANIFEST = ".codex-plugin/plugin.json"; -/** @public */ export const CODEX_PLUGIN_HOOKS: string = `hooks/${CODEX_HOOKS_FILE}`; -/** @public */ export const CODEX_MARKETPLACE_MANIFEST = ".agents/plugins/marketplace.json"; -/** @public */ export const CODEX_HOOKS_POINTER = "/hooks"; -/** @public */ export const CODEX_HOOK_LAYOUT = "grouped"; -/** @public */ export const CODEX_CONFIG_FORMAT = "toml"; -/** @public */ export const CODEX_HOOK_FORMAT = "json"; -/** @public */ export const CODEX_ROLLOUT_PREFIX = "rollout-"; -/** @public */ export const CODEX_SESSION_SUFFIX = ".jsonl"; -/** @public */ export const CODEX_SESSION_SUFFIX_PATTERN: RegExp = /\.jsonl$/; -/** @public */ export const CODEX_ACP_COMMAND = "codex-acp"; -/** @public */ export const CODEX_ACP_ENV: readonly string[] = ["OPENAI_*", "CODEX_*", "AZURE_OPENAI_*"]; /** @public */ diff --git a/packages/providers/cursor/src/facts.ts b/packages/providers/cursor/src/facts.ts index 1ff69be4..d0d46c5f 100644 --- a/packages/providers/cursor/src/facts.ts +++ b/packages/providers/cursor/src/facts.ts @@ -1,42 +1,27 @@ -/** @public */ export const CURSOR_ID = "cursor"; -/** @public */ export const CURSOR_DISPLAY_NAME = "Cursor"; -/** @public */ export const CURSOR_AGENT_COMMAND = "cursor-agent"; -/** @public */ export const CURSOR_APP_PATH = "/Applications/Cursor.app"; -/** @public */ export const CURSOR_CREDENTIAL_PATHS: readonly string[] = [ "~/.config/cursor/auth.json", "~/AppData/Roaming/Cursor/auth.json" ]; -/** @public */ export const CURSOR_CONFIG_PATHS: readonly string[] = [ "~/Library/Application Support/Cursor/User/globalStorage", "~/.config/Cursor/User/globalStorage", "~/AppData/Roaming/Cursor/User/globalStorage", ...CURSOR_CREDENTIAL_PATHS ]; -/** @public */ export const CURSOR_PLUGIN_HOME = ".cursor"; -/** @public */ export const CURSOR_LOCAL_PLUGINS = "plugins/local"; -/** @public */ export const CURSOR_PLUGIN_MANIFEST = ".cursor-plugin/plugin.json"; -/** @public */ export const CURSOR_PLUGIN_HOOKS = "hooks/hooks.json"; -/** @public */ export const CURSOR_HOOKS_FILE = "hooks.json"; /** @public */ export const CURSOR_VERSION_ENV = "CURSOR_VERSION"; -/** @public */ export const CURSOR_VERSION_FIELD = "cursor_version"; -/** @public */ export const CURSOR_TRANSCRIPT_ENV = "CURSOR_TRANSCRIPT_PATH"; -/** @public */ export const CURSOR_FOREIGN_AGENT = "claude-code"; -/** @public */ export const CURSOR_FOREIGN_HOOK_FILES: readonly string[] = [ "~/.claude/settings.json", ".claude/settings.json", diff --git a/packages/providers/dim/src/facts.ts b/packages/providers/dim/src/facts.ts index a504cab5..1dffe5ea 100644 --- a/packages/providers/dim/src/facts.ts +++ b/packages/providers/dim/src/facts.ts @@ -3,45 +3,28 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; // DimCode (DimAgent, npm `dimcode`, binary `dim`, https://dimagent.com). Verified on 0.5.27 by installing and // inspecting the CLI: `dim acp` serves ACP v1, `dim exec` runs headless, and the v2 data root is a SQLite database. -/** @public */ export const DIM_ID = "dim"; -/** @public */ export const DIM_DISPLAY_NAME = "DimCode"; -/** @public */ export const DIM_COMMAND = "dim"; /** @public */ export const HOME_DIR = ".dimcode"; -/** @public */ -export const HOME_SUBDIR = "v2"; +const HOME_SUBDIR = "v2"; // The override names a base directory under which DimCode appends `v2`, like GEMINI_CLI_HOME does for Gemini. /** @public */ export const HOME_ENV = "DIMCODE_HOME"; -/** @public */ export const DIM_HOME: HomeRule = { envVar: HOME_ENV, envSubpath: [HOME_SUBDIR], defaultPath: [HOME_DIR, HOME_SUBDIR] }; -/** @public */ export const DIM_DATABASE = "dimcode.sqlite"; -/** @public */ export const DIM_WAL_SUFFIX = "-wal"; -/** @public */ export const DIM_CONFIG_FILE = "config.json"; -/** @public */ export const DIM_PROVIDERS_FILE = "providers.json"; -/** @public */ export const DIM_AUTH_FILE = "auth.json"; -/** @public */ export const DIM_HOOKS_FILE = "hooks.json"; -/** @public */ export const DIM_HOOKS_POINTER = "/hooks"; -/** @public */ export const DIM_HOOK_FORMAT = "json"; -/** @public */ export const DIM_HOOK_LAYOUT = "grouped"; -/** @public */ export const DIM_SKILLS_DIR = "skills"; -/** @public */ export const DIM_DATABASE_BELOW_HOME: string = `${DIM_DATABASE}`; // The provider catalog's `environmentVariableName`s the CLI reads beside its stored credentials. -/** @public */ export const DIM_API_KEY_ENVS: readonly string[] = [ "ANTHROPIC_API_KEY", "OPENAI_API_KEY", @@ -52,9 +35,7 @@ export const DIM_API_KEY_ENVS: readonly string[] = [ "AZURE_API_KEY", "AIHUBMIX_API_KEY" ]; -/** @public */ export const DIM_ACP_ARGS: readonly string[] = ["acp"]; -/** @public */ export const DIM_ACP_ENV: readonly string[] = ["DIMCODE_*", ...DIM_API_KEY_ENVS]; /** @public */ diff --git a/packages/providers/dim/src/usage.ts b/packages/providers/dim/src/usage.ts index 51aebb69..124c6dda 100644 --- a/packages/providers/dim/src/usage.ts +++ b/packages/providers/dim/src/usage.ts @@ -12,7 +12,8 @@ import { type UsageRecord, type UsageSource, type UsageSourceFailure, - type UsageStream + type UsageStream, + usageWindowKey } from "@rivus/agent-kit-sessions/spi"; import { DIM_DATABASE, DIM_HOME, DIM_ID, DIM_WAL_SUFFIX } from "./facts.js"; import { dimDatabasePath } from "./layout.js"; @@ -68,11 +69,6 @@ export function dimLedgerRecord(value: unknown, row: SqliteAppendRow): UsageReco return record; } -/** The key under which a scan counts a record once in its window: the session and the run id. */ -function dimUsageKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} - /** The `ReadFailed` a decode yields for an error the platform did not classify: the thrown value's message, kept for the report. */ function readFailed(path: string, cause: unknown): ReadFailed { return { _tag: "ReadFailed", path, message: cause instanceof Error ? cause.message : String(cause), cause }; @@ -112,7 +108,7 @@ export const dimUsageDecoder: UsageDecoder = { specificationVersion: "usage-v1", agent: DIM_ID, home: DIM_HOME, - usageKey: dimUsageKey, + usageKey: usageWindowKey, async *sources(platform, home, options = {}) { const { since, signal } = options; signal?.throwIfAborted(); diff --git a/packages/providers/dim/test/fixtures/hooks.ts b/packages/providers/dim/test/fixtures/hooks.ts index 43e63161..d2987c2f 100644 --- a/packages/providers/dim/test/fixtures/hooks.ts +++ b/packages/providers/dim/test/fixtures/hooks.ts @@ -1,6 +1,4 @@ -import type { LifecycleEvent } from "@rivus/agent-kit-harness/public/events"; - -import type { HookDialectSample } from "@rivus/agent-kit-testing/public"; +import { hookEventSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Synthetic DimCode hook payloads, from the CLI's own parser (0.5.27): the documented base fields on stdin, plus the // session fields. The per-event tool fields are not documented and stay unmapped until a capture confirms them. @@ -10,26 +8,17 @@ const cwd = "/u/me/work"; const transcriptPath = `${cwd}/.dimcode/v2/tracelog/${sessionId}/run.jsonl`; const identity = { agent: "dim", sessionId, cwd, transcriptPath } as const; -function sample( - event: string, - fields: Record, - expected: Omit -): HookDialectSample { - return { - name: event, - payload: { - hook_event_name: event, - session_id: sessionId, - transcript_path: transcriptPath, - cwd, - model: "glm-4.6", - permission_mode: "default", - run_id: "run-1", - ...fields - }, - expected: { ...identity, nativeEvent: event, ...expected } - }; -} +const sample = hookEventSampleFactory({ + payload: { + session_id: sessionId, + transcript_path: transcriptPath, + cwd, + model: "glm-4.6", + permission_mode: "default", + run_id: "run-1" + }, + expected: identity +}); export const dimSamples: readonly HookDialectSample[] = [ sample("SessionStart", { source: "startup" }, { phase: "start", scope: "session" }), diff --git a/packages/providers/dsh/src/facts.ts b/packages/providers/dsh/src/facts.ts index 5d4a3f03..759c4dff 100644 --- a/packages/providers/dsh/src/facts.ts +++ b/packages/providers/dsh/src/facts.ts @@ -1,32 +1,24 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const DSH_ID = "dsh"; -/** @public */ export const DSH_DISPLAY_NAME = "DeepSeek Harness"; /** @public */ export const HOME_ENV = "DSH_HOME"; // The override names the harness home itself, not a parent directory. -/** @public */ export const DSH_HOME: HomeRule = { envVar: HOME_ENV, expandsTilde: true, defaultPath: [".dsh"] }; -/** @public */ export const DSH_SESSIONS_DIR = "sessions"; /** The session format generation this adapter reads. */ -/** @public */ export const DSH_SESSION_VERSION = 4; /** The npm package `@deepseek-ai/dsh` installs this command. */ -/** @public */ export const DSH_COMMAND = "dsh"; /** The profile that serves ACP v1 over stdio. */ -/** @public */ export const DSH_ACP_ARGS: readonly string[] = ["--profile", "acp"]; /** * Known launch settings for the built-in ACP profile and DeepSeek API. Internal subprocess markers and the * speech worker's generated token are excluded. User-configured pi-ai `apiKeyEnv` names are not enumerable; * callers must explicitly forward a referenced key only when it is available solely in their own environment. */ -/** @public */ export const DSH_ACP_ENV: readonly string[] = [ HOME_ENV, "DSH_AGENTS_HOME", @@ -40,10 +32,8 @@ export const DSH_ACP_ENV: readonly string[] = [ "DEEPSEEK_*" ]; /** Where `dsh` stores the API key a login saves, under `refs.DEEPSEEK_API_KEY`; YAML, so never parsed here. */ -/** @public */ export const DSH_CREDENTIAL_FILE = ".credentials.yaml"; /** The variable the stored credential is named after; the launch environment's value is a fallback to the file. */ -/** @public */ export const DSH_API_KEY_ENV = "DEEPSEEK_API_KEY"; /** @public */ diff --git a/packages/providers/dsh/src/usage.ts b/packages/providers/dsh/src/usage.ts index 16780aab..88c6f801 100644 --- a/packages/providers/dsh/src/usage.ts +++ b/packages/providers/dsh/src/usage.ts @@ -26,7 +26,8 @@ import { readBytes, sameFile, sourceOf, - unknownFormatGeneration + unknownFormatGeneration, + usageWindowKey } from "@rivus/agent-kit-sessions/spi"; import { DSH_ID, DSH_SESSION_VERSION } from "./facts.js"; @@ -189,11 +190,6 @@ function dshUsageLines(file: UsageFile, saved?: unknown): UsageLineDecoder { return createDshUsageLines(file, restoreDshState(saved)); } -/** The key under which a scan counts a record once in its window: the session and the event seq, unique in its session. */ -function dshUsageKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} - const layout: JsonlUsageLayout = { agent: DSH_ID, file: sameFile((path) => ({ sessionId: dshSessionIdOf(path) })), @@ -367,7 +363,7 @@ function decodeDshZstd(platform: UsagePlatform, target: UsageTarget, options: De export const dshUsageDecoder: UsageDecoder = { specificationVersion: "usage-v1", agent: DSH_ID, - usageKey: dshUsageKey, + usageKey: usageWindowKey, sources(platform, home, options = {}) { return fileSources(platform, DSH_ID, dshRoots(home), DSH_SESSION_FILES, { ...options, diff --git a/packages/providers/gemini-cli/src/facts.ts b/packages/providers/gemini-cli/src/facts.ts index ac96f0c8..7bf15ac2 100644 --- a/packages/providers/gemini-cli/src/facts.ts +++ b/packages/providers/gemini-cli/src/facts.ts @@ -1,51 +1,30 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const GEMINI_CLI_ID = "gemini-cli"; -/** @public */ export const GEMINI_CLI_DISPLAY_NAME = "Gemini CLI"; -/** @public */ export const GEMINI_CLI_COMMAND = "gemini"; /** @public */ export const HOME_DIR = ".gemini"; /** @public */ export const HOME_ENV = "GEMINI_CLI_HOME"; // The override names the user's home directory; the CLI appends its own directory. -/** @public */ export const GEMINI_CLI_HOME: HomeRule = { envVar: HOME_ENV, envSubpath: [HOME_DIR], defaultPath: [HOME_DIR] }; -/** @public */ export const GEMINI_CLI_SETTINGS_FILE = "settings.json"; -/** @public */ export const GEMINI_CLI_CREDENTIAL_FILE = "oauth_creds.json"; -/** @public */ export const GEMINI_CLI_API_KEY_ENV = "GEMINI_API_KEY"; -/** @public */ export const GEMINI_CLI_SESSION_ENV = "GEMINI_SESSION_ID"; -/** @public */ export const GEMINI_CLI_CWD_ENV = "GEMINI_CWD"; -/** @public */ export const GEMINI_CLI_TMP_DIR = "tmp"; -/** @public */ export const GEMINI_CLI_CHATS_DIR = "chats"; -/** @public */ export const GEMINI_CLI_EXTENSIONS_DIR = "extensions"; -/** @public */ export const GEMINI_CLI_EXTENSION_FILE = "gemini-extension.json"; -/** @public */ export const GEMINI_CLI_HOOKS_FILE = "hooks/hooks.json"; -/** @public */ export const GEMINI_CLI_HOOKS_POINTER = "/hooks"; -/** @public */ export const GEMINI_CLI_JSONL_SUFFIX = ".jsonl"; -/** @public */ export const GEMINI_CLI_JSON_SUFFIX = ".json"; -/** @public */ export const GEMINI_CLI_CHAT_SUFFIX_PATTERN: RegExp = /\.jsonl?$/; -/** @public */ export const GEMINI_CLI_MESSAGE_TYPE = "gemini"; -/** @public */ export const GEMINI_CLI_ACP_ARGS: readonly string[] = ["--experimental-acp"]; -/** @public */ export const GEMINI_CLI_ACP_ENV: readonly string[] = ["GEMINI_*", "GOOGLE_*"]; /** @public */ diff --git a/packages/providers/gemini-cli/src/usage.ts b/packages/providers/gemini-cli/src/usage.ts index 08d722aa..770beb71 100644 --- a/packages/providers/gemini-cli/src/usage.ts +++ b/packages/providers/gemini-cli/src/usage.ts @@ -24,7 +24,8 @@ import { fileSources, type JsonlUsageLayout, sameFile, - usageStreamOf + usageStreamOf, + usageWindowKey } from "@rivus/agent-kit-sessions/spi"; import { GEMINI_CLI_CHAT_FILES, @@ -203,11 +204,6 @@ export function geminiCliLegacyUsage(value: unknown, file: UsageFile, source: So return out; } -/** The key under which a scan counts a record once in its window: the session and the message id, which a migrated chat keeps. */ -function geminiCliUsageKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} - const layout: JsonlUsageLayout = { agent: AGENT, file: sameFile((path) => ({ sessionId: geminiCliSessionStem(path) })), @@ -275,7 +271,7 @@ function decodeLegacyChat(platform: UsagePlatform, target: UsageTarget, options: export const geminiCliUsageDecoder: UsageDecoder = { specificationVersion: "usage-v1", agent: AGENT, - usageKey: geminiCliUsageKey, + usageKey: usageWindowKey, sources(platform, home, options = {}) { return fileSources(platform, AGENT, geminiCliUsageRoots(home), GEMINI_CLI_CHAT_FILES, { ...options, diff --git a/packages/providers/gemini-cli/test/fixtures/hooks.ts b/packages/providers/gemini-cli/test/fixtures/hooks.ts index 23476ce1..a74a6a7c 100644 --- a/packages/providers/gemini-cli/test/fixtures/hooks.ts +++ b/packages/providers/gemini-cli/test/fixtures/hooks.ts @@ -1,4 +1,3 @@ - import { hookSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Scrubbed Gemini CLI hook payloads (docs/hooks/reference.md in google-gemini/gemini-cli), one per event. @@ -16,7 +15,6 @@ const identity = { cwd: common.cwd } as const; - const shell = { tool_name: "run_shell_command", tool_input: { command: "npm test" } }; const request = { llm_request: { model: "gemini-3-pro", messages: [] } }; diff --git a/packages/providers/grok/src/facts.ts b/packages/providers/grok/src/facts.ts index f44b7985..ef799d8e 100644 --- a/packages/providers/grok/src/facts.ts +++ b/packages/providers/grok/src/facts.ts @@ -1,75 +1,48 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const GROK_ID = "grok"; -/** @public */ export const GROK_DISPLAY_NAME = "Grok"; /** @public */ export const HOME_DIR = ".grok"; /** @public */ export const HOME_ENV = "GROK_HOME"; // The override names the Grok home itself. -/** @public */ export const GROK_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [HOME_DIR] }; -/** @public */ export const GROK_SESSIONS_DIR = "sessions"; -/** @public */ export const GROK_AUTH_FILE = "auth.json"; -/** @public */ export const GROK_API_KEY_ENV = "XAI_API_KEY"; -/** @public */ export const GROK_HOOKS_DIR = "hooks"; -/** @public */ export const GROK_HOOK_SUFFIX = ".json"; -/** @public */ export const GROK_UPDATES_FILE = "updates.jsonl"; -/** @public */ export const GROK_EVENTS_FILE = "events.jsonl"; -/** @public */ export const GROK_CHAT_HISTORY_FILE = "chat_history.jsonl"; -/** @public */ export const GROK_SUMMARY_FILE = "summary.json"; /** * The join files read for per-call requests (`events.jsonl` and `chat_history.jsonl`) are context echoes, not * transcripts: a session past this size joins no calls and the translation keeps its turn-level request. */ -/** @public */ export const GROK_CALLS_FILE_BYTES: number = 32 * 1024 * 1024; -/** @public */ export const GROK_SYSTEM_PROMPT_FILE = "system_prompt.txt"; -/** @public */ export const GROK_TOOLS_FILE = "tool_definitions.json"; -/** @public */ export const GROK_SUBAGENTS_DIR = "subagents"; -/** @public */ export const GROK_SUBAGENT_META_FILE = "meta.json"; -/** @public */ export const GROK_EVENT_FIELD = "hookEventName"; -/** @public */ export const GROK_EVENT_ENV = "GROK_HOOK_EVENT"; -/** @public */ export const GROK_SESSION_ENV = "GROK_SESSION_ID"; -/** @public */ export const GROK_CLAUDE_AGENT = "claude-code"; -/** @public */ export const GROK_CLAUDE_HOOK_FILES: readonly string[] = [ "~/.claude/settings.json", "~/.claude/settings.local.json", ".claude/settings.json", ".claude/settings.local.json" ]; -/** @public */ export const GROK_CURSOR_AGENT = "cursor"; -/** @public */ export const GROK_CURSOR_HOOK_FILES: readonly string[] = ["~/.cursor/hooks.json", ".cursor/hooks.json"]; -/** @public */ export const GROK_ACP_ARGS: readonly string[] = ["agent", "stdio"]; -/** @public */ export const GROK_ACP_ENV: readonly string[] = ["GROK_*", "XAI_*"]; -/** @public */ export const GROK_VERSION_SIDE_EFFECT = "Creates ~/.grok, or $GROK_HOME, when it does not exist, as every grok run does."; diff --git a/packages/providers/grok/src/records.ts b/packages/providers/grok/src/records.ts index 495f8d51..c7721dd7 100644 --- a/packages/providers/grok/src/records.ts +++ b/packages/providers/grok/src/records.ts @@ -449,8 +449,3 @@ export function grokUsageLines(file: UsageFile, saved?: unknown): UsageLineDecod } }; } - -/** The key under which a scan counts a record once in its window: the session and the turn's prompt id. */ -export function grokUsageKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} diff --git a/packages/providers/grok/src/usage.ts b/packages/providers/grok/src/usage.ts index 0d158d8b..f89cd6c6 100644 --- a/packages/providers/grok/src/usage.ts +++ b/packages/providers/grok/src/usage.ts @@ -11,13 +11,14 @@ import { grokUsageSessionId, grokUsageSourceId } from "./layout.js"; -import { grokUsageKey, grokUsageLines } from "./records.js"; +import { grokUsageLines } from "./records.js"; import { readText, type UsageDecoder, decodeJsonlUsage, fileSources, - type JsonlUsageLayout + type JsonlUsageLayout, + usageWindowKey } from "@rivus/agent-kit-sessions/spi"; const layout: JsonlUsageLayout = { @@ -56,7 +57,7 @@ const layout: JsonlUsageLayout = { export const grokUsageDecoder: UsageDecoder = { specificationVersion: "usage-v1", agent: GROK_ID, - usageKey: grokUsageKey, + usageKey: usageWindowKey, sources(platform, home, options = {}) { return fileSources(platform, GROK_ID, grokRoots(home), GROK_SESSION_FILES, { ...options, diff --git a/packages/providers/kimi/src/facts.ts b/packages/providers/kimi/src/facts.ts index 8da1364e..ecefea43 100644 --- a/packages/providers/kimi/src/facts.ts +++ b/packages/providers/kimi/src/facts.ts @@ -3,54 +3,32 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; // https://www.kimi.com/code/docs/en/kimi-code-cli/ (getting started, data locations, env vars, providers, hooks, // and the `kimi acp` reference). -/** @public */ export const KIMI_ID = "kimi"; -/** @public */ export const KIMI_DISPLAY_NAME = "Kimi Code"; /** @public */ export const HOME_DIR = ".kimi-code"; // The override names the data root itself, rather than its parent. /** @public */ export const HOME_ENV = "KIMI_CODE_HOME"; -/** @public */ export const KIMI_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [HOME_DIR] }; -/** @public */ export const KIMI_CONFIG_FILE = "config.toml"; -/** @public */ export const KIMI_MCP_FILE = "mcp.json"; -/** @public */ export const KIMI_SESSIONS_DIR = "sessions"; -/** @public */ -export const KIMI_SESSION_INDEX_FILE = "session_index.jsonl"; -/** @public */ export const KIMI_SESSION_STATE_FILE = "state.json"; -/** @public */ export const KIMI_SESSION_WIRE_FILE = "agents/main/wire.jsonl"; -/** @public */ export const KIMI_CREDENTIALS_DIR = "credentials"; -/** @public */ export const KIMI_CONFIG_PATH: string = `~/${HOME_DIR}/${KIMI_CONFIG_FILE}`; // Hooks are `[[hooks]]` entries of the user config, each carrying its event in an `event` field; there is no // project-level hook file. -/** @public */ export const KIMI_HOOKS_POINTER = "/hooks"; -/** @public */ export const KIMI_HOOK_FORMAT = "toml"; -/** @public */ export const KIMI_HOOK_LAYOUT = "event-list"; -/** @public */ export const KIMI_HOOK_MEMBER_KEYS: readonly string[] = ["event", "command"]; // The one payload field only Kimi's hooks carry (see the hooks guide's event data format). -/** @public */ export const KIMI_CLIENT_TYPE_FIELD = "client_type"; -/** @public */ -export const KIMI_CLIENT_TYPE = "kimi_code_cli"; // Kimi reads keys from config.toml, never from the environment, except the temporary KIMI_MODEL_* provider. -/** @public */ export const KIMI_MODEL_API_KEY_ENV = "KIMI_MODEL_API_KEY"; -/** @public */ export const KIMI_ACP_ARGS: readonly string[] = ["acp"]; -/** @public */ export const KIMI_ACP_ENV: readonly string[] = ["KIMI_*"]; /** @public */ diff --git a/packages/providers/kimi/src/install.ts b/packages/providers/kimi/src/install.ts index 8652b969..1c63ee44 100644 --- a/packages/providers/kimi/src/install.ts +++ b/packages/providers/kimi/src/install.ts @@ -6,6 +6,7 @@ import { KIMI_CONFIG_FILE, KIMI_CONFIG_PATH, KIMI_HOOK_FORMAT, + KIMI_HOOK_LAYOUT, KIMI_HOOK_MEMBER_KEYS, KIMI_HOOKS_POINTER, KIMI_HOME, @@ -64,7 +65,7 @@ export const kimiInstallAdapter: InstallAdapter = { { locator: { kind: "dir", path: `${sharedSkillsDir(context)}/${skill.name}` }, content: skill.files, strategy } ], hookSources: (context) => [ - { path: kimiConfigFile(context), format: KIMI_HOOK_FORMAT, layout: "event-list", pointer: KIMI_HOOKS_POINTER } + { path: kimiConfigFile(context), format: KIMI_HOOK_FORMAT, layout: KIMI_HOOK_LAYOUT, pointer: KIMI_HOOKS_POINTER } ], legacySources: (context) => [ { diff --git a/packages/providers/kimi/src/records.ts b/packages/providers/kimi/src/records.ts index e5283e2a..af36cbef 100644 --- a/packages/providers/kimi/src/records.ts +++ b/packages/providers/kimi/src/records.ts @@ -1,6 +1,12 @@ import * as z from "zod/mini"; import { compactUsage, lenient, type Usage } from "@rivus/agent-kit-sessions/spi"; +// The `wire.jsonl` event stream of a Kimi Code session, captured on 2.6.0 against a scripted model: a metadata +// header names the protocol version, `turn.prompt` frames turns, `context.append_message` records the messages +// the model saw, `context.append_loop_event` the per-step model loop (content parts, tool calls and results, +// step ends with usage), and `turn.ended` closes it. The schemas stay module-private; the value types are +// declared by hand, like the other adapters', and the `*Of` functions return them. + /** One part of a message's content: text is the only kind the verified protocol writes. */ export interface KimiContentPartValue { type: string; diff --git a/packages/providers/kimi/test/fixtures/hooks.ts b/packages/providers/kimi/test/fixtures/hooks.ts index 5dbe80f9..0ee7086e 100644 --- a/packages/providers/kimi/test/fixtures/hooks.ts +++ b/packages/providers/kimi/test/fixtures/hooks.ts @@ -7,9 +7,8 @@ const sessionId = "session_abc123"; const cwd = "/u/me/work"; const identity = { agent: "kimi", sessionId, cwd } as const; - const sample = hookEventSampleFactory({ - payload: { hook_event_name: "", session_id: sessionId, session_title: "Fix the login page", client_type: "kimi_code_cli", cwd }, + payload: { session_id: sessionId, session_title: "Fix the login page", client_type: "kimi_code_cli", cwd }, expected: identity }); diff --git a/packages/providers/opencode/src/facts.ts b/packages/providers/opencode/src/facts.ts index 9c311ecc..a29ac02b 100644 --- a/packages/providers/opencode/src/facts.ts +++ b/packages/providers/opencode/src/facts.ts @@ -1,42 +1,26 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const OPENCODE_ID = "opencode"; const HOME_ENV = "XDG_DATA_HOME"; // OpenCode keeps data in the XDG data directory and plugins in the XDG configuration directory. -/** @public */ export const OPENCODE_HOME: HomeRule = { envVar: HOME_ENV, envSubpath: [OPENCODE_ID], defaultPath: [".local", "share", OPENCODE_ID] }; -/** @public */ export const OPENCODE_DATABASE = "opencode.db"; -/** @public */ export const OPENCODE_MESSAGE_DIR = "storage/message"; -/** @public */ export const OPENCODE_AUTH_FILE = "auth.json"; -/** @public */ export const OPENCODE_AUTH_ENV = "OPENCODE_AUTH_CONTENT"; -/** @public */ export const OPENCODE_PLUGINS_DIR = "plugins"; -/** @public */ export const OPENCODE_CONFIG_FILE = "opencode.json"; -/** @public */ export const OPENCODE_PLUGINS_POINTER = "/plugin"; -/** @public */ export const OPENCODE_PLUGIN_SUFFIX = ".js"; -/** @public */ export const OPENCODE_PLUGIN_SUFFIXES: readonly string[] = [OPENCODE_PLUGIN_SUFFIX, ".ts"]; -/** @public */ export const OPENCODE_MESSAGE_SUFFIX = ".json"; -/** @public */ export const OPENCODE_DATABASE_SUFFIX = ".db"; -/** @public */ export const OPENCODE_WAL_SUFFIX = "-wal"; -/** @public */ export const OPENCODE_ACP_ARGS: readonly string[] = ["acp"]; -/** @public */ export const OPENCODE_ACP_ENV: readonly string[] = [ "OPENCODE_*", "*_API_KEY", @@ -49,7 +33,6 @@ export const OPENCODE_ACP_ENV: readonly string[] = [ ]; /** The bridge remembers the session under a key absent from native payloads. */ -/** @public */ export const OPENCODE_CURRENT_SESSION_FIELD = "currentSessionId"; /** @public */ diff --git a/packages/providers/pi/src/facts.ts b/packages/providers/pi/src/facts.ts index ec469310..992753ea 100644 --- a/packages/providers/pi/src/facts.ts +++ b/packages/providers/pi/src/facts.ts @@ -1,37 +1,24 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const PI_ID = "pi"; -/** @public */ export const PI_DISPLAY_NAME = "Pi"; /** @public */ export const HOME_DIR = ".pi"; /** @public */ export const HOME_ENV = "PI_CODING_AGENT_DIR"; // The override names the agent directory itself, rather than its parent. -/** @public */ export const PI_HOME: HomeRule = { envVar: HOME_ENV, expandsTilde: true, defaultPath: [HOME_DIR, "agent"] }; -/** @public */ export const PI_SESSIONS_DIR = "sessions"; -/** @public */ export const PI_EXTENSIONS_DIR = "extensions"; -/** @public */ export const PI_SETTINGS_FILE = "settings.json"; -/** @public */ export const PI_EXTENSIONS_POINTER = "/extensions"; -/** @public */ export const PI_EXTENSION_SUFFIX = ".ts"; -/** @public */ export const PI_EXTENSION_SUFFIXES: readonly string[] = [".js", PI_EXTENSION_SUFFIX]; -/** @public */ export const PI_SESSION_SUFFIX = ".jsonl"; -/** @public */ export const PI_SESSION_SUFFIX_PATTERN: RegExp = /\.jsonl$/; // Pi ships no ACP server; the community adapter (npm `pi-acp`, svkozak/pi-acp) drives `pi --mode rpc`. -/** @public */ export const PI_ACP_COMMAND = "pi-acp"; -/** @public */ export const PI_ACP_ENV: readonly string[] = [ "PI_*", // Pi reads provider keys from the environment (or `~/.pi/agent/auth.json` and `models.json`); these globs cover diff --git a/packages/providers/pi/src/usage.ts b/packages/providers/pi/src/usage.ts index 0978182f..aadf5d15 100644 --- a/packages/providers/pi/src/usage.ts +++ b/packages/providers/pi/src/usage.ts @@ -15,7 +15,8 @@ import { decodeJsonlUsage, fileSources, type JsonlUsageLayout, - sameFile + sameFile, + usageWindowKey } from "@rivus/agent-kit-sessions/spi"; import { PI_ID as AGENT } from "./facts.js"; import { PI_SESSION_FILES, piSessionStem, piUsageRoots } from "./layout.js"; @@ -165,11 +166,6 @@ export function piUsageLines(file: UsageFile, saved?: unknown): UsageLineDecoder }; } -/** The key under which a scan counts a record once in its window: the session and the entry id, unique in its session (a provider's response id need not be unique: a local model server numbers them). */ -function piUsageKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} - const layout: JsonlUsageLayout = { agent: AGENT, file: sameFile((path) => ({ sessionId: piSessionStem(path) })), @@ -180,7 +176,7 @@ const layout: JsonlUsageLayout = { export const piUsageDecoder: UsageDecoder = { specificationVersion: "usage-v1", agent: AGENT, - usageKey: piUsageKey, + usageKey: usageWindowKey, sources(platform, home, options = {}) { return fileSources(platform, AGENT, piUsageRoots(home), PI_SESSION_FILES, { ...options, identify: basenamePath }); }, diff --git a/packages/providers/qoder/src/facts.ts b/packages/providers/qoder/src/facts.ts index 2f354228..be8d539a 100644 --- a/packages/providers/qoder/src/facts.ts +++ b/packages/providers/qoder/src/facts.ts @@ -5,12 +5,9 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; // ships `qodercli hooks migrate` from Claude Code), per its agent SDK's protocol types // (npm `@qoder-ai/qoder-agent-sdk`, dist/types/{hooks,settings}.d.ts) and the binary strings. -/** @public */ export const QODER_ID = "qoder"; -/** @public */ export const QODER_DISPLAY_NAME = "Qoder CLI"; // The entry point the installer puts on PATH; the versioned binary lives under `~/.qoder/bin/qodercli/`. -/** @public */ export const QODER_COMMAND = "qodercli"; /** @public */ export const HOME_DIR = ".qoder"; @@ -18,28 +15,15 @@ export const HOME_DIR = ".qoder"; // also appears there). /** @public */ export const HOME_ENV = "QODER_CONFIG_DIR"; -/** @public */ export const QODER_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [HOME_DIR] }; -/** @public */ export const QODER_SETTINGS_FILE = "settings.json"; -/** @public */ export const QODER_SETTINGS_PATH: string = `~/${HOME_DIR}/${QODER_SETTINGS_FILE}`; -/** @public */ export const QODER_HOOKS_POINTER = "/hooks"; -/** @public */ export const QODER_HOOK_FORMAT = "json"; -/** @public */ export const QODER_HOOK_LAYOUT = "grouped"; -// Project settings live in the workspace under `.qoder/`, beside `settings.local.json`. -/** @public */ -export const QODER_PROJECT_SETTINGS_DIR = ".qoder"; -/** @public */ export const QODER_OAUTH_FILE = "oauth_creds.json"; -/** @public */ export const QODER_PAT_ENV = "QODER_PERSONAL_ACCESS_TOKEN"; -/** @public */ export const QODER_ACP_ARGS: readonly string[] = ["--acp"]; -/** @public */ export const QODER_ACP_ENV: readonly string[] = ["QODER_*", "DASHSCOPE_API_KEY"]; /** @public */ diff --git a/packages/providers/qoder/test/fixtures/hooks.ts b/packages/providers/qoder/test/fixtures/hooks.ts index c5790334..f9a3561e 100644 --- a/packages/providers/qoder/test/fixtures/hooks.ts +++ b/packages/providers/qoder/test/fixtures/hooks.ts @@ -1,4 +1,3 @@ - import { hookEventSampleFactory, type HookDialectSample } from "@rivus/agent-kit-testing/public"; // Synthetic Qoder CLI hook payloads, per the agent SDK's protocol hook types: the Claude-Code-shaped snake_case base @@ -9,11 +8,10 @@ const cwd = "/u/me/work"; const transcriptPath = `${cwd}/.qoder/t.jsonl`; const identity = { agent: "qoder", sessionId, cwd, transcriptPath } as const; - const tool = { tool_name: "Bash", tool_use_id: "tc_3", tool_input: { command: "ls" } }; const sample = hookEventSampleFactory({ - payload: { hook_event_name: "", session_id: sessionId, cwd, transcript_path: transcriptPath }, + payload: { session_id: sessionId, cwd, transcript_path: transcriptPath }, expected: identity }); diff --git a/packages/providers/zcode/src/facts.ts b/packages/providers/zcode/src/facts.ts index de45e033..acf3cccb 100644 --- a/packages/providers/zcode/src/facts.ts +++ b/packages/providers/zcode/src/facts.ts @@ -1,37 +1,23 @@ import type { HomeRule } from "@rivus/agent-kit-catalog/spi"; -/** @public */ export const ZCODE_ID = "zcode"; -/** @public */ export const ZCODE_DISPLAY_NAME = "ZCode"; -/** @public */ export const HOME_DIR = ".zcode"; /** @public */ export const HOME_ENV = "ZCODE_STORAGE_DIR"; -/** @public */ export const ZCODE_HOME: HomeRule = { envVar: HOME_ENV, defaultPath: [HOME_DIR] }; -/** @public */ export const ZCODE_DB_DIR = "cli/db"; -/** @public */ export const ZCODE_DATABASE = "db.sqlite"; -/** @public */ export const ZCODE_WAL_SUFFIX = "-wal"; -/** @public */ export const ZCODE_CONFIG_FILE = "cli/config.json"; -/** @public */ export const ZCODE_KIT_PLUGINS = "agent-kit/zcode"; -/** @public */ export const ZCODE_PLUGIN_MANIFEST = ".zcode-plugin/plugin.json"; -/** @public */ export const ZCODE_PLUGIN_HOOKS = "hooks/hooks.json"; -/** @public */ export const ZCODE_PLUGIN_DIRS_POINTER = "/plugins/dirs"; // The login the CLI shares with the app sits under ZCODE_DATA_BASE_DIR (default the home directory), not under // ZCODE_STORAGE_DIR; the variable-named base is what a probe path cannot express. -/** @public */ export const ZCODE_CREDENTIAL_FILE = "~/.zcode/v2/credentials.json"; /** Keys whose non-empty string value means a login is stored; checked by name only, never read out. */ -/** @public */ export const ZCODE_CREDENTIAL_KEYS: readonly string[] = [ "oauth:bigmodel:access_token", "oauth:zai:access_token", @@ -39,10 +25,8 @@ export const ZCODE_CREDENTIAL_KEYS: readonly string[] = [ ]; /** The session id ZCode exports to every hook process, beside Claude Code's `CLAUDE_CODE_SESSION_ID`. */ -/** @public */ export const ZCODE_SESSION_ENV = "ZCODE_SESSION_ID"; /** A payload field only ZCode's hook input carries; see the hook dialect. */ -/** @public */ export const ZCODE_HOST_FIELD = "traceId"; /** @public */ diff --git a/packages/providers/zcode/src/hooks.ts b/packages/providers/zcode/src/hooks.ts index 16a96be4..f5391f44 100644 --- a/packages/providers/zcode/src/hooks.ts +++ b/packages/providers/zcode/src/hooks.ts @@ -1,4 +1,11 @@ -import type { HookDialect, HookOutput } from "@rivus/agent-kit-harness/spi"; +import { + claudeShapedField, + claudeShapedHookOutput, + claudeShapedSessionId, + claudeShapedTurnId, + type HookDialect, + type HookOutput +} from "@rivus/agent-kit-harness/spi"; import { ZCODE_HOST_FIELD, ZCODE_ID, ZCODE_SESSION_ENV } from "./facts.js"; // Read from ZCode 3.17.2's engine (Contents/Resources/glm/zcode.cjs); ZCode documents no hook reference. Command hooks @@ -28,13 +35,7 @@ const FIELDS: readonly string[] = [ * schema, or whose `hookSpecificOutput` names another event, fails the hook instead. Exit 2 blocks; any other exit * fails the hook, which a PreToolUse declaration's `onError: "deny"` turns into a denial. `{}` decides nothing. */ -const OUTPUT: HookOutput = { - emptyStdout: "proceed", - invalidStdout: "proceed", - exitCode2: "block", - otherExitCodes: "hook-failed", - passThrough: "{}" -}; +const OUTPUT: HookOutput = { ...claudeShapedHookOutput }; export const zcodeHookDialect: HookDialect = { specificationVersion: "harness-v1", @@ -50,12 +51,12 @@ export const zcodeHookDialect: HookDialect = { output: OUTPUT, // `transcript_path` is not mapped: it names a file ZCode writes for one run and deletes afterwards. fields: { - event: { paths: [["hook_event_name"]] }, - sessionId: { paths: [["session_id"]], env: [ZCODE_SESSION_ENV] }, - cwd: { paths: [["cwd"]] }, - turnId: { paths: [["turnId"]] }, - toolName: { paths: [["tool_name"]] }, - toolCallId: { paths: [["tool_use_id"]] } + event: claudeShapedField("hook_event_name"), + sessionId: claudeShapedSessionId([ZCODE_SESSION_ENV]), + cwd: claudeShapedField("cwd"), + turnId: claudeShapedTurnId("turnId"), + toolName: claudeShapedField("tool_name"), + toolCallId: claudeShapedField("tool_use_id") }, events: { // `source` is `startup` or `resume`. diff --git a/packages/sessions/src/domain/usage/services/usage-window.test.ts b/packages/sessions/src/domain/usage/services/usage-window.test.ts index b3eb924c..14332597 100644 --- a/packages/sessions/src/domain/usage/services/usage-window.test.ts +++ b/packages/sessions/src/domain/usage/services/usage-window.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vite-plus/test"; import type { UsageRecord } from "../value-objects/usage-record.js"; -import { restoreUsageWindow } from "./usage-window.js"; +import { restoreUsageWindow, usageWindowKey } from "./usage-window.js"; const DAY_MS = 24 * 60 * 60 * 1000; @@ -37,4 +37,12 @@ describe("usage window", () => { expect(after.count(record("codex", "old", 2 * DAY_MS), "old")).toBe(true); expect(after.count(record("codex", "new", 6 * DAY_MS + 1), "new")).toBe(false); }); + + it("keys records by session and request id when present, else undefined", () => { + const withRequest = record("codex", "req-1", DAY_MS); + expect(usageWindowKey(withRequest)).toBe("s req-1"); + + const { requestId: _omitted, ...withoutRequest } = withRequest; + expect(usageWindowKey(withoutRequest)).toBeUndefined(); + }); }); diff --git a/packages/sessions/src/domain/usage/services/usage-window.ts b/packages/sessions/src/domain/usage/services/usage-window.ts index 7a7cf9e0..10e9e073 100644 --- a/packages/sessions/src/domain/usage/services/usage-window.ts +++ b/packages/sessions/src/domain/usage/services/usage-window.ts @@ -71,3 +71,11 @@ export function restoreUsageWindow( } }; } + +/** + * The key under which a usage scan counts a record once in its window: the + * session and the request id, when the record carries one. + */ +export function usageWindowKey(record: UsageRecord): string | undefined { + return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; +} diff --git a/packages/sessions/src/spi.ts b/packages/sessions/src/spi.ts index 49ca39d4..0f191392 100644 --- a/packages/sessions/src/spi.ts +++ b/packages/sessions/src/spi.ts @@ -161,16 +161,8 @@ export { export { type UsageFile, type UsageLineDecoder } from "./domain/usage/adapters/usage-lines.js"; export { rememberKey } from "./lib/remember-key.js"; export { decodeIsFinal } from "./domain/usage/services/quiet.js"; +export { usageWindowKey } from "./domain/usage/services/usage-window.js"; export { shortHash } from "./lib/short-hash.js"; export { type UsageCursor } from "./domain/usage/value-objects/usage-cursor.js"; export { type ModelUsage, type UsageRecord } from "./domain/usage/value-objects/usage-record.js"; -import type { UsageRecord } from "./domain/usage/value-objects/usage-record.js"; - -/** - * The key under which a usage scan counts a record once in its window: the - * session and the request id, when the record carries one. - */ -export function usageWindowKey(record: UsageRecord): string | undefined { - return record.requestId === undefined ? undefined : `${record.sessionId} ${record.requestId}`; -} export { type Usage, compactUsage } from "./domain/usage/value-objects/usage.js"; diff --git a/packages/testing/src/hook-dialect-conformance.ts b/packages/testing/src/hook-dialect-conformance.ts index 413b12f3..239c99e3 100644 --- a/packages/testing/src/hook-dialect-conformance.ts +++ b/packages/testing/src/hook-dialect-conformance.ts @@ -27,25 +27,29 @@ export interface HookDialectFixtures { readonly samples: readonly HookDialectSample[]; } +type HookSampleIdentity = { readonly agent: CodingAgentId } & Partial< + Omit +>; +type HookSampleExpected = Omit; + /** * The sample builder every agent's hook fixtures share: the agent's base payload and identity are * captured once, and each sample names its event and the per-event fields. */ export function hookSampleFactory(base: { readonly payload: Readonly>; - readonly expected: Partial>; + readonly expected: HookSampleIdentity; }): ( name: string, event: string, fields: Readonly>, - expected: Omit + expected: HookSampleExpected ) => HookDialectSample { - return (name, event, fields, expected) => - ({ - name, - payload: { ...base.payload, hook_event_name: event, ...fields }, - expected: { ...base.expected, nativeEvent: event, ...expected } - }) as HookDialectSample; + return (name, event, fields, expected) => ({ + name, + payload: { ...base.payload, hook_event_name: event, ...fields }, + expected: { ...base.expected, nativeEvent: event, ...expected } + }); } /** @@ -54,14 +58,10 @@ export function hookSampleFactory(base: { */ export function hookEventSampleFactory(base: { readonly payload: Readonly>; - readonly expected: Partial>; -}): ( - event: string, - fields?: Readonly>, - expected?: Partial> -) => HookDialectSample { + readonly expected: HookSampleIdentity; +}): (event: string, fields: Readonly>, expected: HookSampleExpected) => HookDialectSample { const byName = hookSampleFactory(base); - return (event, fields = {}, expected = {}) => byName(event, event, fields, expected as never); + return (event, fields, expected) => byName(event, event, fields, expected); } const PHASES = new Set(["start", "activity", "blocked", "finish", "unknown"]); From 5c254de1325c7770ca58e2d05b3dd6eb1e2bfe3d Mon Sep 17 00:00:00 2001 From: PerfectPan <24316656+PerfectPan@users.noreply.github.com> Date: Tue, 17 Nov 2026 14:16:54 +0800 Subject: [PATCH 7/7] refactor(codex): check record schema keys with inline satisfies --- .../providers/codex/src/records/record.ts | 44 +++++++------------ packages/providers/codex/src/records/usage.ts | 6 +-- 2 files changed, 19 insertions(+), 31 deletions(-) diff --git a/packages/providers/codex/src/records/record.ts b/packages/providers/codex/src/records/record.ts index c11eb08b..996a4eac 100644 --- a/packages/providers/codex/src/records/record.ts +++ b/packages/providers/codex/src/records/record.ts @@ -4,16 +4,6 @@ import * as z from "zod/mini"; // Codex writes one rollout record per line. Agent logs are read leniently: a field of an unexpected type counts as // absent (the sessions SPI's `lenient` helper), and only the record envelope decides whether the format generation is known. -/** - * A field named on one side of a schema/interface pair only — an interface typo, or a schema field the interface - * misses — fails to compile with this: the schema's keys and the value type's keys must be the same. - */ -export type KeysExact = - | Exclude - | Exclude extends never - ? true - : never; - /** A usage object as both `token_usage_record.usage` and `token_count.info` carry it. */ interface CodexTokenCounts { input_tokens?: number; @@ -31,7 +21,7 @@ const CodexTokenCountsSchema = z.looseObject({ output_tokens: lenient(z.number()), reasoning_output_tokens: lenient(z.number()), total_tokens: lenient(z.number()) -}); +} satisfies Record); /** A history item of a `replacement_history`: the fields matching keeps, `content` kept raw for the text. */ interface CodexHistoryItem { @@ -48,7 +38,7 @@ const CodexHistoryItemSchema = z.looseObject({ id: lenient(z.string()), call_id: lenient(z.string()), content: z.optional(z.unknown()) -}); +} satisfies Record); /** * The payload of a rollout record, whatever envelope carries it: the `session_meta` identity, the `turn_context` @@ -148,19 +138,22 @@ const CodexPayloadSchema = z.looseObject({ }) ), replacement_history: lenient(z.array(lenient(CodexHistoryItemSchema))) -}); +} satisfies Record); -/** - * One rollout record: the envelope `type`, the `record_type` bookkeeping marker, the header `id` of a pre-envelope - * rollout, and the presence markers the generation check reads. `payload` stays raw because only the record knows - * whether it is a bare item's record, whose fields sit on the record itself; readers parse it through `codexPayload`. - */ -interface CodexRecord { +interface CodexEnvelope { type?: string; record_type?: string; id?: string; timestamp?: number | string; formatVersion?: unknown; +} + +/** + * One rollout record: the envelope `type`, the `record_type` bookkeeping marker, the header `id` of a pre-envelope + * rollout, and the presence markers the generation check reads. `payload` stays raw because only the record knows + * whether it is a bare item's record, whose fields sit on the record itself; readers parse it through `codexPayload`. + */ +interface CodexRecord extends CodexEnvelope { payload?: unknown; } @@ -189,9 +182,12 @@ export const CodexEnvelopeSchema: z.ZodMiniObject< id: lenient(z.string()), timestamp: logTimestamp, formatVersion: z.optional(z.unknown()) -}); +} satisfies Record); -const CodexRecordSchema = z.looseObject({ ...CodexEnvelopeSchema.shape, payload: z.optional(z.unknown()) }); +const CodexRecordSchema = z.looseObject({ + ...CodexEnvelopeSchema.shape, + payload: z.optional(z.unknown()) +} satisfies Record); /** * A record of a format generation this adapter reads: no `formatVersion`, and a non-empty `type`, a `record_type` @@ -216,12 +212,6 @@ export type CodexPayloadValue = CodexPayload & Record; type CodexTokenCountsValue = CodexTokenCounts & Record; export type CodexHistoryItemValue = CodexHistoryItem & Record; -// Compile-time key checks: the schemas' keys must match the domain types exactly. -void (true satisfies KeysExact); -void (true satisfies KeysExact); -void (true satisfies KeysExact); -void (true satisfies KeysExact); - /** The rollout record `value`, or `undefined` when it is not a record. */ export function codexRecord(value: unknown): CodexRecordValue | undefined { return z.safeParse(CodexRecordSchema, value).data; diff --git a/packages/providers/codex/src/records/usage.ts b/packages/providers/codex/src/records/usage.ts index 5380f954..d83762ac 100644 --- a/packages/providers/codex/src/records/usage.ts +++ b/packages/providers/codex/src/records/usage.ts @@ -14,7 +14,7 @@ import { type UsageFile, type UsageLineDecoder } from "@rivus/agent-kit-sessions/spi"; -import { CodexEnvelopeSchema, codexTokenCounts, type KeysExact, knownCodexRecord } from "./record.js"; +import { CodexEnvelopeSchema, codexTokenCounts, knownCodexRecord } from "./record.js"; import { endForkReplay, FORK_REPLAY_START, type ForkReplayState, stepForkReplay } from "./fork-replay.js"; import * as z from "zod/mini"; @@ -63,9 +63,7 @@ const CodexUsagePayloadSchema = z.looseObject({ }) ), thread_settings: lenient(z.looseObject({ service_tier: lenient(z.string()) })) -}); - -void (true satisfies KeysExact); +} satisfies Record); /** * One rollout record for the usage rule: the envelope every codex reader parses, and the payload fields above. One