@leavewhite9088/harness-bus 0.2.0 → 0.2.1

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 (104) hide show
  1. package/ARCHITECTURE.md +81 -81
  2. package/LICENSE +21 -21
  3. package/README.md +86 -86
  4. package/SETUP_FOR_AI.md +79 -79
  5. package/package.json +4 -2
  6. package/packages/agentd/agentd.config.json +3 -1
  7. package/packages/agentd/cli/commands.mjs +854 -810
  8. package/packages/agentd/cli/format.mjs +294 -238
  9. package/packages/agentd/cli/hbus.mjs +14 -14
  10. package/packages/agentd/cli/index.mjs +4 -4
  11. package/packages/agentd/cli/skill/SKILL.md +66 -61
  12. package/packages/agentd/cli/skill/references/custom.md +12 -0
  13. package/packages/agentd/cli/skill/references/playbooks.md +89 -86
  14. package/packages/agentd/cli/skill/references/routing.md +43 -35
  15. package/packages/agentd/cli/skill-install.mjs +157 -140
  16. package/packages/agentd/cli/update.mjs +221 -221
  17. package/packages/agentd/client/index.mjs +3 -3
  18. package/packages/agentd/contexts/executor.md +13 -12
  19. package/packages/agentd/contexts/templates/architect.md +12 -12
  20. package/packages/agentd/contexts/templates/coder.md +12 -12
  21. package/packages/agentd/contexts/templates/debugger.md +12 -12
  22. package/packages/agentd/contexts/templates/researcher.md +12 -12
  23. package/packages/agentd/contexts/templates/reviewer.md +12 -12
  24. package/packages/agentd/contexts/templates/tester.md +12 -12
  25. package/packages/agentd/core/base/data-dir.mjs +39 -39
  26. package/packages/agentd/core/base/index.mjs +5 -5
  27. package/packages/agentd/core/base/protocol.mjs +13 -13
  28. package/packages/agentd/core/env/config.mjs +52 -1
  29. package/packages/agentd/core/env/index.mjs +6 -1
  30. package/packages/agentd/core/env/install.mjs +82 -4
  31. package/packages/agentd/core/pi/index.mjs +1 -1
  32. package/packages/agentd/core/pi/rpc.mjs +206 -206
  33. package/packages/agentd/core/pool/acp/client.mjs +7 -9
  34. package/packages/agentd/core/pool/acp/process.mjs +27 -18
  35. package/packages/agentd/core/pool/acp/run-tracker.mjs +293 -293
  36. package/packages/agentd/core/pool/acp/sessions.mjs +465 -465
  37. package/packages/agentd/core/pool/acp/turn-runner.mjs +5 -3
  38. package/packages/agentd/core/pool/index.mjs +2 -2
  39. package/packages/agentd/core/pool/instances.mjs +3 -5
  40. package/packages/agentd/core/pool/probe.mjs +91 -85
  41. package/packages/agentd/core/pool/registry.mjs +45 -1
  42. package/packages/agentd/core/pool/support/compaction.mjs +2 -43
  43. package/packages/agentd/core/pool/support/index.mjs +1 -1
  44. package/packages/agentd/core/prompts/index.mjs +12 -12
  45. package/packages/agentd/core/prompts/rules.mjs +22 -22
  46. package/packages/agentd/core/prompts/templates.mjs +172 -172
  47. package/packages/agentd/core/providers/index.mjs +14 -14
  48. package/packages/agentd/core/providers/store.mjs +206 -206
  49. package/packages/agentd/core/records/cleanup.mjs +51 -51
  50. package/packages/agentd/core/records/index.mjs +8 -8
  51. package/packages/agentd/core/records/metrics.mjs +73 -73
  52. package/packages/agentd/core/records/recovery.mjs +39 -39
  53. package/packages/agentd/core/records/transcripts.mjs +122 -122
  54. package/packages/agentd/core/threads/index.mjs +18 -17
  55. package/packages/agentd/core/threads/manager.mjs +498 -476
  56. package/packages/agentd/core/threads/paths.mjs +78 -78
  57. package/packages/agentd/core/threads/store.mjs +146 -125
  58. package/packages/agentd/daemon/agentd.mjs +58 -58
  59. package/packages/agentd/daemon/events.mjs +126 -126
  60. package/packages/agentd/daemon/guard.mjs +127 -127
  61. package/packages/agentd/daemon/lifecycle.mjs +61 -61
  62. package/packages/agentd/daemon/ops/index.mjs +15 -15
  63. package/packages/agentd/daemon/ops/providers.mjs +46 -46
  64. package/packages/agentd/daemon/ops/run.mjs +413 -400
  65. package/packages/agentd/daemon/ops/system.mjs +76 -69
  66. package/packages/agentd/daemon/ops/threads.mjs +156 -153
  67. package/packages/agentd/daemon/server.mjs +130 -130
  68. package/packages/agentd/package.json +1 -1
  69. package/packages/agentd/pi-adapter/acp-adapter.mjs +501 -501
  70. package/packages/agentd/scripts/restart-daemon.mjs +74 -74
  71. package/packages/agentd/scripts/run-isolated.mjs +42 -42
  72. package/packages/agentd/scripts/run-unit.mjs +28 -28
  73. package/packages/backend/src/daemon.mjs +69 -69
  74. package/packages/backend/src/server.mjs +270 -270
  75. package/packages/drivers/{agy.mjs → agy/index.mjs} +2 -1
  76. package/packages/drivers/{claude.mjs → claude/index.mjs} +23 -1
  77. package/packages/drivers/{codex.mjs → codex/index.mjs} +2 -1
  78. package/packages/drivers/{dsh.mjs → dsh/index.mjs} +3 -2
  79. package/packages/drivers/grok/index.mjs +96 -0
  80. package/packages/drivers/index.mjs +25 -12
  81. package/packages/drivers/{kimi.mjs → kimi/index.mjs} +2 -1
  82. package/packages/drivers/{mcode.mjs → mcode/index.mjs} +2 -1
  83. package/packages/drivers/{opencode.mjs → opencode/index.mjs} +2 -1
  84. package/packages/drivers/{pi.mjs → pi/index.mjs} +3 -2
  85. package/packages/drivers/probes/acp.mjs +109 -109
  86. package/packages/drivers/probes/index.mjs +131 -129
  87. package/packages/drivers/probes/provider.mjs +222 -222
  88. package/packages/drivers/qoder/index.mjs +32 -0
  89. package/packages/drivers/{bin.mjs → shared/bin.mjs} +2 -0
  90. package/packages/drivers/shared/index.mjs +2 -0
  91. package/packages/preflight/bin/preflight.mjs +116 -116
  92. package/packages/preflight/src/index.mjs +5 -5
  93. package/packages/preflight/src/report.mjs +18 -1
  94. package/packages/web/dist/apple-touch-icon.png +0 -0
  95. package/packages/web/dist/assets/index-CT8dIwav.css +2 -0
  96. package/packages/web/dist/assets/index-CypTUMFB.js +79 -0
  97. package/packages/web/dist/favicon-32.png +0 -0
  98. package/packages/web/dist/favicon.svg +19 -15
  99. package/packages/web/dist/index.html +5 -5
  100. package/packages/web/dist/assets/index-B2kdkHNw.js +0 -79
  101. package/packages/web/dist/assets/index-DQTyjC4x.css +0 -2
  102. /package/packages/drivers/{dsh-sessions.mjs → dsh/sessions.mjs} +0 -0
  103. /package/packages/drivers/{pi-catalog.mjs → pi/catalog.mjs} +0 -0
  104. /package/packages/drivers/{lib.mjs → shared/lib.mjs} +0 -0
@@ -1,78 +1,78 @@
1
- import { createHash } from 'node:crypto';
2
- import { existsSync, realpathSync, statSync } from 'node:fs';
3
- import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
-
5
- const isWin = process.platform === 'win32';
6
- const normCmp = (p) => (isWin ? p.toLowerCase() : p);
7
-
8
- function realAnchor(p) {
9
- let cur = resolve(p);
10
- const tail = [];
11
- while (!existsSync(cur)) {
12
- const parent = dirname(cur);
13
- if (parent === cur) break;
14
- tail.unshift(basename(cur));
15
- cur = parent;
16
- }
17
- let base = cur;
18
- try {
19
- base = realpathSync(cur);
20
- } catch {
21
- }
22
- return tail.length ? resolve(base, ...tail) : base;
23
- }
24
-
25
- export function canonicalDir(dir) {
26
- const raw = String(dir ?? '').trim();
27
- if (!raw) throw new Error('a working directory (cwd) is required');
28
- const abs = resolve(raw);
29
- if (!existsSync(abs)) throw new Error(`working directory does not exist: ${abs}`);
30
- if (!statSync(abs).isDirectory()) throw new Error(`working path is not a directory: ${abs}`);
31
- try {
32
- return realpathSync(abs);
33
- } catch {
34
- return abs;
35
- }
36
- }
37
-
38
- export function resolveInside(root, target = '.') {
39
- const realRoot = realAnchor(root);
40
- const raw = String(target ?? '.').trim() || '.';
41
- const candidate = isAbsolute(raw) ? resolve(raw) : resolve(realRoot, raw);
42
- const realTarget = realAnchor(candidate);
43
- const rel = relative(normCmp(realRoot), normCmp(realTarget));
44
- if (rel.startsWith('..') || isAbsolute(rel)) {
45
- throw new Error(`path "${raw}" escapes workspace root "${realRoot}"`);
46
- }
47
- return realTarget;
48
- }
49
-
50
- export function workspaceIdOf(root) {
51
- const canon = normCmp(resolve(root)).replace(/[\\/]+$/, '');
52
- const hash = createHash('sha1').update(canon).digest('hex').slice(0, 8);
53
- const slug = basename(resolve(root))
54
- .toLowerCase()
55
- .replace(/[^a-z0-9_-]+/g, '-')
56
- .replace(/^-+|-+$/g, '')
57
- .slice(0, 24);
58
- return `ws-${slug || 'dir'}-${hash}`;
59
- }
60
-
61
- export function threadIdForTopic(topic) {
62
- const trimmed = String(topic ?? '').trim();
63
- if (!trimmed) throw new Error('topic cannot be empty');
64
- if (/^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/.test(trimmed)) return trimmed;
65
- const hash = createHash('sha1').update(trimmed).digest('hex').slice(0, 10);
66
- const ascii = trimmed
67
- .toLowerCase()
68
- .replace(/[^a-z0-9_-]+/g, '-')
69
- .replace(/^-+|-+$/g, '')
70
- .slice(0, 18);
71
- return ascii ? `${ascii}-${hash.slice(0, 6)}` : `topic-${hash}`;
72
- }
73
-
74
- export function relativeInside(root, target) {
75
- const abs = resolveInside(root, target);
76
- const rel = relative(realAnchor(root), abs).split(sep).join('/');
77
- return rel || '.';
78
- }
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, realpathSync, statSync } from 'node:fs';
3
+ import { basename, dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
+
5
+ const isWin = process.platform === 'win32';
6
+ const normCmp = (p) => (isWin ? p.toLowerCase() : p);
7
+
8
+ function realAnchor(p) {
9
+ let cur = resolve(p);
10
+ const tail = [];
11
+ while (!existsSync(cur)) {
12
+ const parent = dirname(cur);
13
+ if (parent === cur) break;
14
+ tail.unshift(basename(cur));
15
+ cur = parent;
16
+ }
17
+ let base = cur;
18
+ try {
19
+ base = realpathSync(cur);
20
+ } catch {
21
+ }
22
+ return tail.length ? resolve(base, ...tail) : base;
23
+ }
24
+
25
+ export function canonicalDir(dir) {
26
+ const raw = String(dir ?? '').trim();
27
+ if (!raw) throw new Error('a working directory (cwd) is required');
28
+ const abs = resolve(raw);
29
+ if (!existsSync(abs)) throw new Error(`working directory does not exist: ${abs}`);
30
+ if (!statSync(abs).isDirectory()) throw new Error(`working path is not a directory: ${abs}`);
31
+ try {
32
+ return realpathSync(abs);
33
+ } catch {
34
+ return abs;
35
+ }
36
+ }
37
+
38
+ export function resolveInside(root, target = '.') {
39
+ const realRoot = realAnchor(root);
40
+ const raw = String(target ?? '.').trim() || '.';
41
+ const candidate = isAbsolute(raw) ? resolve(raw) : resolve(realRoot, raw);
42
+ const realTarget = realAnchor(candidate);
43
+ const rel = relative(normCmp(realRoot), normCmp(realTarget));
44
+ if (rel.startsWith('..') || isAbsolute(rel)) {
45
+ throw new Error(`path "${raw}" escapes workspace root "${realRoot}"`);
46
+ }
47
+ return realTarget;
48
+ }
49
+
50
+ export function workspaceIdOf(root) {
51
+ const canon = normCmp(resolve(root)).replace(/[\\/]+$/, '');
52
+ const hash = createHash('sha1').update(canon).digest('hex').slice(0, 8);
53
+ const slug = basename(resolve(root))
54
+ .toLowerCase()
55
+ .replace(/[^a-z0-9_-]+/g, '-')
56
+ .replace(/^-+|-+$/g, '')
57
+ .slice(0, 24);
58
+ return `ws-${slug || 'dir'}-${hash}`;
59
+ }
60
+
61
+ export function threadIdForTopic(topic) {
62
+ const trimmed = String(topic ?? '').trim();
63
+ if (!trimmed) throw new Error('topic cannot be empty');
64
+ if (/^[A-Za-z0-9][A-Za-z0-9._-]{0,39}$/.test(trimmed)) return trimmed;
65
+ const hash = createHash('sha1').update(trimmed).digest('hex').slice(0, 10);
66
+ const ascii = trimmed
67
+ .toLowerCase()
68
+ .replace(/[^a-z0-9_-]+/g, '-')
69
+ .replace(/^-+|-+$/g, '')
70
+ .slice(0, 18);
71
+ return ascii ? `${ascii}-${hash.slice(0, 6)}` : `topic-${hash}`;
72
+ }
73
+
74
+ export function relativeInside(root, target) {
75
+ const abs = resolveInside(root, target);
76
+ const rel = relative(realAnchor(root), abs).split(sep).join('/');
77
+ return rel || '.';
78
+ }
@@ -1,125 +1,146 @@
1
- import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
2
- import { basename, join } from 'node:path';
3
- import { PROJECT_SEP, WORKSPACES_DIR, atomicWriteJson, ensureDir } from '../base/index.mjs';
4
-
5
- export const SEP = PROJECT_SEP;
6
- export const keyOf = (workspaceId, threadId) => `${workspaceId}${SEP}${threadId}`;
7
- export const EPHEMERAL_KEEP_MAX = 20;
8
- export const EPHEMERAL_KEEP_MS = 24 * 3600 * 1000;
9
-
10
- const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
11
-
12
- export function checkId(kind, id) {
13
- if (!ID_RE.test(String(id ?? ''))) {
14
- throw new Error(`${kind} id must be 1-64 safe characters starting with a letter or digit`);
15
- }
16
- }
17
-
18
- export const workspaceFile = (workspaceId) => join(WORKSPACES_DIR, workspaceId, 'threads.json');
19
-
20
- const workspaces = new Map();
21
-
22
- export function allWorkspaces() {
23
- return [...workspaces.values()];
24
- }
25
-
26
- export function getWorkspace(id) {
27
- return workspaces.get(id) ?? null;
28
- }
29
-
30
- export function findWorkspaceByRoot(root) {
31
- const cmp = process.platform === 'win32' ? root.toLowerCase() : root;
32
- for (const ws of workspaces.values()) {
33
- const wCmp = process.platform === 'win32' ? ws.root.toLowerCase() : ws.root;
34
- if (wCmp === cmp) return ws;
35
- }
36
- return null;
37
- }
38
-
39
- export function pruneEphemeralList(list, { now = Date.now(), keepMax = EPHEMERAL_KEEP_MAX, keepMs = EPHEMERAL_KEEP_MS, busyIds = null } = {}) {
40
- const persistent = [];
41
- const ephemeral = [];
42
- for (const t of list ?? []) {
43
- if (!t.ephemeral) {
44
- persistent.push(t);
45
- continue;
46
- }
47
- const ts = Date.parse(t.lastActiveAt || t.createdAt || '') || now;
48
- if (busyIds?.has(t.id) || now - ts <= keepMs) ephemeral.push(t);
49
- }
50
- ephemeral.sort((a, b) => Number(Boolean(busyIds?.has(b.id))) - Number(Boolean(busyIds?.has(a.id))) || String(b.lastActiveAt || b.createdAt || '').localeCompare(String(a.lastActiveAt || a.createdAt || '')));
51
- const busyCount = busyIds ? ephemeral.filter((t) => busyIds.has(t.id)).length : 0;
52
- return [...persistent, ...ephemeral.slice(0, Math.max(keepMax, busyCount))];
53
- }
54
-
55
- export function saveWorkspace(ws, { busyIds = null } = {}) {
56
- const before = Array.isArray(ws.threads) ? ws.threads : [];
57
- const trimmed = pruneEphemeralList(before, { busyIds });
58
- const keptIds = new Set(trimmed.map((t) => t.id));
59
- const dropped = before.filter((t) => !keptIds.has(t.id));
60
- ws.threads = trimmed;
61
- const payload = {
62
- id: ws.id,
63
- root: ws.root,
64
- label: ws.label || basename(ws.root) || ws.id,
65
- updatedAt: ws.updatedAt || new Date().toISOString(),
66
- threads: trimmed,
67
- };
68
- ensureDir(join(WORKSPACES_DIR, ws.id));
69
- atomicWriteJson(workspaceFile(ws.id), payload);
70
- return { dropped };
71
- }
72
-
73
- export function upsertWorkspace({ id, root, label }) {
74
- let ws = workspaces.get(id);
75
- if (!ws) {
76
- ws = {
77
- id,
78
- root,
79
- label: label || basename(root) || id,
80
- updatedAt: new Date().toISOString(),
81
- threads: [],
82
- };
83
- workspaces.set(id, ws);
84
- saveWorkspace(ws);
85
- }
86
- return ws;
87
- }
88
-
89
- export function deleteWorkspace(id) {
90
- workspaces.delete(id);
91
- try {
92
- rmSync(join(WORKSPACES_DIR, id), { recursive: true, force: true });
93
- } catch {
94
- }
95
- }
96
-
97
- export function loadWorkspacesFromDisk() {
98
- workspaces.clear();
99
- if (!existsSync(WORKSPACES_DIR)) return [];
100
- for (const name of readdirSync(WORKSPACES_DIR)) {
101
- const dir = join(WORKSPACES_DIR, name);
102
- try {
103
- if (!statSync(dir).isDirectory()) continue;
104
- const file = workspaceFile(name);
105
- if (!existsSync(file)) continue;
106
- const raw = JSON.parse(readFileSync(file, 'utf8'));
107
- if (!raw || typeof raw !== 'object' || !raw.root) continue;
108
- const loaded = Array.isArray(raw.threads) ? raw.threads.map((t) => ({ ...t, ephemeral: Boolean(t.ephemeral) })) : [];
109
- const ws = {
110
- id: String(raw.id || name),
111
- root: String(raw.root),
112
- label: String(raw.label || basename(String(raw.root)) || name),
113
- updatedAt: raw.updatedAt || new Date().toISOString(),
114
- threads: pruneEphemeralList(loaded),
115
- };
116
- workspaces.set(ws.id, ws);
117
- } catch {
118
- }
119
- }
120
- return [...workspaces.values()];
121
- }
122
-
123
- export function clearMemoryStore() {
124
- workspaces.clear();
125
- }
1
+ import { existsSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs';
2
+ import { basename, join } from 'node:path';
3
+ import { PROJECT_SEP, WORKSPACES_DIR, atomicWriteJson, ensureDir } from '../base/index.mjs';
4
+
5
+ export const SEP = PROJECT_SEP;
6
+ export const keyOf = (workspaceId, threadId) => `${workspaceId}${SEP}${threadId}`;
7
+ export const NAMED_KEEP_MAX = 15;
8
+ export const EPHEMERAL_KEEP_MAX = 20;
9
+ export const EPHEMERAL_KEEP_MS = 24 * 3600 * 1000;
10
+
11
+ const ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
12
+
13
+ export function checkId(kind, id) {
14
+ if (!ID_RE.test(String(id ?? ''))) {
15
+ throw new Error(`${kind} id must be 1-64 safe characters starting with a letter or digit`);
16
+ }
17
+ }
18
+
19
+ export const workspaceFile = (workspaceId) => join(WORKSPACES_DIR, workspaceId, 'threads.json');
20
+
21
+ const workspaces = new Map();
22
+
23
+ export function allWorkspaces() {
24
+ return [...workspaces.values()];
25
+ }
26
+
27
+ export function getWorkspace(id) {
28
+ return workspaces.get(id) ?? null;
29
+ }
30
+
31
+ export function findWorkspaceByRoot(root) {
32
+ const cmp = process.platform === 'win32' ? root.toLowerCase() : root;
33
+ for (const ws of workspaces.values()) {
34
+ const wCmp = process.platform === 'win32' ? ws.root.toLowerCase() : ws.root;
35
+ if (wCmp === cmp) return ws;
36
+ }
37
+ return null;
38
+ }
39
+
40
+ function sortByRecency(entries, busyIds) {
41
+ entries.sort((a, b) => {
42
+ const busyDiff = Number(Boolean(busyIds?.has(b.item.id))) - Number(Boolean(busyIds?.has(a.item.id)));
43
+ if (busyDiff !== 0) return busyDiff;
44
+ const timeDiff = String(b.item.lastActiveAt || b.item.createdAt || '').localeCompare(String(a.item.lastActiveAt || a.item.createdAt || ''));
45
+ if (timeDiff !== 0) return timeDiff;
46
+ return a.idx - b.idx;
47
+ });
48
+ }
49
+
50
+ export function pruneThreadList(
51
+ list,
52
+ { now = Date.now(), namedKeepMax = NAMED_KEEP_MAX, keepMax = EPHEMERAL_KEEP_MAX, keepMs = EPHEMERAL_KEEP_MS, busyIds = null } = {},
53
+ ) {
54
+ const named = [];
55
+ const ephemeral = [];
56
+ (list ?? []).forEach((item, idx) => {
57
+ if (!item.ephemeral) {
58
+ named.push({ item, idx });
59
+ return;
60
+ }
61
+ const ts = Date.parse(item.lastActiveAt || item.createdAt || '') || now;
62
+ if (busyIds?.has(item.id) || now - ts <= keepMs) ephemeral.push({ item, idx });
63
+ });
64
+ sortByRecency(named, busyIds);
65
+ sortByRecency(ephemeral, busyIds);
66
+ const busyNamed = busyIds ? named.filter((e) => busyIds.has(e.item.id)).length : 0;
67
+ const busyEphemeral = busyIds ? ephemeral.filter((e) => busyIds.has(e.item.id)).length : 0;
68
+ return [
69
+ ...named.slice(0, Math.max(namedKeepMax, busyNamed)).map((e) => e.item),
70
+ ...ephemeral.slice(0, Math.max(keepMax, busyEphemeral)).map((e) => e.item),
71
+ ];
72
+ }
73
+
74
+ export const pruneEphemeralList = pruneThreadList;
75
+
76
+ export function saveWorkspace(ws, { busyIds = null, namedKeepMax = NAMED_KEEP_MAX } = {}) {
77
+ const before = Array.isArray(ws.threads) ? ws.threads : [];
78
+ const trimmed = pruneThreadList(before, { busyIds, namedKeepMax });
79
+ const keptIds = new Set(trimmed.map((t) => t.id));
80
+ const dropped = before.filter((t) => !keptIds.has(t.id));
81
+ ws.threads = trimmed;
82
+ const payload = {
83
+ id: ws.id,
84
+ root: ws.root,
85
+ label: ws.label || basename(ws.root) || ws.id,
86
+ updatedAt: ws.updatedAt || new Date().toISOString(),
87
+ threads: trimmed,
88
+ };
89
+ ensureDir(join(WORKSPACES_DIR, ws.id));
90
+ atomicWriteJson(workspaceFile(ws.id), payload);
91
+ return { dropped };
92
+ }
93
+
94
+ export function upsertWorkspace({ id, root, label }) {
95
+ let ws = workspaces.get(id);
96
+ if (!ws) {
97
+ ws = {
98
+ id,
99
+ root,
100
+ label: label || basename(root) || id,
101
+ updatedAt: new Date().toISOString(),
102
+ threads: [],
103
+ };
104
+ workspaces.set(id, ws);
105
+ saveWorkspace(ws);
106
+ }
107
+ return ws;
108
+ }
109
+
110
+ export function deleteWorkspace(id) {
111
+ workspaces.delete(id);
112
+ try {
113
+ rmSync(join(WORKSPACES_DIR, id), { recursive: true, force: true });
114
+ } catch {
115
+ }
116
+ }
117
+
118
+ export function loadWorkspacesFromDisk() {
119
+ workspaces.clear();
120
+ if (!existsSync(WORKSPACES_DIR)) return [];
121
+ for (const name of readdirSync(WORKSPACES_DIR)) {
122
+ const dir = join(WORKSPACES_DIR, name);
123
+ try {
124
+ if (!statSync(dir).isDirectory()) continue;
125
+ const file = workspaceFile(name);
126
+ if (!existsSync(file)) continue;
127
+ const raw = JSON.parse(readFileSync(file, 'utf8'));
128
+ if (!raw || typeof raw !== 'object' || !raw.root) continue;
129
+ const loaded = Array.isArray(raw.threads) ? raw.threads.map((t) => ({ ...t, ephemeral: Boolean(t.ephemeral) })) : [];
130
+ const ws = {
131
+ id: String(raw.id || name),
132
+ root: String(raw.root),
133
+ label: String(raw.label || basename(String(raw.root)) || name),
134
+ updatedAt: raw.updatedAt || new Date().toISOString(),
135
+ threads: pruneThreadList(loaded),
136
+ };
137
+ workspaces.set(ws.id, ws);
138
+ } catch {
139
+ }
140
+ }
141
+ return [...workspaces.values()];
142
+ }
143
+
144
+ export function clearMemoryStore() {
145
+ workspaces.clear();
146
+ }
@@ -1,58 +1,58 @@
1
- import { CONFIG, ENDPOINT_FILE, PIPE_NAME, PORT, PROTOCOL, isMainModule, loadConfig } from '../core/base/index.mjs';
2
- import { pool, seedContexts } from '../core/pool/index.mjs';
3
- import { initRecords, pruneAllRunLogs, readReceipts, recordInterruptedJobs } from '../core/records/index.mjs';
4
- import * as threads from '../core/threads/index.mjs';
5
- import { allocEvent, publish, publishEphemeral, publishLive } from './events.mjs';
6
- import { scopeArgs } from './guard.mjs';
7
- import { startLifecycle } from './lifecycle.mjs';
8
- import { buildOps } from './ops/index.mjs';
9
- import { startServer } from './server.mjs';
10
-
11
- const log = (...a) => process.stderr.write(`[agentd] ${a.join(' ')}\n`);
12
-
13
- export function boot() {
14
- const cfg = loadConfig();
15
- const idleMs = Number(process.env.AGENTD_IDLE_MIN || 30) * 60_000;
16
- const idleInstanceMs = Number(process.env.AGENTD_INSTANCE_IDLE_MIN || cfg?.limits?.idleMinutes || CONFIG?.limits?.idleMinutes || 15) * 60_000;
17
- const startedAt = new Date().toISOString();
18
-
19
- const pruned = pruneAllRunLogs();
20
- if (pruned) log(`removed ${pruned} run logs older than 14 days`);
21
-
22
- initRecords();
23
- threads.setThreadHooks({
24
- onProgress: (agent, jobId, payload) => publishEphemeral(jobId, { thread: agent.name, agent: agent.name, ...payload }),
25
- onRunStart: (agent, info) => publishLive('job.running', { thread: agent.name, agent: agent.name, ...info }),
26
- onExit: (agent, info) => publishLive('agent.exit', { thread: agent.name, agent: agent.name, ...info }),
27
- onForcedStop: (agent, info) => publishLive('agent.forced-stop', { thread: agent.name, agent: agent.name, ...info }),
28
- onCompact: (agent, info) => publishLive('agent.compacted', { thread: agent.name, agent: agent.name, ...info }),
29
- });
30
- threads.initThreads();
31
-
32
- const lostJobs = recordInterruptedJobs();
33
-
34
- let lifecycle;
35
- const ops = buildOps({ protocol: PROTOCOL, startedAt, idleInstanceMs, shutdown: (code) => lifecycle.shutdown(code) });
36
-
37
- const { stats } = startServer({
38
- ops,
39
- scopeArgs,
40
- pipe: PIPE_NAME,
41
- port: PORT,
42
- endpointFile: ENDPOINT_FILE,
43
- info: { protocol: PROTOCOL, startedAt },
44
- onListening: (endpoint) => {
45
- seedContexts(readReceipts(500));
46
- for (const j of lostJobs) publish(allocEvent('job.interrupted', { ...j }));
47
- if (lostJobs.length) log(`interrupted by the last shutdown: ${lostJobs.map((j) => `${j.agent}/${j.jobId}`).join(', ')}`);
48
- log(`listening on ${endpoint} (pid ${process.pid})`);
49
- log(`threads: ${[...pool.keys()].join(', ') || '(none yet: created on demand)'}`);
50
- },
51
- log,
52
- });
53
-
54
- lifecycle = startLifecycle({ endpointFile: ENDPOINT_FILE, socketPath: PORT ? null : PIPE_NAME, pool, sweepIdle: threads.sweepIdle, stats, idleMs, idleInstanceMs, log });
55
- return { stats, lifecycle };
56
- }
57
-
58
- if (isMainModule(import.meta.url)) boot();
1
+ import { CONFIG, ENDPOINT_FILE, PIPE_NAME, PORT, PROTOCOL, isMainModule, loadConfig } from '../core/base/index.mjs';
2
+ import { pool, seedContexts } from '../core/pool/index.mjs';
3
+ import { initRecords, pruneAllRunLogs, readReceipts, recordInterruptedJobs } from '../core/records/index.mjs';
4
+ import * as threads from '../core/threads/index.mjs';
5
+ import { allocEvent, publish, publishEphemeral, publishLive } from './events.mjs';
6
+ import { scopeArgs } from './guard.mjs';
7
+ import { startLifecycle } from './lifecycle.mjs';
8
+ import { buildOps } from './ops/index.mjs';
9
+ import { startServer } from './server.mjs';
10
+
11
+ const log = (...a) => process.stderr.write(`[agentd] ${a.join(' ')}\n`);
12
+
13
+ export function boot() {
14
+ const cfg = loadConfig();
15
+ const idleMs = Number(process.env.AGENTD_IDLE_MIN || 30) * 60_000;
16
+ const idleInstanceMs = Number(process.env.AGENTD_INSTANCE_IDLE_MIN || cfg?.limits?.idleMinutes || CONFIG?.limits?.idleMinutes || 15) * 60_000;
17
+ const startedAt = new Date().toISOString();
18
+
19
+ const pruned = pruneAllRunLogs();
20
+ if (pruned) log(`removed ${pruned} run logs older than 14 days`);
21
+
22
+ initRecords();
23
+ threads.setThreadHooks({
24
+ onProgress: (agent, jobId, payload) => publishEphemeral(jobId, { thread: agent.name, agent: agent.name, ...payload }),
25
+ onRunStart: (agent, info) => publishLive('job.running', { thread: agent.name, agent: agent.name, ...info }),
26
+ onExit: (agent, info) => publishLive('agent.exit', { thread: agent.name, agent: agent.name, ...info }),
27
+ onForcedStop: (agent, info) => publishLive('agent.forced-stop', { thread: agent.name, agent: agent.name, ...info }),
28
+ onCompact: (agent, info) => publishLive('agent.compacted', { thread: agent.name, agent: agent.name, ...info }),
29
+ });
30
+ threads.initThreads();
31
+
32
+ const lostJobs = recordInterruptedJobs();
33
+
34
+ let lifecycle;
35
+ const ops = buildOps({ protocol: PROTOCOL, startedAt, idleInstanceMs, shutdown: (code) => lifecycle.shutdown(code) });
36
+
37
+ const { stats } = startServer({
38
+ ops,
39
+ scopeArgs,
40
+ pipe: PIPE_NAME,
41
+ port: PORT,
42
+ endpointFile: ENDPOINT_FILE,
43
+ info: { protocol: PROTOCOL, startedAt },
44
+ onListening: (endpoint) => {
45
+ seedContexts(readReceipts(500));
46
+ for (const j of lostJobs) publish(allocEvent('job.interrupted', { ...j }));
47
+ if (lostJobs.length) log(`interrupted by the last shutdown: ${lostJobs.map((j) => `${j.agent}/${j.jobId}`).join(', ')}`);
48
+ log(`listening on ${endpoint} (pid ${process.pid})`);
49
+ log(`threads: ${[...pool.keys()].join(', ') || '(none yet: created on demand)'}`);
50
+ },
51
+ log,
52
+ });
53
+
54
+ lifecycle = startLifecycle({ endpointFile: ENDPOINT_FILE, socketPath: PORT ? null : PIPE_NAME, pool, sweepIdle: threads.sweepIdle, stats, idleMs, idleInstanceMs, log });
55
+ return { stats, lifecycle };
56
+ }
57
+
58
+ if (isMainModule(import.meta.url)) boot();