@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,6 +1,6 @@
1
1
  import { MAX_RUN_MS, log } from '../../env/index.mjs';
2
2
  import { appendEntry } from '../../records/index.mjs';
3
- import { COMPACT_PROMPT, noteSession } from '../support/index.mjs';
3
+ import { isCompactCommand, noteSession } from '../support/index.mjs';
4
4
  import { refusedRun } from './runs.mjs';
5
5
 
6
6
  const MAX_NUDGES = 2;
@@ -175,7 +175,7 @@ async function sendTurn(client, run, text, { timeoutMs, meta, display }) {
175
175
  }
176
176
 
177
177
  // Skip auto-nudge for slash commands (e.g. /compact legitimately ends without text).
178
- const nudgeable = text !== COMPACT_PROMPT[client.type] && !String(text).trim().startsWith('/');
178
+ const nudgeable = !isCompactCommand(client.type, text) && !String(text).trim().startsWith('/');
179
179
  for (let n = 0; n < MAX_NUDGES; n += 1) {
180
180
  const why = nudgeable && client.child && client.run === run && !run.cancelRequested && res?.stopReason !== 'cancelled' ? client.tracker.unfinished() : null;
181
181
  if (!why) break;
@@ -246,7 +246,9 @@ function completeTurn(client, run, text, res, meta) {
246
246
  sessionId: client.sessionId,
247
247
  metrics: client._finishRun(run),
248
248
  };
249
- if (text !== COMPACT_PROMPT[client.type]) setTimeout(() => void client._maybeCompact(), 0);
249
+ if (isCompactCommand(client.type, text) && client.sessionId) {
250
+ client.primed.delete(client.sessionId);
251
+ }
250
252
  return out;
251
253
  }
252
254
 
@@ -1,5 +1,5 @@
1
1
  export { AcpClient } from './acp/index.mjs';
2
2
  export { buildInstance, listInstances } from './instances.mjs';
3
3
  export { probeEffort, probeModels } from './probe.mjs';
4
- export { aliveCount, assertProcessLimit, getAgent, maxProcesses, pool, withStartLock } from './registry.mjs';
5
- export { canCompact, compactIfNeeded, contextOf, forgetProject, formatMetrics, injectionFor, saved, seedContexts, unmarkEphemeral } from './support/index.mjs';
4
+ export { aliveCount, assertProcessLimit, ensureProcessSlot, getAgent, maxProcesses, pickIdleEvictionVictim, pool, withStartLock } from './registry.mjs';
5
+ export { canCompact, contextOf, forgetProject, formatMetrics, injectionFor, isCompactCommand, saved, seedContexts, unmarkEphemeral } from './support/index.mjs';
@@ -2,10 +2,10 @@ import { join } from 'node:path';
2
2
  import { GLOBAL_DIR, instanceIdOf, projectPath } from '../base/index.mjs';
3
3
  import { AGENTS } from '../env/index.mjs';
4
4
  import { AcpClient } from './acp/index.mjs';
5
- import { assertProcessLimit, pool, withStartLock } from './registry.mjs';
5
+ import { assertProcessLimit, ensureProcessSlot, pool, withStartLock } from './registry.mjs';
6
6
  import { canCompact, contextOf, markEphemeral, saved, savedAll } from './support/index.mjs';
7
7
 
8
- export function buildInstance({ id, type, cwd, project = null, shortId = id, role = null, model = null, effort = null, sessionId = null, onSession = null, compactAt = null, systemPrompt = null, mcpServers = [], provider = null, ephemeral = false }) {
8
+ export function buildInstance({ id, type, cwd, project = null, shortId = id, role = null, model = null, effort = null, sessionId = null, onSession = null, systemPrompt = null, mcpServers = [], provider = null, ephemeral = false }) {
9
9
  const base = AGENTS[type];
10
10
  if (!base) throw new Error(`unknown type "${type}"; available: ${Object.keys(AGENTS).join(', ')}`);
11
11
  if (!cwd || typeof cwd !== 'string') throw new Error('an instance needs a directory (cwd)');
@@ -25,7 +25,6 @@ export function buildInstance({ id, type, cwd, project = null, shortId = id, rol
25
25
  effort,
26
26
  sessionId,
27
27
  onSession,
28
- compactAt,
29
28
  systemPrompt,
30
29
  mcpServers,
31
30
  provider,
@@ -36,7 +35,7 @@ export function buildInstance({ id, type, cwd, project = null, shortId = id, rol
36
35
  defaultCwd: cwd,
37
36
  env,
38
37
  };
39
- return new AcpClient(id, spec, { assertProcessLimit, withStartLock });
38
+ return new AcpClient(id, spec, { assertProcessLimit, ensureProcessSlot, withStartLock });
40
39
  }
41
40
 
42
41
  export function listInstances() {
@@ -83,7 +82,6 @@ export function listInstances() {
83
82
  unstable: a.unstable,
84
83
  lastError: a.child ? null : (a.lastError ?? null),
85
84
  context: contextOf(a),
86
- compactAt: a.compactAt,
87
85
  canCompact: canCompact(a.type),
88
86
  compactions: saved(a.name, a.sessionId ?? a.preferSession)?.compactions ?? 0,
89
87
  sessionId: a.sessionId,
@@ -1,85 +1,91 @@
1
- import { mkdirSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { GLOBAL_DIR } from '../base/index.mjs';
4
- import { AGENTS, defaultModelFor, effortOf } from '../env/index.mjs';
5
- import { cleanInstanceProvider } from '../providers/index.mjs';
6
- import { buildInstance } from './instances.mjs';
7
- import { unmarkEphemeral } from './support/index.mjs';
8
-
9
- const PROBE_DIR = join(GLOBAL_DIR, 'probe');
10
- const modelCache = new Map();
11
- const modelInflight = new Map();
12
- const effortCache = new Map();
13
- const effortInflight = new Map();
14
- let probeSeq = 0;
15
-
16
- export async function probeModels(type, { refresh = false } = {}) {
17
- if (!AGENTS[type]) throw new Error(`unknown type "${type}"; available: ${Object.keys(AGENTS).join(', ')}`);
18
- if (modelCache.has(type) && !refresh) return modelCache.get(type);
19
- if (!refresh && modelInflight.has(type)) return modelInflight.get(type);
20
-
21
- const run = (async () => {
22
- mkdirSync(PROBE_DIR, { recursive: true });
23
- const tmp = buildInstance({ id: `probe-${type}-${++probeSeq}`, type, cwd: PROBE_DIR, ephemeral: true });
24
- try {
25
- const d = await tmp.describeModels();
26
- const opt = d.configOptions.find((o) => o.id === 'model');
27
- const out = {
28
- type,
29
- current: opt?.currentValue ?? null,
30
- default: defaultModelFor(type),
31
- models: (opt?.options ?? []).map((o) => ({ value: o.value, name: o.name ?? o.value })),
32
- effort: effortOf(d.configOptions),
33
- };
34
- // Never cache empty lists so transient startup hiccups recover on next probe.
35
- if (out.models.length > 0) modelCache.set(type, out);
36
- return out;
37
- } finally {
38
- await tmp.shutdown().catch(() => {});
39
- unmarkEphemeral(tmp.name);
40
- }
41
- })();
42
-
43
- if (!refresh) {
44
- modelInflight.set(type, run);
45
- run
46
- .finally(() => {
47
- if (modelInflight.get(type) === run) modelInflight.delete(type);
48
- })
49
- .catch(() => {});
50
- }
51
- return run;
52
- }
53
-
54
- export async function probeEffort(type, model, { refresh = false, provider = null } = {}) {
55
- if (!AGENTS[type]) throw new Error(`unknown type "${type}"; available: ${Object.keys(AGENTS).join(', ')}`);
56
- const choice = provider ? cleanInstanceProvider(provider, type) : null;
57
- const key = `${type}|${model ?? ''}|${choice ? `${choice.id}/${choice.model}` : ''}`;
58
- if (effortCache.has(key) && !refresh) return effortCache.get(key);
59
- if (!refresh && effortInflight.has(key)) return effortInflight.get(key);
60
-
61
- const run = (async () => {
62
- mkdirSync(PROBE_DIR, { recursive: true });
63
- const tmp = buildInstance({ id: `probe-${type}-e-${++probeSeq}`, type, cwd: PROBE_DIR, provider: choice, ephemeral: true });
64
- try {
65
- // Some CLIs only reveal reasoning options after switching the session onto a reasoning-capable model.
66
- if (model) await tmp.setConfigOption('model', model);
67
- const out = effortOf((await tmp.describeModels()).configOptions);
68
- if (out?.options?.length > 0) effortCache.set(key, out);
69
- return out;
70
- } finally {
71
- await tmp.shutdown().catch(() => {});
72
- unmarkEphemeral(tmp.name);
73
- }
74
- })();
75
-
76
- if (!refresh) {
77
- effortInflight.set(key, run);
78
- run
79
- .finally(() => {
80
- if (effortInflight.get(key) === run) effortInflight.delete(key);
81
- })
82
- .catch(() => {});
83
- }
84
- return run;
85
- }
1
+ import { mkdirSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { GLOBAL_DIR } from '../base/index.mjs';
4
+ import { AGENTS, defaultModelFor, effortOf } from '../env/index.mjs';
5
+ import { cleanInstanceProvider } from '../providers/index.mjs';
6
+ import { buildInstance } from './instances.mjs';
7
+ import { unmarkEphemeral } from './support/index.mjs';
8
+
9
+ const PROBE_DIR = join(GLOBAL_DIR, 'probe');
10
+ const modelCache = new Map();
11
+ const modelInflight = new Map();
12
+ const effortCache = new Map();
13
+ const effortInflight = new Map();
14
+ let probeSeq = 0;
15
+
16
+ export async function probeModels(type, { refresh = false } = {}) {
17
+ if (!AGENTS[type]) throw new Error(`unknown type "${type}"; available: ${Object.keys(AGENTS).join(', ')}`);
18
+ const endpointOf = () => AGENTS[type]?.driver?.endpointInfo?.() ?? null;
19
+ if (modelCache.has(type) && !refresh) {
20
+ const endpoint = endpointOf();
21
+ return { ...modelCache.get(type), ...(endpoint ? { endpoint } : {}) };
22
+ }
23
+ if (!refresh && modelInflight.has(type)) return modelInflight.get(type);
24
+
25
+ const run = (async () => {
26
+ mkdirSync(PROBE_DIR, { recursive: true });
27
+ const tmp = buildInstance({ id: `probe-${type}-${++probeSeq}`, type, cwd: PROBE_DIR, ephemeral: true });
28
+ try {
29
+ const d = await tmp.describeModels();
30
+ const opt = d.configOptions.find((o) => o.id === 'model');
31
+ const endpoint = endpointOf();
32
+ const out = {
33
+ type,
34
+ current: opt?.currentValue ?? null,
35
+ default: defaultModelFor(type),
36
+ models: (opt?.options ?? []).map((o) => ({ value: o.value, name: o.name ?? o.value })),
37
+ effort: effortOf(d.configOptions),
38
+ ...(endpoint ? { endpoint } : {}),
39
+ };
40
+ // Never cache empty lists so transient startup hiccups recover on next probe.
41
+ if (out.models.length > 0) modelCache.set(type, out);
42
+ return out;
43
+ } finally {
44
+ await tmp.shutdown().catch(() => {});
45
+ unmarkEphemeral(tmp.name);
46
+ }
47
+ })();
48
+
49
+ if (!refresh) {
50
+ modelInflight.set(type, run);
51
+ run
52
+ .finally(() => {
53
+ if (modelInflight.get(type) === run) modelInflight.delete(type);
54
+ })
55
+ .catch(() => {});
56
+ }
57
+ return run;
58
+ }
59
+
60
+ export async function probeEffort(type, model, { refresh = false, provider = null } = {}) {
61
+ if (!AGENTS[type]) throw new Error(`unknown type "${type}"; available: ${Object.keys(AGENTS).join(', ')}`);
62
+ const choice = provider ? cleanInstanceProvider(provider, type) : null;
63
+ const key = `${type}|${model ?? ''}|${choice ? `${choice.id}/${choice.model}` : ''}`;
64
+ if (effortCache.has(key) && !refresh) return effortCache.get(key);
65
+ if (!refresh && effortInflight.has(key)) return effortInflight.get(key);
66
+
67
+ const run = (async () => {
68
+ mkdirSync(PROBE_DIR, { recursive: true });
69
+ const tmp = buildInstance({ id: `probe-${type}-e-${++probeSeq}`, type, cwd: PROBE_DIR, provider: choice, ephemeral: true });
70
+ try {
71
+ // Some CLIs only reveal reasoning options after switching the session onto a reasoning-capable model.
72
+ if (model) await tmp.setConfigOption('model', model);
73
+ const out = effortOf((await tmp.describeModels()).configOptions);
74
+ if (out?.options?.length > 0) effortCache.set(key, out);
75
+ return out;
76
+ } finally {
77
+ await tmp.shutdown().catch(() => {});
78
+ unmarkEphemeral(tmp.name);
79
+ }
80
+ })();
81
+
82
+ if (!refresh) {
83
+ effortInflight.set(key, run);
84
+ run
85
+ .finally(() => {
86
+ if (effortInflight.get(key) === run) effortInflight.delete(key);
87
+ })
88
+ .catch(() => {});
89
+ }
90
+ return run;
91
+ }
@@ -1,10 +1,17 @@
1
- import { CONFIG } from '../env/index.mjs';
1
+ import { CONFIG, log } from '../env/index.mjs';
2
2
 
3
3
  export const pool = new Map();
4
4
 
5
5
  export const maxProcesses = () => Number(process.env.AGENTD_MAX_PROCESSES) || Number(CONFIG?.limits?.maxProcesses) || 12;
6
6
 
7
7
  const startChains = new Map();
8
+ let slotChain = Promise.resolve();
9
+
10
+ function withSlotLock(fn) {
11
+ const next = slotChain.then(fn, fn);
12
+ slotChain = next.catch(() => {});
13
+ return next;
14
+ }
8
15
 
9
16
  export function withStartLock(key, fn) {
10
17
  const prev = startChains.get(key) ?? Promise.resolve();
@@ -19,6 +26,23 @@ export function aliveCount(filter = () => true) {
19
26
  return n;
20
27
  }
21
28
 
29
+ function isIdleEvictable(agent, requester, tried) {
30
+ if (!agent || agent === requester || tried.has(agent)) return false;
31
+ if (!agent.child) return false;
32
+ if (agent.busy || agent.inUse || (agent.inflight ?? 0) > 0) return false;
33
+ if (agent.stopping || agent._shuttingDown || agent._initializing) return false;
34
+ return true;
35
+ }
36
+
37
+ export function pickIdleEvictionVictim(requester = null, tried = new Set()) {
38
+ let victim = null;
39
+ for (const a of pool.values()) {
40
+ if (!isIdleEvictable(a, requester, tried)) continue;
41
+ if (!victim || (a.lastActive ?? 0) < (victim.lastActive ?? 0)) victim = a;
42
+ }
43
+ return victim;
44
+ }
45
+
22
46
  export function assertProcessLimit() {
23
47
  const limit = maxProcesses();
24
48
  if (aliveCount() >= limit) {
@@ -28,6 +52,26 @@ export function assertProcessLimit() {
28
52
  }
29
53
  }
30
54
 
55
+ export function ensureProcessSlot(requester = null, spawnFn = null) {
56
+ return withSlotLock(async () => {
57
+ if (requester?.child) return;
58
+ const limit = maxProcesses();
59
+ const tried = new Set();
60
+ while (aliveCount() >= limit) {
61
+ const victim = pickIdleEvictionVictim(requester, tried);
62
+ if (!victim) {
63
+ throw new Error(
64
+ `process limit reached (${limit} active agent processes are busy); wait for a running task to finish or cancel one`,
65
+ );
66
+ }
67
+ tried.add(victim);
68
+ log(`[pool] process limit (${limit}) reached; evicting least-recently-used idle process ${victim.name}`);
69
+ await victim.shutdown({ clearQueue: false }).catch(() => {});
70
+ }
71
+ if (typeof spawnFn === 'function') spawnFn();
72
+ });
73
+ }
74
+
31
75
  export function getAgent(name) {
32
76
  if (!name) throw new Error('an executor is required (<project>~<id>); there is no default one');
33
77
  const agent = pool.get(name);
@@ -1,9 +1,9 @@
1
1
  import { driverTypes, getDriver } from '../../../../drivers/index.mjs';
2
- import { log } from '../../env/index.mjs';
3
- import { entry, noteSession, saved } from './store.mjs';
2
+ import { saved } from './store.mjs';
4
3
 
5
4
  export const COMPACT_PROMPT = Object.fromEntries(driverTypes.map((t) => [t, getDriver(t).capabilities.compact]).filter(([, c]) => c));
6
5
  export const canCompact = (type) => Boolean(COMPACT_PROMPT[type]);
6
+ export const isCompactCommand = (type, text) => Boolean(COMPACT_PROMPT[type] && String(text ?? '').trim() === COMPACT_PROMPT[type]);
7
7
 
8
8
  export function contextOf(a) {
9
9
  const now = a.sessionId ?? a.preferSession;
@@ -15,44 +15,3 @@ export function contextOf(a) {
15
15
  const percent = c.used != null && size ? +((c.used / size) * 100).toFixed(1) : c.percent;
16
16
  return { used: c.used, size, percent };
17
17
  }
18
-
19
- export async function compactIfNeeded(t) {
20
- const ctx = t.context();
21
- if (!t.compactAt || t.owner._compacting || t.busy || !t.sessionKey || ctx?.used == null) return;
22
- const limit = ctx.size ? Math.min(t.compactAt, Math.floor(ctx.size * 0.9)) : t.compactAt;
23
- if (ctx.used < limit) return;
24
- const e = entry(t.name, t.sessionKey);
25
- if (e.lastCompactUsed != null && ctx.used >= e.lastCompactUsed * 0.9 && e.compactedAt && Date.now() - e.compactedAt < 30 * 60_000) return;
26
- t.owner._compacting = true;
27
- const sessionKey = t.sessionKey;
28
- try {
29
- await t.compact();
30
- const after = (await t.contextAfter?.()) ?? t.context();
31
- const compactions = (e.compactions ?? 0) + 1;
32
- noteSession(t.name, sessionKey, { compactions, compactedAt: Date.now(), lastCompactUsed: ctx.used });
33
- t.onCompact?.({ agent: t.name, sessionId: sessionKey, before: ctx, after, threshold: limit, compactions });
34
- } catch (err) {
35
- log(`[${t.name}] compaction failed: ${err.message}`);
36
- } finally {
37
- t.owner._compacting = false;
38
- }
39
- }
40
-
41
- export function maybeCompact(agent) {
42
- const cmd = COMPACT_PROMPT[agent.type];
43
- if (!cmd) return Promise.resolve();
44
- const sessionId = agent.sessionId;
45
- return compactIfNeeded({
46
- name: agent.name,
47
- owner: agent,
48
- compactAt: agent.compactAt,
49
- busy: agent.busy,
50
- sessionKey: sessionId,
51
- context: () => contextOf(agent),
52
- compact: async () => {
53
- await agent.startPrompt(cmd, { timeoutMs: 600_000 }).done;
54
- agent.primed.delete(sessionId);
55
- },
56
- onCompact: (info) => agent.onCompact?.(info),
57
- });
58
- }
@@ -1,4 +1,4 @@
1
- export { COMPACT_PROMPT, canCompact, compactIfNeeded, contextOf, maybeCompact } from './compaction.mjs';
1
+ export { COMPACT_PROMPT, canCompact, contextOf, isCompactCommand } from './compaction.mjs';
2
2
  export { formatMetrics, modelName, runMetrics } from './metrics.mjs';
3
3
  export { entry, flushStore, forgetProject, markEphemeral, noteSession, saveStore, saved, savedAll, seedContexts, unmarkEphemeral } from './store.mjs';
4
4
  export { injectionFor } from './system-prompt.mjs';
@@ -1,12 +1,12 @@
1
- export { CONTEXTS, executorRules, stripComments } from './rules.mjs';
2
- export {
3
- executorRulesFor,
4
- getRole,
5
- getTemplate,
6
- listRoles,
7
- listTemplates,
8
- removeRole,
9
- removeTemplate,
10
- saveRole,
11
- saveTemplate,
12
- } from './templates.mjs';
1
+ export { CONTEXTS, executorRules, stripComments } from './rules.mjs';
2
+ export {
3
+ executorRulesFor,
4
+ getRole,
5
+ getTemplate,
6
+ listRoles,
7
+ listTemplates,
8
+ removeRole,
9
+ removeTemplate,
10
+ saveRole,
11
+ saveTemplate,
12
+ } from './templates.mjs';
@@ -1,22 +1,22 @@
1
- import { readFileSync } from 'node:fs';
2
- import { dirname, join } from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
-
5
- export const CONTEXTS = join(dirname(dirname(dirname(fileURLToPath(import.meta.url)))), 'contexts');
6
- const cache = new Map();
7
-
8
- export const stripComments = (text) => String(text).replace(/<!--[\s\S]*?-->/g, '').trim();
9
-
10
- function load(name) {
11
- if (!cache.has(name)) {
12
- let text = '';
13
- try {
14
- text = stripComments(readFileSync(join(CONTEXTS, name), 'utf8'));
15
- } catch {
16
- }
17
- cache.set(name, text);
18
- }
19
- return cache.get(name);
20
- }
21
-
22
- export const executorRules = () => load('executor.md');
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export const CONTEXTS = join(dirname(dirname(dirname(fileURLToPath(import.meta.url)))), 'contexts');
6
+ const cache = new Map();
7
+
8
+ export const stripComments = (text) => String(text).replace(/<!--[\s\S]*?-->/g, '').trim();
9
+
10
+ function load(name) {
11
+ if (!cache.has(name)) {
12
+ let text = '';
13
+ try {
14
+ text = stripComments(readFileSync(join(CONTEXTS, name), 'utf8'));
15
+ } catch {
16
+ }
17
+ cache.set(name, text);
18
+ }
19
+ return cache.get(name);
20
+ }
21
+
22
+ export const executorRules = () => load('executor.md');