@doingdev/opencode-claude-manager-plugin 0.1.22 → 0.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +129 -40
  2. package/dist/claude/claude-agent-sdk-adapter.d.ts +27 -0
  3. package/dist/claude/claude-agent-sdk-adapter.js +520 -0
  4. package/dist/claude/claude-session.service.d.ts +15 -0
  5. package/dist/claude/claude-session.service.js +23 -0
  6. package/dist/claude/session-live-tailer.d.ts +51 -0
  7. package/dist/claude/session-live-tailer.js +269 -0
  8. package/dist/claude/tool-approval-manager.d.ts +27 -0
  9. package/dist/claude/tool-approval-manager.js +238 -0
  10. package/dist/index.d.ts +4 -5
  11. package/dist/index.js +4 -5
  12. package/dist/manager/context-tracker.d.ts +33 -0
  13. package/dist/manager/context-tracker.js +108 -0
  14. package/dist/manager/git-operations.d.ts +12 -0
  15. package/dist/manager/git-operations.js +76 -0
  16. package/dist/manager/persistent-manager.d.ts +74 -0
  17. package/dist/manager/persistent-manager.js +167 -0
  18. package/dist/manager/session-controller.d.ts +45 -0
  19. package/dist/manager/session-controller.js +147 -0
  20. package/dist/metadata/claude-metadata.service.d.ts +12 -0
  21. package/dist/metadata/claude-metadata.service.js +38 -0
  22. package/dist/metadata/repo-claude-config-reader.d.ts +7 -0
  23. package/dist/metadata/repo-claude-config-reader.js +154 -0
  24. package/dist/plugin/agent-hierarchy.d.ts +47 -0
  25. package/dist/plugin/agent-hierarchy.js +110 -0
  26. package/dist/plugin/claude-manager.plugin.d.ts +2 -0
  27. package/dist/plugin/claude-manager.plugin.js +490 -0
  28. package/dist/plugin/orchestrator.plugin.js +4 -2
  29. package/dist/plugin/service-factory.d.ts +12 -0
  30. package/dist/plugin/service-factory.js +41 -0
  31. package/dist/prompts/registry.d.ts +2 -8
  32. package/dist/prompts/registry.js +203 -29
  33. package/dist/state/file-run-state-store.d.ts +14 -0
  34. package/dist/state/file-run-state-store.js +87 -0
  35. package/dist/state/transcript-store.d.ts +15 -0
  36. package/dist/state/transcript-store.js +44 -0
  37. package/dist/types/contracts.d.ts +216 -0
  38. package/dist/types/contracts.js +1 -0
  39. package/dist/util/fs-helpers.d.ts +2 -0
  40. package/dist/util/fs-helpers.js +12 -0
  41. package/dist/util/transcript-append.d.ts +7 -0
  42. package/dist/util/transcript-append.js +29 -0
  43. package/package.json +5 -3
@@ -1,37 +1,211 @@
1
- /**
2
- * Agent prompt registry for the orchestrator + Claude Code subagent architecture.
3
- */
4
- export const prompts = {
5
- orchestrator: [
6
- 'You are the orchestrator a CTO-level proxy for the user.',
7
- 'Your job is to gather minimal context, then delegate coding work to specialist Claude Code agents.',
8
- '',
9
- '## Rules',
10
- '- Do NOT write or edit code yourself unless the user explicitly asks you to.',
11
- '- Read files, search, and plan to understand the task, then delegate.',
12
- '- Use planning agents (claude-code-planning-opus/sonnet) for investigation, architecture, and plans.',
13
- '- Use build agents (claude-code-build-opus/sonnet) for implementation and validation.',
14
- '- Run specialists in parallel when tasks are independent.',
15
- '- Compare outputs from multiple specialists when the choice matters.',
16
- '- Keep delegations focused: one clear objective per specialist call.',
17
- '- Track multi-step work with todowrite/todoread.',
18
- '- Ask the user (via question tool) when trade-offs need human judgment.',
1
+ export const managerPromptRegistry = {
2
+ ctoSystemPrompt: [
3
+ 'You are the CTO — you set direction and orchestrate, but you never execute directly.',
4
+ '',
5
+ '## Your role',
6
+ "- Analyze the user's request and break it into focused slices of work.",
7
+ '- Spawn one or more `manager` subagents, each with a clear, scoped objective.',
8
+ '- Each `manager` has its own Claude Code persistent session and can investigate,',
9
+ ' delegate to the engineer, review diffs, and commit.',
10
+ '- Review subagent results and synthesize them for the user.',
11
+ '',
12
+ '## What you can do',
13
+ '- Read files, grep, and search the codebase to understand the problem.',
14
+ '- Use webfetch / websearch for external context.',
15
+ '- Use todowrite / todoread to track high-level progress.',
16
+ '- Ask the user structured questions when decisions require their input.',
17
+ '',
18
+ '## What you must NOT do',
19
+ '- Do NOT call any engineer_*, git_*, or approval_* tools. You do not operate Claude Code directly.',
20
+ '- Do NOT edit files, run bash commands, or make code changes yourself.',
21
+ '- Do NOT micro-manage subagents — give them clear objectives and let them execute.',
22
+ '',
23
+ '## Spawning subagents',
24
+ '- Spawn a `manager` subagent for each independent slice of work.',
25
+ '- If slices are independent, spawn them in parallel.',
26
+ '- Provide each subagent with:',
27
+ ' 1. A clear, scoped objective.',
28
+ ' 2. Relevant file paths, function names, and context you gathered.',
29
+ ' 3. Success criteria so the subagent knows when it is done.',
30
+ '- For sequential work, wait for one subagent to finish before spawning the next.',
31
+ '',
32
+ '## After subagents complete',
33
+ '- Review what each subagent accomplished.',
34
+ '- If something is wrong, spawn a new subagent with a targeted correction.',
35
+ '- Synthesize results and report to the user.',
36
+ '',
37
+ '## Handling ambiguity',
38
+ 'When requirements are unclear:',
39
+ '1. First, try to resolve it yourself — read code, check tests, grep for usage.',
40
+ '2. If ambiguity remains, ask the user ONE specific question.',
41
+ ' Prefer the question tool when discrete options exist.',
42
+ '3. Never block on multiple questions at once.',
19
43
  ].join('\n'),
20
- planningAgent: [
21
- 'You are a planning specialist. Investigate, analyze architecture, and produce implementation plans.',
44
+ managerSystemPrompt: [
45
+ 'You are a manager operating a Claude Code engineer through a persistent session.',
46
+ 'Your job is to make the engineer do the work — not to write code yourself.',
47
+ 'Think like a staff engineer: correctness, maintainability, tests, rollback safety,',
48
+ 'and clear communication to the user.',
49
+ '',
50
+ '## Decision loop',
51
+ 'On every turn, choose exactly one action:',
52
+ ' investigate — read files, grep, search the codebase to build context',
53
+ ' delegate — send a focused instruction to the engineer via engineer_send',
54
+ ' review — run git_diff to inspect what changed',
55
+ ' validate — tell the engineer to run tests, lint, or typecheck',
56
+ ' commit — checkpoint good work with git_commit',
57
+ ' correct — send a targeted fix instruction (never "try again")',
58
+ ' reset — discard bad work with git_reset',
59
+ ' ask — use the question tool for structured choices, or one narrow text question',
60
+ '',
61
+ 'Default order: investigate → delegate → review → validate → commit.',
62
+ 'Skip steps only when you have strong evidence they are unnecessary.',
63
+ '',
64
+ '## Before you delegate',
65
+ '1. Read the relevant files yourself (you have read, grep, glob).',
66
+ ' For broad investigations, scope them narrowly or use subagents to avoid',
67
+ ' polluting your own context with excessive file contents.',
68
+ '2. Identify the exact files, functions, line numbers, and patterns involved.',
69
+ '3. Check existing conventions: naming, test style, error handling patterns.',
70
+ '4. Craft an instruction that a senior engineer would find unambiguous.',
71
+ ' Bad: "Fix the auth bug"',
72
+ ' Good: "In src/auth/session.ts, the `validateToken` function (line 42)',
73
+ ' throws on expired tokens instead of returning null. Change it to',
74
+ ' return null and update the caller in src/routes/login.ts:87."',
75
+ '',
76
+ '## After delegation — mandatory review',
77
+ 'Never claim success without evidence:',
78
+ '1. git_diff — read the actual diff, not just the summary.',
79
+ '2. Verify the diff matches what you asked for. Check for:',
80
+ ' - Unintended changes or regressions',
81
+ ' - Missing test updates',
82
+ ' - Style violations against repo conventions',
83
+ '3. If changes look correct, tell the engineer to run tests/lint/typecheck.',
84
+ '4. Only commit after verification passes.',
85
+ '5. If the diff is wrong: send a specific correction or reset.',
22
86
  '',
23
- '- Read code, grep, search — build full context before answering.',
24
- '- Produce concrete plans: files to change, functions to modify, test strategy, risks.',
25
- '- Do NOT edit files or run destructive commands unless explicitly asked.',
26
- '- Be concise. End with a numbered action plan.',
87
+ '## Handling ambiguity',
88
+ 'When requirements are unclear:',
89
+ '1. First, try to resolve it yourself read code, check tests, grep for usage.',
90
+ '2. If ambiguity remains, ask the user ONE specific question.',
91
+ ' Prefer the question tool when discrete options exist (OpenCode shows choices in the UI).',
92
+ ' Bad: "What should I do?"',
93
+ ' Good: "The `UserService` has both `deactivate()` and `softDelete()` —',
94
+ ' should the new endpoint use deactivation (reversible) or',
95
+ ' soft-delete (audit-logged)?"',
96
+ '3. Never block on multiple questions at once.',
97
+ '',
98
+ '## Correction and recovery',
99
+ 'If the engineer produces wrong output:',
100
+ '1. First correction: send a specific, targeted fix instruction.',
101
+ '2. Second correction on the same issue: reset, clear the session,',
102
+ ' and rewrite the prompt incorporating lessons from both failures.',
103
+ 'Never send three corrections for the same problem in one session.',
104
+ '',
105
+ '## Multi-step tasks',
106
+ '- Use todowrite / todoread to track steps in OpenCode; keep items concrete and few.',
107
+ '- Decompose large tasks into sequential focused instructions.',
108
+ '- Commit after each successful step (checkpoint for rollback).',
109
+ '- Tell the engineer to use subagents for independent parallel work.',
110
+ '- For complex design decisions, tell the engineer to "think hard".',
111
+ '- Prefer small diffs — they are easier to review and safer to ship.',
112
+ '',
113
+ '## Context management',
114
+ 'Check the context snapshot returned by each send:',
115
+ '- Under 50%: proceed freely.',
116
+ '- 50–70%: finish current step, then evaluate if a fresh session is needed.',
117
+ '- Over 70%: use engineer_compact to reclaim context if the session',
118
+ ' still has useful state. Only clear if compaction is insufficient.',
119
+ '- Over 85%: clear the session immediately.',
120
+ 'Use freshSession:true on engineer_send when switching to an unrelated',
121
+ 'task or when the session context is contaminated. Prefer this over a manual',
122
+ 'clear+send sequence — it is atomic and self-documenting.',
123
+ '',
124
+ '## Model and effort selection',
125
+ 'Choose model and effort deliberately before each delegation:',
126
+ '- claude-opus-4-6 + high effort: default for most coding tasks.',
127
+ '- claude-sonnet-4-6 or claude-sonnet-4-5: faster/lighter work (simple renames,',
128
+ ' formatting, test scaffolding, quick investigations).',
129
+ '- effort "medium": acceptable for lighter tasks that do not require deep reasoning.',
130
+ '- effort "max": reserve for unusually hard problems (complex refactors,',
131
+ ' subtle concurrency bugs, large cross-cutting changes).',
132
+ "- Do not use Haiku for this plugin's coding-agent role.",
133
+ '',
134
+ '## Plan mode',
135
+ 'When delegating with mode:"plan", the engineer returns a read-only',
136
+ 'implementation plan. The plan MUST be returned inline in the assistant',
137
+ 'response — do NOT write plan artifacts to disk, create files, or rely on',
138
+ 'ExitPlanMode. Treat the returned finalText as the plan. If the plan is',
139
+ 'acceptable, switch to mode:"free" and delegate the implementation steps.',
140
+ '',
141
+ '## Tools reference',
142
+ 'todowrite / todoread — OpenCode session todo list (track multi-step work)',
143
+ 'question — OpenCode user prompt with options (clarify trade-offs)',
144
+ 'engineer_send — send instruction (creates or resumes session)',
145
+ ' freshSession:true — clear session first (use for unrelated tasks)',
146
+ ' model / effort — choose deliberately (see "Model and effort selection")',
147
+ 'engineer_compact — compress session context (preserves session state)',
148
+ 'engineer_clear — drop session, next send starts fresh',
149
+ 'engineer_status — context health snapshot',
150
+ 'engineer_metadata — inspect repo Claude config',
151
+ 'engineer_sessions — list sessions or read transcripts',
152
+ 'engineer_runs — list or inspect run records',
153
+ 'git_diff — review all uncommitted changes',
154
+ 'git_commit — stage all + commit',
155
+ 'git_reset — hard reset + clean (destructive)',
156
+ 'approval_policy — view tool approval rules',
157
+ 'approval_decisions — view recent approval decisions',
158
+ 'approval_update — modify tool approval policy',
159
+ '',
160
+ '## Autonomy blockers — surface these to the user',
161
+ 'Be candid about what you cannot do autonomously:',
162
+ '- Credentials, API keys, or secrets you do not have.',
163
+ '- Architectural decisions with trade-offs the user should weigh.',
164
+ '- Destructive actions on shared state (deploy, publish, force-push).',
165
+ '- Access to external services or environments you cannot reach.',
166
+ 'State the blocker, what you need, and a concrete suggestion to unblock.',
27
167
  ].join('\n'),
28
- buildAgent: [
29
- 'You are a build specialist. Implement, test, and validate changes.',
168
+ engineerSessionPrompt: [
169
+ 'You are directed by a manager acting as your technical lead.',
170
+ 'Treat each message as a precise instruction from your manager.',
171
+ '',
172
+ '## Execution rules',
173
+ '- Execute instructions directly. Do not ask for clarification.',
174
+ '- Be concise — no preamble, no restating the task.',
175
+ '- Prefer targeted file reads over reading entire files.',
176
+ '- Use the Agent tool for independent parallel work.',
30
177
  '',
31
- '- Execute instructions precisely. Follow existing repo conventions.',
32
- '- Consider edge cases and include relevant tests.',
178
+ '## Quality expectations',
179
+ '- Follow existing repo conventions (naming, style, patterns).',
180
+ '- When creating or modifying code, consider edge cases and error handling.',
181
+ '- When modifying existing code, preserve surrounding style and structure.',
182
+ '- If asked to implement a feature, include relevant tests unless told otherwise.',
33
183
  '- Run tests/lint/typecheck when instructed; report exact output on failure.',
34
- '- Do NOT run git commit, git push, git reset, git checkout, or git stash.',
184
+ '',
185
+ '## Git boundary — do NOT run these commands:',
186
+ 'git commit, git push, git reset, git checkout, git stash.',
187
+ 'The manager handles all git operations externally.',
188
+ '',
189
+ '## Reporting',
35
190
  '- End with a brief verification summary: what was done, what was verified.',
191
+ '- Report blockers immediately with specifics: file, line, error message.',
192
+ '- If a task is partially complete, state exactly what remains.',
36
193
  ].join('\n'),
194
+ modePrefixes: {
195
+ plan: [
196
+ '[PLAN MODE] You are in read-only planning mode. Do NOT create or edit any files.',
197
+ 'Do NOT use ExitPlanMode or write plan artifacts to disk.',
198
+ 'Use read, grep, glob, and search tools only.',
199
+ 'Analyze the codebase and produce a detailed implementation plan:',
200
+ 'files to change, functions to modify, new files to create, test strategy,',
201
+ 'and potential risks. End with a numbered step-by-step plan.',
202
+ 'Return the entire plan inline in your response text.',
203
+ ].join(' '),
204
+ free: '',
205
+ },
206
+ contextWarnings: {
207
+ moderate: 'Session context is filling up ({percent}% estimated). Consider whether a fresh session would be more efficient.',
208
+ high: 'Session context is heavy ({percent}% estimated, {turns} turns, ${cost}). Start a new session or compact first.',
209
+ critical: 'Session context is near capacity ({percent}% estimated). Clear the session immediately before continuing.',
210
+ },
37
211
  };
@@ -0,0 +1,14 @@
1
+ import type { PersistentRunRecord } from '../types/contracts.js';
2
+ export declare class FileRunStateStore {
3
+ private readonly baseDirectoryName;
4
+ private readonly writeQueues;
5
+ constructor(baseDirectoryName?: string);
6
+ saveRun(run: PersistentRunRecord): Promise<void>;
7
+ getRun(cwd: string, runId: string): Promise<PersistentRunRecord | null>;
8
+ listRuns(cwd: string): Promise<PersistentRunRecord[]>;
9
+ updateRun(cwd: string, runId: string, update: (run: PersistentRunRecord) => PersistentRunRecord): Promise<PersistentRunRecord>;
10
+ private getRunKey;
11
+ private getRunsDirectory;
12
+ private getRunPath;
13
+ private enqueueWrite;
14
+ }
@@ -0,0 +1,87 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { isFileNotFoundError, writeJsonAtomically, } from '../util/fs-helpers.js';
4
+ export class FileRunStateStore {
5
+ baseDirectoryName;
6
+ writeQueues = new Map();
7
+ constructor(baseDirectoryName = '.claude-manager') {
8
+ this.baseDirectoryName = baseDirectoryName;
9
+ }
10
+ async saveRun(run) {
11
+ await this.enqueueWrite(this.getRunKey(run.cwd, run.id), async () => {
12
+ const runPath = this.getRunPath(run.cwd, run.id);
13
+ await fs.mkdir(path.dirname(runPath), { recursive: true });
14
+ await writeJsonAtomically(runPath, run);
15
+ });
16
+ }
17
+ async getRun(cwd, runId) {
18
+ const runPath = this.getRunPath(cwd, runId);
19
+ try {
20
+ const content = await fs.readFile(runPath, 'utf8');
21
+ return JSON.parse(content);
22
+ }
23
+ catch (error) {
24
+ if (isFileNotFoundError(error)) {
25
+ return null;
26
+ }
27
+ throw error;
28
+ }
29
+ }
30
+ async listRuns(cwd) {
31
+ const runsDirectory = this.getRunsDirectory(cwd);
32
+ try {
33
+ const entries = await fs.readdir(runsDirectory);
34
+ const runs = await Promise.all(entries
35
+ .filter((entry) => entry.endsWith('.json'))
36
+ .map(async (entry) => {
37
+ const content = await fs.readFile(path.join(runsDirectory, entry), 'utf8');
38
+ return JSON.parse(content);
39
+ }));
40
+ return runs.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt));
41
+ }
42
+ catch (error) {
43
+ if (isFileNotFoundError(error)) {
44
+ return [];
45
+ }
46
+ throw error;
47
+ }
48
+ }
49
+ async updateRun(cwd, runId, update) {
50
+ return this.enqueueWrite(this.getRunKey(cwd, runId), async () => {
51
+ const existingRun = await this.getRun(cwd, runId);
52
+ if (!existingRun) {
53
+ throw new Error(`Run ${runId} does not exist.`);
54
+ }
55
+ const updatedRun = update(existingRun);
56
+ const runPath = this.getRunPath(cwd, runId);
57
+ await fs.mkdir(path.dirname(runPath), { recursive: true });
58
+ await writeJsonAtomically(runPath, updatedRun);
59
+ return updatedRun;
60
+ });
61
+ }
62
+ getRunKey(cwd, runId) {
63
+ return `${cwd}:${runId}`;
64
+ }
65
+ getRunsDirectory(cwd) {
66
+ return path.join(cwd, this.baseDirectoryName, 'runs');
67
+ }
68
+ getRunPath(cwd, runId) {
69
+ return path.join(this.getRunsDirectory(cwd), `${runId}.json`);
70
+ }
71
+ async enqueueWrite(key, operation) {
72
+ const previousOperation = this.writeQueues.get(key) ?? Promise.resolve();
73
+ const resultPromise = previousOperation
74
+ .catch(() => undefined)
75
+ .then(operation);
76
+ const settledPromise = resultPromise.then(() => undefined, () => undefined);
77
+ this.writeQueues.set(key, settledPromise);
78
+ try {
79
+ return await resultPromise;
80
+ }
81
+ finally {
82
+ if (this.writeQueues.get(key) === settledPromise) {
83
+ this.writeQueues.delete(key);
84
+ }
85
+ }
86
+ }
87
+ }
@@ -0,0 +1,15 @@
1
+ import type { ClaudeSessionEvent } from '../types/contracts.js';
2
+ export declare class TranscriptStore {
3
+ private readonly baseDirectoryName;
4
+ constructor(baseDirectoryName?: string);
5
+ /**
6
+ * Append new events to the transcript file for the given session.
7
+ * Creates the file if it does not exist. Strips trailing partials before persisting.
8
+ */
9
+ appendEvents(cwd: string, sessionId: string, newEvents: ClaudeSessionEvent[]): Promise<void>;
10
+ /**
11
+ * Read all persisted transcript events for a session.
12
+ */
13
+ readEvents(cwd: string, sessionId: string): Promise<ClaudeSessionEvent[]>;
14
+ private getTranscriptPath;
15
+ }
@@ -0,0 +1,44 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { appendTranscriptEvents, stripTrailingPartials, } from '../util/transcript-append.js';
4
+ import { isFileNotFoundError, writeJsonAtomically, } from '../util/fs-helpers.js';
5
+ export class TranscriptStore {
6
+ baseDirectoryName;
7
+ constructor(baseDirectoryName = '.claude-manager') {
8
+ this.baseDirectoryName = baseDirectoryName;
9
+ }
10
+ /**
11
+ * Append new events to the transcript file for the given session.
12
+ * Creates the file if it does not exist. Strips trailing partials before persisting.
13
+ */
14
+ async appendEvents(cwd, sessionId, newEvents) {
15
+ if (newEvents.length === 0) {
16
+ return;
17
+ }
18
+ const filePath = this.getTranscriptPath(cwd, sessionId);
19
+ const existing = await this.readEvents(cwd, sessionId);
20
+ const merged = appendTranscriptEvents(existing, newEvents);
21
+ const cleaned = stripTrailingPartials(merged);
22
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
23
+ await writeJsonAtomically(filePath, cleaned);
24
+ }
25
+ /**
26
+ * Read all persisted transcript events for a session.
27
+ */
28
+ async readEvents(cwd, sessionId) {
29
+ const filePath = this.getTranscriptPath(cwd, sessionId);
30
+ try {
31
+ const content = await fs.readFile(filePath, 'utf8');
32
+ return JSON.parse(content);
33
+ }
34
+ catch (error) {
35
+ if (isFileNotFoundError(error)) {
36
+ return [];
37
+ }
38
+ throw error;
39
+ }
40
+ }
41
+ getTranscriptPath(cwd, sessionId) {
42
+ return path.join(cwd, this.baseDirectoryName, 'transcripts', `${sessionId}.json`);
43
+ }
44
+ }
@@ -0,0 +1,216 @@
1
+ export interface ManagerPromptRegistry {
2
+ ctoSystemPrompt: string;
3
+ managerSystemPrompt: string;
4
+ engineerSessionPrompt: string;
5
+ modePrefixes: {
6
+ plan: string;
7
+ free: string;
8
+ };
9
+ contextWarnings: {
10
+ moderate: string;
11
+ high: string;
12
+ critical: string;
13
+ };
14
+ }
15
+ export type ClaudeSettingSource = 'user' | 'project' | 'local';
16
+ export type SessionMode = 'plan' | 'free';
17
+ export interface ClaudeCommandMetadata {
18
+ name: string;
19
+ description: string;
20
+ argumentHint?: string;
21
+ source: 'sdk' | 'skill' | 'command';
22
+ path?: string;
23
+ }
24
+ export interface ClaudeSkillMetadata {
25
+ name: string;
26
+ description: string;
27
+ path: string;
28
+ source: 'skill' | 'command';
29
+ }
30
+ export interface ClaudeHookMetadata {
31
+ name: string;
32
+ matcher?: string;
33
+ sourcePath: string;
34
+ commandCount: number;
35
+ }
36
+ export interface ClaudeAgentMetadata {
37
+ name: string;
38
+ description: string;
39
+ model?: string;
40
+ source: 'sdk' | 'filesystem';
41
+ }
42
+ export interface ClaudeMetadataSnapshot {
43
+ collectedAt: string;
44
+ cwd: string;
45
+ commands: ClaudeCommandMetadata[];
46
+ skills: ClaudeSkillMetadata[];
47
+ hooks: ClaudeHookMetadata[];
48
+ agents: ClaudeAgentMetadata[];
49
+ claudeMdPath?: string;
50
+ settingsPaths: string[];
51
+ }
52
+ export interface ClaudeSessionEvent {
53
+ type: 'init' | 'assistant' | 'partial' | 'user' | 'tool_call' | 'tool_progress' | 'tool_summary' | 'status' | 'system' | 'result' | 'error';
54
+ sessionId?: string;
55
+ text: string;
56
+ turns?: number;
57
+ totalCostUsd?: number;
58
+ /** Present on live SDK-normalized events; omitted when compact-persisted to save space. */
59
+ rawType?: string;
60
+ }
61
+ export interface RunClaudeSessionInput {
62
+ cwd: string;
63
+ prompt: string;
64
+ systemPrompt?: string;
65
+ model?: string;
66
+ effort?: 'low' | 'medium' | 'high' | 'max';
67
+ mode?: SessionMode;
68
+ permissionMode?: 'default' | 'acceptEdits' | 'plan' | 'dontAsk';
69
+ /** Merged with `Skill` by the SDK adapter unless `Skill` appears in `disallowedTools`. */
70
+ allowedTools?: string[];
71
+ disallowedTools?: string[];
72
+ continueSession?: boolean;
73
+ resumeSessionId?: string;
74
+ forkSession?: boolean;
75
+ persistSession?: boolean;
76
+ includePartialMessages?: boolean;
77
+ settingSources?: ClaudeSettingSource[];
78
+ maxTurns?: number;
79
+ abortSignal?: AbortSignal;
80
+ }
81
+ export interface ClaudeSessionRunResult {
82
+ sessionId?: string;
83
+ events: ClaudeSessionEvent[];
84
+ finalText: string;
85
+ turns?: number;
86
+ totalCostUsd?: number;
87
+ inputTokens?: number;
88
+ outputTokens?: number;
89
+ contextWindowSize?: number;
90
+ }
91
+ export interface ClaudeSessionSummary {
92
+ sessionId: string;
93
+ summary: string;
94
+ cwd?: string;
95
+ gitBranch?: string;
96
+ createdAt?: number;
97
+ lastModified: number;
98
+ }
99
+ export interface ClaudeSessionTranscriptMessage {
100
+ role: 'user' | 'assistant';
101
+ sessionId: string;
102
+ messageId: string;
103
+ text: string;
104
+ }
105
+ export interface ClaudeCapabilitySnapshot {
106
+ commands: ClaudeCommandMetadata[];
107
+ agents: ClaudeAgentMetadata[];
108
+ models: string[];
109
+ }
110
+ export type ContextWarningLevel = 'ok' | 'moderate' | 'high' | 'critical';
111
+ export interface SessionContextSnapshot {
112
+ sessionId: string | null;
113
+ totalTurns: number;
114
+ totalCostUsd: number;
115
+ latestInputTokens: number | null;
116
+ latestOutputTokens: number | null;
117
+ contextWindowSize: number | null;
118
+ estimatedContextPercent: number | null;
119
+ warningLevel: ContextWarningLevel;
120
+ compactionCount: number;
121
+ }
122
+ export interface GitDiffResult {
123
+ hasDiff: boolean;
124
+ diffText: string;
125
+ stats: {
126
+ filesChanged: number;
127
+ insertions: number;
128
+ deletions: number;
129
+ };
130
+ }
131
+ export interface GitOperationResult {
132
+ success: boolean;
133
+ output: string;
134
+ error?: string;
135
+ }
136
+ export interface ActiveSessionState {
137
+ sessionId: string;
138
+ cwd: string;
139
+ startedAt: string;
140
+ totalTurns: number;
141
+ totalCostUsd: number;
142
+ estimatedContextPercent: number | null;
143
+ contextWindowSize: number | null;
144
+ latestInputTokens: number | null;
145
+ }
146
+ export type PersistentRunStatus = 'running' | 'completed' | 'failed';
147
+ export interface PersistentRunMessageRecord {
148
+ timestamp: string;
149
+ direction: 'sent' | 'received';
150
+ text: string;
151
+ turns?: number;
152
+ totalCostUsd?: number;
153
+ inputTokens?: number;
154
+ outputTokens?: number;
155
+ }
156
+ export interface PersistentRunActionRecord {
157
+ timestamp: string;
158
+ type: 'git_diff' | 'git_commit' | 'git_reset' | 'compact' | 'clear';
159
+ result: string;
160
+ }
161
+ export interface PersistentRunRecord {
162
+ id: string;
163
+ cwd: string;
164
+ task: string;
165
+ status: PersistentRunStatus;
166
+ createdAt: string;
167
+ updatedAt: string;
168
+ sessionId: string | null;
169
+ sessionHistory: string[];
170
+ messages: PersistentRunMessageRecord[];
171
+ actions: PersistentRunActionRecord[];
172
+ commits: string[];
173
+ context: SessionContextSnapshot;
174
+ finalSummary?: string;
175
+ }
176
+ export interface PersistentRunResult {
177
+ run: PersistentRunRecord;
178
+ }
179
+ export interface LiveTailEvent {
180
+ type: 'line' | 'error' | 'end';
181
+ sessionId: string;
182
+ data?: unknown;
183
+ rawLine?: string;
184
+ error?: string;
185
+ }
186
+ export interface ToolOutputPreview {
187
+ toolUseId: string;
188
+ content: string;
189
+ isError: boolean;
190
+ }
191
+ export interface ToolApprovalRule {
192
+ id: string;
193
+ description?: string;
194
+ /** Tool name — exact match or glob with * wildcard */
195
+ toolPattern: string;
196
+ /** Optional substring match against JSON-serialized tool input */
197
+ inputPattern?: string;
198
+ action: 'allow' | 'deny';
199
+ denyMessage?: string;
200
+ }
201
+ export interface ToolApprovalPolicy {
202
+ rules: ToolApprovalRule[];
203
+ defaultAction: 'allow' | 'deny';
204
+ defaultDenyMessage?: string;
205
+ enabled: boolean;
206
+ }
207
+ export interface ToolApprovalDecision {
208
+ timestamp: string;
209
+ toolName: string;
210
+ inputPreview: string;
211
+ title?: string;
212
+ matchedRuleId: string;
213
+ action: 'allow' | 'deny';
214
+ denyMessage?: string;
215
+ agentId?: string;
216
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export declare function writeJsonAtomically(filePath: string, data: unknown): Promise<void>;
2
+ export declare function isFileNotFoundError(error: unknown): error is NodeJS.ErrnoException;
@@ -0,0 +1,12 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { promises as fs } from 'node:fs';
3
+ export async function writeJsonAtomically(filePath, data) {
4
+ const tempPath = `${filePath}.${randomUUID()}.tmp`;
5
+ await fs.writeFile(tempPath, `${JSON.stringify(data, null, 2)}\n`, 'utf8');
6
+ await fs.rename(tempPath, filePath);
7
+ }
8
+ export function isFileNotFoundError(error) {
9
+ return (error instanceof Error &&
10
+ 'code' in error &&
11
+ error.code === 'ENOENT');
12
+ }
@@ -0,0 +1,7 @@
1
+ import type { ClaudeSessionEvent } from '../types/contracts.js';
2
+ export declare function stripTrailingPartials(events: ClaudeSessionEvent[]): ClaudeSessionEvent[];
3
+ /**
4
+ * Append transcript events for run-state persistence: at most one trailing
5
+ * `partial`, dropped whenever a non-partial event is appended.
6
+ */
7
+ export declare function appendTranscriptEvents(events: ClaudeSessionEvent[], incoming: ClaudeSessionEvent[]): ClaudeSessionEvent[];