@hyperwindmill/caretaker-cli 0.23.0 → 0.25.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.
Files changed (94) hide show
  1. package/dist/acp/index.d.ts +3 -0
  2. package/dist/acp/index.d.ts.map +1 -0
  3. package/dist/acp/index.js +2 -0
  4. package/dist/acp/install.d.ts +12 -0
  5. package/dist/acp/install.d.ts.map +1 -0
  6. package/dist/acp/install.js +110 -0
  7. package/dist/acp/registry.d.ts +10 -0
  8. package/dist/acp/registry.d.ts.map +1 -0
  9. package/dist/acp/registry.js +116 -0
  10. package/dist/cli/web/mcp_bridge.d.ts +7 -1
  11. package/dist/cli/web/mcp_bridge.d.ts.map +1 -1
  12. package/dist/cli/web/mcp_bridge.js +10 -6
  13. package/dist/cli/web/scheduler/memory_extract.d.ts +55 -0
  14. package/dist/cli/web/scheduler/memory_extract.d.ts.map +1 -0
  15. package/dist/cli/web/scheduler/memory_extract.js +112 -0
  16. package/dist/cli/web/scheduler/memory_sweep.d.ts +68 -0
  17. package/dist/cli/web/scheduler/memory_sweep.d.ts.map +1 -0
  18. package/dist/cli/web/scheduler/memory_sweep.js +330 -0
  19. package/dist/cli/web/scheduler/task_review.d.ts +3 -0
  20. package/dist/cli/web/scheduler/task_review.d.ts.map +1 -1
  21. package/dist/cli/web/scheduler/task_review.js +26 -0
  22. package/dist/cli/web/scheduler/task_roles.d.ts +1 -1
  23. package/dist/cli/web/scheduler/task_roles.d.ts.map +1 -1
  24. package/dist/cli/web/scheduler/task_roles.js +6 -6
  25. package/dist/cli/web/scheduler/task_strategy.d.ts.map +1 -1
  26. package/dist/cli/web/scheduler/task_strategy.js +27 -2
  27. package/dist/cli/web/scheduler.d.ts.map +1 -1
  28. package/dist/cli/web/scheduler.js +5 -0
  29. package/dist/cli/web/server.d.ts +1 -1
  30. package/dist/cli/web/server.d.ts.map +1 -1
  31. package/dist/cli/web/server.js +33 -6
  32. package/dist/harness/acp_policy.d.ts +41 -0
  33. package/dist/harness/acp_policy.d.ts.map +1 -0
  34. package/dist/harness/acp_policy.js +59 -0
  35. package/dist/harness/acp_pool.d.ts +33 -0
  36. package/dist/harness/acp_pool.d.ts.map +1 -0
  37. package/dist/harness/acp_pool.js +148 -0
  38. package/dist/harness/acp_runner.d.ts +4 -0
  39. package/dist/harness/acp_runner.d.ts.map +1 -0
  40. package/dist/harness/acp_runner.js +347 -0
  41. package/dist/harness/claude_code_runner.d.ts +2 -0
  42. package/dist/harness/claude_code_runner.d.ts.map +1 -1
  43. package/dist/harness/claude_code_runner.js +6 -1
  44. package/dist/harness/confirm_gate.d.ts +12 -0
  45. package/dist/harness/confirm_gate.d.ts.map +1 -0
  46. package/dist/harness/confirm_gate.js +33 -0
  47. package/dist/harness/index.d.ts +1 -0
  48. package/dist/harness/index.d.ts.map +1 -1
  49. package/dist/harness/index.js +1 -0
  50. package/dist/harness/loop.d.ts +12 -0
  51. package/dist/harness/loop.d.ts.map +1 -1
  52. package/dist/harness/loop.js +16 -0
  53. package/dist/harness/memory_recall.d.ts +28 -0
  54. package/dist/harness/memory_recall.d.ts.map +1 -0
  55. package/dist/harness/memory_recall.js +74 -0
  56. package/dist/harness/title.js +1 -1
  57. package/dist/harness/tools/builtin/index.d.ts +2 -1
  58. package/dist/harness/tools/builtin/index.d.ts.map +1 -1
  59. package/dist/harness/tools/builtin/index.js +4 -1
  60. package/dist/harness/tools/builtin/memory_tools.d.ts +3 -0
  61. package/dist/harness/tools/builtin/memory_tools.d.ts.map +1 -0
  62. package/dist/harness/tools/builtin/memory_tools.js +60 -0
  63. package/dist/harness/tools/resolve.d.ts.map +1 -1
  64. package/dist/harness/tools/resolve.js +15 -0
  65. package/dist/harness/tools/types.d.ts +6 -0
  66. package/dist/harness/tools/types.d.ts.map +1 -1
  67. package/dist/lib/project_resolve.d.ts +5 -0
  68. package/dist/lib/project_resolve.d.ts.map +1 -0
  69. package/dist/lib/project_resolve.js +23 -0
  70. package/dist/mcp/builtin_server.d.ts +2 -0
  71. package/dist/mcp/builtin_server.d.ts.map +1 -1
  72. package/dist/mcp/builtin_server.js +9 -7
  73. package/dist/mcp/run_command_tool.d.ts +13 -0
  74. package/dist/mcp/run_command_tool.d.ts.map +1 -0
  75. package/dist/mcp/run_command_tool.js +51 -0
  76. package/dist/session/store.d.ts +1 -0
  77. package/dist/session/store.d.ts.map +1 -1
  78. package/dist/session/store.js +6 -0
  79. package/dist/session/types.d.ts +3 -0
  80. package/dist/session/types.d.ts.map +1 -1
  81. package/dist/store/db.d.ts +66 -0
  82. package/dist/store/db.d.ts.map +1 -1
  83. package/dist/store/db.js +68 -0
  84. package/dist/tui/agents.d.ts.map +1 -1
  85. package/dist/tui/agents.js +62 -25
  86. package/dist/tui/chat.d.ts.map +1 -1
  87. package/dist/tui/chat.js +7 -8
  88. package/dist/tui/providers.d.ts.map +1 -1
  89. package/dist/tui/providers.js +116 -17
  90. package/dist/webview/standalone.css +18 -0
  91. package/dist/webview/standalone.css.map +2 -2
  92. package/dist/webview/standalone.js +792 -440
  93. package/dist/webview/standalone.js.map +4 -4
  94. package/package.json +8 -3
@@ -0,0 +1,3 @@
1
+ export { fetchAcpRegistry, normalizeRegistry, platformKey, REGISTRY_URL } from './registry.js';
2
+ export { installAcpAgent, type InstalledAcp } from './install.js';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/acp/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AAC/F,OAAO,EAAE,eAAe,EAAE,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { fetchAcpRegistry, normalizeRegistry, platformKey, REGISTRY_URL } from './registry.js';
2
+ export { installAcpAgent } from './install.js';
@@ -0,0 +1,12 @@
1
+ import type { AcpAgentPreset } from '../types.js';
2
+ type FetchLike = (url: string) => Promise<Response>;
3
+ export declare function __setFetch(f: FetchLike): void;
4
+ export declare function __resetFetch(): void;
5
+ export type InstalledAcp = {
6
+ command: string;
7
+ args: string[];
8
+ env?: Record<string, string>;
9
+ };
10
+ export declare function installAcpAgent(preset: AcpAgentPreset, onProgress?: (line: string) => void): Promise<InstalledAcp>;
11
+ export {};
12
+ //# sourceMappingURL=install.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"install.d.ts","sourceRoot":"","sources":["../../src/acp/install.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAOlD,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAGpD,wBAAgB,UAAU,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,CAE7C;AACD,wBAAgB,YAAY,IAAI,IAAI,CAEnC;AAED,MAAM,MAAM,YAAY,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IAAC,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAAE,CAAC;AAwB7F,wBAAsB,eAAe,CACnC,MAAM,EAAE,cAAc,EACtB,UAAU,GAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAe,GAC5C,OAAO,CAAC,YAAY,CAAC,CAqEvB"}
@@ -0,0 +1,110 @@
1
+ // Managed install of binary-distributed ACP agents (spec:
2
+ // 2026-08-25-acp-registry-presets). Download → sha256 verify → extract →
3
+ // chmod, all into a tmp sibling renamed into place on success, so a failed
4
+ // install leaves nothing behind. Idempotent per <id>/<version>: the saved
5
+ // provider just points at the resulting absolute path — nothing else in
6
+ // caretaker knows the binary is "managed".
7
+ import { createHash } from 'node:crypto';
8
+ import { createWriteStream } from 'node:fs';
9
+ import { chmod, mkdir, rename, rm, rmdir, stat } from 'node:fs/promises';
10
+ import { pipeline } from 'node:stream/promises';
11
+ import { Readable, Transform } from 'node:stream';
12
+ import { execFile } from 'node:child_process';
13
+ import { promisify } from 'node:util';
14
+ import { basename, join, resolve } from 'node:path';
15
+ import { dataDir } from '../store/json.js';
16
+ const exec = promisify(execFile);
17
+ /** Whole-download ceiling (headers + body): archives are tens of MB, so this is
18
+ * generous, but a stalled mirror must not leave the Install button spinning. */
19
+ const DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
20
+ const defaultFetch = (url) => fetch(url, { signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS) });
21
+ let fetchImpl = defaultFetch;
22
+ export function __setFetch(f) {
23
+ fetchImpl = f;
24
+ }
25
+ export function __resetFetch() {
26
+ fetchImpl = defaultFetch;
27
+ }
28
+ function isExtractable(name) {
29
+ return /\.(tar\.(gz|bz2|xz)|tgz|tbz2|tar|zip)$/i.test(name);
30
+ }
31
+ async function extract(archive, dest) {
32
+ if (/\.zip$/i.test(archive) && process.platform === 'linux') {
33
+ // GNU tar has no zip support; macOS and Windows ship bsdtar (which does).
34
+ try {
35
+ await exec('unzip', ['-o', archive, '-d', dest]);
36
+ return;
37
+ }
38
+ catch (err) {
39
+ if (err?.code === 'ENOENT') {
40
+ throw new Error('unzip is required to extract .zip archives on Linux — install it (e.g. apt install unzip)');
41
+ }
42
+ throw err;
43
+ }
44
+ }
45
+ await exec('tar', ['-xf', archive, '-C', dest]);
46
+ }
47
+ export async function installAcpAgent(preset, onProgress = () => { }) {
48
+ const d = preset.dist;
49
+ if (!d || d.kind !== 'binary') {
50
+ throw new Error(`"${preset.id}" has no binary distribution for this platform`);
51
+ }
52
+ const dir = join(dataDir(), 'acp', preset.id, preset.version || 'latest');
53
+ const command = resolve(dir, d.cmd);
54
+ const result = { command, args: d.args ?? [], ...(d.env ? { env: d.env } : {}) };
55
+ if (await stat(command).then(() => true).catch(() => false)) {
56
+ onProgress('already installed');
57
+ return result;
58
+ }
59
+ const tmp = `${dir}.tmp-${process.pid}`;
60
+ try {
61
+ await mkdir(tmp, { recursive: true });
62
+ onProgress(`downloading ${d.archive}`);
63
+ const res = await fetchImpl(d.archive);
64
+ if (!res.ok || !res.body)
65
+ throw new Error(`download failed: HTTP ${res.status}`);
66
+ const archiveName = basename(new URL(d.archive).pathname);
67
+ const archivePath = join(tmp, archiveName);
68
+ // Hash while streaming to disk: archives are tens of MB, no need to
69
+ // re-read them into memory for the checksum.
70
+ const hasher = createHash('sha256');
71
+ await pipeline(Readable.fromWeb(res.body), new Transform({
72
+ transform(chunk, _enc, cb) {
73
+ hasher.update(chunk);
74
+ cb(null, chunk);
75
+ },
76
+ }), createWriteStream(archivePath));
77
+ if (d.sha256) {
78
+ onProgress('verifying checksum');
79
+ const hash = hasher.digest('hex');
80
+ if (hash !== d.sha256)
81
+ throw new Error(`sha256 mismatch: expected ${d.sha256}, got ${hash}`);
82
+ }
83
+ if (isExtractable(archiveName)) {
84
+ onProgress('extracting');
85
+ await extract(archivePath, tmp);
86
+ await rm(archivePath, { force: true });
87
+ }
88
+ else {
89
+ // Raw executable download (no archive): move it to the cmd path.
90
+ const target = resolve(tmp, d.cmd);
91
+ await mkdir(join(target, '..'), { recursive: true });
92
+ await rename(archivePath, target);
93
+ }
94
+ const cmdInTmp = resolve(tmp, d.cmd);
95
+ if (!(await stat(cmdInTmp).then(() => true).catch(() => false))) {
96
+ throw new Error(`archive did not contain the expected command "${d.cmd}"`);
97
+ }
98
+ await chmod(cmdInTmp, 0o755).catch(() => { }); // no-op semantics on Windows
99
+ await rm(dir, { recursive: true, force: true });
100
+ await rename(tmp, dir);
101
+ onProgress('installed');
102
+ return result;
103
+ }
104
+ catch (err) {
105
+ await rm(tmp, { recursive: true, force: true });
106
+ // Remove the (possibly just-created, empty) id dir if this was the first version.
107
+ await rmdir(join(dataDir(), 'acp', preset.id)).catch(() => { });
108
+ throw err instanceof Error ? err : new Error(String(err));
109
+ }
110
+ }
@@ -0,0 +1,10 @@
1
+ import type { AcpAgentPreset } from '../types.js';
2
+ export declare const REGISTRY_URL = "https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json";
3
+ type FetchLike = (url: string) => Promise<Response>;
4
+ export declare function __setFetch(f: FetchLike): void;
5
+ export declare function __resetFetch(): void;
6
+ export declare function platformKey(platform?: NodeJS.Platform, arch?: string): string;
7
+ export declare function normalizeRegistry(raw: unknown, platKey?: string): AcpAgentPreset[];
8
+ export declare function fetchAcpRegistry(now?: number): Promise<AcpAgentPreset[]>;
9
+ export {};
10
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/acp/registry.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAElD,eAAO,MAAM,YAAY,yEAAyE,CAAC;AAOnG,KAAK,SAAS,GAAG,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC,QAAQ,CAAC,CAAC;AAGpD,wBAAgB,UAAU,CAAC,CAAC,EAAE,SAAS,GAAG,IAAI,CAE7C;AACD,wBAAgB,YAAY,IAAI,IAAI,CAEnC;AAUD,wBAAgB,WAAW,CACzB,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAC5C,IAAI,GAAE,MAAqB,GAC1B,MAAM,CAIR;AAED,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,MAAsB,GAAG,cAAc,EAAE,CA4CjG;AAMD,wBAAsB,gBAAgB,CAAC,GAAG,GAAE,MAAmB,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CA0B1F"}
@@ -0,0 +1,116 @@
1
+ // ACP Agent Registry client: fetch + normalize + disk cache. The registry is
2
+ // the census of known ACP agents (spec: 2026-08-25-acp-registry-presets);
3
+ // the provider form offers these as presets instead of hand-typed commands.
4
+ import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';
5
+ import { join } from 'node:path';
6
+ import { dataDir } from '../store/json.js';
7
+ export const REGISTRY_URL = 'https://cdn.agentclientprotocol.com/registry/v1/latest/registry.json';
8
+ const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
9
+ /** A CDN that accepts the socket and goes silent must not pin the provider
10
+ * form on "loading presets…" forever (same rationale as NET_TIMEOUT_MS in
11
+ * lib/task_git.ts). */
12
+ const FETCH_TIMEOUT_MS = 15_000;
13
+ const defaultFetch = (url) => fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
14
+ let fetchImpl = defaultFetch;
15
+ export function __setFetch(f) {
16
+ fetchImpl = f;
17
+ }
18
+ export function __resetFetch() {
19
+ fetchImpl = defaultFetch;
20
+ }
21
+ /** What the registry does not know: context files an agent self-loads (the
22
+ * fabricated context block must skip them — see the ACP runner spec). */
23
+ const SELF_LOADED = {
24
+ 'claude-acp': ['CLAUDE.md'],
25
+ 'codex-acp': ['AGENTS.md'],
26
+ gemini: ['GEMINI.md'],
27
+ };
28
+ export function platformKey(platform = process.platform, arch = process.arch) {
29
+ const os = platform === 'win32' ? 'windows' : platform === 'darwin' ? 'darwin' : 'linux';
30
+ const cpu = arch === 'arm64' ? 'aarch64' : 'x86_64';
31
+ return `${os}-${cpu}`;
32
+ }
33
+ export function normalizeRegistry(raw, platKey = platformKey()) {
34
+ const agents = Array.isArray(raw?.agents) ? raw.agents : [];
35
+ const out = [];
36
+ for (const a of agents) {
37
+ if (!a?.id || !a?.name)
38
+ continue;
39
+ const d = a.distribution ?? {};
40
+ let dist = null;
41
+ if (d.npx?.package) {
42
+ // -y: without it, npx prompts "Ok to proceed?" on stdin on first run,
43
+ // which would corrupt the ACP JSON-RPC handshake on the same pipe.
44
+ dist = {
45
+ kind: 'npx',
46
+ command: 'npx',
47
+ args: ['-y', String(d.npx.package), ...(d.npx.args ?? [])],
48
+ ...(d.npx.env ? { env: d.npx.env } : {}),
49
+ };
50
+ }
51
+ else if (d.uvx?.package) {
52
+ dist = {
53
+ kind: 'uvx',
54
+ command: 'uvx',
55
+ args: [String(d.uvx.package), ...(d.uvx.args ?? [])],
56
+ ...(d.uvx.env ? { env: d.uvx.env } : {}),
57
+ };
58
+ }
59
+ else if (d.binary?.[platKey]) {
60
+ const b = d.binary[platKey];
61
+ dist = {
62
+ kind: 'binary',
63
+ archive: String(b.archive),
64
+ cmd: String(b.cmd),
65
+ ...(b.args ? { args: b.args } : {}),
66
+ ...(b.env ? { env: b.env } : {}),
67
+ ...(b.sha256 ? { sha256: String(b.sha256) } : {}),
68
+ };
69
+ }
70
+ out.push({
71
+ id: String(a.id),
72
+ name: String(a.name),
73
+ description: String(a.description ?? ''),
74
+ version: String(a.version ?? ''),
75
+ dist,
76
+ selfLoadedContextFiles: SELF_LOADED[a.id] ?? [],
77
+ });
78
+ }
79
+ return out;
80
+ }
81
+ function cachePath() {
82
+ return join(dataDir(), 'cache', 'acp-registry.json');
83
+ }
84
+ export async function fetchAcpRegistry(now = Date.now()) {
85
+ let cached = null;
86
+ try {
87
+ cached = JSON.parse(await readFile(cachePath(), 'utf8'));
88
+ }
89
+ catch {
90
+ /* no cache */
91
+ }
92
+ if (cached && now - cached.fetchedAt < CACHE_TTL_MS)
93
+ return normalizeRegistry(cached.raw);
94
+ try {
95
+ const res = await fetchImpl(REGISTRY_URL);
96
+ if (!res.ok)
97
+ throw new Error(`ACP registry fetch failed: HTTP ${res.status}`);
98
+ const raw = await res.json();
99
+ const list = normalizeRegistry(raw); // validate before caching
100
+ // An agentless 200 (edge error page, half-deployed CDN) must not overwrite
101
+ // a good last-good with an empty census for 24h.
102
+ if (list.length === 0)
103
+ throw new Error('ACP registry returned no agents');
104
+ await mkdir(join(dataDir(), 'cache'), { recursive: true });
105
+ const tmp = `${cachePath()}.tmp-${process.pid}`;
106
+ await writeFile(tmp, JSON.stringify({ fetchedAt: now, raw }), { mode: 0o600 });
107
+ await rename(tmp, cachePath());
108
+ return list;
109
+ }
110
+ catch (err) {
111
+ // Last-good: a stale cache beats an error (offline-first).
112
+ if (cached)
113
+ return normalizeRegistry(cached.raw);
114
+ throw err instanceof Error ? err : new Error(String(err));
115
+ }
116
+ }
@@ -1,5 +1,11 @@
1
1
  import type { Hono } from 'hono';
2
- export declare function issueBridgeToken(agentId?: string): string;
2
+ export declare function issueBridgeToken(agentId?: string, opts?: {
3
+ exec?: {
4
+ container: string;
5
+ workdir: string;
6
+ };
7
+ execOnly?: boolean;
8
+ }): string;
3
9
  export declare function revokeBridgeToken(token: string): void;
4
10
  export declare function setTaskBridgeUrl(url: string): void;
5
11
  export declare function getTaskBridgeUrl(): string | null;
@@ -1 +1 @@
1
- {"version":3,"file":"mcp_bridge.d.ts","sourceRoot":"","sources":["../../../src/cli/web/mcp_bridge.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AASjC,wBAAgB,gBAAgB,CAAC,OAAO,SAAK,GAAG,MAAM,CAIrD;AACD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAErD;AAGD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAElD;AACD,wBAAgB,gBAAgB,IAAI,MAAM,GAAG,IAAI,CAEhD;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CAuBlD"}
1
+ {"version":3,"file":"mcp_bridge.d.ts","sourceRoot":"","sources":["../../../src/cli/web/mcp_bridge.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,MAAM,CAAC;AAiBjC,wBAAgB,gBAAgB,CAC9B,OAAO,SAAK,EACZ,IAAI,GAAE;IAAE,IAAI,CAAC,EAAE;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IAAC,QAAQ,CAAC,EAAE,OAAO,CAAA;CAAO,GAC/E,MAAM,CAIR;AACD,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAErD;AAGD,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAElD;AACD,wBAAgB,gBAAgB,IAAI,MAAM,GAAG,IAAI,CAEhD;AAED,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,GAAG,IAAI,CA0BlD"}
@@ -14,13 +14,14 @@
14
14
  import { randomBytes } from 'node:crypto';
15
15
  import { RESPONSE_ALREADY_SENT } from '@hono/node-server/utils/response';
16
16
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
17
- import { buildBuiltinMcpServer } from '../../mcp/builtin_server.js';
17
+ import { buildBuiltinMcpServer, builtinMcpTools } from '../../mcp/builtin_server.js';
18
+ import { makeRunCommandTool } from '../../mcp/run_command_tool.js';
18
19
  import { loadAgents } from '../../store/json.js';
19
- /** token → the agent id the run belongs to ('' when the caller didn't say). */
20
+ /** token → token info (agent id, exec binding, exec-only mode). */
20
21
  const activeTokens = new Map();
21
- export function issueBridgeToken(agentId = '') {
22
+ export function issueBridgeToken(agentId = '', opts = {}) {
22
23
  const token = randomBytes(24).toString('hex');
23
- activeTokens.set(token, agentId);
24
+ activeTokens.set(token, { agentId, exec: opts.exec, execOnly: opts.execOnly });
24
25
  return token;
25
26
  }
26
27
  export function revokeBridgeToken(token) {
@@ -43,11 +44,14 @@ export function registerTaskBridge(app) {
43
44
  // Resolve the run's agent so ctx.callerAgent is set for the tools that scope
44
45
  // by it. A token issued without an agent id (or pointing at a since-deleted
45
46
  // agent) leaves it unset, which the email tools treat as an unscoped caller.
46
- const agentId = activeTokens.get(token) ?? '';
47
+ const tokenInfo = activeTokens.get(token);
48
+ const agentId = tokenInfo.agentId;
47
49
  const callerAgent = agentId
48
50
  ? (await loadAgents().catch(() => [])).find((a) => a.id === agentId)
49
51
  : undefined;
50
- const server = buildBuiltinMcpServer(undefined, { callerAgent });
52
+ const extraTools = tokenInfo.exec ? [makeRunCommandTool(tokenInfo.exec)] : [];
53
+ const tools = tokenInfo.execOnly ? extraTools : [...builtinMcpTools(), ...extraTools];
54
+ const server = buildBuiltinMcpServer(undefined, { callerAgent, tools });
51
55
  const transport = new StreamableHTTPServerTransport({
52
56
  sessionIdGenerator: undefined, // stateless
53
57
  enableJsonResponse: true, // plain JSON responses, no SSE needed
@@ -0,0 +1,55 @@
1
+ import type { AgentConfig, ProjectConfig } from '../../../types.js';
2
+ export declare const MAX_DEDUP_CHARS = 4000;
3
+ export declare const MAX_MEMORIES_PER_CALL = 5;
4
+ export declare const MAX_MEMORY_TITLE_CHARS = 200;
5
+ export declare const MAX_MEMORY_BODY_CHARS = 2000;
6
+ export declare const MAX_MEMORY_KEYWORDS = 10;
7
+ /** One validated memory candidate out of the model. `level` is the model's
8
+ * only scope verb — the host maps it to a concrete projectId. */
9
+ export interface ExtractedMemory {
10
+ level: 'project' | 'global';
11
+ kind: 'fact' | 'episode';
12
+ importance: 'low' | 'normal' | 'high';
13
+ title: string;
14
+ body: string;
15
+ keywords: string[];
16
+ }
17
+ export interface CombinedResult {
18
+ summary: string;
19
+ memories: ExtractedMemory[];
20
+ }
21
+ /** Everything the combined call needs; assembled by the sweep per chunk. */
22
+ export interface SummarizeContext {
23
+ prevSummary: string;
24
+ chunkText: string;
25
+ /** Preformatted "existing memories" lines (formatDedupBlock), '' when none. */
26
+ dedupBlock: string;
27
+ /** Whether a project is resolved for this session — gates the level choice. */
28
+ hasProject: boolean;
29
+ }
30
+ export declare function buildCombinedPrompt(ctx: SummarizeContext): string;
31
+ /** Outermost-braces JSON extraction (also strips fences/prose for free).
32
+ * null = failed chunk: the caller leaves the cursor, next sweep retries.
33
+ * Deliberately NO raw-text-as-summary fallback — it would poison the digest. */
34
+ export declare function parseCombinedResponse(text: string): {
35
+ summary: string;
36
+ memories: unknown;
37
+ } | null;
38
+ /** Host-side gate on model output: drop entries without title/body, coerce
39
+ * invalid enums to fact/normal, degrade project→global when no project is
40
+ * in scope, cap count and field sizes. Extraction is best-effort — a bad
41
+ * entry is dropped, never a failed chunk. */
42
+ export declare function validateMemories(raw: unknown, hasProject: boolean): ExtractedMemory[];
43
+ /** One line per existing memory (newest first — caller sorts), stopping
44
+ * before MAX_DEDUP_CHARS. Titles + keywords only, never bodies. */
45
+ export declare function formatDedupBlock(entries: Array<{
46
+ title: string;
47
+ keywords: string[];
48
+ }>): string;
49
+ /** Host-side project resolution (scope ids are never chosen by a model):
50
+ * the session agent's workingDir prefix-matched, path-aware, against the
51
+ * configured projects' workingDir. Longest match wins (nested projects).
52
+ * '' = no project in scope → global-only extraction.
53
+ * Delegates to lib/project_resolve.ts — shared with the read path. */
54
+ export declare function resolveProjectId(sessionAgentId: string, agents: AgentConfig[], projects: ProjectConfig[]): string;
55
+ //# sourceMappingURL=memory_extract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory_extract.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/memory_extract.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEpE,eAAO,MAAM,eAAe,OAAO,CAAC;AACpC,eAAO,MAAM,qBAAqB,IAAI,CAAC;AACvC,eAAO,MAAM,sBAAsB,MAAM,CAAC;AAC1C,eAAO,MAAM,qBAAqB,OAAO,CAAC;AAC1C,eAAO,MAAM,mBAAmB,KAAK,CAAC;AAEtC;kEACkE;AAClE,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,SAAS,GAAG,QAAQ,CAAC;IAC5B,IAAI,EAAE,MAAM,GAAG,SAAS,CAAC;IACzB,UAAU,EAAE,KAAK,GAAG,QAAQ,GAAG,MAAM,CAAC;IACtC,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,MAAM,WAAW,cAAc;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,eAAe,EAAE,CAAC;CAC7B;AAED,4EAA4E;AAC5E,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,+EAA+E;IAC/E,UAAU,EAAE,MAAM,CAAC;IACnB,+EAA+E;IAC/E,UAAU,EAAE,OAAO,CAAC;CACrB;AAMD,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,gBAAgB,GAAG,MAAM,CAwBjE;AAED;;iFAEiF;AACjF,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,OAAO,CAAA;CAAE,GAAG,IAAI,CAYjG;AAED;;;8CAG8C;AAC9C,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,GAAG,eAAe,EAAE,CAuBrF;AAED;oEACoE;AACpE,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,GAAG,MAAM,CAU9F;AAED;;;;uEAIuE;AACvE,wBAAgB,gBAAgB,CAC9B,cAAc,EAAE,MAAM,EACtB,MAAM,EAAE,WAAW,EAAE,EACrB,QAAQ,EAAE,aAAa,EAAE,GACxB,MAAM,CAGR"}
@@ -0,0 +1,112 @@
1
+ // Pure helpers for the sweep's combined summarize+extract call: prompt
2
+ // assembly, defensive JSON parsing, entry validation, dedup-block formatting,
3
+ // and host-side project resolution. No harness or store imports (types only)
4
+ // so everything here is unit-testable without CARETAKER_HOME.
5
+ // See docs/superpowers/specs/2026-08-24-memory-daemon-step2-extraction-design.md
6
+ import { resolveProjectIdForDir } from '../../../lib/project_resolve.js';
7
+ export const MAX_DEDUP_CHARS = 4000;
8
+ export const MAX_MEMORIES_PER_CALL = 5;
9
+ export const MAX_MEMORY_TITLE_CHARS = 200;
10
+ export const MAX_MEMORY_BODY_CHARS = 2000;
11
+ export const MAX_MEMORY_KEYWORDS = 10;
12
+ const LEVEL_PROJECT = '"level": "project" for facts about this specific project, "global" for facts about the user or their machine/environment that hold everywhere.';
13
+ const LEVEL_GLOBAL_ONLY = '"level": always "global" (no project is in scope).';
14
+ export function buildCombinedPrompt(ctx) {
15
+ return [
16
+ 'You maintain a rolling summary of a conversation between a user and an AI agent, and you extract durable memories from it.',
17
+ '',
18
+ 'Reply with ONLY a JSON object, no code fences, in this exact shape:',
19
+ '{"summary": "<updated rolling summary>", "memories": [{"level": "...", "kind": "...", "importance": "...", "title": "...", "body": "...", "keywords": ["..."]}]}',
20
+ '',
21
+ 'SUMMARY: integrate the NEW MESSAGES into the PREVIOUS SUMMARY and rewrite it as one standalone plain-text summary, at most 300 words. Keep durable facts, decisions, preferences, constraints, and open threads; drop pleasantries and dead ends.',
22
+ '',
23
+ `MEMORIES: at most ${MAX_MEMORIES_PER_CALL} facts worth remembering beyond this conversation, using the summary as context. Only NEW information — never re-emit anything under EXISTING MEMORIES. Most chunks contain nothing durable: an empty array is the normal answer. Fields:`,
24
+ `- ${ctx.hasProject ? LEVEL_PROJECT : LEVEL_GLOBAL_ONLY}`,
25
+ '- "kind": "fact" (timeless knowledge: conventions, preferences, constraints, decisions) or "episode" (a dated event: something that happened).',
26
+ '- "importance": judge it from the TONE of the conversation. "high" only when the user marked it explicitly ("remember this", "never again"), was emphatic or frustrated, or corrected a mistake; "normal" for ordinary facts and decisions; "low" for incidental context.',
27
+ `- "title": short and searchable. "body": the fact itself, self-contained markdown. "keywords": up to ${MAX_MEMORY_KEYWORDS} lowercase search words.`,
28
+ '',
29
+ 'EXISTING MEMORIES (do not re-emit):',
30
+ ctx.dedupBlock || '(none)',
31
+ '',
32
+ 'PREVIOUS SUMMARY:',
33
+ ctx.prevSummary.trim() || '(none)',
34
+ '',
35
+ 'NEW MESSAGES:',
36
+ ctx.chunkText,
37
+ ].join('\n');
38
+ }
39
+ /** Outermost-braces JSON extraction (also strips fences/prose for free).
40
+ * null = failed chunk: the caller leaves the cursor, next sweep retries.
41
+ * Deliberately NO raw-text-as-summary fallback — it would poison the digest. */
42
+ export function parseCombinedResponse(text) {
43
+ const start = text.indexOf('{');
44
+ const end = text.lastIndexOf('}');
45
+ if (start === -1 || end <= start)
46
+ return null;
47
+ let obj;
48
+ try {
49
+ obj = JSON.parse(text.slice(start, end + 1));
50
+ }
51
+ catch {
52
+ return null;
53
+ }
54
+ if (typeof obj?.summary !== 'string' || !obj.summary.trim())
55
+ return null;
56
+ return { summary: obj.summary.trim(), memories: obj.memories };
57
+ }
58
+ /** Host-side gate on model output: drop entries without title/body, coerce
59
+ * invalid enums to fact/normal, degrade project→global when no project is
60
+ * in scope, cap count and field sizes. Extraction is best-effort — a bad
61
+ * entry is dropped, never a failed chunk. */
62
+ export function validateMemories(raw, hasProject) {
63
+ if (!Array.isArray(raw))
64
+ return [];
65
+ const out = [];
66
+ for (const e of raw) {
67
+ if (out.length >= MAX_MEMORIES_PER_CALL)
68
+ break;
69
+ if (typeof e?.title !== 'string' || !e.title.trim())
70
+ continue;
71
+ if (typeof e?.body !== 'string' || !e.body.trim())
72
+ continue;
73
+ const keywords = Array.isArray(e.keywords)
74
+ ? e.keywords
75
+ .filter((k) => typeof k === 'string' && k.trim() !== '')
76
+ .map((k) => k.trim())
77
+ .slice(0, MAX_MEMORY_KEYWORDS)
78
+ : [];
79
+ out.push({
80
+ level: e.level === 'project' && hasProject ? 'project' : 'global',
81
+ kind: e.kind === 'episode' ? 'episode' : 'fact',
82
+ importance: e.importance === 'low' || e.importance === 'high' ? e.importance : 'normal',
83
+ title: e.title.trim().slice(0, MAX_MEMORY_TITLE_CHARS),
84
+ body: e.body.trim().slice(0, MAX_MEMORY_BODY_CHARS),
85
+ keywords,
86
+ });
87
+ }
88
+ return out;
89
+ }
90
+ /** One line per existing memory (newest first — caller sorts), stopping
91
+ * before MAX_DEDUP_CHARS. Titles + keywords only, never bodies. */
92
+ export function formatDedupBlock(entries) {
93
+ const lines = [];
94
+ let len = 0;
95
+ for (const e of entries) {
96
+ const line = e.keywords.length ? `- ${e.title} [${e.keywords.join(', ')}]` : `- ${e.title}`;
97
+ if (len + line.length + 1 > MAX_DEDUP_CHARS)
98
+ break;
99
+ lines.push(line);
100
+ len += line.length + 1;
101
+ }
102
+ return lines.join('\n');
103
+ }
104
+ /** Host-side project resolution (scope ids are never chosen by a model):
105
+ * the session agent's workingDir prefix-matched, path-aware, against the
106
+ * configured projects' workingDir. Longest match wins (nested projects).
107
+ * '' = no project in scope → global-only extraction.
108
+ * Delegates to lib/project_resolve.ts — shared with the read path. */
109
+ export function resolveProjectId(sessionAgentId, agents, projects) {
110
+ const dir = agents.find((a) => a.id === sessionAgentId)?.workingDir;
111
+ return dir ? resolveProjectIdForDir(dir, projects) : '';
112
+ }
@@ -0,0 +1,68 @@
1
+ import type { AgentConfig, CaretakerConfig, ProjectConfig, ProviderConfig } from '../../../types.js';
2
+ import type { MessageRecord } from '../../../session/types.js';
3
+ import { type CombinedResult, type SummarizeContext } from './memory_extract.js';
4
+ export declare const DEFAULT_SWEEP_MINUTES = 5;
5
+ export declare const DEFAULT_MIN_NEW_MESSAGES = 4;
6
+ export declare const MAX_CALLS_PER_SWEEP = 10;
7
+ export declare const MAX_CHUNK_CHARS = 20000;
8
+ export declare const MAX_TOOL_RESULT_CHARS = 500;
9
+ export declare const MAX_SUMMARY_CHARS = 4000;
10
+ export declare const SUMMARIZE_TIMEOUT_MS = 120000;
11
+ export interface ResolvedMemoryConfig {
12
+ agent: AgentConfig;
13
+ provider: ProviderConfig;
14
+ sweepMinutes: number;
15
+ minNewMessages: number;
16
+ /** Full lists, for per-session project resolution (the session's agent is
17
+ * a different agent than the memory agent). */
18
+ agents: AgentConfig[];
19
+ projects: ProjectConfig[];
20
+ }
21
+ /** null = subsystem off (unset config, deleted agent, or the agent's provider
22
+ * no longer exists). Any provider type works — the summarize call launches
23
+ * through the harness loop, which already dispatches claude-code. */
24
+ export declare function resolveMemoryConfig(config: CaretakerConfig, agents: AgentConfig[]): ResolvedMemoryConfig | null;
25
+ /** One role-labelled line per message. Thinking parts are dropped (never fed
26
+ * to the memory model); tool results are hard-truncated — they are the
27
+ * largest strings in a session and carry the least durable meaning. */
28
+ export declare function formatMessage(m: MessageRecord): string;
29
+ /** Index of the cursor message; -1 when lastMessageId is '' or not found
30
+ * (both mean: process from the beginning). */
31
+ export declare function locateCursor(messages: MessageRecord[], lastMessageId: string): number;
32
+ /** Consecutive chunks whose formatted text stays under MAX_CHUNK_CHARS. A
33
+ * single oversized message becomes its own chunk with its text truncated —
34
+ * the cursor must always be able to advance past it. */
35
+ export declare function chunkMessages(messages: MessageRecord[]): Array<{
36
+ messages: MessageRecord[];
37
+ text: string;
38
+ }>;
39
+ /** null = failure (network, non-OK, empty or non-JSON response). The caller
40
+ * leaves the cursor where it was; the next sweep retries. Best-effort, the
41
+ * same contract as titling (harness/title.ts). */
42
+ export type SummarizeFn = (ctx: SummarizeContext) => Promise<CombinedResult | null>;
43
+ /** The summarize call launches through the harness loop with the memory
44
+ * agent's identity: every provider type works (claude-code spawns a one-shot
45
+ * `claude -p`, no session persisted), and the agent's systemPrompt shapes
46
+ * the summaries. Always a fresh conversation — never the agent's sessions.
47
+ * `tools: []` plus `dontAsk` (auto-denies every claude-side tool call) keep
48
+ * it pure text generation; workingDir is pinned to CARETAKER_HOME so the
49
+ * project AGENTS.md walk stays out of the prompt. */
50
+ export declare function makeSummarizer(resolved: ResolvedMemoryConfig): SummarizeFn;
51
+ export interface SweepResult {
52
+ scanned: number;
53
+ summarized: number;
54
+ memories: number;
55
+ calls: number;
56
+ budgetSkipped: number;
57
+ }
58
+ /** One full pass over every session on disk. Sessions written by any surface
59
+ * are picked up — the sweep reads shared state, it is not wired per surface.
60
+ * Failures are per-session and best-effort: warn, skip, retry next sweep. */
61
+ export declare function sweepMemory(resolved: ResolvedMemoryConfig, summarize: SummarizeFn): Promise<SweepResult>;
62
+ /** The scheduler-facing entry: called every 15 s tick, does work at most once
63
+ * per sweepMinutes, never overlapping. `summarizeOverride` is test-only. */
64
+ export declare function runMemorySweepTick(now: Date, summarizeOverride?: SummarizeFn): Promise<void>;
65
+ export declare const __memorySweepTesting: {
66
+ reset(): void;
67
+ };
68
+ //# sourceMappingURL=memory_sweep.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"memory_sweep.d.ts","sourceRoot":"","sources":["../../../../src/cli/web/scheduler/memory_sweep.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACrG,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAa/D,OAAO,EAML,KAAK,cAAc,EACnB,KAAK,gBAAgB,EACtB,MAAM,qBAAqB,CAAC;AAE7B,eAAO,MAAM,qBAAqB,IAAI,CAAC;AACvC,eAAO,MAAM,wBAAwB,IAAI,CAAC;AAC1C,eAAO,MAAM,mBAAmB,KAAK,CAAC;AACtC,eAAO,MAAM,eAAe,QAAS,CAAC;AACtC,eAAO,MAAM,qBAAqB,MAAM,CAAC;AACzC,eAAO,MAAM,iBAAiB,OAAQ,CAAC;AACvC,eAAO,MAAM,oBAAoB,SAAU,CAAC;AAE5C,MAAM,WAAW,oBAAoB;IACnC,KAAK,EAAE,WAAW,CAAC;IACnB,QAAQ,EAAE,cAAc,CAAC;IACzB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB;oDACgD;IAChD,MAAM,EAAE,WAAW,EAAE,CAAC;IACtB,QAAQ,EAAE,aAAa,EAAE,CAAC;CAC3B;AAED;;sEAEsE;AACtE,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,WAAW,EAAE,GACpB,oBAAoB,GAAG,IAAI,CAe7B;AAED;;wEAEwE;AACxE,wBAAgB,aAAa,CAAC,CAAC,EAAE,aAAa,GAAG,MAAM,CAiBtD;AAED;+CAC+C;AAC/C,wBAAgB,YAAY,CAAC,QAAQ,EAAE,aAAa,EAAE,EAAE,aAAa,EAAE,MAAM,GAAG,MAAM,CAGrF;AAED;;yDAEyD;AACzD,wBAAgB,aAAa,CAC3B,QAAQ,EAAE,aAAa,EAAE,GACxB,KAAK,CAAC;IAAE,QAAQ,EAAE,aAAa,EAAE,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC,CAoBpD;AAED;;mDAEmD;AACnD,MAAM,MAAM,WAAW,GAAG,CAAC,GAAG,EAAE,gBAAgB,KAAK,OAAO,CAAC,cAAc,GAAG,IAAI,CAAC,CAAC;AAEpF;;;;;;sDAMsD;AACtD,wBAAgB,cAAc,CAAC,QAAQ,EAAE,oBAAoB,GAAG,WAAW,CA8B1E;AAED,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,KAAK,EAAE,MAAM,CAAC;IACd,aAAa,EAAE,MAAM,CAAC;CACvB;AAED;;8EAE8E;AAC9E,wBAAsB,WAAW,CAC/B,QAAQ,EAAE,oBAAoB,EAC9B,SAAS,EAAE,WAAW,GACrB,OAAO,CAAC,WAAW,CAAC,CAqJtB;AAMD;6EAC6E;AAC7E,wBAAsB,kBAAkB,CACtC,GAAG,EAAE,IAAI,EACT,iBAAiB,CAAC,EAAE,WAAW,GAC9B,OAAO,CAAC,IAAI,CAAC,CA8Bf;AAED,eAAO,MAAM,oBAAoB;aACtB,IAAI;CAKd,CAAC"}