@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,970 @@
|
|
|
1
|
+
import { fileURLToPath } from 'node:url';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import { watch, existsSync, mkdirSync } from 'node:fs';
|
|
5
|
+
import { randomUUID } from 'node:crypto';
|
|
6
|
+
import { Hono } from 'hono';
|
|
7
|
+
import { serve } from '@hono/node-server';
|
|
8
|
+
import { WebSocketServer, WebSocket } from 'ws';
|
|
9
|
+
import * as harness from '../../harness/index.js';
|
|
10
|
+
import { getDb, getTaskById, saveTask, createTask, addTaskMessage, deleteTask, runQuery } from '../../store/db.js';
|
|
11
|
+
import { discardWorktree } from '../../lib/task_git.js';
|
|
12
|
+
import { runningTasks } from './scheduler/locks.js';
|
|
13
|
+
import { registerTaskBridge, setTaskBridgeUrl } from './mcp_bridge.js';
|
|
14
|
+
import { loadAgents, loadConfig, dataDir, saveAgents, saveConfig, loadPlugins, loadMcpServers, } from '../../store/json.js';
|
|
15
|
+
import { createSource, deleteSource, patchSource, refreshSource, } from '../../plugins/source_manager.js';
|
|
16
|
+
import { createMcpServer, deleteMcpServer, patchMcpServer, readOAuthBlob } from '../../mcp/server_manager.js';
|
|
17
|
+
import { authenticateMcpServer, revokeMcpAuth } from '../../mcp/oauth.js';
|
|
18
|
+
import { listForAgent, readSession, deleteSession, computeContextUsage, createSession, userMessage, appendMessage, saveAttachment, attachmentsDir, } from '../../session/index.js';
|
|
19
|
+
import { startBackgroundScheduler, loadTaskRuns } from './scheduler.js';
|
|
20
|
+
import { fsRouter } from './fs.js';
|
|
21
|
+
import { activationStatus, resolvePlanningEnabled } from './scheduler/task_roles.js';
|
|
22
|
+
// Resolve Webview static files path.
|
|
23
|
+
// Published npm package ships the assets under dist/webview (see scripts/copy-webview.mjs);
|
|
24
|
+
// in the monorepo dev tree they live in the sibling webview-ui package.
|
|
25
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
26
|
+
const bundledWebviewDist = path.resolve(__dirname, '../../webview');
|
|
27
|
+
const devWebviewDist = path.resolve(__dirname, '../../../../webview-ui/dist');
|
|
28
|
+
const webviewDistPath = fs.existsSync(bundledWebviewDist) ? bundledWebviewDist : devWebviewDist;
|
|
29
|
+
export class WebSessionController {
|
|
30
|
+
opts;
|
|
31
|
+
metaRecord = null;
|
|
32
|
+
history = [];
|
|
33
|
+
inflight = null;
|
|
34
|
+
confirmSet;
|
|
35
|
+
sessionId;
|
|
36
|
+
constructor(opts) {
|
|
37
|
+
this.opts = opts;
|
|
38
|
+
this.confirmSet = new Set(opts.agent.confirmTools ?? []);
|
|
39
|
+
this.sessionId = opts.sessionId;
|
|
40
|
+
}
|
|
41
|
+
get isRunning() {
|
|
42
|
+
return this.inflight !== null;
|
|
43
|
+
}
|
|
44
|
+
getContextUsage() {
|
|
45
|
+
return computeContextUsage(this.history, this.opts.agent.model);
|
|
46
|
+
}
|
|
47
|
+
async start(prompt, cb, rawAttachments) {
|
|
48
|
+
if (this.inflight) {
|
|
49
|
+
cb.onError('A turn is already in progress.');
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
const ac = new AbortController();
|
|
53
|
+
this.inflight = ac;
|
|
54
|
+
try {
|
|
55
|
+
if (!this.metaRecord) {
|
|
56
|
+
if (this.sessionId) {
|
|
57
|
+
const sessionData = await readSession(this.opts.agent.id, this.sessionId);
|
|
58
|
+
this.metaRecord = sessionData.meta;
|
|
59
|
+
this.history = sessionData.messages;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
const title = prompt.length > 50 ? `${prompt.slice(0, 50)}…` : prompt;
|
|
63
|
+
const metaRec = await createSession({ agentId: this.opts.agent.id, title });
|
|
64
|
+
this.metaRecord = metaRec;
|
|
65
|
+
cb.onSessionCreated?.(metaRec.id);
|
|
66
|
+
this.history = [];
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
const meta = this.metaRecord;
|
|
70
|
+
const attachmentRecords = [];
|
|
71
|
+
if (rawAttachments && rawAttachments.length > 0) {
|
|
72
|
+
for (const att of rawAttachments) {
|
|
73
|
+
const buf = Buffer.from(att.base64, 'base64');
|
|
74
|
+
const ext = path.extname(att.name) || '';
|
|
75
|
+
const id = await saveAttachment(meta.id, buf, ext);
|
|
76
|
+
attachmentRecords.push({ mime: att.mime, id, name: att.name });
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const userMsg = userMessage(prompt, {
|
|
80
|
+
attachments: attachmentRecords.length > 0 ? attachmentRecords : undefined,
|
|
81
|
+
});
|
|
82
|
+
await appendMessage(meta, userMsg);
|
|
83
|
+
const priorHistory = [...this.history];
|
|
84
|
+
this.history.push(userMsg);
|
|
85
|
+
await harness.run({
|
|
86
|
+
agent: this.opts.agent,
|
|
87
|
+
provider: this.opts.provider,
|
|
88
|
+
tools: this.opts.tools,
|
|
89
|
+
prompt,
|
|
90
|
+
history: priorHistory,
|
|
91
|
+
signal: ac.signal,
|
|
92
|
+
workingDir: this.opts.workingDir,
|
|
93
|
+
sessionId: meta.id,
|
|
94
|
+
promptAttachments: attachmentRecords.length > 0 ? attachmentRecords : undefined,
|
|
95
|
+
}, {
|
|
96
|
+
onChunk: cb.onChunk,
|
|
97
|
+
onThinking: cb.onThinking,
|
|
98
|
+
onToolCall: cb.onToolCall,
|
|
99
|
+
onToolResult: cb.onToolResult,
|
|
100
|
+
confirmTool: async (id, name, args) => {
|
|
101
|
+
if (!this.confirmSet.has(name))
|
|
102
|
+
return 'once';
|
|
103
|
+
const decision = await cb.askConfirm(id, name, args);
|
|
104
|
+
if (decision === 'always')
|
|
105
|
+
this.confirmSet.delete(name);
|
|
106
|
+
return decision;
|
|
107
|
+
},
|
|
108
|
+
onMessage: async (msg) => {
|
|
109
|
+
await appendMessage(meta, msg);
|
|
110
|
+
this.history.push(msg);
|
|
111
|
+
},
|
|
112
|
+
});
|
|
113
|
+
cb.onDone();
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
cb.onError(err instanceof Error ? err.message : String(err));
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
this.inflight = null;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
abort() {
|
|
123
|
+
this.inflight?.abort();
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export async function startServer(port, host) {
|
|
127
|
+
const app = new Hono();
|
|
128
|
+
app.route('/api/fs', fsRouter);
|
|
129
|
+
registerTaskBridge(app);
|
|
130
|
+
// Pure-Node static serving with absolute path validation and fallback
|
|
131
|
+
app.get('/', (c) => {
|
|
132
|
+
try {
|
|
133
|
+
const html = fs.readFileSync(path.join(webviewDistPath, 'index.html'), 'utf-8');
|
|
134
|
+
return c.html(html);
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
return c.text('Caretaker Web standalone build not found. Did you run "pnpm -F webview-ui build"?', 500);
|
|
138
|
+
}
|
|
139
|
+
});
|
|
140
|
+
app.get('/standalone.js', (c) => {
|
|
141
|
+
const file = fs.readFileSync(path.join(webviewDistPath, 'standalone.js'));
|
|
142
|
+
c.header('Content-Type', 'application/javascript');
|
|
143
|
+
return c.body(file);
|
|
144
|
+
});
|
|
145
|
+
app.get('/standalone.js.map', (c) => {
|
|
146
|
+
const file = fs.readFileSync(path.join(webviewDistPath, 'standalone.js.map'));
|
|
147
|
+
c.header('Content-Type', 'application/json');
|
|
148
|
+
return c.body(file);
|
|
149
|
+
});
|
|
150
|
+
app.get('/standalone.css', (c) => {
|
|
151
|
+
const file = fs.readFileSync(path.join(webviewDistPath, 'standalone.css'));
|
|
152
|
+
c.header('Content-Type', 'text/css');
|
|
153
|
+
return c.body(file);
|
|
154
|
+
});
|
|
155
|
+
app.get('/standalone.css.map', (c) => {
|
|
156
|
+
const file = fs.readFileSync(path.join(webviewDistPath, 'standalone.css.map'));
|
|
157
|
+
c.header('Content-Type', 'application/json');
|
|
158
|
+
return c.body(file);
|
|
159
|
+
});
|
|
160
|
+
// Attachments REST endpoint
|
|
161
|
+
app.get('/api/attachments/:sessionId/:id', async (c) => {
|
|
162
|
+
const sessionId = c.req.param('sessionId');
|
|
163
|
+
const id = c.req.param('id');
|
|
164
|
+
try {
|
|
165
|
+
const filePath = path.join(attachmentsDir(sessionId), id);
|
|
166
|
+
if (!fs.existsSync(filePath) || fs.statSync(filePath).isDirectory()) {
|
|
167
|
+
return c.text('Attachment not found', 404);
|
|
168
|
+
}
|
|
169
|
+
const fileBuffer = fs.readFileSync(filePath);
|
|
170
|
+
const ext = path.extname(id).toLowerCase();
|
|
171
|
+
let contentType = 'application/octet-stream';
|
|
172
|
+
if (ext === '.png')
|
|
173
|
+
contentType = 'image/png';
|
|
174
|
+
else if (ext === '.jpg' || ext === '.jpeg')
|
|
175
|
+
contentType = 'image/jpeg';
|
|
176
|
+
else if (ext === '.webp')
|
|
177
|
+
contentType = 'image/webp';
|
|
178
|
+
else if (ext === '.gif')
|
|
179
|
+
contentType = 'image/gif';
|
|
180
|
+
else if (ext === '.pdf')
|
|
181
|
+
contentType = 'application/pdf';
|
|
182
|
+
else if (ext === '.txt')
|
|
183
|
+
contentType = 'text/plain; charset=utf-8';
|
|
184
|
+
else if (ext === '.json')
|
|
185
|
+
contentType = 'application/json';
|
|
186
|
+
c.header('Content-Type', contentType);
|
|
187
|
+
return c.body(fileBuffer);
|
|
188
|
+
}
|
|
189
|
+
catch (err) {
|
|
190
|
+
return c.text(`Failed to serve attachment: ${err}`, 500);
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
const db = getDb();
|
|
194
|
+
// Projects REST endpoints
|
|
195
|
+
app.get('/api/projects', async (c) => {
|
|
196
|
+
try {
|
|
197
|
+
const config = await loadConfig();
|
|
198
|
+
return c.json(config.projects || []);
|
|
199
|
+
}
|
|
200
|
+
catch (err) {
|
|
201
|
+
return c.json([], 200);
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
app.post('/api/projects', async (c) => {
|
|
205
|
+
try {
|
|
206
|
+
const body = await c.req.json();
|
|
207
|
+
const { name, description, workingDir, agentId, plannerAgentId, reviewerAgentId, planningEnabled, reviewEnabled, sddEnabled } = body;
|
|
208
|
+
const config = await loadConfig();
|
|
209
|
+
if (!config.projects) {
|
|
210
|
+
config.projects = [];
|
|
211
|
+
}
|
|
212
|
+
const nextId = config.projects.length > 0 ? Math.max(...config.projects.map((p) => p.id)) + 1 : 1;
|
|
213
|
+
const project = {
|
|
214
|
+
id: nextId,
|
|
215
|
+
name,
|
|
216
|
+
description: description || '',
|
|
217
|
+
workingDir,
|
|
218
|
+
agentId,
|
|
219
|
+
active: true,
|
|
220
|
+
plannerAgentId: plannerAgentId || null,
|
|
221
|
+
reviewerAgentId: reviewerAgentId || null,
|
|
222
|
+
planningEnabled: typeof planningEnabled === 'boolean' ? planningEnabled : null,
|
|
223
|
+
reviewEnabled: typeof reviewEnabled === 'boolean' ? reviewEnabled : null,
|
|
224
|
+
sddEnabled: typeof sddEnabled === 'boolean' ? sddEnabled : null,
|
|
225
|
+
};
|
|
226
|
+
config.projects.push(project);
|
|
227
|
+
await saveConfig(config);
|
|
228
|
+
return c.json({ ok: true });
|
|
229
|
+
}
|
|
230
|
+
catch (err) {
|
|
231
|
+
return c.json({ error: String(err) }, 500);
|
|
232
|
+
}
|
|
233
|
+
});
|
|
234
|
+
app.delete('/api/projects/:id', async (c) => {
|
|
235
|
+
try {
|
|
236
|
+
const id = Number(c.req.param('id'));
|
|
237
|
+
const config = await loadConfig();
|
|
238
|
+
if (config.projects) {
|
|
239
|
+
config.projects = config.projects.filter((p) => p.id !== id);
|
|
240
|
+
await saveConfig(config);
|
|
241
|
+
}
|
|
242
|
+
// Delete task messages first, then tasks — avoids orphaned message rows.
|
|
243
|
+
await runQuery(`DELETE FROM task_messages WHERE taskId IN (SELECT id FROM tasks WHERE projectId = ${id})`);
|
|
244
|
+
await runQuery(`DELETE FROM tasks WHERE projectId = ${id}`);
|
|
245
|
+
return c.json({ ok: true });
|
|
246
|
+
}
|
|
247
|
+
catch (err) {
|
|
248
|
+
return c.json({ error: String(err) }, 500);
|
|
249
|
+
}
|
|
250
|
+
});
|
|
251
|
+
// Tasks REST endpoints
|
|
252
|
+
app.get('/api/projects/:id/tasks', async (c) => {
|
|
253
|
+
const id = Number(c.req.param('id'));
|
|
254
|
+
const includeArchived = c.req.query('archived') === 'true';
|
|
255
|
+
try {
|
|
256
|
+
const rows = (await runQuery(`SELECT * FROM tasks WHERE projectId = ${id}`));
|
|
257
|
+
const filtered = includeArchived ? rows : rows.filter((t) => !t.archived);
|
|
258
|
+
return c.json(filtered);
|
|
259
|
+
}
|
|
260
|
+
catch (err) {
|
|
261
|
+
return c.json([], 200);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
app.post('/api/projects/:id/tasks', async (c) => {
|
|
265
|
+
const projectId = Number(c.req.param('id'));
|
|
266
|
+
const body = await c.req.json();
|
|
267
|
+
const { title, objective, checklist, startActive, agentId, plannerAgentId, reviewerAgentId, planningEnabled, reviewEnabled, sddEnabled } = body;
|
|
268
|
+
// Validate that the specified agents exist (if provided).
|
|
269
|
+
const idsToValidate = [agentId, plannerAgentId, reviewerAgentId].filter(Boolean);
|
|
270
|
+
if (idsToValidate.length > 0) {
|
|
271
|
+
const agents = await loadAgents();
|
|
272
|
+
for (const id of idsToValidate) {
|
|
273
|
+
if (!agents.some((a) => a.id === id)) {
|
|
274
|
+
return c.json({ ok: false, error: `Agent "${id}" not found.` }, 400);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const checklistItems = (checklist || []).map((item, idx) => ({
|
|
279
|
+
id: randomUUID(),
|
|
280
|
+
text: item.text,
|
|
281
|
+
status: 'pending',
|
|
282
|
+
order: idx,
|
|
283
|
+
}));
|
|
284
|
+
const config = await loadConfig();
|
|
285
|
+
const project = (config.projects || []).find((p) => p.id === projectId);
|
|
286
|
+
const taskPlanning = typeof planningEnabled === 'boolean' ? planningEnabled : null;
|
|
287
|
+
const startStatus = startActive
|
|
288
|
+
? (resolvePlanningEnabled({ planningEnabled: taskPlanning }, project) ? 'planning' : 'active')
|
|
289
|
+
: 'draft';
|
|
290
|
+
await createTask({
|
|
291
|
+
projectId,
|
|
292
|
+
title,
|
|
293
|
+
objective,
|
|
294
|
+
checklist: checklistItems,
|
|
295
|
+
status: startStatus,
|
|
296
|
+
blockedReason: null,
|
|
297
|
+
noProgressCount: 0,
|
|
298
|
+
maxNoProgress: 5,
|
|
299
|
+
lockedAt: null,
|
|
300
|
+
agentId: agentId || null,
|
|
301
|
+
plannerAgentId: plannerAgentId || null,
|
|
302
|
+
reviewerAgentId: reviewerAgentId || null,
|
|
303
|
+
planningEnabled: taskPlanning,
|
|
304
|
+
reviewEnabled: typeof reviewEnabled === 'boolean' ? reviewEnabled : null,
|
|
305
|
+
sddEnabled: typeof sddEnabled === 'boolean' ? sddEnabled : null,
|
|
306
|
+
});
|
|
307
|
+
return c.json({ ok: true });
|
|
308
|
+
});
|
|
309
|
+
app.get('/api/tasks/:id/messages', async (c) => {
|
|
310
|
+
const taskId = Number(c.req.param('id'));
|
|
311
|
+
try {
|
|
312
|
+
const rows = (await runQuery(`SELECT * FROM task_messages WHERE taskId = ${taskId}`));
|
|
313
|
+
rows.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
|
|
314
|
+
return c.json(rows);
|
|
315
|
+
}
|
|
316
|
+
catch (err) {
|
|
317
|
+
return c.json([], 200);
|
|
318
|
+
}
|
|
319
|
+
});
|
|
320
|
+
app.post('/api/tasks/:id/messages', async (c) => {
|
|
321
|
+
const taskId = Number(c.req.param('id'));
|
|
322
|
+
const body = await c.req.json();
|
|
323
|
+
const { content } = body;
|
|
324
|
+
await addTaskMessage({
|
|
325
|
+
taskId,
|
|
326
|
+
role: 'user',
|
|
327
|
+
messageType: 'chat',
|
|
328
|
+
content,
|
|
329
|
+
});
|
|
330
|
+
// Wake up/unpause/unblock the task so it runs on next scheduler tick
|
|
331
|
+
const task = await getTaskById(taskId);
|
|
332
|
+
if (task) {
|
|
333
|
+
const config = await loadConfig();
|
|
334
|
+
const project = (config.projects || []).find((p) => p.id === task.projectId);
|
|
335
|
+
task.status = await activationStatus(task, project);
|
|
336
|
+
task.blockedReason = null;
|
|
337
|
+
task.noProgressCount = 0;
|
|
338
|
+
task.updatedAt = new Date().toISOString();
|
|
339
|
+
await saveTask(task);
|
|
340
|
+
}
|
|
341
|
+
return c.json({ ok: true });
|
|
342
|
+
});
|
|
343
|
+
app.post('/api/tasks/:id/status', async (c) => {
|
|
344
|
+
const taskId = Number(c.req.param('id'));
|
|
345
|
+
const body = await c.req.json();
|
|
346
|
+
const { status } = body;
|
|
347
|
+
const task = await getTaskById(taskId);
|
|
348
|
+
if (task) {
|
|
349
|
+
if (status === 'active') {
|
|
350
|
+
const config = await loadConfig();
|
|
351
|
+
const project = (config.projects || []).find((p) => p.id === task.projectId);
|
|
352
|
+
task.status = await activationStatus(task, project);
|
|
353
|
+
task.noProgressCount = 0;
|
|
354
|
+
task.blockedReason = null;
|
|
355
|
+
}
|
|
356
|
+
else {
|
|
357
|
+
task.status = status;
|
|
358
|
+
}
|
|
359
|
+
task.updatedAt = new Date().toISOString();
|
|
360
|
+
await saveTask(task);
|
|
361
|
+
}
|
|
362
|
+
return c.json({ ok: true });
|
|
363
|
+
});
|
|
364
|
+
app.post('/api/tasks/:id/discard-worktree', async (c) => {
|
|
365
|
+
const taskId = Number(c.req.param('id'));
|
|
366
|
+
const task = await getTaskById(taskId);
|
|
367
|
+
if (!task)
|
|
368
|
+
return c.json({ ok: false, error: 'not found' }, 404);
|
|
369
|
+
if (!task.worktreePath)
|
|
370
|
+
return c.json({ ok: false, error: 'no worktree' }, 400);
|
|
371
|
+
await discardWorktree(task.worktreePath, task.title);
|
|
372
|
+
task.worktreePath = null;
|
|
373
|
+
task.updatedAt = new Date().toISOString();
|
|
374
|
+
await saveTask(task);
|
|
375
|
+
return c.json({ ok: true, branch: task.branch });
|
|
376
|
+
});
|
|
377
|
+
app.post('/api/tasks/:id/archive', async (c) => {
|
|
378
|
+
const taskId = Number(c.req.param('id'));
|
|
379
|
+
const task = await getTaskById(taskId);
|
|
380
|
+
if (!task)
|
|
381
|
+
return c.json({ ok: false, error: 'not found' }, 404);
|
|
382
|
+
task.archived = true;
|
|
383
|
+
if (task.status === 'active' || task.status === 'reviewing') {
|
|
384
|
+
task.status = 'paused';
|
|
385
|
+
}
|
|
386
|
+
task.updatedAt = new Date().toISOString();
|
|
387
|
+
await saveTask(task);
|
|
388
|
+
await addTaskMessage({
|
|
389
|
+
taskId,
|
|
390
|
+
role: 'assistant',
|
|
391
|
+
messageType: 'system',
|
|
392
|
+
content: 'Task archived.',
|
|
393
|
+
});
|
|
394
|
+
return c.json({ ok: true });
|
|
395
|
+
});
|
|
396
|
+
app.post('/api/tasks/:id/unarchive', async (c) => {
|
|
397
|
+
const taskId = Number(c.req.param('id'));
|
|
398
|
+
const task = await getTaskById(taskId);
|
|
399
|
+
if (!task)
|
|
400
|
+
return c.json({ ok: false, error: 'not found' }, 404);
|
|
401
|
+
task.archived = false;
|
|
402
|
+
task.updatedAt = new Date().toISOString();
|
|
403
|
+
await saveTask(task);
|
|
404
|
+
await addTaskMessage({
|
|
405
|
+
taskId,
|
|
406
|
+
role: 'assistant',
|
|
407
|
+
messageType: 'system',
|
|
408
|
+
content: 'Task unarchived.',
|
|
409
|
+
});
|
|
410
|
+
return c.json({ ok: true });
|
|
411
|
+
});
|
|
412
|
+
app.delete('/api/tasks/:id', async (c) => {
|
|
413
|
+
const taskId = Number(c.req.param('id'));
|
|
414
|
+
const task = await getTaskById(taskId);
|
|
415
|
+
if (!task)
|
|
416
|
+
return c.json({ ok: false, error: 'not found' }, 404);
|
|
417
|
+
// Guard against deleting a task that is currently being processed by the
|
|
418
|
+
// scheduler heartbeat. Deleting mid-run would cause the heartbeat's
|
|
419
|
+
// finally block to resurrect the task as a zombie via saveTask.
|
|
420
|
+
const lockKey = `task_db_${taskId}`;
|
|
421
|
+
if (task.lockedAt || runningTasks.has(lockKey)) {
|
|
422
|
+
return c.json({ ok: false, error: 'Task is currently running. Wait for it to finish or pause it first.' }, 409);
|
|
423
|
+
}
|
|
424
|
+
// Clean up any active worktree before deleting the task record.
|
|
425
|
+
if (task.worktreePath) {
|
|
426
|
+
try {
|
|
427
|
+
await discardWorktree(task.worktreePath, task.title);
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
// Best-effort: proceed with deletion even if worktree cleanup fails.
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
await deleteTask(taskId);
|
|
434
|
+
return c.json({ ok: true });
|
|
435
|
+
});
|
|
436
|
+
app.post('/api/tasks/:id/checklist-item', async (c) => {
|
|
437
|
+
const taskId = Number(c.req.param('id'));
|
|
438
|
+
const body = await c.req.json();
|
|
439
|
+
const { itemId, status } = body;
|
|
440
|
+
const task = await getTaskById(taskId);
|
|
441
|
+
if (task) {
|
|
442
|
+
task.checklist = (task.checklist || []).map((item) => item.id === itemId ? { ...item, status } : item);
|
|
443
|
+
task.updatedAt = new Date().toISOString();
|
|
444
|
+
await saveTask(task);
|
|
445
|
+
}
|
|
446
|
+
return c.json({ ok: true });
|
|
447
|
+
});
|
|
448
|
+
app.patch('/api/tasks/:id/agent', async (c) => {
|
|
449
|
+
const taskId = Number(c.req.param('id'));
|
|
450
|
+
const body = await c.req.json();
|
|
451
|
+
const { agentId, role } = body;
|
|
452
|
+
const task = await getTaskById(taskId);
|
|
453
|
+
if (!task)
|
|
454
|
+
return c.json({ ok: false, error: 'not found' }, 404);
|
|
455
|
+
// Guard against reassigning a task that is currently running.
|
|
456
|
+
const lockKey = `task_db_${taskId}`;
|
|
457
|
+
if (task.lockedAt || runningTasks.has(lockKey)) {
|
|
458
|
+
return c.json({ ok: false, error: 'Task is currently running. Wait for it to finish or pause it first.' }, 409);
|
|
459
|
+
}
|
|
460
|
+
// Validate that the specified agent exists (if provided and non-null).
|
|
461
|
+
if (agentId) {
|
|
462
|
+
const agents = await loadAgents();
|
|
463
|
+
if (!agents.some((a) => a.id === agentId)) {
|
|
464
|
+
return c.json({ ok: false, error: `Agent "${agentId}" not found.` }, 400);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
const targetRole = role === 'planner' || role === 'reviewer' ? role : 'developer';
|
|
468
|
+
if (targetRole === 'planner')
|
|
469
|
+
task.plannerAgentId = agentId || null;
|
|
470
|
+
else if (targetRole === 'reviewer')
|
|
471
|
+
task.reviewerAgentId = agentId || null;
|
|
472
|
+
else
|
|
473
|
+
task.agentId = agentId || null;
|
|
474
|
+
task.updatedAt = new Date().toISOString();
|
|
475
|
+
await saveTask(task);
|
|
476
|
+
return c.json({ ok: true, role: targetRole, agentId: agentId || null });
|
|
477
|
+
});
|
|
478
|
+
app.patch('/api/tasks/:id/flags', async (c) => {
|
|
479
|
+
const taskId = Number(c.req.param('id'));
|
|
480
|
+
const body = await c.req.json();
|
|
481
|
+
const task = await getTaskById(taskId);
|
|
482
|
+
if (!task)
|
|
483
|
+
return c.json({ ok: false, error: 'not found' }, 404);
|
|
484
|
+
if ('planningEnabled' in body) {
|
|
485
|
+
task.planningEnabled = typeof body.planningEnabled === 'boolean' ? body.planningEnabled : null;
|
|
486
|
+
}
|
|
487
|
+
if ('reviewEnabled' in body) {
|
|
488
|
+
task.reviewEnabled = typeof body.reviewEnabled === 'boolean' ? body.reviewEnabled : null;
|
|
489
|
+
}
|
|
490
|
+
if ('sddEnabled' in body) {
|
|
491
|
+
task.sddEnabled = typeof body.sddEnabled === 'boolean' ? body.sddEnabled : null;
|
|
492
|
+
}
|
|
493
|
+
task.updatedAt = new Date().toISOString();
|
|
494
|
+
await saveTask(task);
|
|
495
|
+
return c.json({
|
|
496
|
+
ok: true,
|
|
497
|
+
planningEnabled: task.planningEnabled ?? null,
|
|
498
|
+
reviewEnabled: task.reviewEnabled ?? null,
|
|
499
|
+
sddEnabled: task.sddEnabled ?? null,
|
|
500
|
+
});
|
|
501
|
+
});
|
|
502
|
+
const nodeServer = serve({
|
|
503
|
+
fetch: app.fetch,
|
|
504
|
+
port,
|
|
505
|
+
hostname: host,
|
|
506
|
+
});
|
|
507
|
+
const bridgeHost = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host;
|
|
508
|
+
setTaskBridgeUrl(`http://${bridgeHost}:${port}/api/mcp/task`);
|
|
509
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
510
|
+
nodeServer.on('upgrade', (request, socket, head) => {
|
|
511
|
+
const { pathname } = new URL(request.url || '', `http://${host}:${port}`);
|
|
512
|
+
if (pathname === '/api/ws') {
|
|
513
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
514
|
+
wss.emit('connection', ws, request);
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
else {
|
|
518
|
+
socket.destroy();
|
|
519
|
+
}
|
|
520
|
+
});
|
|
521
|
+
console.log(`\n🚀 Caretaker Server running at http://${host}:${port}\n`);
|
|
522
|
+
// Start the background scheduler trigger daemon
|
|
523
|
+
startBackgroundScheduler();
|
|
524
|
+
wss.on('connection', async (ws) => {
|
|
525
|
+
let controller = null;
|
|
526
|
+
let currentAgent = null;
|
|
527
|
+
let currentProvider = null;
|
|
528
|
+
let currentTools = null;
|
|
529
|
+
let currentSessionId = null;
|
|
530
|
+
let agents = [];
|
|
531
|
+
const pendingConfirms = new Map();
|
|
532
|
+
const post = (msg) => {
|
|
533
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
534
|
+
ws.send(JSON.stringify(msg));
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
const resolveAllPending = (decision) => {
|
|
538
|
+
for (const resolve of pendingConfirms.values())
|
|
539
|
+
resolve(decision);
|
|
540
|
+
pendingConfirms.clear();
|
|
541
|
+
};
|
|
542
|
+
const loadAgentsAndSend = async () => {
|
|
543
|
+
try {
|
|
544
|
+
const [agentsRes, configRes] = await Promise.all([loadAgents(), loadConfig()]);
|
|
545
|
+
agents = agentsRes;
|
|
546
|
+
const providers = configRes.providers;
|
|
547
|
+
const agentSummaries = agents.map((a) => ({
|
|
548
|
+
id: a.id,
|
|
549
|
+
name: a.name,
|
|
550
|
+
model: a.model,
|
|
551
|
+
provider: a.provider,
|
|
552
|
+
}));
|
|
553
|
+
post({ type: 'agentsLoaded', agents: agentSummaries });
|
|
554
|
+
// Select the first agent as default if none is active
|
|
555
|
+
if (!currentAgent && agents.length > 0) {
|
|
556
|
+
await selectAgentInternal(agents[0], providers);
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
// If currentAgent is set, check if it was modified on disk and refresh in-place
|
|
560
|
+
if (currentAgent) {
|
|
561
|
+
const freshAgent = agents.find((a) => a.id === currentAgent.id);
|
|
562
|
+
if (freshAgent) {
|
|
563
|
+
// Detect fields that affect runtime and update them in-place
|
|
564
|
+
const needsToolRefresh = freshAgent.allowedTools.join('|') !== currentAgent.allowedTools.join('|') ||
|
|
565
|
+
(freshAgent.plugins ?? []).join('|') !== (currentAgent.plugins ?? []).join('|') ||
|
|
566
|
+
(freshAgent.mcpServers ?? []).join('|') !== (currentAgent.mcpServers ?? []).join('|');
|
|
567
|
+
// Update currentAgent fields that may have changed
|
|
568
|
+
currentAgent = { ...freshAgent };
|
|
569
|
+
if (needsToolRefresh && currentProvider) {
|
|
570
|
+
// Re-resolve tools if allowedTools/plugins/mcpServers changed
|
|
571
|
+
currentTools = await harness.resolveAgentTools(currentAgent, harness.tools);
|
|
572
|
+
post({ type: 'contextUsage', usage: controller?.getContextUsage() ?? null });
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
catch (err) {
|
|
578
|
+
post({
|
|
579
|
+
type: 'error',
|
|
580
|
+
message: `Failed to load Caretaker config: ${err instanceof Error ? err.message : String(err)}`,
|
|
581
|
+
});
|
|
582
|
+
}
|
|
583
|
+
};
|
|
584
|
+
const selectAgentInternal = async (agent, providers) => {
|
|
585
|
+
const provider = providers.find((p) => p.name === agent.provider);
|
|
586
|
+
if (!provider) {
|
|
587
|
+
post({
|
|
588
|
+
type: 'error',
|
|
589
|
+
message: `Provider "${agent.provider}" for agent "${agent.name}" is missing from caretaker.json.`,
|
|
590
|
+
});
|
|
591
|
+
return;
|
|
592
|
+
}
|
|
593
|
+
currentAgent = agent;
|
|
594
|
+
currentProvider = provider;
|
|
595
|
+
currentTools = await harness.resolveAgentTools(agent, harness.tools);
|
|
596
|
+
currentSessionId = null;
|
|
597
|
+
controller = null;
|
|
598
|
+
post({ type: 'contextUsage', usage: null });
|
|
599
|
+
await loadSessionsAndSend(agent.id);
|
|
600
|
+
};
|
|
601
|
+
const loadSessionsAndSend = async (agentId) => {
|
|
602
|
+
try {
|
|
603
|
+
const entries = await listForAgent(agentId);
|
|
604
|
+
const sessionSummaries = entries.map((e) => ({
|
|
605
|
+
id: e.meta.id,
|
|
606
|
+
title: e.meta.title,
|
|
607
|
+
updatedAt: e.updatedAt.toISOString(),
|
|
608
|
+
}));
|
|
609
|
+
post({ type: 'sessionsLoaded', sessions: sessionSummaries });
|
|
610
|
+
}
|
|
611
|
+
catch (err) {
|
|
612
|
+
post({ type: 'sessionsLoaded', sessions: [] });
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
const loadSessionMessagesAndSend = async (agentId, sessionId) => {
|
|
616
|
+
try {
|
|
617
|
+
const sessionData = await readSession(agentId, sessionId);
|
|
618
|
+
const messages = sessionData.messages.map((m) => ({
|
|
619
|
+
id: m.id,
|
|
620
|
+
role: m.role,
|
|
621
|
+
content: m.content,
|
|
622
|
+
parts: m.parts,
|
|
623
|
+
toolCallId: m.toolCallId,
|
|
624
|
+
createdAt: m.createdAt,
|
|
625
|
+
}));
|
|
626
|
+
post({ type: 'sessionLoaded', messages });
|
|
627
|
+
const usage = computeContextUsage(sessionData.messages, currentAgent?.model ?? null);
|
|
628
|
+
post({ type: 'contextUsage', usage });
|
|
629
|
+
}
|
|
630
|
+
catch (err) {
|
|
631
|
+
console.warn('[web] failed to load session messages:', err);
|
|
632
|
+
post({ type: 'error', message: 'Failed to load conversation history' });
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
const sendSettingsData = async () => {
|
|
636
|
+
try {
|
|
637
|
+
const [config, agentsRes, pluginsFile, mcpServersFile] = await Promise.all([
|
|
638
|
+
loadConfig(),
|
|
639
|
+
loadAgents(),
|
|
640
|
+
loadPlugins(),
|
|
641
|
+
loadMcpServers(),
|
|
642
|
+
]);
|
|
643
|
+
const availableTools = harness.tools.list()
|
|
644
|
+
.map((t) => t.name)
|
|
645
|
+
.filter((name) => !name.startsWith('mcp__task__'));
|
|
646
|
+
availableTools.push('mcp__task__*');
|
|
647
|
+
const enrichedServers = mcpServersFile.servers.map((server) => {
|
|
648
|
+
let hasMcpTokens = false;
|
|
649
|
+
try {
|
|
650
|
+
hasMcpTokens = readOAuthBlob(server).tokens != null;
|
|
651
|
+
}
|
|
652
|
+
catch {
|
|
653
|
+
// Decrypt failures treated as no tokens to prevent settings page crash
|
|
654
|
+
}
|
|
655
|
+
return { ...server, hasMcpTokens };
|
|
656
|
+
});
|
|
657
|
+
post({
|
|
658
|
+
type: 'settingsDataLoaded',
|
|
659
|
+
config,
|
|
660
|
+
agents: agentsRes,
|
|
661
|
+
pluginsFile,
|
|
662
|
+
mcpServersFile: { servers: enrichedServers },
|
|
663
|
+
availableTools,
|
|
664
|
+
});
|
|
665
|
+
}
|
|
666
|
+
catch (err) {
|
|
667
|
+
console.warn('[web] failed to load settings data:', err);
|
|
668
|
+
}
|
|
669
|
+
};
|
|
670
|
+
// Set up file watcher to sync state changes live, just like in VSCode
|
|
671
|
+
const dir = dataDir();
|
|
672
|
+
if (!existsSync(dir)) {
|
|
673
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
674
|
+
}
|
|
675
|
+
const watcher = watch(dir, (eventType, filename) => {
|
|
676
|
+
if (filename === 'agents.json' ||
|
|
677
|
+
filename === 'caretaker.json' ||
|
|
678
|
+
filename === 'plugins.json' ||
|
|
679
|
+
filename === 'mcp.json') {
|
|
680
|
+
void loadAgentsAndSend();
|
|
681
|
+
void sendSettingsData();
|
|
682
|
+
}
|
|
683
|
+
});
|
|
684
|
+
ws.on('close', () => {
|
|
685
|
+
resolveAllPending('reject');
|
|
686
|
+
controller?.abort();
|
|
687
|
+
watcher.close();
|
|
688
|
+
});
|
|
689
|
+
ws.on('message', async (data) => {
|
|
690
|
+
try {
|
|
691
|
+
const msg = JSON.parse(data);
|
|
692
|
+
switch (msg.type) {
|
|
693
|
+
case 'webviewReady':
|
|
694
|
+
post({ type: 'ready' });
|
|
695
|
+
await loadAgentsAndSend();
|
|
696
|
+
return;
|
|
697
|
+
case 'start': {
|
|
698
|
+
if (!currentAgent || !currentProvider || !currentTools) {
|
|
699
|
+
post({
|
|
700
|
+
type: 'error',
|
|
701
|
+
message: 'Agent not selected. Please select an agent from the dropdown.',
|
|
702
|
+
});
|
|
703
|
+
return;
|
|
704
|
+
}
|
|
705
|
+
const workspaceFolder = (currentAgent.workingDir && currentAgent.workingDir.trim())
|
|
706
|
+
? currentAgent.workingDir.trim()
|
|
707
|
+
: process.cwd();
|
|
708
|
+
if (!controller) {
|
|
709
|
+
controller = new WebSessionController({
|
|
710
|
+
agent: currentAgent,
|
|
711
|
+
provider: currentProvider,
|
|
712
|
+
tools: currentTools,
|
|
713
|
+
workingDir: workspaceFolder,
|
|
714
|
+
sessionId: currentSessionId ?? undefined,
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
await controller.start(msg.prompt, {
|
|
718
|
+
onChunk: (text) => post({ type: 'chunk', text }),
|
|
719
|
+
onThinking: (text) => post({ type: 'thinking', text }),
|
|
720
|
+
onToolCall: (id, name, args) => post({ type: 'tool_call', id, name, args }),
|
|
721
|
+
onToolResult: (id, content) => post({ type: 'tool_result', id, content }),
|
|
722
|
+
askConfirm: (id, toolName, args) => new Promise((resolve) => {
|
|
723
|
+
pendingConfirms.set(id, resolve);
|
|
724
|
+
post({ type: 'permission_request', id, toolName, args });
|
|
725
|
+
}),
|
|
726
|
+
onError: (message) => {
|
|
727
|
+
resolveAllPending('reject');
|
|
728
|
+
post({ type: 'error', message });
|
|
729
|
+
},
|
|
730
|
+
onDone: () => {
|
|
731
|
+
resolveAllPending('reject');
|
|
732
|
+
post({ type: 'done' });
|
|
733
|
+
if (controller) {
|
|
734
|
+
const usage = controller.getContextUsage();
|
|
735
|
+
post({ type: 'contextUsage', usage });
|
|
736
|
+
}
|
|
737
|
+
},
|
|
738
|
+
onSessionCreated: (sessionId) => {
|
|
739
|
+
currentSessionId = sessionId;
|
|
740
|
+
void loadSessionsAndSend(currentAgent.id);
|
|
741
|
+
},
|
|
742
|
+
}, msg.attachments);
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
case 'abort':
|
|
746
|
+
resolveAllPending('reject');
|
|
747
|
+
controller?.abort();
|
|
748
|
+
return;
|
|
749
|
+
case 'permission_response': {
|
|
750
|
+
const resolve = pendingConfirms.get(msg.id);
|
|
751
|
+
if (resolve) {
|
|
752
|
+
pendingConfirms.delete(msg.id);
|
|
753
|
+
resolve(msg.decision);
|
|
754
|
+
}
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
case 'selectAgent': {
|
|
758
|
+
const agent = agents.find((a) => a.id === msg.agentId);
|
|
759
|
+
if (!agent)
|
|
760
|
+
return;
|
|
761
|
+
const providers = (await loadConfig()).providers;
|
|
762
|
+
await selectAgentInternal(agent, providers);
|
|
763
|
+
await loadSessionsAndSend(agent.id);
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
case 'selectSession': {
|
|
767
|
+
currentSessionId = msg.sessionId;
|
|
768
|
+
controller = null; // Reset controller to load existing session
|
|
769
|
+
if (currentAgent) {
|
|
770
|
+
await loadSessionMessagesAndSend(currentAgent.id, msg.sessionId);
|
|
771
|
+
}
|
|
772
|
+
return;
|
|
773
|
+
}
|
|
774
|
+
case 'createSession': {
|
|
775
|
+
currentSessionId = null;
|
|
776
|
+
controller = null;
|
|
777
|
+
post({ type: 'contextUsage', usage: null });
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
case 'deleteSession': {
|
|
781
|
+
try {
|
|
782
|
+
if (currentAgent) {
|
|
783
|
+
await deleteSession(currentAgent.id, msg.sessionId);
|
|
784
|
+
if (currentSessionId === msg.sessionId) {
|
|
785
|
+
currentSessionId = null;
|
|
786
|
+
controller = null;
|
|
787
|
+
post({ type: 'contextUsage', usage: null });
|
|
788
|
+
}
|
|
789
|
+
await loadSessionsAndSend(currentAgent.id);
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
catch (err) {
|
|
793
|
+
post({ type: 'error', message: `Failed to delete conversation: ${err}` });
|
|
794
|
+
}
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
case 'getSettingsData':
|
|
798
|
+
void sendSettingsData();
|
|
799
|
+
return;
|
|
800
|
+
case 'saveConfig':
|
|
801
|
+
try {
|
|
802
|
+
await saveConfig(msg.config);
|
|
803
|
+
void loadAgentsAndSend();
|
|
804
|
+
void sendSettingsData();
|
|
805
|
+
}
|
|
806
|
+
catch (err) {
|
|
807
|
+
post({ type: 'error', message: `Failed to save config: ${err}` });
|
|
808
|
+
}
|
|
809
|
+
return;
|
|
810
|
+
case 'saveAgent':
|
|
811
|
+
try {
|
|
812
|
+
const agentsList = await loadAgents();
|
|
813
|
+
const existingIdx = agentsList.findIndex((a) => a.id === msg.agent.id);
|
|
814
|
+
if (existingIdx !== -1) {
|
|
815
|
+
agentsList[existingIdx] = msg.agent;
|
|
816
|
+
}
|
|
817
|
+
else {
|
|
818
|
+
agentsList.push(msg.agent);
|
|
819
|
+
}
|
|
820
|
+
await saveAgents(agentsList);
|
|
821
|
+
void loadAgentsAndSend();
|
|
822
|
+
void sendSettingsData();
|
|
823
|
+
}
|
|
824
|
+
catch (err) {
|
|
825
|
+
post({ type: 'error', message: `Failed to save agent: ${err}` });
|
|
826
|
+
}
|
|
827
|
+
return;
|
|
828
|
+
case 'deleteAgent':
|
|
829
|
+
try {
|
|
830
|
+
let agentsList = await loadAgents();
|
|
831
|
+
agentsList = agentsList.filter((a) => a.id !== msg.agentId);
|
|
832
|
+
await saveAgents(agentsList);
|
|
833
|
+
void loadAgentsAndSend();
|
|
834
|
+
void sendSettingsData();
|
|
835
|
+
}
|
|
836
|
+
catch (err) {
|
|
837
|
+
post({ type: 'error', message: `Failed to delete agent: ${err}` });
|
|
838
|
+
}
|
|
839
|
+
return;
|
|
840
|
+
case 'savePluginSource':
|
|
841
|
+
try {
|
|
842
|
+
if (msg.source.id) {
|
|
843
|
+
await patchSource(msg.source.id, {
|
|
844
|
+
url: msg.source.url,
|
|
845
|
+
ref: msg.source.ref,
|
|
846
|
+
authToken: msg.source.authToken,
|
|
847
|
+
refreshOnStart: msg.source.refreshOnStart,
|
|
848
|
+
});
|
|
849
|
+
}
|
|
850
|
+
else {
|
|
851
|
+
await createSource(msg.source);
|
|
852
|
+
}
|
|
853
|
+
void loadAgentsAndSend();
|
|
854
|
+
void sendSettingsData();
|
|
855
|
+
}
|
|
856
|
+
catch (err) {
|
|
857
|
+
post({ type: 'error', message: `Failed to save plugin source: ${err}` });
|
|
858
|
+
}
|
|
859
|
+
return;
|
|
860
|
+
case 'deletePluginSource':
|
|
861
|
+
try {
|
|
862
|
+
await deleteSource(msg.sourceId);
|
|
863
|
+
void loadAgentsAndSend();
|
|
864
|
+
void sendSettingsData();
|
|
865
|
+
}
|
|
866
|
+
catch (err) {
|
|
867
|
+
post({ type: 'error', message: `Failed to delete plugin source: ${err}` });
|
|
868
|
+
}
|
|
869
|
+
return;
|
|
870
|
+
case 'refreshPluginSource':
|
|
871
|
+
try {
|
|
872
|
+
post({ type: 'refreshingPlugin', sourceId: msg.sourceId });
|
|
873
|
+
const outcome = await refreshSource(msg.sourceId);
|
|
874
|
+
void loadAgentsAndSend();
|
|
875
|
+
void sendSettingsData();
|
|
876
|
+
post({ type: 'refreshPluginOutcome', outcome });
|
|
877
|
+
}
|
|
878
|
+
catch (err) {
|
|
879
|
+
post({
|
|
880
|
+
type: 'refreshPluginOutcome',
|
|
881
|
+
outcome: { pluginsFound: 0, sha: null, error: String(err) },
|
|
882
|
+
});
|
|
883
|
+
}
|
|
884
|
+
return;
|
|
885
|
+
case 'saveMcpServer':
|
|
886
|
+
try {
|
|
887
|
+
if (msg.server.id) {
|
|
888
|
+
await patchMcpServer(msg.server.id, {
|
|
889
|
+
name: msg.server.name,
|
|
890
|
+
enabled: msg.server.enabled,
|
|
891
|
+
command: msg.server.command,
|
|
892
|
+
args: msg.server.args,
|
|
893
|
+
env: msg.server.env,
|
|
894
|
+
url: msg.server.url,
|
|
895
|
+
headers: msg.server.headers,
|
|
896
|
+
});
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
await createMcpServer(msg.server);
|
|
900
|
+
}
|
|
901
|
+
void loadAgentsAndSend();
|
|
902
|
+
void sendSettingsData();
|
|
903
|
+
}
|
|
904
|
+
catch (err) {
|
|
905
|
+
post({ type: 'error', message: `Failed to save MCP server: ${err}` });
|
|
906
|
+
}
|
|
907
|
+
return;
|
|
908
|
+
case 'deleteMcpServer':
|
|
909
|
+
try {
|
|
910
|
+
await deleteMcpServer(msg.serverId);
|
|
911
|
+
void loadAgentsAndSend();
|
|
912
|
+
void sendSettingsData();
|
|
913
|
+
}
|
|
914
|
+
catch (err) {
|
|
915
|
+
post({ type: 'error', message: `Failed to delete MCP server: ${err}` });
|
|
916
|
+
}
|
|
917
|
+
return;
|
|
918
|
+
case 'authenticateMcpServer':
|
|
919
|
+
try {
|
|
920
|
+
await authenticateMcpServer(msg.serverId);
|
|
921
|
+
void sendSettingsData();
|
|
922
|
+
post({ type: 'mcpAuthOutcome', serverId: msg.serverId, ok: true });
|
|
923
|
+
}
|
|
924
|
+
catch (err) {
|
|
925
|
+
post({ type: 'mcpAuthOutcome', serverId: msg.serverId, ok: false, error: String(err) });
|
|
926
|
+
}
|
|
927
|
+
return;
|
|
928
|
+
case 'revokeMcpAuth':
|
|
929
|
+
try {
|
|
930
|
+
await revokeMcpAuth(msg.serverId);
|
|
931
|
+
void sendSettingsData();
|
|
932
|
+
post({ type: 'mcpAuthOutcome', serverId: msg.serverId, ok: true });
|
|
933
|
+
}
|
|
934
|
+
catch (err) {
|
|
935
|
+
post({ type: 'mcpAuthOutcome', serverId: msg.serverId, ok: false, error: String(err) });
|
|
936
|
+
}
|
|
937
|
+
return;
|
|
938
|
+
case 'fetchModels':
|
|
939
|
+
try {
|
|
940
|
+
const result = await harness.fetchOpenAiStyleModels(msg.endpoint, msg.apiKey ?? null);
|
|
941
|
+
post({ type: 'modelsFetched', result });
|
|
942
|
+
}
|
|
943
|
+
catch (err) {
|
|
944
|
+
post({
|
|
945
|
+
type: 'modelsFetched',
|
|
946
|
+
result: { ok: false, error: String(err) },
|
|
947
|
+
});
|
|
948
|
+
}
|
|
949
|
+
return;
|
|
950
|
+
case 'getTaskRuns':
|
|
951
|
+
try {
|
|
952
|
+
const runs = await loadTaskRuns(msg.taskId);
|
|
953
|
+
post({ type: 'taskRunsLoaded', taskId: msg.taskId, runs });
|
|
954
|
+
}
|
|
955
|
+
catch (err) {
|
|
956
|
+
console.error('[web] failed to load task runs:', err);
|
|
957
|
+
post({
|
|
958
|
+
type: 'error',
|
|
959
|
+
message: `Failed to load task runs: ${err instanceof Error ? err.message : String(err)}`,
|
|
960
|
+
});
|
|
961
|
+
}
|
|
962
|
+
return;
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
catch (err) {
|
|
966
|
+
console.error('[web] WebSocket message handling failed:', err);
|
|
967
|
+
}
|
|
968
|
+
});
|
|
969
|
+
});
|
|
970
|
+
}
|