@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,73 +1,73 @@
1
- import { readAudits, readReceipts } from './receipts.mjs';
2
-
3
- const escProm = (v) => String(v ?? '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
4
-
5
- export function computeMetrics({ windowSec, queues = [] } = {}) {
6
- const winMs = Math.max(10, Number(windowSec) || 300) * 1000;
7
- const cutoff = Date.now() - winMs;
8
- const allReceipts = readReceipts(500);
9
- const allAudits = readAudits(500);
10
-
11
- const invCounts = new Map();
12
- const durations = [];
13
- let recentRuns = 0;
14
- let recentFailed = 0;
15
-
16
- for (const r of allReceipts) {
17
- const agent = r.agent || 'unknown';
18
- const status = r.status || 'done';
19
- const key = `${agent}|${status}`;
20
- invCounts.set(key, (invCounts.get(key) ?? 0) + 1);
21
- if (Number.isFinite(r.durationMs) && r.durationMs >= 0) durations.push(r.durationMs);
22
- const ts = Date.parse(r.ts || '');
23
- if (ts >= cutoff) {
24
- recentRuns++;
25
- if (status === 'failed') recentFailed++;
26
- }
27
- }
28
- durations.sort((a, b) => a - b);
29
- const p95Ms = durations.length ? durations[Math.min(durations.length - 1, Math.floor(durations.length * 0.95))] : 0;
30
-
31
- const recentDenied = allAudits.filter((a) => a.status === 'denied' && Date.parse(a.ts || '') >= cutoff).length;
32
- const recentErrRate = recentRuns > 0 ? recentFailed / recentRuns : 0;
33
-
34
- const alertFiring = recentDenied >= 3 || (recentRuns >= 5 && recentErrRate > 0.05);
35
- const alert = {
36
- rule: '5 分钟窗口内越权拒绝 >= 3 次 或 任务错误率 > 5%(样本 >= 5) -> 标记 FIRING 并写入告警通知记录(附 /api/metrics 与 /api/audits 排查入口)',
37
- state: alertFiring ? 'FIRING' : 'OK',
38
- windowSec: winMs / 1000,
39
- recentDenied,
40
- recentRuns,
41
- recentFailed,
42
- action: alertFiring ? 'notify-maintainer: inspect /api/audits and /api/receipts' : 'none',
43
- };
44
-
45
- const promLines = [
46
- '# HELP agent_invocations_total Total executor invocations partitioned by agent and status.',
47
- '# TYPE agent_invocations_total counter',
48
- ...[...invCounts.entries()].map(([k, v]) => {
49
- const [ag, st] = k.split('|');
50
- return `agent_invocations_total{agent="${escProm(ag)}",status="${escProm(st)}"} ${v}`;
51
- }),
52
- '# HELP agent_invocation_p95_ms 95th percentile invocation duration in milliseconds.',
53
- '# TYPE agent_invocation_p95_ms gauge',
54
- `agent_invocation_p95_ms ${p95Ms}`,
55
- '# HELP agent_queue_depth Current waiting + inflight tasks per executor.',
56
- '# TYPE agent_queue_depth gauge',
57
- ...queues.map((q) => `agent_queue_depth{agent="${escProm(q.agent)}"} ${q.inflight}`),
58
- '# HELP security_audit_denied_recent Rejected unauthorized calls within the alert window.',
59
- '# TYPE security_audit_denied_recent gauge',
60
- `security_audit_denied_recent ${recentDenied}`,
61
- '# HELP system_alert_firing 1 when the 3-part alert rule is firing, else 0.',
62
- '# TYPE system_alert_firing gauge',
63
- `system_alert_firing ${alertFiring ? 1 : 0}`,
64
- ];
65
-
66
- return {
67
- invocations: Object.fromEntries(invCounts),
68
- p95DurationMs: p95Ms,
69
- queues,
70
- alert,
71
- prometheus: promLines.join('\n') + '\n',
72
- };
73
- }
1
+ import { readAudits, readReceipts } from './receipts.mjs';
2
+
3
+ const escProm = (v) => String(v ?? '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n');
4
+
5
+ export function computeMetrics({ windowSec, queues = [] } = {}) {
6
+ const winMs = Math.max(10, Number(windowSec) || 300) * 1000;
7
+ const cutoff = Date.now() - winMs;
8
+ const allReceipts = readReceipts(500);
9
+ const allAudits = readAudits(500);
10
+
11
+ const invCounts = new Map();
12
+ const durations = [];
13
+ let recentRuns = 0;
14
+ let recentFailed = 0;
15
+
16
+ for (const r of allReceipts) {
17
+ const agent = r.agent || 'unknown';
18
+ const status = r.status || 'done';
19
+ const key = `${agent}|${status}`;
20
+ invCounts.set(key, (invCounts.get(key) ?? 0) + 1);
21
+ if (Number.isFinite(r.durationMs) && r.durationMs >= 0) durations.push(r.durationMs);
22
+ const ts = Date.parse(r.ts || '');
23
+ if (ts >= cutoff) {
24
+ recentRuns++;
25
+ if (status === 'failed') recentFailed++;
26
+ }
27
+ }
28
+ durations.sort((a, b) => a - b);
29
+ const p95Ms = durations.length ? durations[Math.min(durations.length - 1, Math.floor(durations.length * 0.95))] : 0;
30
+
31
+ const recentDenied = allAudits.filter((a) => a.status === 'denied' && Date.parse(a.ts || '') >= cutoff).length;
32
+ const recentErrRate = recentRuns > 0 ? recentFailed / recentRuns : 0;
33
+
34
+ const alertFiring = recentDenied >= 3 || (recentRuns >= 5 && recentErrRate > 0.05);
35
+ const alert = {
36
+ rule: '5 分钟窗口内越权拒绝 >= 3 次 或 任务错误率 > 5%(样本 >= 5) -> 标记 FIRING 并写入告警通知记录(附 /api/metrics 与 /api/audits 排查入口)',
37
+ state: alertFiring ? 'FIRING' : 'OK',
38
+ windowSec: winMs / 1000,
39
+ recentDenied,
40
+ recentRuns,
41
+ recentFailed,
42
+ action: alertFiring ? 'notify-maintainer: inspect /api/audits and /api/receipts' : 'none',
43
+ };
44
+
45
+ const promLines = [
46
+ '# HELP agent_invocations_total Total executor invocations partitioned by agent and status.',
47
+ '# TYPE agent_invocations_total counter',
48
+ ...[...invCounts.entries()].map(([k, v]) => {
49
+ const [ag, st] = k.split('|');
50
+ return `agent_invocations_total{agent="${escProm(ag)}",status="${escProm(st)}"} ${v}`;
51
+ }),
52
+ '# HELP agent_invocation_p95_ms 95th percentile invocation duration in milliseconds.',
53
+ '# TYPE agent_invocation_p95_ms gauge',
54
+ `agent_invocation_p95_ms ${p95Ms}`,
55
+ '# HELP agent_queue_depth Current waiting + inflight tasks per executor.',
56
+ '# TYPE agent_queue_depth gauge',
57
+ ...queues.map((q) => `agent_queue_depth{agent="${escProm(q.agent)}"} ${q.inflight}`),
58
+ '# HELP security_audit_denied_recent Rejected unauthorized calls within the alert window.',
59
+ '# TYPE security_audit_denied_recent gauge',
60
+ `security_audit_denied_recent ${recentDenied}`,
61
+ '# HELP system_alert_firing 1 when the 3-part alert rule is firing, else 0.',
62
+ '# TYPE system_alert_firing gauge',
63
+ `system_alert_firing ${alertFiring ? 1 : 0}`,
64
+ ];
65
+
66
+ return {
67
+ invocations: Object.fromEntries(invCounts),
68
+ p95DurationMs: p95Ms,
69
+ queues,
70
+ alert,
71
+ prometheus: promLines.join('\n') + '\n',
72
+ };
73
+ }
@@ -1,39 +1,39 @@
1
- import { initJournal, interruptedOf, reconcileJournal } from './journal.mjs';
2
- import { appendReceipt } from './receipts.mjs';
3
- import { endRun, initTasks } from './tasks.mjs';
4
- import { appendEntry, findJobSession } from './transcripts.mjs';
5
-
6
- export function initRecords() {
7
- initJournal();
8
- initTasks();
9
- }
10
-
11
- export function recordInterruptedJobs() {
12
- const lostJobs = reconcileJournal();
13
- for (const j of lostJobs) {
14
- endRun(j.jobId, 'interrupted');
15
- const error = 'the daemon stopped while this task was queued or running; the executor may have done part of it';
16
- appendReceipt(
17
- j.agent,
18
- { sessionId: null, metrics: { jobId: j.jobId, outcome: 'interrupted', error, health: 'error', attention: [{ code: 'interrupted', severity: 'error', source: 'system', text: error }] } },
19
- j.prompt,
20
- null,
21
- j,
22
- );
23
- // The executor's own conversation must say so too: without this the person sees their message and then nothing.
24
- const sid = findJobSession(j.agent, j.jobId);
25
- if (sid) {
26
- appendEntry(j.agent, sid, {
27
- role: 'error',
28
- jobId: j.jobId,
29
- taskId: j.taskId,
30
- attempt: j.attempt,
31
- interrupted: true,
32
- error: '这次任务因服务重启被中断,没有得到回复。执行者可能已经做了一部分,请先检查文件,再决定要不要重发。',
33
- });
34
- }
35
- }
36
- return lostJobs;
37
- }
38
-
39
- export const withInterrupted = (rows, keyOf = (r) => r.id) => rows.map((r) => ({ ...r, interrupted: interruptedOf(keyOf(r)) }));
1
+ import { initJournal, interruptedOf, reconcileJournal } from './journal.mjs';
2
+ import { appendReceipt } from './receipts.mjs';
3
+ import { endRun, initTasks } from './tasks.mjs';
4
+ import { appendEntry, findJobSession } from './transcripts.mjs';
5
+
6
+ export function initRecords() {
7
+ initJournal();
8
+ initTasks();
9
+ }
10
+
11
+ export function recordInterruptedJobs() {
12
+ const lostJobs = reconcileJournal();
13
+ for (const j of lostJobs) {
14
+ endRun(j.jobId, 'interrupted');
15
+ const error = 'the daemon stopped while this task was queued or running; the executor may have done part of it';
16
+ appendReceipt(
17
+ j.agent,
18
+ { sessionId: null, metrics: { jobId: j.jobId, outcome: 'interrupted', error, health: 'error', attention: [{ code: 'interrupted', severity: 'error', source: 'system', text: error }] } },
19
+ j.prompt,
20
+ null,
21
+ j,
22
+ );
23
+ // The executor's own conversation must say so too: without this the person sees their message and then nothing.
24
+ const sid = findJobSession(j.agent, j.jobId);
25
+ if (sid) {
26
+ appendEntry(j.agent, sid, {
27
+ role: 'error',
28
+ jobId: j.jobId,
29
+ taskId: j.taskId,
30
+ attempt: j.attempt,
31
+ interrupted: true,
32
+ error: '这次任务因服务重启被中断,没有得到回复。执行者可能已经做了一部分,请先检查文件,再决定要不要重发。',
33
+ });
34
+ }
35
+ }
36
+ return lostJobs;
37
+ }
38
+
39
+ export const withInterrupted = (rows, keyOf = (r) => r.id) => rows.map((r) => ({ ...r, interrupted: interruptedOf(keyOf(r)) }));
@@ -1,122 +1,122 @@
1
- import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
- import { dirname, join } from 'node:path';
3
- import { instanceIdOf, projectDir, projectPath } from '../base/index.mjs';
4
-
5
- const safe = (s) => String(s).replace(/[^A-Za-z0-9._~-]/g, '_');
6
- const dirFor = (instance) => projectPath(instance, 'transcripts', safe(instanceIdOf(instance)));
7
- const fileFor = (instance, sessionId) => join(dirFor(instance), `${safe(sessionId)}.jsonl`);
8
-
9
- export function findJobSession(instance, jobId) {
10
- try {
11
- const dir = dirFor(instance);
12
- const files = readdirSync(dir)
13
- .filter((f) => f.endsWith('.jsonl'))
14
- .map((f) => ({ f, t: statSync(join(dir, f)).mtimeMs }))
15
- .sort((a, b) => b.t - a.t)
16
- .slice(0, 8);
17
- for (const { f } of files) {
18
- if (readFileSync(join(dir, f), 'utf8').includes(`"jobId":"${jobId}"`)) return f.slice(0, -'.jsonl'.length);
19
- }
20
- } catch {
21
- }
22
- return null;
23
- }
24
-
25
- export function appendEntry(instance, sessionId, entry) {
26
- if (!instance || !sessionId) return false;
27
- try {
28
- const file = fileFor(instance, sessionId);
29
- mkdirSync(dirname(file), { recursive: true });
30
- appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n', 'utf8');
31
- return true;
32
- } catch {
33
- return false;
34
- }
35
- }
36
-
37
- const indexes = new Map();
38
- const NEWLINE = 0x0a;
39
-
40
- function indexOf(file, size) {
41
- let ix = indexes.get(file);
42
- if (!ix || size < ix.size) ix = { size: 0, scanned: 0, starts: [], lineStart: 0, blank: true };
43
- if (size > ix.scanned) {
44
- const fd = openSync(file, 'r');
45
- try {
46
- const CHUNK = 1 << 20;
47
- const buf = Buffer.allocUnsafe(Math.min(CHUNK, size - ix.scanned));
48
- let pos = ix.scanned;
49
- while (pos < size) {
50
- const n = readSync(fd, buf, 0, Math.min(buf.length, size - pos), pos);
51
- if (n <= 0) break;
52
- for (let i = 0; i < n; i += 1) {
53
- const b = buf[i];
54
- if (b === NEWLINE) {
55
- if (!ix.blank) ix.starts.push(ix.lineStart);
56
- ix.lineStart = pos + i + 1;
57
- ix.blank = true;
58
- } else if (ix.blank && b !== 0x20 && b !== 0x0d && b !== 0x09) {
59
- ix.blank = false;
60
- }
61
- }
62
- pos += n;
63
- }
64
- ix.scanned = pos;
65
- } finally {
66
- closeSync(fd);
67
- }
68
- }
69
- ix.size = size;
70
- indexes.set(file, ix);
71
- return ix;
72
- }
73
-
74
- function readRange(file, from, to) {
75
- const fd = openSync(file, 'r');
76
- try {
77
- const buf = Buffer.allocUnsafe(Math.max(0, to - from));
78
- let got = 0;
79
- while (got < buf.length) {
80
- const n = readSync(fd, buf, got, buf.length - got, from + got);
81
- if (n <= 0) break;
82
- got += n;
83
- }
84
- return buf.toString('utf8', 0, got);
85
- } finally {
86
- closeSync(fd);
87
- }
88
- }
89
-
90
- export function readTranscript(instance, sessionId, { afterSeq = 0, limit = 200, tail = false } = {}) {
91
- const max = Math.min(Math.max(Number(limit) || 200, 1), 1000);
92
- const file = fileFor(instance, sessionId);
93
- if (!existsSync(file)) {
94
- return { agent: instance, sessionId, recorded: false, total: 0, entries: [], hasMore: false };
95
- }
96
-
97
- const ix = indexOf(file, statSync(file).size);
98
- const total = ix.starts.length;
99
- const after = Math.min(Math.max(Number(afterSeq) || 0, 0), total);
100
- const first = tail ? Math.max(after, total - max) : after;
101
- const last = Math.min(total, first + max);
102
- const entries = [];
103
- if (last > first) {
104
- const from = ix.starts[first];
105
- const to = last < total ? ix.starts[last] : ix.lineStart;
106
- const lines = readRange(file, from, to).split('\n').filter((l) => l.trim());
107
- lines.forEach((line, i) => {
108
- try {
109
- entries.push({ seq: first + i + 1, ...JSON.parse(line) });
110
- } catch {
111
- }
112
- });
113
- }
114
- return { agent: instance, sessionId, recorded: true, total, entries, hasMore: total - after > max };
115
- }
116
-
117
- export function forgetTranscripts(project) {
118
- const prefix = projectDir(project);
119
- for (const key of indexes.keys()) {
120
- if (key.startsWith(prefix)) indexes.delete(key);
121
- }
122
- }
1
+ import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { instanceIdOf, projectDir, projectPath } from '../base/index.mjs';
4
+
5
+ const safe = (s) => String(s).replace(/[^A-Za-z0-9._~-]/g, '_');
6
+ const dirFor = (instance) => projectPath(instance, 'transcripts', safe(instanceIdOf(instance)));
7
+ const fileFor = (instance, sessionId) => join(dirFor(instance), `${safe(sessionId)}.jsonl`);
8
+
9
+ export function findJobSession(instance, jobId) {
10
+ try {
11
+ const dir = dirFor(instance);
12
+ const files = readdirSync(dir)
13
+ .filter((f) => f.endsWith('.jsonl'))
14
+ .map((f) => ({ f, t: statSync(join(dir, f)).mtimeMs }))
15
+ .sort((a, b) => b.t - a.t)
16
+ .slice(0, 8);
17
+ for (const { f } of files) {
18
+ if (readFileSync(join(dir, f), 'utf8').includes(`"jobId":"${jobId}"`)) return f.slice(0, -'.jsonl'.length);
19
+ }
20
+ } catch {
21
+ }
22
+ return null;
23
+ }
24
+
25
+ export function appendEntry(instance, sessionId, entry) {
26
+ if (!instance || !sessionId) return false;
27
+ try {
28
+ const file = fileFor(instance, sessionId);
29
+ mkdirSync(dirname(file), { recursive: true });
30
+ appendFileSync(file, JSON.stringify({ ts: new Date().toISOString(), ...entry }) + '\n', 'utf8');
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ const indexes = new Map();
38
+ const NEWLINE = 0x0a;
39
+
40
+ function indexOf(file, size) {
41
+ let ix = indexes.get(file);
42
+ if (!ix || size < ix.size) ix = { size: 0, scanned: 0, starts: [], lineStart: 0, blank: true };
43
+ if (size > ix.scanned) {
44
+ const fd = openSync(file, 'r');
45
+ try {
46
+ const CHUNK = 1 << 20;
47
+ const buf = Buffer.allocUnsafe(Math.min(CHUNK, size - ix.scanned));
48
+ let pos = ix.scanned;
49
+ while (pos < size) {
50
+ const n = readSync(fd, buf, 0, Math.min(buf.length, size - pos), pos);
51
+ if (n <= 0) break;
52
+ for (let i = 0; i < n; i += 1) {
53
+ const b = buf[i];
54
+ if (b === NEWLINE) {
55
+ if (!ix.blank) ix.starts.push(ix.lineStart);
56
+ ix.lineStart = pos + i + 1;
57
+ ix.blank = true;
58
+ } else if (ix.blank && b !== 0x20 && b !== 0x0d && b !== 0x09) {
59
+ ix.blank = false;
60
+ }
61
+ }
62
+ pos += n;
63
+ }
64
+ ix.scanned = pos;
65
+ } finally {
66
+ closeSync(fd);
67
+ }
68
+ }
69
+ ix.size = size;
70
+ indexes.set(file, ix);
71
+ return ix;
72
+ }
73
+
74
+ function readRange(file, from, to) {
75
+ const fd = openSync(file, 'r');
76
+ try {
77
+ const buf = Buffer.allocUnsafe(Math.max(0, to - from));
78
+ let got = 0;
79
+ while (got < buf.length) {
80
+ const n = readSync(fd, buf, got, buf.length - got, from + got);
81
+ if (n <= 0) break;
82
+ got += n;
83
+ }
84
+ return buf.toString('utf8', 0, got);
85
+ } finally {
86
+ closeSync(fd);
87
+ }
88
+ }
89
+
90
+ export function readTranscript(instance, sessionId, { afterSeq = 0, limit = 200, tail = false } = {}) {
91
+ const max = Math.min(Math.max(Number(limit) || 200, 1), 1000);
92
+ const file = fileFor(instance, sessionId);
93
+ if (!existsSync(file)) {
94
+ return { agent: instance, sessionId, recorded: false, total: 0, entries: [], hasMore: false };
95
+ }
96
+
97
+ const ix = indexOf(file, statSync(file).size);
98
+ const total = ix.starts.length;
99
+ const after = Math.min(Math.max(Number(afterSeq) || 0, 0), total);
100
+ const first = tail ? Math.max(after, total - max) : after;
101
+ const last = Math.min(total, first + max);
102
+ const entries = [];
103
+ if (last > first) {
104
+ const from = ix.starts[first];
105
+ const to = last < total ? ix.starts[last] : ix.lineStart;
106
+ const lines = readRange(file, from, to).split('\n').filter((l) => l.trim());
107
+ lines.forEach((line, i) => {
108
+ try {
109
+ entries.push({ seq: first + i + 1, ...JSON.parse(line) });
110
+ } catch {
111
+ }
112
+ });
113
+ }
114
+ return { agent: instance, sessionId, recorded: true, total, entries, hasMore: total - after > max };
115
+ }
116
+
117
+ export function forgetTranscripts(project) {
118
+ const prefix = projectDir(project);
119
+ for (const key of indexes.keys()) {
120
+ if (key.startsWith(prefix)) indexes.delete(key);
121
+ }
122
+ }
@@ -1,17 +1,18 @@
1
- export {
2
- findThread,
3
- findThreadByKey,
4
- getThreadView,
5
- initThreads,
6
- listThreads,
7
- listWorkspaces,
8
- removeThread,
9
- resetThreadsForTest,
10
- resolveThread,
11
- setThreadHooks,
12
- sweepIdle,
13
- updateThread,
14
- workspaceRootOf,
15
- } from './manager.mjs';
16
- export { canonicalDir, relativeInside, resolveInside, threadIdForTopic, workspaceIdOf } from './paths.mjs';
17
- export { SEP, checkId, getWorkspace, keyOf } from './store.mjs';
1
+ export {
2
+ findThread,
3
+ findThreadByKey,
4
+ getThreadView,
5
+ initThreads,
6
+ listThreads,
7
+ listWorkspaces,
8
+ removeThread,
9
+ resetThreadsForTest,
10
+ resolveThread,
11
+ setThreadHooks,
12
+ sweepIdle,
13
+ touchThreadByKey,
14
+ updateThread,
15
+ workspaceRootOf,
16
+ } from './manager.mjs';
17
+ export { canonicalDir, relativeInside, resolveInside, threadIdForTopic, workspaceIdOf } from './paths.mjs';
18
+ export { EPHEMERAL_KEEP_MAX, NAMED_KEEP_MAX, SEP, checkId, getWorkspace, keyOf, pruneThreadList } from './store.mjs';