oh-my-opencode 3.0.0-beta.1 → 3.0.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ja.md +109 -89
- package/README.md +113 -104
- package/README.zh-cn.md +664 -511
- package/bin/oh-my-opencode.js +80 -0
- package/bin/platform.js +38 -0
- package/bin/platform.test.ts +148 -0
- package/dist/agents/metis.d.ts +1 -0
- package/dist/agents/momus.d.ts +1 -1
- package/dist/agents/orchestrator-sisyphus.d.ts +3 -2
- package/dist/agents/prometheus-prompt.d.ts +3 -1
- package/dist/agents/sisyphus-junior.d.ts +6 -1
- package/dist/agents/types.d.ts +1 -0
- package/dist/agents/utils.d.ts +3 -2
- package/dist/cli/config-manager.d.ts +9 -1
- package/dist/cli/doctor/checks/opencode.d.ts +5 -1
- package/dist/cli/index.js +3886 -3763
- package/dist/cli/run/events.d.ts +1 -0
- package/dist/cli/types.d.ts +3 -0
- package/dist/config/schema.d.ts +538 -208
- package/dist/features/background-agent/concurrency.d.ts +17 -0
- package/dist/features/background-agent/manager.d.ts +44 -5
- package/dist/features/background-agent/types.d.ts +9 -1
- package/dist/features/builtin-commands/templates/init-deep.d.ts +1 -1
- package/dist/features/builtin-commands/templates/refactor.d.ts +1 -1
- package/dist/features/builtin-commands/types.d.ts +1 -1
- package/dist/features/claude-code-session-state/state.d.ts +6 -1
- package/dist/features/context-injector/index.d.ts +1 -1
- package/dist/features/context-injector/injector.d.ts +1 -1
- package/dist/features/hook-message-injector/index.d.ts +2 -2
- package/dist/features/hook-message-injector/injector.d.ts +7 -0
- package/dist/features/opencode-skill-loader/skill-content.d.ts +17 -2
- package/dist/features/skill-mcp-manager/manager.d.ts +11 -0
- package/dist/features/task-toast-manager/index.d.ts +1 -1
- package/dist/features/task-toast-manager/manager.d.ts +2 -1
- package/dist/features/task-toast-manager/types.d.ts +5 -0
- package/dist/hooks/agent-usage-reminder/constants.d.ts +1 -1
- package/dist/hooks/anthropic-context-window-limit-recovery/executor.d.ts +1 -1
- package/dist/hooks/anthropic-context-window-limit-recovery/index.d.ts +1 -2
- package/dist/hooks/anthropic-context-window-limit-recovery/types.d.ts +0 -5
- package/dist/hooks/auto-update-checker/checker.d.ts +1 -1
- package/dist/hooks/auto-update-checker/index.d.ts +4 -0
- package/dist/hooks/background-compaction/index.d.ts +19 -0
- package/dist/hooks/background-notification/index.d.ts +6 -0
- package/dist/hooks/comment-checker/cli.d.ts +0 -1
- package/dist/hooks/compaction-context-injector/index.d.ts +7 -1
- package/dist/hooks/delegate-task-retry/index.d.ts +24 -0
- package/dist/hooks/index.d.ts +1 -2
- package/dist/hooks/keyword-detector/index.d.ts +2 -1
- package/dist/hooks/prometheus-md-only/constants.d.ts +2 -2
- package/dist/hooks/prometheus-md-only/index.d.ts +1 -1
- package/dist/hooks/ralph-loop/index.d.ts +1 -0
- package/dist/hooks/ralph-loop/types.d.ts +1 -0
- package/dist/index.js +22506 -23819
- package/dist/mcp/context7.d.ts +1 -0
- package/dist/mcp/grep-app.d.ts +1 -0
- package/dist/mcp/index.d.ts +1 -0
- package/dist/mcp/websearch.d.ts +1 -0
- package/dist/plugin-handlers/config-handler.d.ts +2 -0
- package/dist/plugin-handlers/config-handler.test.d.ts +1 -0
- package/dist/shared/agent-tool-restrictions.d.ts +7 -0
- package/dist/shared/agent-variant.d.ts +5 -0
- package/dist/shared/agent-variant.test.d.ts +1 -0
- package/dist/shared/deep-merge.test.d.ts +1 -0
- package/dist/shared/first-message-variant.d.ts +11 -0
- package/dist/shared/first-message-variant.test.d.ts +1 -0
- package/dist/shared/index.d.ts +6 -0
- package/dist/shared/migration.d.ts +1 -0
- package/dist/shared/opencode-version.d.ts +6 -3
- package/dist/shared/permission-compat.d.ts +22 -7
- package/dist/shared/session-cursor.d.ts +13 -0
- package/dist/shared/session-cursor.test.d.ts +1 -0
- package/dist/shared/shell-env.d.ts +41 -0
- package/dist/shared/shell-env.test.d.ts +1 -0
- package/dist/shared/system-directive.d.ts +31 -0
- package/dist/shared/zip-extractor.d.ts +1 -0
- package/dist/tools/{sisyphus-task → delegate-task}/constants.d.ts +3 -3
- package/dist/tools/{sisyphus-task → delegate-task}/index.d.ts +1 -1
- package/dist/tools/{sisyphus-task → delegate-task}/tools.d.ts +5 -3
- package/dist/tools/delegate-task/tools.test.d.ts +1 -0
- package/dist/tools/{sisyphus-task → delegate-task}/types.d.ts +1 -1
- package/dist/tools/glob/cli.d.ts +4 -0
- package/dist/tools/glob/cli.test.d.ts +1 -0
- package/dist/tools/glob/types.d.ts +1 -0
- package/dist/tools/index.d.ts +3 -1
- package/dist/tools/interactive-bash/constants.d.ts +1 -1
- package/dist/tools/look-at/tools.d.ts +7 -0
- package/dist/tools/look-at/tools.test.d.ts +1 -0
- package/dist/tools/lsp/client.d.ts +1 -3
- package/dist/tools/lsp/config.test.d.ts +1 -0
- package/dist/tools/lsp/index.d.ts +1 -1
- package/dist/tools/lsp/tools.d.ts +1 -6
- package/dist/tools/lsp/types.d.ts +0 -33
- package/dist/tools/lsp/utils.d.ts +1 -4
- package/dist/tools/skill/tools.d.ts +1 -7
- package/dist/tools/skill/types.d.ts +3 -0
- package/dist/tools/skill-mcp/types.d.ts +1 -1
- package/dist/tools/slashcommand/tools.d.ts +1 -7
- package/package.json +21 -14
- package/postinstall.mjs +43 -0
- package/dist/agents/build-prompt.d.ts +0 -31
- package/dist/agents/plan-prompt.d.ts +0 -64
- package/dist/auth/antigravity/accounts.d.ts +0 -40
- package/dist/auth/antigravity/browser.d.ts +0 -27
- package/dist/auth/antigravity/cli.d.ts +0 -2
- package/dist/auth/antigravity/constants.d.ts +0 -98
- package/dist/auth/antigravity/fetch.d.ts +0 -69
- package/dist/auth/antigravity/index.d.ts +0 -13
- package/dist/auth/antigravity/integration.test.d.ts +0 -10
- package/dist/auth/antigravity/message-converter.d.ts +0 -54
- package/dist/auth/antigravity/oauth.d.ts +0 -51
- package/dist/auth/antigravity/plugin.d.ts +0 -54
- package/dist/auth/antigravity/project.d.ts +0 -10
- package/dist/auth/antigravity/request.d.ts +0 -116
- package/dist/auth/antigravity/response.d.ts +0 -137
- package/dist/auth/antigravity/storage.d.ts +0 -5
- package/dist/auth/antigravity/thinking.d.ts +0 -278
- package/dist/auth/antigravity/thinking.test.d.ts +0 -10
- package/dist/auth/antigravity/thought-signature-store.d.ts +0 -52
- package/dist/auth/antigravity/token.d.ts +0 -38
- package/dist/auth/antigravity/tools.d.ts +0 -119
- package/dist/auth/antigravity/types.d.ts +0 -229
- package/dist/cli/ast-grep-napi.linux-x64-gnu-jfv8414z.node +0 -0
- package/dist/cli/ast-grep-napi.linux-x64-musl-8cj2e5cf.node +0 -0
- package/dist/cli/commands/auth.d.ts +0 -2
- package/dist/google-auth.d.ts +0 -3
- package/dist/google-auth.js +0 -3871
- package/dist/hooks/anthropic-context-window-limit-recovery/pruning-executor.d.ts +0 -3
- package/dist/hooks/anthropic-context-window-limit-recovery/pruning-purge-errors.d.ts +0 -7
- package/dist/hooks/anthropic-context-window-limit-recovery/pruning-storage.d.ts +0 -2
- package/dist/hooks/anthropic-context-window-limit-recovery/pruning-supersede.d.ts +0 -6
- package/dist/hooks/comment-checker/constants.d.ts +0 -3
- package/dist/hooks/comment-checker/filters/bdd.d.ts +0 -2
- package/dist/hooks/comment-checker/filters/directive.d.ts +0 -2
- package/dist/hooks/comment-checker/filters/docstring.d.ts +0 -2
- package/dist/hooks/comment-checker/filters/index.d.ts +0 -7
- package/dist/hooks/comment-checker/filters/shebang.d.ts +0 -2
- package/dist/hooks/comment-checker/output/formatter.d.ts +0 -2
- package/dist/hooks/comment-checker/output/index.d.ts +0 -2
- package/dist/hooks/comment-checker/output/xml-builder.d.ts +0 -2
- package/dist/hooks/empty-message-sanitizer/index.d.ts +0 -12
- package/dist/hooks/preemptive-compaction/constants.d.ts +0 -3
- package/dist/hooks/preemptive-compaction/index.d.ts +0 -24
- package/dist/hooks/preemptive-compaction/types.d.ts +0 -17
- package/dist/tools/ast-grep/napi.d.ts +0 -13
- package/dist/tools/interactive-bash/types.d.ts +0 -3
- /package/dist/{auth/antigravity/accounts.test.d.ts → agents/momus.test.d.ts} +0 -0
- /package/dist/{auth/antigravity/browser.test.d.ts → agents/prometheus-prompt.test.d.ts} +0 -0
- /package/dist/{auth/antigravity/cli.test.d.ts → agents/sisyphus-junior.test.d.ts} +0 -0
- /package/dist/{auth/antigravity/constants.test.d.ts → features/claude-code-session-state/state.test.d.ts} +0 -0
- /package/dist/{auth/antigravity/oauth.test.d.ts → hooks/auto-update-checker/checker.test.d.ts} +0 -0
- /package/dist/{auth/antigravity/request.test.d.ts → hooks/auto-update-checker/index.test.d.ts} +0 -0
- /package/dist/{auth/antigravity/storage.test.d.ts → hooks/comment-checker/cli.test.d.ts} +0 -0
- /package/dist/{auth/antigravity/token.test.d.ts → hooks/delegate-task-retry/index.test.d.ts} +0 -0
- /package/dist/{tools/sisyphus-task/tools.test.d.ts → plugin-config.test.d.ts} +0 -0
|
@@ -7,4 +7,21 @@ export declare class ConcurrencyManager {
|
|
|
7
7
|
getConcurrencyLimit(model: string): number;
|
|
8
8
|
acquire(model: string): Promise<void>;
|
|
9
9
|
release(model: string): void;
|
|
10
|
+
/**
|
|
11
|
+
* Cancel all waiting acquires for a model. Used during cleanup.
|
|
12
|
+
*/
|
|
13
|
+
cancelWaiters(model: string): void;
|
|
14
|
+
/**
|
|
15
|
+
* Clear all state. Used during manager cleanup/shutdown.
|
|
16
|
+
* Cancels all pending waiters.
|
|
17
|
+
*/
|
|
18
|
+
clear(): void;
|
|
19
|
+
/**
|
|
20
|
+
* Get current count for a model (for testing/debugging)
|
|
21
|
+
*/
|
|
22
|
+
getCount(model: string): number;
|
|
23
|
+
/**
|
|
24
|
+
* Get queue length for a model (for testing/debugging)
|
|
25
|
+
*/
|
|
26
|
+
getQueueLength(model: string): number;
|
|
10
27
|
}
|
|
@@ -13,12 +13,18 @@ interface Event {
|
|
|
13
13
|
properties?: EventProperties;
|
|
14
14
|
}
|
|
15
15
|
export declare class BackgroundManager {
|
|
16
|
+
private static cleanupManagers;
|
|
17
|
+
private static cleanupRegistered;
|
|
18
|
+
private static cleanupHandlers;
|
|
16
19
|
private tasks;
|
|
17
20
|
private notifications;
|
|
21
|
+
private pendingByParent;
|
|
18
22
|
private client;
|
|
19
23
|
private directory;
|
|
20
24
|
private pollingInterval?;
|
|
21
25
|
private concurrencyManager;
|
|
26
|
+
private shutdownTriggered;
|
|
27
|
+
private config?;
|
|
22
28
|
constructor(ctx: PluginInput, config?: BackgroundTaskConfig);
|
|
23
29
|
launch(input: LaunchInput): Promise<BackgroundTask>;
|
|
24
30
|
getTask(id: string): BackgroundTask | undefined;
|
|
@@ -26,30 +32,63 @@ export declare class BackgroundManager {
|
|
|
26
32
|
getAllDescendantTasks(sessionID: string): BackgroundTask[];
|
|
27
33
|
findBySession(sessionID: string): BackgroundTask | undefined;
|
|
28
34
|
/**
|
|
29
|
-
*
|
|
30
|
-
* This allows tasks created by
|
|
35
|
+
* Track a task created elsewhere (e.g., from delegate_task) for notification tracking.
|
|
36
|
+
* This allows tasks created by other tools to receive the same toast/prompt notifications.
|
|
31
37
|
*/
|
|
32
|
-
|
|
38
|
+
trackTask(input: {
|
|
33
39
|
taskId: string;
|
|
34
40
|
sessionID: string;
|
|
35
41
|
parentSessionID: string;
|
|
36
42
|
description: string;
|
|
37
43
|
agent?: string;
|
|
38
|
-
|
|
44
|
+
parentAgent?: string;
|
|
45
|
+
concurrencyKey?: string;
|
|
46
|
+
}): Promise<BackgroundTask>;
|
|
39
47
|
resume(input: ResumeInput): Promise<BackgroundTask>;
|
|
40
48
|
private checkSessionTodos;
|
|
41
49
|
handleEvent(event: Event): void;
|
|
42
50
|
markForNotification(task: BackgroundTask): void;
|
|
43
51
|
getPendingNotifications(sessionID: string): BackgroundTask[];
|
|
44
52
|
clearNotifications(sessionID: string): void;
|
|
53
|
+
/**
|
|
54
|
+
* Validates that a session has actual assistant/tool output before marking complete.
|
|
55
|
+
* Prevents premature completion when session.idle fires before agent responds.
|
|
56
|
+
*/
|
|
57
|
+
private validateSessionHasOutput;
|
|
45
58
|
private clearNotificationsForTask;
|
|
59
|
+
/**
|
|
60
|
+
* Remove task from pending tracking for its parent session.
|
|
61
|
+
* Cleans up the parent entry if no pending tasks remain.
|
|
62
|
+
*/
|
|
63
|
+
private cleanupPendingByParent;
|
|
46
64
|
private startPolling;
|
|
47
65
|
private stopPolling;
|
|
48
|
-
|
|
66
|
+
private registerProcessCleanup;
|
|
67
|
+
private unregisterProcessCleanup;
|
|
68
|
+
/**
|
|
69
|
+
* Get all running tasks (for compaction hook)
|
|
70
|
+
*/
|
|
71
|
+
getRunningTasks(): BackgroundTask[];
|
|
72
|
+
/**
|
|
73
|
+
* Get all completed tasks still in memory (for compaction hook)
|
|
74
|
+
*/
|
|
75
|
+
getCompletedTasks(): BackgroundTask[];
|
|
76
|
+
/**
|
|
77
|
+
* Safely complete a task with race condition protection.
|
|
78
|
+
* Returns true if task was successfully completed, false if already completed by another path.
|
|
79
|
+
*/
|
|
80
|
+
private tryCompleteTask;
|
|
49
81
|
private notifyParentSession;
|
|
50
82
|
private formatDuration;
|
|
51
83
|
private hasRunningTasks;
|
|
52
84
|
private pruneStaleTasksAndNotifications;
|
|
85
|
+
private checkAndInterruptStaleTasks;
|
|
53
86
|
private pollRunningTasks;
|
|
87
|
+
/**
|
|
88
|
+
* Shutdown the manager gracefully.
|
|
89
|
+
* Cancels all pending concurrency waiters and clears timers.
|
|
90
|
+
* Should be called when the plugin is unloaded.
|
|
91
|
+
*/
|
|
92
|
+
shutdown(): void;
|
|
54
93
|
}
|
|
55
94
|
export {};
|
|
@@ -27,11 +27,18 @@ export interface BackgroundTask {
|
|
|
27
27
|
model?: {
|
|
28
28
|
providerID: string;
|
|
29
29
|
modelID: string;
|
|
30
|
+
variant?: string;
|
|
30
31
|
};
|
|
31
|
-
/**
|
|
32
|
+
/** Active concurrency slot key */
|
|
32
33
|
concurrencyKey?: string;
|
|
34
|
+
/** Persistent key for re-acquiring concurrency on resume */
|
|
35
|
+
concurrencyGroup?: string;
|
|
33
36
|
/** Parent session's agent name for notification */
|
|
34
37
|
parentAgent?: string;
|
|
38
|
+
/** Last message count for stability detection */
|
|
39
|
+
lastMsgCount?: number;
|
|
40
|
+
/** Number of consecutive polls with stable message count */
|
|
41
|
+
stablePolls?: number;
|
|
35
42
|
}
|
|
36
43
|
export interface LaunchInput {
|
|
37
44
|
description: string;
|
|
@@ -47,6 +54,7 @@ export interface LaunchInput {
|
|
|
47
54
|
model?: {
|
|
48
55
|
providerID: string;
|
|
49
56
|
modelID: string;
|
|
57
|
+
variant?: string;
|
|
50
58
|
};
|
|
51
59
|
skills?: string[];
|
|
52
60
|
skillContent?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const INIT_DEEP_TEMPLATE = "# /init-deep\n\nGenerate hierarchical AGENTS.md files. Root + complexity-scored subdirectories.\n\n## Usage\n\n```\n/init-deep # Update mode: modify existing + create new where warranted\n/init-deep --create-new # Read existing \u2192 remove all \u2192 regenerate from scratch\n/init-deep --max-depth=2 # Limit directory depth (default: 3)\n```\n\n---\n\n## Workflow (High-Level)\n\n1. **Discovery + Analysis** (concurrent)\n - Fire background explore agents immediately\n - Main session: bash structure + LSP codemap + read existing AGENTS.md\n2. **Score & Decide** - Determine AGENTS.md locations from merged findings\n3. **Generate** - Root first, then subdirs in parallel\n4. **Review** - Deduplicate, trim, validate\n\n<critical>\n**TodoWrite ALL phases. Mark in_progress \u2192 completed in real-time.**\n```\nTodoWrite([\n { id: \"discovery\", content: \"Fire explore agents + LSP codemap + read existing\", status: \"pending\", priority: \"high\" },\n { id: \"scoring\", content: \"Score directories, determine locations\", status: \"pending\", priority: \"high\" },\n { id: \"generate\", content: \"Generate AGENTS.md files (root + subdirs)\", status: \"pending\", priority: \"high\" },\n { id: \"review\", content: \"Deduplicate, validate, trim\", status: \"pending\", priority: \"medium\" }\n])\n```\n</critical>\n\n---\n\n## Phase 1: Discovery + Analysis (Concurrent)\n\n**Mark \"discovery\" as in_progress.**\n\n### Fire Background Explore Agents IMMEDIATELY\n\nDon't wait\u2014these run async while main session works.\n\n```\n// Fire all at once, collect results later\
|
|
1
|
+
export declare const INIT_DEEP_TEMPLATE = "# /init-deep\n\nGenerate hierarchical AGENTS.md files. Root + complexity-scored subdirectories.\n\n## Usage\n\n```\n/init-deep # Update mode: modify existing + create new where warranted\n/init-deep --create-new # Read existing \u2192 remove all \u2192 regenerate from scratch\n/init-deep --max-depth=2 # Limit directory depth (default: 3)\n```\n\n---\n\n## Workflow (High-Level)\n\n1. **Discovery + Analysis** (concurrent)\n - Fire background explore agents immediately\n - Main session: bash structure + LSP codemap + read existing AGENTS.md\n2. **Score & Decide** - Determine AGENTS.md locations from merged findings\n3. **Generate** - Root first, then subdirs in parallel\n4. **Review** - Deduplicate, trim, validate\n\n<critical>\n**TodoWrite ALL phases. Mark in_progress \u2192 completed in real-time.**\n```\nTodoWrite([\n { id: \"discovery\", content: \"Fire explore agents + LSP codemap + read existing\", status: \"pending\", priority: \"high\" },\n { id: \"scoring\", content: \"Score directories, determine locations\", status: \"pending\", priority: \"high\" },\n { id: \"generate\", content: \"Generate AGENTS.md files (root + subdirs)\", status: \"pending\", priority: \"high\" },\n { id: \"review\", content: \"Deduplicate, validate, trim\", status: \"pending\", priority: \"medium\" }\n])\n```\n</critical>\n\n---\n\n## Phase 1: Discovery + Analysis (Concurrent)\n\n**Mark \"discovery\" as in_progress.**\n\n### Fire Background Explore Agents IMMEDIATELY\n\nDon't wait\u2014these run async while main session works.\n\n```\n// Fire all at once, collect results later\ndelegate_task(agent=\"explore\", prompt=\"Project structure: PREDICT standard patterns for detected language \u2192 REPORT deviations only\")\ndelegate_task(agent=\"explore\", prompt=\"Entry points: FIND main files \u2192 REPORT non-standard organization\")\ndelegate_task(agent=\"explore\", prompt=\"Conventions: FIND config files (.eslintrc, pyproject.toml, .editorconfig) \u2192 REPORT project-specific rules\")\ndelegate_task(agent=\"explore\", prompt=\"Anti-patterns: FIND 'DO NOT', 'NEVER', 'ALWAYS', 'DEPRECATED' comments \u2192 LIST forbidden patterns\")\ndelegate_task(agent=\"explore\", prompt=\"Build/CI: FIND .github/workflows, Makefile \u2192 REPORT non-standard patterns\")\ndelegate_task(agent=\"explore\", prompt=\"Test patterns: FIND test configs, test structure \u2192 REPORT unique conventions\")\n```\n\n<dynamic-agents>\n**DYNAMIC AGENT SPAWNING**: After bash analysis, spawn ADDITIONAL explore agents based on project scale:\n\n| Factor | Threshold | Additional Agents |\n|--------|-----------|-------------------|\n| **Total files** | >100 | +1 per 100 files |\n| **Total lines** | >10k | +1 per 10k lines |\n| **Directory depth** | \u22654 | +2 for deep exploration |\n| **Large files (>500 lines)** | >10 files | +1 for complexity hotspots |\n| **Monorepo** | detected | +1 per package/workspace |\n| **Multiple languages** | >1 | +1 per language |\n\n```bash\n# Measure project scale first\ntotal_files=$(find . -type f -not -path '*/node_modules/*' -not -path '*/.git/*' | wc -l)\ntotal_lines=$(find . -type f \\( -name \"*.ts\" -o -name \"*.py\" -o -name \"*.go\" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}')\nlarge_files=$(find . -type f \\( -name \"*.ts\" -o -name \"*.py\" \\) -not -path '*/node_modules/*' -exec wc -l {} + 2>/dev/null | awk '$1 > 500 {count++} END {print count+0}')\nmax_depth=$(find . -type d -not -path '*/node_modules/*' -not -path '*/.git/*' | awk -F/ '{print NF}' | sort -rn | head -1)\n```\n\nExample spawning:\n```\n// 500 files, 50k lines, depth 6, 15 large files \u2192 spawn 5+5+2+1 = 13 additional agents\ndelegate_task(agent=\"explore\", prompt=\"Large file analysis: FIND files >500 lines, REPORT complexity hotspots\")\ndelegate_task(agent=\"explore\", prompt=\"Deep modules at depth 4+: FIND hidden patterns, internal conventions\")\ndelegate_task(agent=\"explore\", prompt=\"Cross-cutting concerns: FIND shared utilities across directories\")\n// ... more based on calculation\n```\n</dynamic-agents>\n\n### Main Session: Concurrent Analysis\n\n**While background agents run**, main session does:\n\n#### 1. Bash Structural Analysis\n```bash\n# Directory depth + file counts\nfind . -type d -not -path '*/\\.*' -not -path '*/node_modules/*' -not -path '*/venv/*' -not -path '*/dist/*' -not -path '*/build/*' | awk -F/ '{print NF-1}' | sort -n | uniq -c\n\n# Files per directory (top 30)\nfind . -type f -not -path '*/\\.*' -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -30\n\n# Code concentration by extension\nfind . -type f \\( -name \"*.py\" -o -name \"*.ts\" -o -name \"*.tsx\" -o -name \"*.js\" -o -name \"*.go\" -o -name \"*.rs\" \\) -not -path '*/node_modules/*' | sed 's|/[^/]*$||' | sort | uniq -c | sort -rn | head -20\n\n# Existing AGENTS.md / CLAUDE.md\nfind . -type f \\( -name \"AGENTS.md\" -o -name \"CLAUDE.md\" \\) -not -path '*/node_modules/*' 2>/dev/null\n```\n\n#### 2. Read Existing AGENTS.md\n```\nFor each existing file found:\n Read(filePath=file)\n Extract: key insights, conventions, anti-patterns\n Store in EXISTING_AGENTS map\n```\n\nIf `--create-new`: Read all existing first (preserve context) \u2192 then delete all \u2192 regenerate.\n\n#### 3. LSP Codemap (if available)\n```\nLspServers() # Check availability\n\n# Entry points (parallel)\nLspDocumentSymbols(filePath=\"src/index.ts\")\nLspDocumentSymbols(filePath=\"main.py\")\n\n# Key symbols (parallel)\nLspWorkspaceSymbols(filePath=\".\", query=\"class\")\nLspWorkspaceSymbols(filePath=\".\", query=\"interface\")\nLspWorkspaceSymbols(filePath=\".\", query=\"function\")\n\n# Centrality for top exports\nLspFindReferences(filePath=\"...\", line=X, character=Y)\n```\n\n**LSP Fallback**: If unavailable, rely on explore agents + AST-grep.\n\n### Collect Background Results\n\n```\n// After main session analysis done, collect all task results\nfor each task_id: background_output(task_id=\"...\")\n```\n\n**Merge: bash + LSP + existing + explore findings. Mark \"discovery\" as completed.**\n\n---\n\n## Phase 2: Scoring & Location Decision\n\n**Mark \"scoring\" as in_progress.**\n\n### Scoring Matrix\n\n| Factor | Weight | High Threshold | Source |\n|--------|--------|----------------|--------|\n| File count | 3x | >20 | bash |\n| Subdir count | 2x | >5 | bash |\n| Code ratio | 2x | >70% | bash |\n| Unique patterns | 1x | Has own config | explore |\n| Module boundary | 2x | Has index.ts/__init__.py | bash |\n| Symbol density | 2x | >30 symbols | LSP |\n| Export count | 2x | >10 exports | LSP |\n| Reference centrality | 3x | >20 refs | LSP |\n\n### Decision Rules\n\n| Score | Action |\n|-------|--------|\n| **Root (.)** | ALWAYS create |\n| **>15** | Create AGENTS.md |\n| **8-15** | Create if distinct domain |\n| **<8** | Skip (parent covers) |\n\n### Output\n```\nAGENTS_LOCATIONS = [\n { path: \".\", type: \"root\" },\n { path: \"src/hooks\", score: 18, reason: \"high complexity\" },\n { path: \"src/api\", score: 12, reason: \"distinct domain\" }\n]\n```\n\n**Mark \"scoring\" as completed.**\n\n---\n\n## Phase 3: Generate AGENTS.md\n\n**Mark \"generate\" as in_progress.**\n\n### Root AGENTS.md (Full Treatment)\n\n```markdown\n# PROJECT KNOWLEDGE BASE\n\n**Generated:** {TIMESTAMP}\n**Commit:** {SHORT_SHA}\n**Branch:** {BRANCH}\n\n## OVERVIEW\n{1-2 sentences: what + core stack}\n\n## STRUCTURE\n\\`\\`\\`\n{root}/\n\u251C\u2500\u2500 {dir}/ # {non-obvious purpose only}\n\u2514\u2500\u2500 {entry}\n\\`\\`\\`\n\n## WHERE TO LOOK\n| Task | Location | Notes |\n|------|----------|-------|\n\n## CODE MAP\n{From LSP - skip if unavailable or project <10 files}\n\n| Symbol | Type | Location | Refs | Role |\n|--------|------|----------|------|------|\n\n## CONVENTIONS\n{ONLY deviations from standard}\n\n## ANTI-PATTERNS (THIS PROJECT)\n{Explicitly forbidden here}\n\n## UNIQUE STYLES\n{Project-specific}\n\n## COMMANDS\n\\`\\`\\`bash\n{dev/test/build}\n\\`\\`\\`\n\n## NOTES\n{Gotchas}\n```\n\n**Quality gates**: 50-150 lines, no generic advice, no obvious info.\n\n### Subdirectory AGENTS.md (Parallel)\n\nLaunch document-writer agents for each location:\n\n```\nfor loc in AGENTS_LOCATIONS (except root):\n delegate_task(agent=\"document-writer\", prompt=\\`\n Generate AGENTS.md for: ${loc.path}\n - Reason: ${loc.reason}\n - 30-80 lines max\n - NEVER repeat parent content\n - Sections: OVERVIEW (1 line), STRUCTURE (if >5 subdirs), WHERE TO LOOK, CONVENTIONS (if different), ANTI-PATTERNS\n \\`)\n```\n\n**Wait for all. Mark \"generate\" as completed.**\n\n---\n\n## Phase 4: Review & Deduplicate\n\n**Mark \"review\" as in_progress.**\n\nFor each generated file:\n- Remove generic advice\n- Remove parent duplicates\n- Trim to size limits\n- Verify telegraphic style\n\n**Mark \"review\" as completed.**\n\n---\n\n## Final Report\n\n```\n=== init-deep Complete ===\n\nMode: {update | create-new}\n\nFiles:\n \u2713 ./AGENTS.md (root, {N} lines)\n \u2713 ./src/hooks/AGENTS.md ({N} lines)\n\nDirs Analyzed: {N}\nAGENTS.md Created: {N}\nAGENTS.md Updated: {N}\n\nHierarchy:\n ./AGENTS.md\n \u2514\u2500\u2500 src/hooks/AGENTS.md\n```\n\n---\n\n## Anti-Patterns\n\n- **Static agent count**: MUST vary agents based on project size/depth\n- **Sequential execution**: MUST parallel (explore + LSP concurrent)\n- **Ignoring existing**: ALWAYS read existing first, even with --create-new\n- **Over-documenting**: Not every dir needs AGENTS.md\n- **Redundancy**: Child never repeats parent\n- **Generic content**: Remove anything that applies to ALL projects\n- **Verbose style**: Telegraphic or die";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const REFACTOR_TEMPLATE = "# Intelligent Refactor Command\n\n## Usage\n```\n/refactor <refactoring-target> [--scope=<file|module|project>] [--strategy=<safe|aggressive>]\n\nArguments:\n refactoring-target: What to refactor. Can be:\n - File path: src/auth/handler.ts\n - Symbol name: \"AuthService class\"\n - Pattern: \"all functions using deprecated API\"\n - Description: \"extract validation logic into separate module\"\n\nOptions:\n --scope: Refactoring scope (default: module)\n - file: Single file only\n - module: Module/directory scope\n - project: Entire codebase\n\n --strategy: Risk tolerance (default: safe)\n - safe: Conservative, maximum test coverage required\n - aggressive: Allow broader changes with adequate coverage\n```\n\n## What This Command Does\n\nPerforms intelligent, deterministic refactoring with full codebase awareness. Unlike blind search-and-replace, this command:\n\n1. **Understands your intent** - Analyzes what you actually want to achieve\n2. **Maps the codebase** - Builds a definitive codemap before touching anything\n3. **Assesses risk** - Evaluates test coverage and determines verification strategy\n4. **Plans meticulously** - Creates a detailed plan with Plan agent\n5. **Executes precisely** - Step-by-step refactoring with LSP and AST-grep\n6. **Verifies constantly** - Runs tests after each change to ensure zero regression\n\n---\n\n# PHASE 0: INTENT GATE (MANDATORY FIRST STEP)\n\n**BEFORE ANY ACTION, classify and validate the request.**\n\n## Step 0.1: Parse Request Type\n\n| Signal | Classification | Action |\n|--------|----------------|--------|\n| Specific file/symbol | Explicit | Proceed to codebase analysis |\n| \"Refactor X to Y\" | Clear transformation | Proceed to codebase analysis |\n| \"Improve\", \"Clean up\" | Open-ended | **MUST ask**: \"What specific improvement?\" |\n| Ambiguous scope | Uncertain | **MUST ask**: \"Which modules/files?\" |\n| Missing context | Incomplete | **MUST ask**: \"What's the desired outcome?\" |\n\n## Step 0.2: Validate Understanding\n\nBefore proceeding, confirm:\n- [ ] Target is clearly identified\n- [ ] Desired outcome is understood\n- [ ] Scope is defined (file/module/project)\n- [ ] Success criteria can be articulated\n\n**If ANY of above is unclear, ASK CLARIFYING QUESTION:**\n\n```\nI want to make sure I understand the refactoring goal correctly.\n\n**What I understood**: [interpretation]\n**What I'm unsure about**: [specific ambiguity]\n\nOptions I see:\n1. [Option A] - [implications]\n2. [Option B] - [implications]\n\n**My recommendation**: [suggestion with reasoning]\n\nShould I proceed with [recommendation], or would you prefer differently?\n```\n\n## Step 0.3: Create Initial Todos\n\n**IMMEDIATELY after understanding the request, create todos:**\n\n```\nTodoWrite([\n {\"id\": \"phase-1\", \"content\": \"PHASE 1: Codebase Analysis - launch parallel explore agents\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-2\", \"content\": \"PHASE 2: Build Codemap - map dependencies and impact zones\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-3\", \"content\": \"PHASE 3: Test Assessment - analyze test coverage and verification strategy\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-4\", \"content\": \"PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-5\", \"content\": \"PHASE 5: Execute Refactoring - step-by-step with continuous verification\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-6\", \"content\": \"PHASE 6: Final Verification - full test suite and regression check\", \"status\": \"pending\", \"priority\": \"high\"}\n])\n```\n\n---\n\n# PHASE 1: CODEBASE ANALYSIS (PARALLEL EXPLORATION)\n\n**Mark phase-1 as in_progress.**\n\n## 1.1: Launch Parallel Explore Agents (BACKGROUND)\n\nFire ALL of these simultaneously using `call_omo_agent`:\n\n```\n// Agent 1: Find the refactoring target\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find all occurrences and definitions of [TARGET]. \n Report: file paths, line numbers, usage patterns.\"\n)\n\n// Agent 2: Find related code\ncall_omo_agent(\n subagent_type=\"explore\", \n run_in_background=true,\n prompt=\"Find all code that imports, uses, or depends on [TARGET].\n Report: dependency chains, import graphs.\"\n)\n\n// Agent 3: Find similar patterns\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find similar code patterns to [TARGET] in the codebase.\n Report: analogous implementations, established conventions.\"\n)\n\n// Agent 4: Find tests\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find all test files related to [TARGET].\n Report: test file paths, test case names, coverage indicators.\"\n)\n\n// Agent 5: Architecture context\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find architectural patterns and module organization around [TARGET].\n Report: module boundaries, layer structure, design patterns in use.\"\n)\n```\n\n## 1.2: Direct Tool Exploration (WHILE AGENTS RUN)\n\nWhile background agents are running, use direct tools:\n\n### LSP Tools for Precise Analysis:\n\n```typescript\n// Get symbol information at target location\nlsp_hover(filePath, line, character) // Type info, docs, signatures\n\n// Find definition(s)\nlsp_goto_definition(filePath, line, character) // Where is it defined?\n\n// Find ALL usages across workspace\nlsp_find_references(filePath, line, character, includeDeclaration=true)\n\n// Get file structure\nlsp_document_symbols(filePath) // Hierarchical outline\n\n// Search symbols by name\nlsp_workspace_symbols(filePath, query=\"[target_symbol]\")\n\n// Get current diagnostics\nlsp_diagnostics(filePath) // Errors, warnings before we start\n```\n\n### AST-Grep for Pattern Analysis:\n\n```typescript\n// Find structural patterns\nast_grep_search(\n pattern=\"function $NAME($$$) { $$$ }\", // or relevant pattern\n lang=\"typescript\", // or relevant language\n paths=[\"src/\"]\n)\n\n// Preview refactoring (DRY RUN)\nast_grep_replace(\n pattern=\"[old_pattern]\",\n rewrite=\"[new_pattern]\",\n lang=\"[language]\",\n dryRun=true // ALWAYS preview first\n)\n```\n\n### Grep for Text Patterns:\n\n```\ngrep(pattern=\"[search_term]\", path=\"src/\", include=\"*.ts\")\n```\n\n## 1.3: Collect Background Results\n\n```\nbackground_output(task_id=\"[agent_1_id]\")\nbackground_output(task_id=\"[agent_2_id]\")\n...\n```\n\n**Mark phase-1 as completed after all results collected.**\n\n---\n\n# PHASE 2: BUILD CODEMAP (DEPENDENCY MAPPING)\n\n**Mark phase-2 as in_progress.**\n\n## 2.1: Construct Definitive Codemap\n\nBased on Phase 1 results, build:\n\n```\n## CODEMAP: [TARGET]\n\n### Core Files (Direct Impact)\n- `path/to/file.ts:L10-L50` - Primary definition\n- `path/to/file2.ts:L25` - Key usage\n\n### Dependency Graph\n```\n[TARGET] \n\u251C\u2500\u2500 imports from: \n\u2502 \u251C\u2500\u2500 module-a (types)\n\u2502 \u2514\u2500\u2500 module-b (utils)\n\u251C\u2500\u2500 imported by:\n\u2502 \u251C\u2500\u2500 consumer-1.ts\n\u2502 \u251C\u2500\u2500 consumer-2.ts\n\u2502 \u2514\u2500\u2500 consumer-3.ts\n\u2514\u2500\u2500 used by:\n \u251C\u2500\u2500 handler.ts (direct call)\n \u2514\u2500\u2500 service.ts (dependency injection)\n```\n\n### Impact Zones\n| Zone | Risk Level | Files Affected | Test Coverage |\n|------|------------|----------------|---------------|\n| Core | HIGH | 3 files | 85% covered |\n| Consumers | MEDIUM | 8 files | 70% covered |\n| Edge | LOW | 2 files | 50% covered |\n\n### Established Patterns\n- Pattern A: [description] - used in N places\n- Pattern B: [description] - established convention\n```\n\n## 2.2: Identify Refactoring Constraints\n\nBased on codemap:\n- **MUST follow**: [existing patterns identified]\n- **MUST NOT break**: [critical dependencies]\n- **Safe to change**: [isolated code zones]\n- **Requires migration**: [breaking changes impact]\n\n**Mark phase-2 as completed.**\n\n---\n\n# PHASE 3: TEST ASSESSMENT (VERIFICATION STRATEGY)\n\n**Mark phase-3 as in_progress.**\n\n## 3.1: Detect Test Infrastructure\n\n```bash\n# Check for test commands\ncat package.json | jq '.scripts | keys[] | select(test(\"test\"))'\n\n# Or for Python\nls -la pytest.ini pyproject.toml setup.cfg\n\n# Or for Go\nls -la *_test.go\n```\n\n## 3.2: Analyze Test Coverage\n\n```\n// Find all tests related to target\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=false, // Need this synchronously\n prompt=\"Analyze test coverage for [TARGET]:\n 1. Which test files cover this code?\n 2. What test cases exist?\n 3. Are there integration tests?\n 4. What edge cases are tested?\n 5. Estimated coverage percentage?\"\n)\n```\n\n## 3.3: Determine Verification Strategy\n\nBased on test analysis:\n\n| Coverage Level | Strategy |\n|----------------|----------|\n| HIGH (>80%) | Run existing tests after each step |\n| MEDIUM (50-80%) | Run tests + add safety assertions |\n| LOW (<50%) | **PAUSE**: Propose adding tests first |\n| NONE | **BLOCK**: Refuse aggressive refactoring |\n\n**If coverage is LOW or NONE, ask user:**\n\n```\nTest coverage for [TARGET] is [LEVEL].\n\n**Risk Assessment**: Refactoring without adequate tests is dangerous.\n\nOptions:\n1. Add tests first, then refactor (RECOMMENDED)\n2. Proceed with extra caution, manual verification required\n3. Abort refactoring\n\nWhich approach do you prefer?\n```\n\n## 3.4: Document Verification Plan\n\n```\n## VERIFICATION PLAN\n\n### Test Commands\n- Unit: `bun test` / `npm test` / `pytest` / etc.\n- Integration: [command if exists]\n- Type check: `tsc --noEmit` / `pyright` / etc.\n\n### Verification Checkpoints\nAfter each refactoring step:\n1. lsp_diagnostics \u2192 zero new errors\n2. Run test command \u2192 all pass\n3. Type check \u2192 clean\n\n### Regression Indicators\n- [Specific test that must pass]\n- [Behavior that must be preserved]\n- [API contract that must not change]\n```\n\n**Mark phase-3 as completed.**\n\n---\n\n# PHASE 4: PLAN GENERATION (PLAN AGENT)\n\n**Mark phase-4 as in_progress.**\n\n## 4.1: Invoke Plan Agent\n\n```\nTask(\n subagent_type=\"plan\",\n prompt=\"Create a detailed refactoring plan:\n\n ## Refactoring Goal\n [User's original request]\n\n ## Codemap (from Phase 2)\n [Insert codemap here]\n\n ## Test Coverage (from Phase 3)\n [Insert verification plan here]\n\n ## Constraints\n - MUST follow existing patterns: [list]\n - MUST NOT break: [critical paths]\n - MUST run tests after each step\n\n ## Requirements\n 1. Break down into atomic refactoring steps\n 2. Each step must be independently verifiable\n 3. Order steps by dependency (what must happen first)\n 4. Specify exact files and line ranges for each step\n 5. Include rollback strategy for each step\n 6. Define commit checkpoints\"\n)\n```\n\n## 4.2: Review and Validate Plan\n\nAfter receiving plan from Plan agent:\n\n1. **Verify completeness**: All identified files addressed?\n2. **Verify safety**: Each step reversible?\n3. **Verify order**: Dependencies respected?\n4. **Verify verification**: Test commands specified?\n\n## 4.3: Register Detailed Todos\n\nConvert Plan agent output into granular todos:\n\n```\nTodoWrite([\n // Each step from the plan becomes a todo\n {\"id\": \"refactor-1\", \"content\": \"Step 1: [description]\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"verify-1\", \"content\": \"Verify Step 1: run tests\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"refactor-2\", \"content\": \"Step 2: [description]\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"verify-2\", \"content\": \"Verify Step 2: run tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n // ... continue for all steps\n])\n```\n\n**Mark phase-4 as completed.**\n\n---\n\n# PHASE 5: EXECUTE REFACTORING (DETERMINISTIC EXECUTION)\n\n**Mark phase-5 as in_progress.**\n\n## 5.1: Execution Protocol\n\nFor EACH refactoring step:\n\n### Pre-Step\n1. Mark step todo as `in_progress`\n2. Read current file state\n3. Verify lsp_diagnostics is baseline\n\n### Execute Step\nUse appropriate tool:\n\n**For Symbol Renames:**\n```typescript\nlsp_prepare_rename(filePath, line, character) // Validate rename is possible\nlsp_rename(filePath, line, character, newName) // Execute rename\n```\n\n**For Pattern Transformations:**\n```typescript\n// Preview first\nast_grep_replace(pattern, rewrite, lang, dryRun=true)\n\n// If preview looks good, execute\nast_grep_replace(pattern, rewrite, lang, dryRun=false)\n```\n\n**For Structural Changes:**\n```typescript\n// Use Edit tool for precise changes\nedit(filePath, oldString, newString)\n```\n\n### Post-Step Verification (MANDATORY)\n\n```typescript\n// 1. Check diagnostics\nlsp_diagnostics(filePath) // Must be clean or same as baseline\n\n// 2. Run tests\nbash(\"bun test\") // Or appropriate test command\n\n// 3. Type check\nbash(\"tsc --noEmit\") // Or appropriate type check\n```\n\n### Step Completion\n1. If verification passes \u2192 Mark step todo as `completed`\n2. If verification fails \u2192 **STOP AND FIX**\n\n## 5.2: Failure Recovery Protocol\n\nIf ANY verification fails:\n\n1. **STOP** immediately\n2. **REVERT** the failed change\n3. **DIAGNOSE** what went wrong\n4. **OPTIONS**:\n - Fix the issue and retry\n - Skip this step (if optional)\n - Consult oracle agent for help\n - Ask user for guidance\n\n**NEVER proceed to next step with broken tests.**\n\n## 5.3: Commit Checkpoints\n\nAfter each logical group of changes:\n\n```bash\ngit add [changed-files]\ngit commit -m \"refactor(scope): description\n\n[details of what was changed and why]\"\n```\n\n**Mark phase-5 as completed when all refactoring steps done.**\n\n---\n\n# PHASE 6: FINAL VERIFICATION (REGRESSION CHECK)\n\n**Mark phase-6 as in_progress.**\n\n## 6.1: Full Test Suite\n\n```bash\n# Run complete test suite\nbun test # or npm test, pytest, go test, etc.\n```\n\n## 6.2: Type Check\n\n```bash\n# Full type check\ntsc --noEmit # or equivalent\n```\n\n## 6.3: Lint Check\n\n```bash\n# Run linter\neslint . # or equivalent\n```\n\n## 6.4: Build Verification (if applicable)\n\n```bash\n# Ensure build still works\nbun run build # or npm run build, etc.\n```\n\n## 6.5: Final Diagnostics\n\n```typescript\n// Check all changed files\nfor (file of changedFiles) {\n lsp_diagnostics(file) // Must all be clean\n}\n```\n\n## 6.6: Generate Summary\n\n```markdown\n## Refactoring Complete\n\n### What Changed\n- [List of changes made]\n\n### Files Modified\n- `path/to/file.ts` - [what changed]\n- `path/to/file2.ts` - [what changed]\n\n### Verification Results\n- Tests: PASSED (X/Y passing)\n- Type Check: CLEAN\n- Lint: CLEAN\n- Build: SUCCESS\n\n### No Regressions Detected\nAll existing tests pass. No new errors introduced.\n```\n\n**Mark phase-6 as completed.**\n\n---\n\n# CRITICAL RULES\n\n## NEVER DO\n- Skip lsp_diagnostics check after changes\n- Proceed with failing tests\n- Make changes without understanding impact\n- Use `as any`, `@ts-ignore`, `@ts-expect-error`\n- Delete tests to make them pass\n- Commit broken code\n- Refactor without understanding existing patterns\n\n## ALWAYS DO\n- Understand before changing\n- Preview before applying (ast_grep dryRun=true)\n- Verify after every change\n- Follow existing codebase patterns\n- Keep todos updated in real-time\n- Commit at logical checkpoints\n- Report issues immediately\n\n## ABORT CONDITIONS\nIf any of these occur, **STOP and consult user**:\n- Test coverage is zero for target code\n- Changes would break public API\n- Refactoring scope is unclear\n- 3 consecutive verification failures\n- User-defined constraints violated\n\n---\n\n# Tool Usage Philosophy\n\nYou already know these tools. Use them intelligently:\n\n## LSP Tools\nLeverage the full LSP toolset (`lsp_*`) for precision analysis. Key patterns:\n- **Understand before changing**: `lsp_hover`, `lsp_goto_definition` to grasp context\n- **Impact analysis**: `lsp_find_references` to map all usages before modification\n- **Safe refactoring**: `lsp_prepare_rename` \u2192 `lsp_rename` for symbol renames\n- **Continuous verification**: `lsp_diagnostics` after every change\n\n## AST-Grep\nUse `ast_grep_search` and `ast_grep_replace` for structural transformations.\n**Critical**: Always `dryRun=true` first, review, then execute.\n\n## Agents\n- `explore`: Parallel codebase pattern discovery\n- `plan`: Detailed refactoring plan generation\n- `oracle`: Read-only consultation for complex architectural decisions and debugging\n- `librarian`: **Use proactively** when encountering deprecated methods or library migration tasks. Query official docs and OSS examples for modern replacements.\n\n## Deprecated Code & Library Migration\nWhen you encounter deprecated methods/APIs during refactoring:\n1. Fire `librarian` to find the recommended modern alternative\n2. **DO NOT auto-upgrade to latest version** unless user explicitly requests migration\n3. If user requests library migration, use `librarian` to fetch latest API docs before making changes\n\n---\n\n**Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.**\n\n<user-request>\n$ARGUMENTS\n</user-request>\n";
|
|
1
|
+
export declare const REFACTOR_TEMPLATE = "# Intelligent Refactor Command\n\n## Usage\n```\n/refactor <refactoring-target> [--scope=<file|module|project>] [--strategy=<safe|aggressive>]\n\nArguments:\n refactoring-target: What to refactor. Can be:\n - File path: src/auth/handler.ts\n - Symbol name: \"AuthService class\"\n - Pattern: \"all functions using deprecated API\"\n - Description: \"extract validation logic into separate module\"\n\nOptions:\n --scope: Refactoring scope (default: module)\n - file: Single file only\n - module: Module/directory scope\n - project: Entire codebase\n\n --strategy: Risk tolerance (default: safe)\n - safe: Conservative, maximum test coverage required\n - aggressive: Allow broader changes with adequate coverage\n```\n\n## What This Command Does\n\nPerforms intelligent, deterministic refactoring with full codebase awareness. Unlike blind search-and-replace, this command:\n\n1. **Understands your intent** - Analyzes what you actually want to achieve\n2. **Maps the codebase** - Builds a definitive codemap before touching anything\n3. **Assesses risk** - Evaluates test coverage and determines verification strategy\n4. **Plans meticulously** - Creates a detailed plan with Plan agent\n5. **Executes precisely** - Step-by-step refactoring with LSP and AST-grep\n6. **Verifies constantly** - Runs tests after each change to ensure zero regression\n\n---\n\n# PHASE 0: INTENT GATE (MANDATORY FIRST STEP)\n\n**BEFORE ANY ACTION, classify and validate the request.**\n\n## Step 0.1: Parse Request Type\n\n| Signal | Classification | Action |\n|--------|----------------|--------|\n| Specific file/symbol | Explicit | Proceed to codebase analysis |\n| \"Refactor X to Y\" | Clear transformation | Proceed to codebase analysis |\n| \"Improve\", \"Clean up\" | Open-ended | **MUST ask**: \"What specific improvement?\" |\n| Ambiguous scope | Uncertain | **MUST ask**: \"Which modules/files?\" |\n| Missing context | Incomplete | **MUST ask**: \"What's the desired outcome?\" |\n\n## Step 0.2: Validate Understanding\n\nBefore proceeding, confirm:\n- [ ] Target is clearly identified\n- [ ] Desired outcome is understood\n- [ ] Scope is defined (file/module/project)\n- [ ] Success criteria can be articulated\n\n**If ANY of above is unclear, ASK CLARIFYING QUESTION:**\n\n```\nI want to make sure I understand the refactoring goal correctly.\n\n**What I understood**: [interpretation]\n**What I'm unsure about**: [specific ambiguity]\n\nOptions I see:\n1. [Option A] - [implications]\n2. [Option B] - [implications]\n\n**My recommendation**: [suggestion with reasoning]\n\nShould I proceed with [recommendation], or would you prefer differently?\n```\n\n## Step 0.3: Create Initial Todos\n\n**IMMEDIATELY after understanding the request, create todos:**\n\n```\nTodoWrite([\n {\"id\": \"phase-1\", \"content\": \"PHASE 1: Codebase Analysis - launch parallel explore agents\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-2\", \"content\": \"PHASE 2: Build Codemap - map dependencies and impact zones\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-3\", \"content\": \"PHASE 3: Test Assessment - analyze test coverage and verification strategy\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-4\", \"content\": \"PHASE 4: Plan Generation - invoke Plan agent for detailed refactoring plan\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-5\", \"content\": \"PHASE 5: Execute Refactoring - step-by-step with continuous verification\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"phase-6\", \"content\": \"PHASE 6: Final Verification - full test suite and regression check\", \"status\": \"pending\", \"priority\": \"high\"}\n])\n```\n\n---\n\n# PHASE 1: CODEBASE ANALYSIS (PARALLEL EXPLORATION)\n\n**Mark phase-1 as in_progress.**\n\n## 1.1: Launch Parallel Explore Agents (BACKGROUND)\n\nFire ALL of these simultaneously using `call_omo_agent`:\n\n```\n// Agent 1: Find the refactoring target\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find all occurrences and definitions of [TARGET]. \n Report: file paths, line numbers, usage patterns.\"\n)\n\n// Agent 2: Find related code\ncall_omo_agent(\n subagent_type=\"explore\", \n run_in_background=true,\n prompt=\"Find all code that imports, uses, or depends on [TARGET].\n Report: dependency chains, import graphs.\"\n)\n\n// Agent 3: Find similar patterns\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find similar code patterns to [TARGET] in the codebase.\n Report: analogous implementations, established conventions.\"\n)\n\n// Agent 4: Find tests\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find all test files related to [TARGET].\n Report: test file paths, test case names, coverage indicators.\"\n)\n\n// Agent 5: Architecture context\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=true,\n prompt=\"Find architectural patterns and module organization around [TARGET].\n Report: module boundaries, layer structure, design patterns in use.\"\n)\n```\n\n## 1.2: Direct Tool Exploration (WHILE AGENTS RUN)\n\nWhile background agents are running, use direct tools:\n\n### LSP Tools for Precise Analysis:\n\n```typescript\n// Find definition(s)\nLspGotoDefinition(filePath, line, character) // Where is it defined?\n\n// Find ALL usages across workspace\nLspFindReferences(filePath, line, character, includeDeclaration=true)\n\n// Get file structure\nLspDocumentSymbols(filePath) // Hierarchical outline\nLspWorkspaceSymbols(filePath, query=\"[target_symbol]\") // Search by name\n\n// Get current diagnostics\nlsp_diagnostics(filePath) // Errors, warnings before we start\n```\n\n### AST-Grep for Pattern Analysis:\n\n```typescript\n// Find structural patterns\nast_grep_search(\n pattern=\"function $NAME($$$) { $$$ }\", // or relevant pattern\n lang=\"typescript\", // or relevant language\n paths=[\"src/\"]\n)\n\n// Preview refactoring (DRY RUN)\nast_grep_replace(\n pattern=\"[old_pattern]\",\n rewrite=\"[new_pattern]\",\n lang=\"[language]\",\n dryRun=true // ALWAYS preview first\n)\n```\n\n### Grep for Text Patterns:\n\n```\ngrep(pattern=\"[search_term]\", path=\"src/\", include=\"*.ts\")\n```\n\n## 1.3: Collect Background Results\n\n```\nbackground_output(task_id=\"[agent_1_id]\")\nbackground_output(task_id=\"[agent_2_id]\")\n...\n```\n\n**Mark phase-1 as completed after all results collected.**\n\n---\n\n# PHASE 2: BUILD CODEMAP (DEPENDENCY MAPPING)\n\n**Mark phase-2 as in_progress.**\n\n## 2.1: Construct Definitive Codemap\n\nBased on Phase 1 results, build:\n\n```\n## CODEMAP: [TARGET]\n\n### Core Files (Direct Impact)\n- `path/to/file.ts:L10-L50` - Primary definition\n- `path/to/file2.ts:L25` - Key usage\n\n### Dependency Graph\n```\n[TARGET] \n\u251C\u2500\u2500 imports from: \n\u2502 \u251C\u2500\u2500 module-a (types)\n\u2502 \u2514\u2500\u2500 module-b (utils)\n\u251C\u2500\u2500 imported by:\n\u2502 \u251C\u2500\u2500 consumer-1.ts\n\u2502 \u251C\u2500\u2500 consumer-2.ts\n\u2502 \u2514\u2500\u2500 consumer-3.ts\n\u2514\u2500\u2500 used by:\n \u251C\u2500\u2500 handler.ts (direct call)\n \u2514\u2500\u2500 service.ts (dependency injection)\n```\n\n### Impact Zones\n| Zone | Risk Level | Files Affected | Test Coverage |\n|------|------------|----------------|---------------|\n| Core | HIGH | 3 files | 85% covered |\n| Consumers | MEDIUM | 8 files | 70% covered |\n| Edge | LOW | 2 files | 50% covered |\n\n### Established Patterns\n- Pattern A: [description] - used in N places\n- Pattern B: [description] - established convention\n```\n\n## 2.2: Identify Refactoring Constraints\n\nBased on codemap:\n- **MUST follow**: [existing patterns identified]\n- **MUST NOT break**: [critical dependencies]\n- **Safe to change**: [isolated code zones]\n- **Requires migration**: [breaking changes impact]\n\n**Mark phase-2 as completed.**\n\n---\n\n# PHASE 3: TEST ASSESSMENT (VERIFICATION STRATEGY)\n\n**Mark phase-3 as in_progress.**\n\n## 3.1: Detect Test Infrastructure\n\n```bash\n# Check for test commands\ncat package.json | jq '.scripts | keys[] | select(test(\"test\"))'\n\n# Or for Python\nls -la pytest.ini pyproject.toml setup.cfg\n\n# Or for Go\nls -la *_test.go\n```\n\n## 3.2: Analyze Test Coverage\n\n```\n// Find all tests related to target\ncall_omo_agent(\n subagent_type=\"explore\",\n run_in_background=false, // Need this synchronously\n prompt=\"Analyze test coverage for [TARGET]:\n 1. Which test files cover this code?\n 2. What test cases exist?\n 3. Are there integration tests?\n 4. What edge cases are tested?\n 5. Estimated coverage percentage?\"\n)\n```\n\n## 3.3: Determine Verification Strategy\n\nBased on test analysis:\n\n| Coverage Level | Strategy |\n|----------------|----------|\n| HIGH (>80%) | Run existing tests after each step |\n| MEDIUM (50-80%) | Run tests + add safety assertions |\n| LOW (<50%) | **PAUSE**: Propose adding tests first |\n| NONE | **BLOCK**: Refuse aggressive refactoring |\n\n**If coverage is LOW or NONE, ask user:**\n\n```\nTest coverage for [TARGET] is [LEVEL].\n\n**Risk Assessment**: Refactoring without adequate tests is dangerous.\n\nOptions:\n1. Add tests first, then refactor (RECOMMENDED)\n2. Proceed with extra caution, manual verification required\n3. Abort refactoring\n\nWhich approach do you prefer?\n```\n\n## 3.4: Document Verification Plan\n\n```\n## VERIFICATION PLAN\n\n### Test Commands\n- Unit: `bun test` / `npm test` / `pytest` / etc.\n- Integration: [command if exists]\n- Type check: `tsc --noEmit` / `pyright` / etc.\n\n### Verification Checkpoints\nAfter each refactoring step:\n1. lsp_diagnostics \u2192 zero new errors\n2. Run test command \u2192 all pass\n3. Type check \u2192 clean\n\n### Regression Indicators\n- [Specific test that must pass]\n- [Behavior that must be preserved]\n- [API contract that must not change]\n```\n\n**Mark phase-3 as completed.**\n\n---\n\n# PHASE 4: PLAN GENERATION (PLAN AGENT)\n\n**Mark phase-4 as in_progress.**\n\n## 4.1: Invoke Plan Agent\n\n```\nTask(\n subagent_type=\"plan\",\n prompt=\"Create a detailed refactoring plan:\n\n ## Refactoring Goal\n [User's original request]\n\n ## Codemap (from Phase 2)\n [Insert codemap here]\n\n ## Test Coverage (from Phase 3)\n [Insert verification plan here]\n\n ## Constraints\n - MUST follow existing patterns: [list]\n - MUST NOT break: [critical paths]\n - MUST run tests after each step\n\n ## Requirements\n 1. Break down into atomic refactoring steps\n 2. Each step must be independently verifiable\n 3. Order steps by dependency (what must happen first)\n 4. Specify exact files and line ranges for each step\n 5. Include rollback strategy for each step\n 6. Define commit checkpoints\"\n)\n```\n\n## 4.2: Review and Validate Plan\n\nAfter receiving plan from Plan agent:\n\n1. **Verify completeness**: All identified files addressed?\n2. **Verify safety**: Each step reversible?\n3. **Verify order**: Dependencies respected?\n4. **Verify verification**: Test commands specified?\n\n## 4.3: Register Detailed Todos\n\nConvert Plan agent output into granular todos:\n\n```\nTodoWrite([\n // Each step from the plan becomes a todo\n {\"id\": \"refactor-1\", \"content\": \"Step 1: [description]\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"verify-1\", \"content\": \"Verify Step 1: run tests\", \"status\": \"pending\", \"priority\": \"high\"},\n {\"id\": \"refactor-2\", \"content\": \"Step 2: [description]\", \"status\": \"pending\", \"priority\": \"medium\"},\n {\"id\": \"verify-2\", \"content\": \"Verify Step 2: run tests\", \"status\": \"pending\", \"priority\": \"medium\"},\n // ... continue for all steps\n])\n```\n\n**Mark phase-4 as completed.**\n\n---\n\n# PHASE 5: EXECUTE REFACTORING (DETERMINISTIC EXECUTION)\n\n**Mark phase-5 as in_progress.**\n\n## 5.1: Execution Protocol\n\nFor EACH refactoring step:\n\n### Pre-Step\n1. Mark step todo as `in_progress`\n2. Read current file state\n3. Verify lsp_diagnostics is baseline\n\n### Execute Step\nUse appropriate tool:\n\n**For Symbol Renames:**\n```typescript\nlsp_prepare_rename(filePath, line, character) // Validate rename is possible\nlsp_rename(filePath, line, character, newName) // Execute rename\n```\n\n**For Pattern Transformations:**\n```typescript\n// Preview first\nast_grep_replace(pattern, rewrite, lang, dryRun=true)\n\n// If preview looks good, execute\nast_grep_replace(pattern, rewrite, lang, dryRun=false)\n```\n\n**For Structural Changes:**\n```typescript\n// Use Edit tool for precise changes\nedit(filePath, oldString, newString)\n```\n\n### Post-Step Verification (MANDATORY)\n\n```typescript\n// 1. Check diagnostics\nlsp_diagnostics(filePath) // Must be clean or same as baseline\n\n// 2. Run tests\nbash(\"bun test\") // Or appropriate test command\n\n// 3. Type check\nbash(\"tsc --noEmit\") // Or appropriate type check\n```\n\n### Step Completion\n1. If verification passes \u2192 Mark step todo as `completed`\n2. If verification fails \u2192 **STOP AND FIX**\n\n## 5.2: Failure Recovery Protocol\n\nIf ANY verification fails:\n\n1. **STOP** immediately\n2. **REVERT** the failed change\n3. **DIAGNOSE** what went wrong\n4. **OPTIONS**:\n - Fix the issue and retry\n - Skip this step (if optional)\n - Consult oracle agent for help\n - Ask user for guidance\n\n**NEVER proceed to next step with broken tests.**\n\n## 5.3: Commit Checkpoints\n\nAfter each logical group of changes:\n\n```bash\ngit add [changed-files]\ngit commit -m \"refactor(scope): description\n\n[details of what was changed and why]\"\n```\n\n**Mark phase-5 as completed when all refactoring steps done.**\n\n---\n\n# PHASE 6: FINAL VERIFICATION (REGRESSION CHECK)\n\n**Mark phase-6 as in_progress.**\n\n## 6.1: Full Test Suite\n\n```bash\n# Run complete test suite\nbun test # or npm test, pytest, go test, etc.\n```\n\n## 6.2: Type Check\n\n```bash\n# Full type check\ntsc --noEmit # or equivalent\n```\n\n## 6.3: Lint Check\n\n```bash\n# Run linter\neslint . # or equivalent\n```\n\n## 6.4: Build Verification (if applicable)\n\n```bash\n# Ensure build still works\nbun run build # or npm run build, etc.\n```\n\n## 6.5: Final Diagnostics\n\n```typescript\n// Check all changed files\nfor (file of changedFiles) {\n lsp_diagnostics(file) // Must all be clean\n}\n```\n\n## 6.6: Generate Summary\n\n```markdown\n## Refactoring Complete\n\n### What Changed\n- [List of changes made]\n\n### Files Modified\n- `path/to/file.ts` - [what changed]\n- `path/to/file2.ts` - [what changed]\n\n### Verification Results\n- Tests: PASSED (X/Y passing)\n- Type Check: CLEAN\n- Lint: CLEAN\n- Build: SUCCESS\n\n### No Regressions Detected\nAll existing tests pass. No new errors introduced.\n```\n\n**Mark phase-6 as completed.**\n\n---\n\n# CRITICAL RULES\n\n## NEVER DO\n- Skip lsp_diagnostics check after changes\n- Proceed with failing tests\n- Make changes without understanding impact\n- Use `as any`, `@ts-ignore`, `@ts-expect-error`\n- Delete tests to make them pass\n- Commit broken code\n- Refactor without understanding existing patterns\n\n## ALWAYS DO\n- Understand before changing\n- Preview before applying (ast_grep dryRun=true)\n- Verify after every change\n- Follow existing codebase patterns\n- Keep todos updated in real-time\n- Commit at logical checkpoints\n- Report issues immediately\n\n## ABORT CONDITIONS\nIf any of these occur, **STOP and consult user**:\n- Test coverage is zero for target code\n- Changes would break public API\n- Refactoring scope is unclear\n- 3 consecutive verification failures\n- User-defined constraints violated\n\n---\n\n# Tool Usage Philosophy\n\nYou already know these tools. Use them intelligently:\n\n## LSP Tools\nLeverage LSP tools for precision analysis. Key patterns:\n- **Understand before changing**: `LspGotoDefinition` to grasp context\n- **Impact analysis**: `LspFindReferences` to map all usages before modification\n- **Safe refactoring**: `lsp_prepare_rename` \u2192 `lsp_rename` for symbol renames\n- **Continuous verification**: `lsp_diagnostics` after every change\n\n## AST-Grep\nUse `ast_grep_search` and `ast_grep_replace` for structural transformations.\n**Critical**: Always `dryRun=true` first, review, then execute.\n\n## Agents\n- `explore`: Parallel codebase pattern discovery\n- `plan`: Detailed refactoring plan generation\n- `oracle`: Read-only consultation for complex architectural decisions and debugging\n- `librarian`: **Use proactively** when encountering deprecated methods or library migration tasks. Query official docs and OSS examples for modern replacements.\n\n## Deprecated Code & Library Migration\nWhen you encounter deprecated methods/APIs during refactoring:\n1. Fire `librarian` to find the recommended modern alternative\n2. **DO NOT auto-upgrade to latest version** unless user explicitly requests migration\n3. If user requests library migration, use `librarian` to fetch latest API docs before making changes\n\n---\n\n**Remember: Refactoring without tests is reckless. Refactoring without understanding is destructive. This command ensures you do neither.**\n\n<user-request>\n$ARGUMENTS\n</user-request>\n";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { CommandDefinition } from "../claude-code-command-loader";
|
|
2
|
-
export type BuiltinCommandName = "init-deep" | "ralph-loop" | "cancel-ralph" | "refactor" | "start-work";
|
|
2
|
+
export type BuiltinCommandName = "init-deep" | "ralph-loop" | "cancel-ralph" | "ulw-loop" | "refactor" | "start-work";
|
|
3
3
|
export interface BuiltinCommandConfig {
|
|
4
4
|
disabled_commands?: BuiltinCommandName[];
|
|
5
5
|
}
|
|
@@ -1,4 +1,9 @@
|
|
|
1
1
|
export declare const subagentSessions: Set<string>;
|
|
2
|
-
export declare let mainSessionID: string | undefined;
|
|
3
2
|
export declare function setMainSession(id: string | undefined): void;
|
|
4
3
|
export declare function getMainSessionID(): string | undefined;
|
|
4
|
+
/** @internal For testing only */
|
|
5
|
+
export declare function _resetForTesting(): void;
|
|
6
|
+
export declare function setSessionAgent(sessionID: string, agent: string): void;
|
|
7
|
+
export declare function updateSessionAgent(sessionID: string, agent: string): void;
|
|
8
|
+
export declare function getSessionAgent(sessionID: string): string | undefined;
|
|
9
|
+
export declare function clearSessionAgent(sessionID: string): void;
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
export { ContextCollector, contextCollector } from "./collector";
|
|
2
|
-
export {
|
|
2
|
+
export { createContextInjectorMessagesTransformHook, } from "./injector";
|
|
3
3
|
export type { ContextSourceType, ContextPriority, ContextEntry, RegisterContextOptions, PendingContext, MessageContext, OutputParts, InjectionStrategy, } from "./types";
|
|
@@ -24,7 +24,7 @@ interface ChatMessageOutput {
|
|
|
24
24
|
parts: OutputPart[];
|
|
25
25
|
}
|
|
26
26
|
export declare function createContextInjectorHook(collector: ContextCollector): {
|
|
27
|
-
"chat.message": (
|
|
27
|
+
"chat.message": (input: ChatMessageInput, output: ChatMessageOutput) => Promise<void>;
|
|
28
28
|
};
|
|
29
29
|
interface MessageWithParts {
|
|
30
30
|
info: Message;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { injectHookMessage, findNearestMessageWithFields } from "./injector";
|
|
1
|
+
export { injectHookMessage, findNearestMessageWithFields, findFirstMessageWithAgent } from "./injector";
|
|
2
2
|
export type { StoredMessage } from "./injector";
|
|
3
|
-
export type { MessageMeta, OriginalMessageContext, TextPart } from "./types";
|
|
3
|
+
export type { MessageMeta, OriginalMessageContext, TextPart, ToolPermission } from "./types";
|
|
4
4
|
export { MESSAGE_STORAGE } from "./constants";
|
|
@@ -8,4 +8,11 @@ export interface StoredMessage {
|
|
|
8
8
|
tools?: Record<string, ToolPermission>;
|
|
9
9
|
}
|
|
10
10
|
export declare function findNearestMessageWithFields(messageDir: string): StoredMessage | null;
|
|
11
|
+
/**
|
|
12
|
+
* Finds the FIRST (oldest) message in the session with agent field.
|
|
13
|
+
* This is used to get the original agent that started the session,
|
|
14
|
+
* avoiding issues where newer messages may have a different agent
|
|
15
|
+
* due to OpenCode's internal agent switching.
|
|
16
|
+
*/
|
|
17
|
+
export declare function findFirstMessageWithAgent(messageDir: string): string | null;
|
|
11
18
|
export declare function injectHookMessage(sessionID: string, hookContent: string, originalMessage: OriginalMessageContext): boolean;
|
|
@@ -1,5 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import type { LoadedSkill } from "./types";
|
|
2
|
+
import type { GitMasterConfig } from "../../config/schema";
|
|
3
|
+
export interface SkillResolutionOptions {
|
|
4
|
+
gitMasterConfig?: GitMasterConfig;
|
|
5
|
+
}
|
|
6
|
+
declare function clearSkillCache(): void;
|
|
7
|
+
declare function getAllSkills(): Promise<LoadedSkill[]>;
|
|
8
|
+
declare function extractSkillTemplate(skill: LoadedSkill): Promise<string>;
|
|
9
|
+
export { clearSkillCache, getAllSkills, extractSkillTemplate };
|
|
10
|
+
export declare function injectGitMasterConfig(template: string, config?: GitMasterConfig): string;
|
|
11
|
+
export declare function resolveSkillContent(skillName: string, options?: SkillResolutionOptions): string | null;
|
|
12
|
+
export declare function resolveMultipleSkills(skillNames: string[], options?: SkillResolutionOptions): {
|
|
3
13
|
resolved: Map<string, string>;
|
|
4
14
|
notFound: string[];
|
|
5
15
|
};
|
|
16
|
+
export declare function resolveSkillContentAsync(skillName: string, options?: SkillResolutionOptions): Promise<string | null>;
|
|
17
|
+
export declare function resolveMultipleSkillsAsync(skillNames: string[], options?: SkillResolutionOptions): Promise<{
|
|
18
|
+
resolved: Map<string, string>;
|
|
19
|
+
notFound: string[];
|
|
20
|
+
}>;
|
|
@@ -12,6 +12,16 @@ export declare class SkillMcpManager {
|
|
|
12
12
|
private registerProcessCleanup;
|
|
13
13
|
getOrCreateClient(info: SkillMcpClientInfo, config: ClaudeCodeMcpServer): Promise<Client>;
|
|
14
14
|
private createClient;
|
|
15
|
+
/**
|
|
16
|
+
* Create an HTTP-based MCP client using StreamableHTTPClientTransport.
|
|
17
|
+
* Supports remote MCP servers with optional authentication headers.
|
|
18
|
+
*/
|
|
19
|
+
private createHttpClient;
|
|
20
|
+
/**
|
|
21
|
+
* Create a stdio-based MCP client using StdioClientTransport.
|
|
22
|
+
* Spawns a local process and communicates via stdin/stdout.
|
|
23
|
+
*/
|
|
24
|
+
private createStdioClient;
|
|
15
25
|
disconnectSession(sessionID: string): Promise<void>;
|
|
16
26
|
disconnectAll(): Promise<void>;
|
|
17
27
|
private startCleanupTimer;
|
|
@@ -23,6 +33,7 @@ export declare class SkillMcpManager {
|
|
|
23
33
|
callTool(info: SkillMcpClientInfo, context: SkillMcpServerContext, name: string, args: Record<string, unknown>): Promise<unknown>;
|
|
24
34
|
readResource(info: SkillMcpClientInfo, context: SkillMcpServerContext, uri: string): Promise<unknown>;
|
|
25
35
|
getPrompt(info: SkillMcpClientInfo, context: SkillMcpServerContext, name: string, args: Record<string, string>): Promise<unknown>;
|
|
36
|
+
private withOperationRetry;
|
|
26
37
|
private getOrCreateClientWithRetry;
|
|
27
38
|
getConnectedServers(): string[];
|
|
28
39
|
isConnected(info: SkillMcpClientInfo): boolean;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export { TaskToastManager, getTaskToastManager, initTaskToastManager } from "./manager";
|
|
2
|
-
export type { TrackedTask, TaskStatus, TaskToastOptions } from "./types";
|
|
2
|
+
export type { TrackedTask, TaskStatus, TaskToastOptions, ModelFallbackInfo } from "./types";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { PluginInput } from "@opencode-ai/plugin";
|
|
2
|
-
import type { TrackedTask, TaskStatus } from "./types";
|
|
2
|
+
import type { TrackedTask, TaskStatus, ModelFallbackInfo } from "./types";
|
|
3
3
|
import type { ConcurrencyManager } from "../background-agent/concurrency";
|
|
4
4
|
type OpencodeClient = PluginInput["client"];
|
|
5
5
|
export declare class TaskToastManager {
|
|
@@ -15,6 +15,7 @@ export declare class TaskToastManager {
|
|
|
15
15
|
isBackground: boolean;
|
|
16
16
|
status?: TaskStatus;
|
|
17
17
|
skills?: string[];
|
|
18
|
+
modelInfo?: ModelFallbackInfo;
|
|
18
19
|
}): void;
|
|
19
20
|
/**
|
|
20
21
|
* Update task status
|
|
@@ -1,4 +1,8 @@
|
|
|
1
1
|
export type TaskStatus = "running" | "queued" | "completed" | "error";
|
|
2
|
+
export interface ModelFallbackInfo {
|
|
3
|
+
model: string;
|
|
4
|
+
type: "user-defined" | "inherited" | "category-default" | "system-default";
|
|
5
|
+
}
|
|
2
6
|
export interface TrackedTask {
|
|
3
7
|
id: string;
|
|
4
8
|
description: string;
|
|
@@ -7,6 +11,7 @@ export interface TrackedTask {
|
|
|
7
11
|
startedAt: Date;
|
|
8
12
|
isBackground: boolean;
|
|
9
13
|
skills?: string[];
|
|
14
|
+
modelInfo?: ModelFallbackInfo;
|
|
10
15
|
}
|
|
11
16
|
export interface TaskToastOptions {
|
|
12
17
|
title: string;
|
|
@@ -2,4 +2,4 @@ export declare const OPENCODE_STORAGE: string;
|
|
|
2
2
|
export declare const AGENT_USAGE_REMINDER_STORAGE: string;
|
|
3
3
|
export declare const TARGET_TOOLS: Set<string>;
|
|
4
4
|
export declare const AGENT_TOOLS: Set<string>;
|
|
5
|
-
export declare const REMINDER_MESSAGE = "\n[Agent Usage Reminder]\n\nYou called a search/fetch tool directly without leveraging specialized agents.\n\nRECOMMENDED: Use
|
|
5
|
+
export declare const REMINDER_MESSAGE = "\n[Agent Usage Reminder]\n\nYou called a search/fetch tool directly without leveraging specialized agents.\n\nRECOMMENDED: Use delegate_task with explore/librarian agents for better results:\n\n```\n// Parallel exploration - fire multiple agents simultaneously\ndelegate_task(agent=\"explore\", prompt=\"Find all files matching pattern X\")\ndelegate_task(agent=\"explore\", prompt=\"Search for implementation of Y\") \ndelegate_task(agent=\"librarian\", prompt=\"Lookup documentation for Z\")\n\n// Then continue your work while they run in background\n// System will notify you when each completes\n```\n\nWHY:\n- Agents can perform deeper, more thorough searches\n- Background tasks run in parallel, saving time\n- Specialized agents have domain expertise\n- Reduces context window usage in main session\n\nALWAYS prefer: Multiple parallel delegate_task calls > Direct tool calls\n";
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { AutoCompactState } from "./types";
|
|
2
2
|
import type { ExperimentalConfig } from "../../config";
|
|
3
3
|
export declare function getLastAssistant(sessionID: string, client: any, directory: string): Promise<Record<string, unknown> | null>;
|
|
4
|
-
export declare function executeCompact(sessionID: string, msg: Record<string, unknown>, autoCompactState: AutoCompactState, client: any, directory: string, experimental?: ExperimentalConfig
|
|
4
|
+
export declare function executeCompact(sessionID: string, msg: Record<string, unknown>, autoCompactState: AutoCompactState, client: any, directory: string, experimental?: ExperimentalConfig): Promise<void>;
|
|
@@ -2,7 +2,6 @@ import type { PluginInput } from "@opencode-ai/plugin";
|
|
|
2
2
|
import type { ExperimentalConfig } from "../../config";
|
|
3
3
|
export interface AnthropicContextWindowLimitRecoveryOptions {
|
|
4
4
|
experimental?: ExperimentalConfig;
|
|
5
|
-
dcpForCompaction?: boolean;
|
|
6
5
|
}
|
|
7
6
|
export declare function createAnthropicContextWindowLimitRecoveryHook(ctx: PluginInput, options?: AnthropicContextWindowLimitRecoveryOptions): {
|
|
8
7
|
event: ({ event }: {
|
|
@@ -12,6 +11,6 @@ export declare function createAnthropicContextWindowLimitRecoveryHook(ctx: Plugi
|
|
|
12
11
|
};
|
|
13
12
|
}) => Promise<void>;
|
|
14
13
|
};
|
|
15
|
-
export type { AutoCompactState,
|
|
14
|
+
export type { AutoCompactState, ParsedTokenLimitError, TruncateState } from "./types";
|
|
16
15
|
export { parseAnthropicTokenLimitError } from "./parser";
|
|
17
16
|
export { executeCompact, getLastAssistant } from "./executor";
|
|
@@ -15,16 +15,11 @@ export interface TruncateState {
|
|
|
15
15
|
truncateAttempt: number;
|
|
16
16
|
lastTruncatedPartId?: string;
|
|
17
17
|
}
|
|
18
|
-
export interface DcpState {
|
|
19
|
-
attempted: boolean;
|
|
20
|
-
itemsPruned: number;
|
|
21
|
-
}
|
|
22
18
|
export interface AutoCompactState {
|
|
23
19
|
pendingCompact: Set<string>;
|
|
24
20
|
errorDataBySession: Map<string, ParsedTokenLimitError>;
|
|
25
21
|
retryStateBySession: Map<string, RetryState>;
|
|
26
22
|
truncateStateBySession: Map<string, TruncateState>;
|
|
27
|
-
dcpStateBySession: Map<string, DcpState>;
|
|
28
23
|
emptyContentAttemptBySession: Map<string, number>;
|
|
29
24
|
compactionInProgress: Set<string>;
|
|
30
25
|
}
|
|
@@ -16,5 +16,5 @@ export declare function getCachedVersion(): string | null;
|
|
|
16
16
|
* Preserves JSONC comments and formatting via string replacement.
|
|
17
17
|
*/
|
|
18
18
|
export declare function updatePinnedVersion(configPath: string, oldEntry: string, newVersion: string): boolean;
|
|
19
|
-
export declare function getLatestVersion(): Promise<string | null>;
|
|
19
|
+
export declare function getLatestVersion(channel?: string): Promise<string | null>;
|
|
20
20
|
export declare function checkForUpdate(directory: string): Promise<UpdateCheckResult>;
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import type { PluginInput } from "@opencode-ai/plugin";
|
|
2
2
|
import type { AutoUpdateCheckerOptions } from "./types";
|
|
3
|
+
export declare function isPrereleaseVersion(version: string): boolean;
|
|
4
|
+
export declare function isDistTag(version: string): boolean;
|
|
5
|
+
export declare function isPrereleaseOrDistTag(pinnedVersion: string | null): boolean;
|
|
6
|
+
export declare function extractChannel(version: string | null): string;
|
|
3
7
|
export declare function createAutoUpdateCheckerHook(ctx: PluginInput, options?: AutoUpdateCheckerOptions): {
|
|
4
8
|
event: ({ event }: {
|
|
5
9
|
event: {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { BackgroundManager } from "../../features/background-agent";
|
|
2
|
+
interface CompactingInput {
|
|
3
|
+
sessionID: string;
|
|
4
|
+
}
|
|
5
|
+
interface CompactingOutput {
|
|
6
|
+
context: string[];
|
|
7
|
+
prompt?: string;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Background agent compaction hook - preserves task state during context compaction.
|
|
11
|
+
*
|
|
12
|
+
* When OpenCode compacts session context to save tokens, this hook injects
|
|
13
|
+
* information about running and recently completed background tasks so the
|
|
14
|
+
* agent doesn't lose awareness of delegated work.
|
|
15
|
+
*/
|
|
16
|
+
export declare function createBackgroundCompactionHook(manager: BackgroundManager): {
|
|
17
|
+
"experimental.session.compacting": (input: CompactingInput, output: CompactingOutput) => Promise<void>;
|
|
18
|
+
};
|
|
19
|
+
export {};
|
|
@@ -6,6 +6,12 @@ interface Event {
|
|
|
6
6
|
interface EventInput {
|
|
7
7
|
event: Event;
|
|
8
8
|
}
|
|
9
|
+
/**
|
|
10
|
+
* Background notification hook - handles event routing to BackgroundManager.
|
|
11
|
+
*
|
|
12
|
+
* Notifications are now delivered directly via session.prompt({ noReply })
|
|
13
|
+
* from the manager, so this hook only needs to handle event routing.
|
|
14
|
+
*/
|
|
9
15
|
export declare function createBackgroundNotificationHook(manager: BackgroundManager): {
|
|
10
16
|
event: ({ event }: EventInput) => Promise<void>;
|
|
11
17
|
};
|
|
@@ -13,7 +13,6 @@ export declare function getCommentCheckerPathSync(): string | null;
|
|
|
13
13
|
* Call this early to trigger download while other init happens.
|
|
14
14
|
*/
|
|
15
15
|
export declare function startBackgroundInit(): void;
|
|
16
|
-
export declare const COMMENT_CHECKER_CLI_PATH: string | null;
|
|
17
16
|
export interface HookInput {
|
|
18
17
|
session_id: string;
|
|
19
18
|
tool_name: string;
|
|
@@ -1,2 +1,8 @@
|
|
|
1
|
-
|
|
1
|
+
export interface SummarizeContext {
|
|
2
|
+
sessionID: string;
|
|
3
|
+
providerID: string;
|
|
4
|
+
modelID: string;
|
|
5
|
+
usageRatio: number;
|
|
6
|
+
directory: string;
|
|
7
|
+
}
|
|
2
8
|
export declare function createCompactionContextInjector(): (ctx: SummarizeContext) => Promise<void>;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { PluginInput } from "@opencode-ai/plugin";
|
|
2
|
+
export interface DelegateTaskErrorPattern {
|
|
3
|
+
pattern: string;
|
|
4
|
+
errorType: string;
|
|
5
|
+
fixHint: string;
|
|
6
|
+
}
|
|
7
|
+
export declare const DELEGATE_TASK_ERROR_PATTERNS: DelegateTaskErrorPattern[];
|
|
8
|
+
export interface DetectedError {
|
|
9
|
+
errorType: string;
|
|
10
|
+
originalOutput: string;
|
|
11
|
+
}
|
|
12
|
+
export declare function detectDelegateTaskError(output: string): DetectedError | null;
|
|
13
|
+
export declare function buildRetryGuidance(errorInfo: DetectedError): string;
|
|
14
|
+
export declare function createDelegateTaskRetryHook(_ctx: PluginInput): {
|
|
15
|
+
"tool.execute.after": (input: {
|
|
16
|
+
tool: string;
|
|
17
|
+
sessionID: string;
|
|
18
|
+
callID: string;
|
|
19
|
+
}, output: {
|
|
20
|
+
title: string;
|
|
21
|
+
output: string;
|
|
22
|
+
metadata: unknown;
|
|
23
|
+
}) => Promise<void>;
|
|
24
|
+
};
|
package/dist/hooks/index.d.ts
CHANGED
|
@@ -8,7 +8,6 @@ export { createDirectoryAgentsInjectorHook } from "./directory-agents-injector";
|
|
|
8
8
|
export { createDirectoryReadmeInjectorHook } from "./directory-readme-injector";
|
|
9
9
|
export { createEmptyTaskResponseDetectorHook } from "./empty-task-response-detector";
|
|
10
10
|
export { createAnthropicContextWindowLimitRecoveryHook, type AnthropicContextWindowLimitRecoveryOptions } from "./anthropic-context-window-limit-recovery";
|
|
11
|
-
export { createPreemptiveCompactionHook, type PreemptiveCompactionOptions, type SummarizeContext, type BeforeSummarizeCallback } from "./preemptive-compaction";
|
|
12
11
|
export { createCompactionContextInjector } from "./compaction-context-injector";
|
|
13
12
|
export { createThinkModeHook } from "./think-mode";
|
|
14
13
|
export { createClaudeCodeHooksHook } from "./claude-code-hooks";
|
|
@@ -19,7 +18,6 @@ export { createAgentUsageReminderHook } from "./agent-usage-reminder";
|
|
|
19
18
|
export { createKeywordDetectorHook } from "./keyword-detector";
|
|
20
19
|
export { createNonInteractiveEnvHook } from "./non-interactive-env";
|
|
21
20
|
export { createInteractiveBashSessionHook } from "./interactive-bash-session";
|
|
22
|
-
export { createEmptyMessageSanitizerHook } from "./empty-message-sanitizer";
|
|
23
21
|
export { createThinkingBlockValidatorHook } from "./thinking-block-validator";
|
|
24
22
|
export { createRalphLoopHook, type RalphLoopHook } from "./ralph-loop";
|
|
25
23
|
export { createAutoSlashCommandHook } from "./auto-slash-command";
|
|
@@ -28,3 +26,4 @@ export { createPrometheusMdOnlyHook } from "./prometheus-md-only";
|
|
|
28
26
|
export { createTaskResumeInfoHook } from "./task-resume-info";
|
|
29
27
|
export { createStartWorkHook } from "./start-work";
|
|
30
28
|
export { createSisyphusOrchestratorHook } from "./sisyphus-orchestrator";
|
|
29
|
+
export { createDelegateTaskRetryHook } from "./delegate-task-retry";
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import type { PluginInput } from "@opencode-ai/plugin";
|
|
2
|
+
import type { ContextCollector } from "../../features/context-injector";
|
|
2
3
|
export * from "./detector";
|
|
3
4
|
export * from "./constants";
|
|
4
5
|
export * from "./types";
|
|
5
|
-
export declare function createKeywordDetectorHook(ctx: PluginInput): {
|
|
6
|
+
export declare function createKeywordDetectorHook(ctx: PluginInput, collector?: ContextCollector): {
|
|
6
7
|
"chat.message": (input: {
|
|
7
8
|
sessionID: string;
|
|
8
9
|
agent?: string;
|