@hyperwindmill/caretaker-cli 0.11.0
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/LICENSE +110 -0
- package/README.md +25 -0
- package/dist/agents/dispatch.d.ts +35 -0
- package/dist/agents/dispatch.d.ts.map +1 -0
- package/dist/agents/dispatch.js +108 -0
- package/dist/agents/sync.d.ts +10 -0
- package/dist/agents/sync.d.ts.map +1 -0
- package/dist/agents/sync.js +95 -0
- package/dist/cli/index.d.ts +2 -0
- package/dist/cli/index.d.ts.map +1 -0
- package/dist/cli/index.js +50 -0
- package/dist/cli/run.d.ts +11 -0
- package/dist/cli/run.d.ts.map +1 -0
- package/dist/cli/run.js +89 -0
- package/dist/cli/web/fs.d.ts +3 -0
- package/dist/cli/web/fs.d.ts.map +1 -0
- package/dist/cli/web/fs.js +35 -0
- package/dist/cli/web/mcp_bridge.d.ts +7 -0
- package/dist/cli/web/mcp_bridge.d.ts.map +1 -0
- package/dist/cli/web/mcp_bridge.js +86 -0
- package/dist/cli/web/scheduler/heartbeat.d.ts +16 -0
- package/dist/cli/web/scheduler/heartbeat.d.ts.map +1 -0
- package/dist/cli/web/scheduler/heartbeat.js +181 -0
- package/dist/cli/web/scheduler/locks.d.ts +8 -0
- package/dist/cli/web/scheduler/locks.d.ts.map +1 -0
- package/dist/cli/web/scheduler/locks.js +7 -0
- package/dist/cli/web/scheduler/logs.d.ts +21 -0
- package/dist/cli/web/scheduler/logs.d.ts.map +1 -0
- package/dist/cli/web/scheduler/logs.js +62 -0
- package/dist/cli/web/scheduler/strategy.d.ts +6 -0
- package/dist/cli/web/scheduler/strategy.d.ts.map +1 -0
- package/dist/cli/web/scheduler/strategy.js +1 -0
- package/dist/cli/web/scheduler/task_review.d.ts +18 -0
- package/dist/cli/web/scheduler/task_review.d.ts.map +1 -0
- package/dist/cli/web/scheduler/task_review.js +77 -0
- package/dist/cli/web/scheduler/task_roles.d.ts +22 -0
- package/dist/cli/web/scheduler/task_roles.d.ts.map +1 -0
- package/dist/cli/web/scheduler/task_roles.js +70 -0
- package/dist/cli/web/scheduler/task_strategy.d.ts +2 -0
- package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -0
- package/dist/cli/web/scheduler/task_strategy.js +437 -0
- package/dist/cli/web/scheduler/telegram.d.ts +7 -0
- package/dist/cli/web/scheduler/telegram.d.ts.map +1 -0
- package/dist/cli/web/scheduler/telegram.js +393 -0
- package/dist/cli/web/scheduler.d.ts +15 -0
- package/dist/cli/web/scheduler.d.ts.map +1 -0
- package/dist/cli/web/scheduler.js +60 -0
- package/dist/cli/web/server.d.ts +38 -0
- package/dist/cli/web/server.d.ts.map +1 -0
- package/dist/cli/web/server.js +970 -0
- package/dist/commands/loader.d.ts +37 -0
- package/dist/commands/loader.d.ts.map +1 -0
- package/dist/commands/loader.js +110 -0
- package/dist/harness/claude_code_runner.d.ts +47 -0
- package/dist/harness/claude_code_runner.d.ts.map +1 -0
- package/dist/harness/claude_code_runner.js +325 -0
- package/dist/harness/claude_code_stream.d.ts +32 -0
- package/dist/harness/claude_code_stream.d.ts.map +1 -0
- package/dist/harness/claude_code_stream.js +121 -0
- package/dist/harness/context_files.d.ts +23 -0
- package/dist/harness/context_files.d.ts.map +1 -0
- package/dist/harness/context_files.js +126 -0
- package/dist/harness/history.d.ts +4 -0
- package/dist/harness/history.d.ts.map +1 -0
- package/dist/harness/history.js +120 -0
- package/dist/harness/index.d.ts +8 -0
- package/dist/harness/index.d.ts.map +1 -0
- package/dist/harness/index.js +8 -0
- package/dist/harness/loop.d.ts +73 -0
- package/dist/harness/loop.d.ts.map +1 -0
- package/dist/harness/loop.js +373 -0
- package/dist/harness/model_limits.d.ts +25 -0
- package/dist/harness/model_limits.d.ts.map +1 -0
- package/dist/harness/model_limits.js +67 -0
- package/dist/harness/models.d.ts +9 -0
- package/dist/harness/models.d.ts.map +1 -0
- package/dist/harness/models.js +38 -0
- package/dist/harness/prelude.d.ts +21 -0
- package/dist/harness/prelude.d.ts.map +1 -0
- package/dist/harness/prelude.js +41 -0
- package/dist/harness/provider.d.ts +87 -0
- package/dist/harness/provider.d.ts.map +1 -0
- package/dist/harness/provider.js +140 -0
- package/dist/harness/runtime_info.d.ts +7 -0
- package/dist/harness/runtime_info.d.ts.map +1 -0
- package/dist/harness/runtime_info.js +15 -0
- package/dist/harness/think_tag_splitter.d.ts +33 -0
- package/dist/harness/think_tag_splitter.d.ts.map +1 -0
- package/dist/harness/think_tag_splitter.js +70 -0
- package/dist/harness/title.d.ts +17 -0
- package/dist/harness/title.d.ts.map +1 -0
- package/dist/harness/title.js +75 -0
- package/dist/harness/tools/builtin/bash.d.ts +3 -0
- package/dist/harness/tools/builtin/bash.d.ts.map +1 -0
- package/dist/harness/tools/builtin/bash.js +137 -0
- package/dist/harness/tools/builtin/edit.d.ts +6 -0
- package/dist/harness/tools/builtin/edit.d.ts.map +1 -0
- package/dist/harness/tools/builtin/edit.js +85 -0
- package/dist/harness/tools/builtin/fetch.d.ts +3 -0
- package/dist/harness/tools/builtin/fetch.d.ts.map +1 -0
- package/dist/harness/tools/builtin/fetch.js +75 -0
- package/dist/harness/tools/builtin/get_agent_context.d.ts +3 -0
- package/dist/harness/tools/builtin/get_agent_context.d.ts.map +1 -0
- package/dist/harness/tools/builtin/get_agent_context.js +76 -0
- package/dist/harness/tools/builtin/glob.d.ts +3 -0
- package/dist/harness/tools/builtin/glob.d.ts.map +1 -0
- package/dist/harness/tools/builtin/glob.js +52 -0
- package/dist/harness/tools/builtin/grep.d.ts +3 -0
- package/dist/harness/tools/builtin/grep.d.ts.map +1 -0
- package/dist/harness/tools/builtin/grep.js +126 -0
- package/dist/harness/tools/builtin/index.d.ts +23 -0
- package/dist/harness/tools/builtin/index.d.ts.map +1 -0
- package/dist/harness/tools/builtin/index.js +74 -0
- package/dist/harness/tools/builtin/invoke_agent.d.ts +3 -0
- package/dist/harness/tools/builtin/invoke_agent.d.ts.map +1 -0
- package/dist/harness/tools/builtin/invoke_agent.js +106 -0
- package/dist/harness/tools/builtin/invoke_command.d.ts +3 -0
- package/dist/harness/tools/builtin/invoke_command.d.ts.map +1 -0
- package/dist/harness/tools/builtin/invoke_command.js +42 -0
- package/dist/harness/tools/builtin/list_agents.d.ts +3 -0
- package/dist/harness/tools/builtin/list_agents.d.ts.map +1 -0
- package/dist/harness/tools/builtin/list_agents.js +32 -0
- package/dist/harness/tools/builtin/list_commands.d.ts +3 -0
- package/dist/harness/tools/builtin/list_commands.d.ts.map +1 -0
- package/dist/harness/tools/builtin/list_commands.js +27 -0
- package/dist/harness/tools/builtin/list_skills.d.ts +3 -0
- package/dist/harness/tools/builtin/list_skills.d.ts.map +1 -0
- package/dist/harness/tools/builtin/list_skills.js +24 -0
- package/dist/harness/tools/builtin/multiedit.d.ts +3 -0
- package/dist/harness/tools/builtin/multiedit.d.ts.map +1 -0
- package/dist/harness/tools/builtin/multiedit.js +88 -0
- package/dist/harness/tools/builtin/read_attachment.d.ts +3 -0
- package/dist/harness/tools/builtin/read_attachment.d.ts.map +1 -0
- package/dist/harness/tools/builtin/read_attachment.js +128 -0
- package/dist/harness/tools/builtin/read_document.d.ts +37 -0
- package/dist/harness/tools/builtin/read_document.d.ts.map +1 -0
- package/dist/harness/tools/builtin/read_document.js +238 -0
- package/dist/harness/tools/builtin/read_file.d.ts +3 -0
- package/dist/harness/tools/builtin/read_file.d.ts.map +1 -0
- package/dist/harness/tools/builtin/read_file.js +141 -0
- package/dist/harness/tools/builtin/read_image.d.ts +3 -0
- package/dist/harness/tools/builtin/read_image.d.ts.map +1 -0
- package/dist/harness/tools/builtin/read_image.js +80 -0
- package/dist/harness/tools/builtin/read_skill.d.ts +3 -0
- package/dist/harness/tools/builtin/read_skill.d.ts.map +1 -0
- package/dist/harness/tools/builtin/read_skill.js +30 -0
- package/dist/harness/tools/builtin/shell-env.d.ts +55 -0
- package/dist/harness/tools/builtin/shell-env.d.ts.map +1 -0
- package/dist/harness/tools/builtin/shell-env.js +181 -0
- package/dist/harness/tools/builtin/task_tools.d.ts +21 -0
- package/dist/harness/tools/builtin/task_tools.d.ts.map +1 -0
- package/dist/harness/tools/builtin/task_tools.js +708 -0
- package/dist/harness/tools/builtin/write.d.ts +3 -0
- package/dist/harness/tools/builtin/write.d.ts.map +1 -0
- package/dist/harness/tools/builtin/write.js +56 -0
- package/dist/harness/tools/index.d.ts +6 -0
- package/dist/harness/tools/index.d.ts.map +1 -0
- package/dist/harness/tools/index.js +7 -0
- package/dist/harness/tools/instance.d.ts +3 -0
- package/dist/harness/tools/instance.d.ts.map +1 -0
- package/dist/harness/tools/instance.js +19 -0
- package/dist/harness/tools/registry.d.ts +21 -0
- package/dist/harness/tools/registry.d.ts.map +1 -0
- package/dist/harness/tools/registry.js +33 -0
- package/dist/harness/tools/resolve.d.ts +5 -0
- package/dist/harness/tools/resolve.d.ts.map +1 -0
- package/dist/harness/tools/resolve.js +60 -0
- package/dist/harness/tools/sandbox.d.ts +6 -0
- package/dist/harness/tools/sandbox.d.ts.map +1 -0
- package/dist/harness/tools/sandbox.js +23 -0
- package/dist/harness/tools/types.d.ts +80 -0
- package/dist/harness/tools/types.d.ts.map +1 -0
- package/dist/harness/tools/types.js +16 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +46 -0
- package/dist/lib/encryption.d.ts +24 -0
- package/dist/lib/encryption.d.ts.map +1 -0
- package/dist/lib/encryption.js +163 -0
- package/dist/lib/open_url.d.ts +9 -0
- package/dist/lib/open_url.d.ts.map +1 -0
- package/dist/lib/open_url.js +23 -0
- package/dist/lib/task_git.d.ts +11 -0
- package/dist/lib/task_git.d.ts.map +1 -0
- package/dist/lib/task_git.js +100 -0
- package/dist/mcp/adapter.d.ts +9 -0
- package/dist/mcp/adapter.d.ts.map +1 -0
- package/dist/mcp/adapter.js +74 -0
- package/dist/mcp/client.d.ts +50 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/client.js +243 -0
- package/dist/mcp/oauth.d.ts +30 -0
- package/dist/mcp/oauth.d.ts.map +1 -0
- package/dist/mcp/oauth.js +171 -0
- package/dist/mcp/oauth_callback.d.ts +9 -0
- package/dist/mcp/oauth_callback.d.ts.map +1 -0
- package/dist/mcp/oauth_callback.js +51 -0
- package/dist/mcp/oauth_store.d.ts +22 -0
- package/dist/mcp/oauth_store.d.ts.map +1 -0
- package/dist/mcp/oauth_store.js +40 -0
- package/dist/mcp/server_manager.d.ts +49 -0
- package/dist/mcp/server_manager.d.ts.map +1 -0
- package/dist/mcp/server_manager.js +271 -0
- package/dist/plugins/fetchers/git.d.ts +67 -0
- package/dist/plugins/fetchers/git.d.ts.map +1 -0
- package/dist/plugins/fetchers/git.js +130 -0
- package/dist/plugins/fetchers/path.d.ts +4 -0
- package/dist/plugins/fetchers/path.d.ts.map +1 -0
- package/dist/plugins/fetchers/path.js +22 -0
- package/dist/plugins/loader.d.ts +31 -0
- package/dist/plugins/loader.d.ts.map +1 -0
- package/dist/plugins/loader.js +146 -0
- package/dist/plugins/manifest.d.ts +56 -0
- package/dist/plugins/manifest.d.ts.map +1 -0
- package/dist/plugins/manifest.js +389 -0
- package/dist/plugins/refresh_on_start.d.ts +7 -0
- package/dist/plugins/refresh_on_start.d.ts.map +1 -0
- package/dist/plugins/refresh_on_start.js +35 -0
- package/dist/plugins/source_manager.d.ts +27 -0
- package/dist/plugins/source_manager.d.ts.map +1 -0
- package/dist/plugins/source_manager.js +211 -0
- package/dist/plugins/types.d.ts +41 -0
- package/dist/plugins/types.d.ts.map +1 -0
- package/dist/plugins/types.js +11 -0
- package/dist/session/context_usage.d.ts +13 -0
- package/dist/session/context_usage.d.ts.map +1 -0
- package/dist/session/context_usage.js +25 -0
- package/dist/session/index.d.ts +7 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/index.js +5 -0
- package/dist/session/store.d.ts +68 -0
- package/dist/session/store.d.ts.map +1 -0
- package/dist/session/store.js +268 -0
- package/dist/session/types.d.ts +60 -0
- package/dist/session/types.d.ts.map +1 -0
- package/dist/session/types.js +11 -0
- package/dist/store/db.d.ts +64 -0
- package/dist/store/db.d.ts.map +1 -0
- package/dist/store/db.js +91 -0
- package/dist/store/json.d.ts +21 -0
- package/dist/store/json.d.ts.map +1 -0
- package/dist/store/json.js +135 -0
- package/dist/tui/agents.d.ts +4 -0
- package/dist/tui/agents.d.ts.map +1 -0
- package/dist/tui/agents.js +616 -0
- package/dist/tui/app.d.ts +2 -0
- package/dist/tui/app.d.ts.map +1 -0
- package/dist/tui/app.js +32 -0
- package/dist/tui/chat.d.ts +10 -0
- package/dist/tui/chat.d.ts.map +1 -0
- package/dist/tui/chat.js +258 -0
- package/dist/tui/logo.d.ts +2 -0
- package/dist/tui/logo.d.ts.map +1 -0
- package/dist/tui/logo.js +10 -0
- package/dist/tui/mcp_servers.d.ts +4 -0
- package/dist/tui/mcp_servers.d.ts.map +1 -0
- package/dist/tui/mcp_servers.js +287 -0
- package/dist/tui/plugins.d.ts +4 -0
- package/dist/tui/plugins.d.ts.map +1 -0
- package/dist/tui/plugins.js +234 -0
- package/dist/tui/providers.d.ts +4 -0
- package/dist/tui/providers.d.ts.map +1 -0
- package/dist/tui/providers.js +178 -0
- package/dist/tui/tool_picker_state.d.ts +9 -0
- package/dist/tui/tool_picker_state.d.ts.map +1 -0
- package/dist/tui/tool_picker_state.js +37 -0
- package/dist/types.d.ts +2 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +1 -0
- package/dist/webview/index.html +22 -0
- package/dist/webview/standalone.css +2732 -0
- package/dist/webview/standalone.css.map +7 -0
- package/dist/webview/standalone.js +20641 -0
- package/dist/webview/standalone.js.map +7 -0
- package/package.json +120 -0
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { CommandSpec } from '../types.js';
|
|
2
|
+
export interface CommandSummary {
|
|
3
|
+
name: string;
|
|
4
|
+
description?: string;
|
|
5
|
+
argumentHint?: string;
|
|
6
|
+
pluginName: string;
|
|
7
|
+
}
|
|
8
|
+
export interface ResolvedCommand {
|
|
9
|
+
name: string;
|
|
10
|
+
spec: CommandSpec;
|
|
11
|
+
pluginName: string;
|
|
12
|
+
}
|
|
13
|
+
/** Catalog of slash commands available to an agent given its active
|
|
14
|
+
* plugins. Used by the chat input for help-style listing and (future)
|
|
15
|
+
* autocomplete. Order follows `activePlugins`, then declaration order. */
|
|
16
|
+
export declare function listActiveCommands(activePlugins: string[]): Promise<CommandSummary[]>;
|
|
17
|
+
/** Look up a command by its scoped name across the agent's active
|
|
18
|
+
* plugins. Returns `null` when the command does not exist for this
|
|
19
|
+
* agent (unknown name OR defined only by a non-active plugin). */
|
|
20
|
+
export declare function resolveCommand(name: string, activePlugins: string[]): Promise<ResolvedCommand | null>;
|
|
21
|
+
/** Tokenize an arg string. Bare words split on whitespace; double-quoted
|
|
22
|
+
* spans are kept as one arg (no escapes). Single quotes are NOT special
|
|
23
|
+
* — Claude Code does not document them either. */
|
|
24
|
+
export declare function tokenizeArgs(s: string): string[];
|
|
25
|
+
/** Replace `$1`, `$2`, …, and `$ARGUMENTS` in the body. Unmatched
|
|
26
|
+
* positionals collapse to empty strings (the user invoked with too few
|
|
27
|
+
* args — the prompt template should be tolerant). `$0`, `$10`+ are not
|
|
28
|
+
* supported on purpose; commands rarely need more than 9 positionals. */
|
|
29
|
+
export declare function expandTemplate(body: string, args: string[], rawTail: string): string;
|
|
30
|
+
/** Parse `/cmd-name args…`. Returns null when the input does not start
|
|
31
|
+
* with `/` or has no command name. */
|
|
32
|
+
export declare function parseSlashInvocation(input: string): {
|
|
33
|
+
name: string;
|
|
34
|
+
args: string[];
|
|
35
|
+
raw: string;
|
|
36
|
+
} | null;
|
|
37
|
+
//# sourceMappingURL=loader.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../src/commands/loader.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,WAAW,EAAgB,MAAM,aAAa,CAAC;AAE7D,MAAM,WAAW,cAAc;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,WAAW,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;CACpB;AAuBD;;2EAE2E;AAC3E,wBAAsB,kBAAkB,CAAC,aAAa,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAkB3F;AAED;;mEAEmE;AACnE,wBAAsB,cAAc,CAClC,IAAI,EAAE,MAAM,EACZ,aAAa,EAAE,MAAM,EAAE,GACtB,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAUjC;AAID;;mDAEmD;AACnD,wBAAgB,YAAY,CAAC,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAQhD;AAED;;;0EAG0E;AAC1E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAIpF;AAED;uCACuC;AACvC,wBAAgB,oBAAoB,CAClC,KAAK,EAAE,MAAM,GACZ;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAMtD"}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
// Slash command resolution at chat time. Commands live on PluginRecord
|
|
2
|
+
// (loaded from plugins.json) and are gated per-agent by AgentConfig.plugins
|
|
3
|
+
// — same model as skills. No separate store; the plugin record is the
|
|
4
|
+
// source of truth.
|
|
5
|
+
//
|
|
6
|
+
// Names are scoped: a plugin named "contract-workflow" with
|
|
7
|
+
// `commands/contract-writing.md` registers as `/contract-writing`. On a
|
|
8
|
+
// collision (two active plugins both define `/foo`), the first plugin
|
|
9
|
+
// listed in `agent.plugins` wins; the duplicate is dropped silently and
|
|
10
|
+
// the user can disambiguate by removing the conflicting plugin from the
|
|
11
|
+
// agent.
|
|
12
|
+
import { loadPlugins } from '../store/json.js';
|
|
13
|
+
async function activePluginRecords(activeNames) {
|
|
14
|
+
const wanted = activeNames.map((n) => n.trim()).filter(Boolean);
|
|
15
|
+
if (wanted.length === 0)
|
|
16
|
+
return [];
|
|
17
|
+
let file;
|
|
18
|
+
try {
|
|
19
|
+
file = await loadPlugins();
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
// Preserve agent.plugins ordering so the "first wins" rule on collision
|
|
25
|
+
// is deterministic and user-controlled.
|
|
26
|
+
const byName = new Map();
|
|
27
|
+
for (const p of file.plugins)
|
|
28
|
+
byName.set(p.name, p);
|
|
29
|
+
const out = [];
|
|
30
|
+
for (const name of wanted) {
|
|
31
|
+
const p = byName.get(name);
|
|
32
|
+
if (p)
|
|
33
|
+
out.push(p);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
/** Catalog of slash commands available to an agent given its active
|
|
38
|
+
* plugins. Used by the chat input for help-style listing and (future)
|
|
39
|
+
* autocomplete. Order follows `activePlugins`, then declaration order. */
|
|
40
|
+
export async function listActiveCommands(activePlugins) {
|
|
41
|
+
const records = await activePluginRecords(activePlugins);
|
|
42
|
+
const seen = new Set();
|
|
43
|
+
const out = [];
|
|
44
|
+
for (const plugin of records) {
|
|
45
|
+
if (!plugin.commands)
|
|
46
|
+
continue;
|
|
47
|
+
for (const [name, spec] of Object.entries(plugin.commands)) {
|
|
48
|
+
if (seen.has(name))
|
|
49
|
+
continue; // first plugin wins
|
|
50
|
+
seen.add(name);
|
|
51
|
+
out.push({
|
|
52
|
+
name,
|
|
53
|
+
description: spec.description,
|
|
54
|
+
argumentHint: spec.argumentHint,
|
|
55
|
+
pluginName: plugin.name,
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return out;
|
|
60
|
+
}
|
|
61
|
+
/** Look up a command by its scoped name across the agent's active
|
|
62
|
+
* plugins. Returns `null` when the command does not exist for this
|
|
63
|
+
* agent (unknown name OR defined only by a non-active plugin). */
|
|
64
|
+
export async function resolveCommand(name, activePlugins) {
|
|
65
|
+
const trimmed = name.trim();
|
|
66
|
+
if (!trimmed)
|
|
67
|
+
return null;
|
|
68
|
+
const records = await activePluginRecords(activePlugins);
|
|
69
|
+
for (const plugin of records) {
|
|
70
|
+
if (!plugin.commands)
|
|
71
|
+
continue;
|
|
72
|
+
const spec = plugin.commands[trimmed];
|
|
73
|
+
if (spec)
|
|
74
|
+
return { name: trimmed, spec, pluginName: plugin.name };
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
// ─── Pure helpers (also exported for unit tests) ────────────────────────
|
|
79
|
+
/** Tokenize an arg string. Bare words split on whitespace; double-quoted
|
|
80
|
+
* spans are kept as one arg (no escapes). Single quotes are NOT special
|
|
81
|
+
* — Claude Code does not document them either. */
|
|
82
|
+
export function tokenizeArgs(s) {
|
|
83
|
+
const out = [];
|
|
84
|
+
const re = /"([^"]*)"|(\S+)/g;
|
|
85
|
+
let m;
|
|
86
|
+
while ((m = re.exec(s)) !== null) {
|
|
87
|
+
out.push(m[1] !== undefined ? m[1] : m[2]);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
/** Replace `$1`, `$2`, …, and `$ARGUMENTS` in the body. Unmatched
|
|
92
|
+
* positionals collapse to empty strings (the user invoked with too few
|
|
93
|
+
* args — the prompt template should be tolerant). `$0`, `$10`+ are not
|
|
94
|
+
* supported on purpose; commands rarely need more than 9 positionals. */
|
|
95
|
+
export function expandTemplate(body, args, rawTail) {
|
|
96
|
+
return body
|
|
97
|
+
.replace(/\$ARGUMENTS\b/g, rawTail)
|
|
98
|
+
.replace(/\$([1-9])\b/g, (_, n) => args[Number(n) - 1] ?? '');
|
|
99
|
+
}
|
|
100
|
+
/** Parse `/cmd-name args…`. Returns null when the input does not start
|
|
101
|
+
* with `/` or has no command name. */
|
|
102
|
+
export function parseSlashInvocation(input) {
|
|
103
|
+
if (!input.startsWith('/'))
|
|
104
|
+
return null;
|
|
105
|
+
const m = /^\/(\S+)(?:\s+([\s\S]*))?$/.exec(input);
|
|
106
|
+
if (!m)
|
|
107
|
+
return null;
|
|
108
|
+
const [, name, tail = ''] = m;
|
|
109
|
+
return { name: name, args: tokenizeArgs(tail), raw: tail };
|
|
110
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { type SpawnOptions } from 'node:child_process';
|
|
2
|
+
import type { RunOptions, RunCallbacks, RunResult } from './loop.js';
|
|
3
|
+
export type ClaudeCodeRunExtras = {
|
|
4
|
+
permissionMode?: string;
|
|
5
|
+
allowedTools?: string[];
|
|
6
|
+
disallowedTools?: string[];
|
|
7
|
+
extraMcpServers?: Record<string, {
|
|
8
|
+
type: 'http';
|
|
9
|
+
url: string;
|
|
10
|
+
headers?: Record<string, string>;
|
|
11
|
+
}>;
|
|
12
|
+
};
|
|
13
|
+
export type ClaudeChildProcess = {
|
|
14
|
+
stdout: NodeJS.ReadableStream | null;
|
|
15
|
+
stderr: NodeJS.ReadableStream | null;
|
|
16
|
+
stdin: NodeJS.WritableStream | null;
|
|
17
|
+
kill(signal?: NodeJS.Signals | number): boolean;
|
|
18
|
+
on(event: 'close', listener: (code: number | null) => void): unknown;
|
|
19
|
+
on(event: 'error', listener: (err: Error) => void): unknown;
|
|
20
|
+
};
|
|
21
|
+
type SpawnFn = (command: string, args: string[], opts: SpawnOptions) => ClaudeChildProcess;
|
|
22
|
+
export declare function __setSpawn(fn: SpawnFn): void;
|
|
23
|
+
export declare function __resetSpawn(): void;
|
|
24
|
+
export declare function detectClaudeDefaultPermissionMode(settingsPath?: string): string | null;
|
|
25
|
+
export interface ClaudeArgsInput {
|
|
26
|
+
model?: string;
|
|
27
|
+
permissionMode?: string;
|
|
28
|
+
appendSystemPrompt?: string;
|
|
29
|
+
allowedTools?: string[];
|
|
30
|
+
disallowedTools?: string[];
|
|
31
|
+
mcpConfigPath?: string;
|
|
32
|
+
resumeId?: string;
|
|
33
|
+
persistSession: boolean;
|
|
34
|
+
}
|
|
35
|
+
export declare function buildClaudeArgs(i: ClaudeArgsInput): string[];
|
|
36
|
+
/** Role restrictions + task-bridge wiring for autonomous task runs. */
|
|
37
|
+
export declare function claudeCodeTaskExtras(p: {
|
|
38
|
+
planning: boolean;
|
|
39
|
+
sdd: boolean;
|
|
40
|
+
bridge?: {
|
|
41
|
+
url: string;
|
|
42
|
+
token: string;
|
|
43
|
+
};
|
|
44
|
+
}): ClaudeCodeRunExtras;
|
|
45
|
+
export declare function runClaudeCode(opts: RunOptions, cb?: RunCallbacks): Promise<RunResult>;
|
|
46
|
+
export {};
|
|
47
|
+
//# sourceMappingURL=claude_code_runner.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude_code_runner.d.ts","sourceRoot":"","sources":["../../src/harness/claude_code_runner.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAM3E,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAcrE,MAAM,MAAM,mBAAmB,GAAG;IAChC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,GAAG,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC,CAAC;CACnG,CAAC;AAQF,MAAM,MAAM,kBAAkB,GAAG;IAC/B,MAAM,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,CAAC;IACrC,MAAM,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,CAAC;IACrC,KAAK,EAAE,MAAM,CAAC,cAAc,GAAG,IAAI,CAAC;IACpC,IAAI,CAAC,MAAM,CAAC,EAAE,MAAM,CAAC,OAAO,GAAG,MAAM,GAAG,OAAO,CAAC;IAChD,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,KAAK,IAAI,GAAG,OAAO,CAAC;IACrE,EAAE,CAAC,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,GAAG,EAAE,KAAK,KAAK,IAAI,GAAG,OAAO,CAAC;CAC7D,CAAC;AACF,KAAK,OAAO,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,IAAI,EAAE,YAAY,KAAK,kBAAkB,CAAC;AAE3F,wBAAgB,UAAU,CAAC,EAAE,EAAE,OAAO,GAAG,IAAI,CAE5C;AACD,wBAAgB,YAAY,IAAI,IAAI,CAEnC;AAED,wBAAgB,iCAAiC,CAC/C,YAAY,GAAE,MAA4D,GACzE,MAAM,GAAG,IAAI,CAQf;AAED,MAAM,WAAW,eAAe;IAC9B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,YAAY,CAAC,EAAE,MAAM,EAAE,CAAC;IACxB,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,OAAO,CAAC;CACzB;AAED,wBAAgB,eAAe,CAAC,CAAC,EAAE,eAAe,GAAG,MAAM,EAAE,CAW5D;AAED,uEAAuE;AACvE,wBAAgB,oBAAoB,CAAC,CAAC,EAAE;IACtC,QAAQ,EAAE,OAAO,CAAC;IAClB,GAAG,EAAE,OAAO,CAAC;IACb,MAAM,CAAC,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,CAAC;CACzC,GAAG,mBAAmB,CAiBtB;AA+LD,wBAAsB,aAAa,CAAC,IAAI,EAAE,UAAU,EAAE,EAAE,GAAE,YAAiB,GAAG,OAAO,CAAC,SAAS,CAAC,CAmH/F"}
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
// Claude Code runner: implements the same run() contract as loop.ts by
|
|
2
|
+
// spawning one `claude -p --output-format stream-json` process per turn.
|
|
3
|
+
// Claude Code owns the agentic loop, tools, and permissions; caretaker
|
|
4
|
+
// owns display persistence (via cb.onMessage) and session continuity
|
|
5
|
+
// (claudeSessionId on the session meta, resumed with --resume).
|
|
6
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
7
|
+
import { createInterface } from 'node:readline';
|
|
8
|
+
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { parseClaudeStreamLine } from './claude_code_stream.js';
|
|
13
|
+
import { loadContextFiles, formatContextBlock, resolveFileReferences } from './context_files.js';
|
|
14
|
+
import { readSession, updateClaudeSessionId, assistantMessage, toolMessage, } from '../session/store.js';
|
|
15
|
+
import { loadMcpServers } from '../store/json.js';
|
|
16
|
+
import { resolvedServerRuntime } from '../mcp/client.js';
|
|
17
|
+
let spawnImpl = nodeSpawn;
|
|
18
|
+
export function __setSpawn(fn) {
|
|
19
|
+
spawnImpl = fn;
|
|
20
|
+
}
|
|
21
|
+
export function __resetSpawn() {
|
|
22
|
+
spawnImpl = nodeSpawn;
|
|
23
|
+
}
|
|
24
|
+
export function detectClaudeDefaultPermissionMode(settingsPath = path.join(os.homedir(), '.claude', 'settings.json')) {
|
|
25
|
+
try {
|
|
26
|
+
const raw = JSON.parse(readFileSync(settingsPath, 'utf8'));
|
|
27
|
+
const mode = raw?.permissions?.defaultMode;
|
|
28
|
+
return typeof mode === 'string' && mode.length > 0 ? mode : null;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
export function buildClaudeArgs(i) {
|
|
35
|
+
const args = ['-p', '--output-format', 'stream-json', '--verbose', '--include-partial-messages'];
|
|
36
|
+
if (i.model)
|
|
37
|
+
args.push('--model', i.model);
|
|
38
|
+
if (i.permissionMode)
|
|
39
|
+
args.push('--permission-mode', i.permissionMode);
|
|
40
|
+
if (i.appendSystemPrompt)
|
|
41
|
+
args.push('--append-system-prompt', i.appendSystemPrompt);
|
|
42
|
+
if (i.allowedTools?.length)
|
|
43
|
+
args.push('--allowedTools', ...i.allowedTools);
|
|
44
|
+
if (i.disallowedTools?.length)
|
|
45
|
+
args.push('--disallowedTools', ...i.disallowedTools);
|
|
46
|
+
if (i.mcpConfigPath)
|
|
47
|
+
args.push('--mcp-config', i.mcpConfigPath, '--strict-mcp-config');
|
|
48
|
+
if (i.resumeId)
|
|
49
|
+
args.push('--resume', i.resumeId);
|
|
50
|
+
else if (!i.persistSession)
|
|
51
|
+
args.push('--no-session-persistence');
|
|
52
|
+
return args;
|
|
53
|
+
}
|
|
54
|
+
/** Role restrictions + task-bridge wiring for autonomous task runs. */
|
|
55
|
+
export function claudeCodeTaskExtras(p) {
|
|
56
|
+
const extraMcpServers = p.bridge
|
|
57
|
+
? {
|
|
58
|
+
task: {
|
|
59
|
+
type: 'http',
|
|
60
|
+
url: p.bridge.url,
|
|
61
|
+
headers: { Authorization: `Bearer ${p.bridge.token}` },
|
|
62
|
+
},
|
|
63
|
+
}
|
|
64
|
+
: undefined;
|
|
65
|
+
if (!p.planning)
|
|
66
|
+
return { permissionMode: 'bypassPermissions', extraMcpServers };
|
|
67
|
+
// Planner: 'manual' mode + explicit allowlist. In -p mode unanswered
|
|
68
|
+
// permission prompts are denied, so everything off-list is blocked.
|
|
69
|
+
// (Not 'plan' mode: it could also block mcp task_submit_plan.)
|
|
70
|
+
const allowedTools = ['Read', 'Glob', 'Grep', 'mcp__task'];
|
|
71
|
+
if (p.sdd)
|
|
72
|
+
allowedTools.push('Write(**/*.md)', 'Edit(**/*.md)', 'MultiEdit(**/*.md)');
|
|
73
|
+
return { permissionMode: 'manual', allowedTools, disallowedTools: ['Bash'], extraMcpServers };
|
|
74
|
+
}
|
|
75
|
+
async function buildMcpConfigFile(serverIds, extra) {
|
|
76
|
+
const servers = {};
|
|
77
|
+
if (serverIds.length > 0) {
|
|
78
|
+
const file = await loadMcpServers();
|
|
79
|
+
for (const id of serverIds) {
|
|
80
|
+
const cfg = file.servers.find((s) => s.id === id);
|
|
81
|
+
if (!cfg)
|
|
82
|
+
continue;
|
|
83
|
+
const resolved = await resolvedServerRuntime(cfg).catch(() => null);
|
|
84
|
+
if (!resolved) {
|
|
85
|
+
console.warn(`[claude-code] skipping MCP server "${id}" (disabled or no usable credentials)`);
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
servers[id] = resolved;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
for (const [name, def] of Object.entries(extra ?? {}))
|
|
92
|
+
servers[name] = def;
|
|
93
|
+
if (Object.keys(servers).length === 0)
|
|
94
|
+
return null;
|
|
95
|
+
const dir = await mkdtemp(path.join(os.tmpdir(), 'caretaker-mcp-'));
|
|
96
|
+
const configPath = path.join(dir, 'mcp-config.json');
|
|
97
|
+
await writeFile(configPath, JSON.stringify({ mcpServers: servers }), { mode: 0o600 });
|
|
98
|
+
return { configPath, cleanup: () => rm(dir, { recursive: true, force: true }) };
|
|
99
|
+
}
|
|
100
|
+
function foldHistory(history, prompt) {
|
|
101
|
+
if (!history?.length)
|
|
102
|
+
return prompt;
|
|
103
|
+
const lines = history.filter((m) => m.role !== 'tool').map((m) => `[${m.role}] ${m.content}`);
|
|
104
|
+
return `<conversation-history>\n${lines.join('\n')}\n</conversation-history>\n\n${prompt}`;
|
|
105
|
+
}
|
|
106
|
+
const zeroUsage = () => ({ input: 0, output: 0 });
|
|
107
|
+
function addUsage(into, u) {
|
|
108
|
+
into.input += u.input;
|
|
109
|
+
into.output += u.output;
|
|
110
|
+
if (u.cacheRead !== undefined)
|
|
111
|
+
into.cacheRead = (into.cacheRead ?? 0) + u.cacheRead;
|
|
112
|
+
if (u.cacheWrite !== undefined)
|
|
113
|
+
into.cacheWrite = (into.cacheWrite ?? 0) + u.cacheWrite;
|
|
114
|
+
}
|
|
115
|
+
/** One spawn-and-read cycle of the Claude Code CLI. Does not throw on a
|
|
116
|
+
* non-zero exit — the caller (runClaudeCode) decides whether to retry. */
|
|
117
|
+
async function attemptRun(command, args, prompt, workingDir, signal, cb) {
|
|
118
|
+
const safeEmit = async (fn) => {
|
|
119
|
+
try {
|
|
120
|
+
await fn?.();
|
|
121
|
+
}
|
|
122
|
+
catch (err) {
|
|
123
|
+
console.warn('[claude-code] callback error:', err);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
const cumulative = zeroUsage();
|
|
127
|
+
let text = '';
|
|
128
|
+
let toolCalls = 0;
|
|
129
|
+
let claudeSessionId;
|
|
130
|
+
let resultEvent;
|
|
131
|
+
let aborted = false;
|
|
132
|
+
let stderrTail = '';
|
|
133
|
+
// Assistant events arrive one block per event, sharing the message id;
|
|
134
|
+
// merge them and flush one MessageRecord per anthropic message.
|
|
135
|
+
let pending = null;
|
|
136
|
+
const flushPending = async () => {
|
|
137
|
+
if (!pending)
|
|
138
|
+
return;
|
|
139
|
+
const p = pending;
|
|
140
|
+
pending = null;
|
|
141
|
+
for (const part of p.parts)
|
|
142
|
+
if (part.type === 'text')
|
|
143
|
+
text += part.text;
|
|
144
|
+
if (p.usage) {
|
|
145
|
+
addUsage(cumulative, p.usage);
|
|
146
|
+
await safeEmit(() => cb.onUsage?.(p.usage));
|
|
147
|
+
}
|
|
148
|
+
await safeEmit(() => cb.onMessage?.(assistantMessage(p.parts, p.usage)));
|
|
149
|
+
};
|
|
150
|
+
const child = spawnImpl(command, args, {
|
|
151
|
+
cwd: workingDir,
|
|
152
|
+
env: process.env,
|
|
153
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
154
|
+
});
|
|
155
|
+
const onAbort = () => {
|
|
156
|
+
aborted = true;
|
|
157
|
+
child.kill('SIGTERM');
|
|
158
|
+
};
|
|
159
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
160
|
+
child.stderr?.on('data', (d) => {
|
|
161
|
+
stderrTail = (stderrTail + String(d)).slice(-4096);
|
|
162
|
+
});
|
|
163
|
+
const spawnError = new Promise((_, reject) => child.on('error', (err) => {
|
|
164
|
+
let message = `claude-code runner failed to start "${command}": ${err.message}`;
|
|
165
|
+
if (process.platform === 'win32') {
|
|
166
|
+
message +=
|
|
167
|
+
' On Windows, point the provider "command" at the Claude Code executable (e.g. claude.exe) — npm .cmd shims cannot be spawned directly.';
|
|
168
|
+
}
|
|
169
|
+
reject(new Error(message));
|
|
170
|
+
}));
|
|
171
|
+
const closed = new Promise((resolve) => child.on('close', (code) => resolve(code)));
|
|
172
|
+
child.stdin?.write(prompt);
|
|
173
|
+
child.stdin?.end();
|
|
174
|
+
const rl = createInterface({ input: child.stdout });
|
|
175
|
+
const reading = (async () => {
|
|
176
|
+
for await (const line of rl) {
|
|
177
|
+
for (const evt of parseClaudeStreamLine(line)) {
|
|
178
|
+
switch (evt.kind) {
|
|
179
|
+
case 'init':
|
|
180
|
+
claudeSessionId = evt.sessionId;
|
|
181
|
+
break;
|
|
182
|
+
case 'text':
|
|
183
|
+
await safeEmit(() => cb.onChunk?.(evt.text));
|
|
184
|
+
break;
|
|
185
|
+
case 'thinking':
|
|
186
|
+
await safeEmit(() => cb.onThinking?.(evt.text));
|
|
187
|
+
break;
|
|
188
|
+
case 'assistant_message': {
|
|
189
|
+
if (pending && pending.id !== evt.id)
|
|
190
|
+
await flushPending();
|
|
191
|
+
if (!pending)
|
|
192
|
+
pending = { id: evt.id, parts: [], usage: undefined };
|
|
193
|
+
pending.parts.push(...evt.parts);
|
|
194
|
+
if (evt.usage)
|
|
195
|
+
pending.usage = evt.usage; // latest event wins per message
|
|
196
|
+
for (const part of evt.parts) {
|
|
197
|
+
if (part.type === 'tool_use') {
|
|
198
|
+
toolCalls += 1;
|
|
199
|
+
await safeEmit(() => cb.onToolCall?.(part.id, part.name, part.args));
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
break;
|
|
203
|
+
}
|
|
204
|
+
case 'tool_result':
|
|
205
|
+
await flushPending();
|
|
206
|
+
await safeEmit(() => cb.onToolResult?.(evt.toolUseId, evt.content));
|
|
207
|
+
await safeEmit(() => cb.onMessage?.(toolMessage(evt.toolUseId, evt.content)));
|
|
208
|
+
break;
|
|
209
|
+
case 'result':
|
|
210
|
+
await flushPending();
|
|
211
|
+
resultEvent = evt;
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
})();
|
|
217
|
+
const exitCode = await Promise.race([
|
|
218
|
+
Promise.all([reading, closed]).then(([, c]) => c),
|
|
219
|
+
spawnError,
|
|
220
|
+
]);
|
|
221
|
+
await flushPending();
|
|
222
|
+
signal?.removeEventListener('abort', onAbort);
|
|
223
|
+
return {
|
|
224
|
+
exitCode,
|
|
225
|
+
aborted,
|
|
226
|
+
text,
|
|
227
|
+
toolCalls,
|
|
228
|
+
cumulative,
|
|
229
|
+
claudeSessionId,
|
|
230
|
+
resultEvent,
|
|
231
|
+
stderrTail,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
export async function runClaudeCode(opts, cb = {}) {
|
|
235
|
+
const { agent, provider } = opts;
|
|
236
|
+
const workingDir = opts.workingDir ?? process.cwd();
|
|
237
|
+
// 1. Resume id from session meta (chat surfaces pass sessionId).
|
|
238
|
+
let resumeId;
|
|
239
|
+
if (opts.sessionId) {
|
|
240
|
+
try {
|
|
241
|
+
resumeId = (await readSession(agent.id, opts.sessionId)).meta.claudeSessionId;
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
/* new session */
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
// 2. --append-system-prompt: agent identity + non-CLAUDE.md context files
|
|
248
|
+
// (Claude Code auto-loads CLAUDE.md itself; AGENTS.md/GEMINI.md and
|
|
249
|
+
// ~/.caretaker/AGENTS.md it does not — verified on CLI 2.1.207).
|
|
250
|
+
const sys = await resolveFileReferences(agent.systemPrompt ?? '', workingDir);
|
|
251
|
+
const ctxEntries = (await loadContextFiles(workingDir)).filter((e) => path.basename(e.path) !== 'CLAUDE.md');
|
|
252
|
+
const appendSystemPrompt = [sys, ctxEntries.length ? formatContextBlock(ctxEntries) : '']
|
|
253
|
+
.filter(Boolean)
|
|
254
|
+
.join('\n\n');
|
|
255
|
+
// 3. Per-run mcp-config temp file (agent's servers + injected bridge).
|
|
256
|
+
const mcp = await buildMcpConfigFile(agent.mcpServers ?? [], opts.claudeCode?.extraMcpServers);
|
|
257
|
+
const permissionMode = opts.claudeCode?.permissionMode ??
|
|
258
|
+
agent.permissionMode ??
|
|
259
|
+
detectClaudeDefaultPermissionMode() ??
|
|
260
|
+
'acceptEdits';
|
|
261
|
+
const command = provider.command || 'claude';
|
|
262
|
+
const runAttempt = (resume) => {
|
|
263
|
+
const args = buildClaudeArgs({
|
|
264
|
+
model: agent.model,
|
|
265
|
+
permissionMode,
|
|
266
|
+
appendSystemPrompt: appendSystemPrompt || undefined,
|
|
267
|
+
allowedTools: opts.claudeCode?.allowedTools,
|
|
268
|
+
disallowedTools: opts.claudeCode?.disallowedTools,
|
|
269
|
+
mcpConfigPath: mcp?.configPath,
|
|
270
|
+
resumeId: resume,
|
|
271
|
+
persistSession: Boolean(opts.sessionId),
|
|
272
|
+
});
|
|
273
|
+
// History only folds into the prompt when there is no CC session to resume.
|
|
274
|
+
const prompt = resume ? opts.prompt : foldHistory(opts.history, opts.prompt);
|
|
275
|
+
return attemptRun(command, args, prompt, workingDir, opts.signal, cb);
|
|
276
|
+
};
|
|
277
|
+
try {
|
|
278
|
+
let attempt = await runAttempt(resumeId);
|
|
279
|
+
// A dead/GC'd --resume session id would otherwise wedge every future turn
|
|
280
|
+
// (the CLI exits non-zero forever). Retry exactly once, folding history
|
|
281
|
+
// into the prompt like a brand-new session; the post-run logic below then
|
|
282
|
+
// persists whatever session id this attempt issues, overwriting the stale
|
|
283
|
+
// one. If the retry also fails, we fall through to the normal error path.
|
|
284
|
+
if (!attempt.aborted && attempt.exitCode !== 0 && resumeId) {
|
|
285
|
+
console.warn(`[claude-code] resume with session "${resumeId}" failed (exit ${attempt.exitCode}); retrying once without --resume`);
|
|
286
|
+
attempt = await runAttempt(undefined);
|
|
287
|
+
}
|
|
288
|
+
const { exitCode, aborted, text, toolCalls, cumulative, claudeSessionId, resultEvent, stderrTail, } = attempt;
|
|
289
|
+
if (aborted)
|
|
290
|
+
return { text, toolCalls, usage: cumulative, stop: 'aborted' };
|
|
291
|
+
if (exitCode !== 0) {
|
|
292
|
+
throw new Error(`claude-code runner: "${command}" exited with code ${exitCode}` +
|
|
293
|
+
(stderrTail
|
|
294
|
+
? `: ${stderrTail.trim()}`
|
|
295
|
+
: ' (is Claude Code installed and authenticated?)'));
|
|
296
|
+
}
|
|
297
|
+
if (resultEvent?.usage) {
|
|
298
|
+
// The result event's usage is authoritative for the whole run.
|
|
299
|
+
cumulative.input = resultEvent.usage.input;
|
|
300
|
+
cumulative.output = resultEvent.usage.output;
|
|
301
|
+
if (resultEvent.usage.cacheRead !== undefined)
|
|
302
|
+
cumulative.cacheRead = resultEvent.usage.cacheRead;
|
|
303
|
+
if (resultEvent.usage.cacheWrite !== undefined)
|
|
304
|
+
cumulative.cacheWrite = resultEvent.usage.cacheWrite;
|
|
305
|
+
}
|
|
306
|
+
if (opts.sessionId && claudeSessionId && claudeSessionId !== resumeId) {
|
|
307
|
+
try {
|
|
308
|
+
await updateClaudeSessionId({ agentId: agent.id, id: opts.sessionId }, claudeSessionId);
|
|
309
|
+
}
|
|
310
|
+
catch (err) {
|
|
311
|
+
console.warn('[claude-code] failed to persist session id:', err);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
if (resultEvent?.isError) {
|
|
315
|
+
if (resultEvent.subtype === 'error_max_turns') {
|
|
316
|
+
return { text, toolCalls, usage: cumulative, stop: 'max_turns' };
|
|
317
|
+
}
|
|
318
|
+
throw new Error(`claude-code runner: ${resultEvent.subtype || 'error'}${resultEvent.text ? `: ${resultEvent.text}` : ''}`);
|
|
319
|
+
}
|
|
320
|
+
return { text, toolCalls, usage: cumulative, stop: 'done' };
|
|
321
|
+
}
|
|
322
|
+
finally {
|
|
323
|
+
await mcp?.cleanup().catch(() => { });
|
|
324
|
+
}
|
|
325
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { AssistantUsage } from './provider.js';
|
|
2
|
+
import type { AssistantPart } from '../session/types.js';
|
|
3
|
+
export type ClaudeStreamEvent = {
|
|
4
|
+
kind: 'init';
|
|
5
|
+
sessionId: string;
|
|
6
|
+
} | {
|
|
7
|
+
kind: 'text';
|
|
8
|
+
text: string;
|
|
9
|
+
} | {
|
|
10
|
+
kind: 'thinking';
|
|
11
|
+
text: string;
|
|
12
|
+
} | {
|
|
13
|
+
kind: 'assistant_message';
|
|
14
|
+
/** Anthropic message id — events for the same message id must be merged. */
|
|
15
|
+
id: string;
|
|
16
|
+
/** Blocks contained in THIS event (Claude Code emits one event per completed block). */
|
|
17
|
+
parts: AssistantPart[];
|
|
18
|
+
usage?: AssistantUsage;
|
|
19
|
+
} | {
|
|
20
|
+
kind: 'tool_result';
|
|
21
|
+
toolUseId: string;
|
|
22
|
+
content: string;
|
|
23
|
+
} | {
|
|
24
|
+
kind: 'result';
|
|
25
|
+
subtype: string;
|
|
26
|
+
text: string;
|
|
27
|
+
usage?: AssistantUsage;
|
|
28
|
+
costUsd?: number;
|
|
29
|
+
isError: boolean;
|
|
30
|
+
};
|
|
31
|
+
export declare function parseClaudeStreamLine(rawLine: string): ClaudeStreamEvent[];
|
|
32
|
+
//# sourceMappingURL=claude_code_stream.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"claude_code_stream.d.ts","sourceRoot":"","sources":["../../src/harness/claude_code_stream.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEzD,MAAM,MAAM,iBAAiB,GACzB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,MAAM,CAAA;CAAE,GACnC;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAClC;IACE,IAAI,EAAE,mBAAmB,CAAC;IAC1B,4EAA4E;IAC5E,EAAE,EAAE,MAAM,CAAC;IACX,wFAAwF;IACxF,KAAK,EAAE,aAAa,EAAE,CAAC;IACvB,KAAK,CAAC,EAAE,cAAc,CAAC;CACxB,GACD;IAAE,IAAI,EAAE,aAAa,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAC3D;IACE,IAAI,EAAE,QAAQ,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,cAAc,CAAC;IACvB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,OAAO,CAAC;CAClB,CAAC;AAwBN,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,GAAG,iBAAiB,EAAE,CAwF1E"}
|