@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,206 +1,206 @@
1
- import { spawn } from 'node:child_process';
2
- import { killTree } from '../base/index.mjs';
3
-
4
- const defaultLog = (...a) => process.stderr.write(`[pi-rpc] ${a.join(' ')}\n`);
5
-
6
- export class PiRpc {
7
- constructor({ label = 'pi', log = defaultLog } = {}) {
8
- this.label = label;
9
- this.log = log;
10
- this.child = null;
11
- this.buf = '';
12
- this.nextId = 1;
13
- this.pending = new Map();
14
- this.listeners = new Set();
15
- this.settledWaiters = [];
16
- this.streaming = false;
17
- this.stderrTail = '';
18
- this.lastError = null;
19
- this.onClose = null;
20
- }
21
-
22
- get running() {
23
- return Boolean(this.child);
24
- }
25
-
26
- start({ cmd, args, cwd, env }) {
27
- if (this.child) throw new Error(`${this.label} is already running`);
28
- const child = spawn(cmd, args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' });
29
- this.child = child;
30
- this.buf = '';
31
-
32
- child.stdout.setEncoding('utf8');
33
- child.stdout.on('data', (chunk) => {
34
- this.buf += chunk;
35
- let i;
36
- while ((i = this.buf.indexOf('\n')) !== -1) {
37
- const line = this.buf.slice(0, i).trim();
38
- this.buf = this.buf.slice(i + 1);
39
- if (line) this._onLine(line);
40
- }
41
- });
42
- child.stderr.setEncoding('utf8');
43
- child.stderr.on('data', (d) => {
44
- this.stderrTail = (this.stderrTail + d).slice(-2000);
45
- });
46
- child.on('error', (err) => {
47
- this.lastError = err.message;
48
- });
49
- child.on('close', (code) => {
50
- this.log(`pi exited (code=${code})`);
51
- if (this.child === child) this.child = null;
52
- this.streaming = false;
53
- for (const { reject } of this.pending.values()) reject(new Error(`${this.label} pi rpc exited`));
54
- this.pending.clear();
55
- for (const w of this.settledWaiters.splice(0)) w(false);
56
- this.onClose?.(code);
57
- });
58
- return child;
59
- }
60
-
61
- stop() {
62
- const child = this.child;
63
- if (!child) return;
64
- try {
65
- child.stdin.end();
66
- killTree(child);
67
- } catch {
68
- }
69
- }
70
-
71
- addListener(fn) {
72
- this.listeners.add(fn);
73
- return () => this.listeners.delete(fn);
74
- }
75
-
76
- _onLine(line) {
77
- let rec;
78
- try {
79
- rec = JSON.parse(line);
80
- } catch {
81
- return;
82
- }
83
- this.handle(rec);
84
- }
85
-
86
- handle(rec) {
87
- if (rec.type === 'response' && rec.id != null && this.pending.has(rec.id)) {
88
- const { resolve } = this.pending.get(rec.id);
89
- this.pending.delete(rec.id);
90
- resolve(rec);
91
- return;
92
- }
93
- if (rec.type === 'agent_start') this.streaming = true;
94
- if (rec.type === 'agent_settled') {
95
- this.streaming = false;
96
- for (const w of this.settledWaiters.splice(0)) w(true);
97
- }
98
- for (const fn of this.listeners) {
99
- try {
100
- fn(rec);
101
- } catch (err) {
102
- this.log(`a listener failed: ${err.message}`);
103
- }
104
- }
105
- }
106
-
107
- write(obj) {
108
- try {
109
- this.child?.stdin.write(JSON.stringify(obj) + '\n');
110
- } catch (err) {
111
- this.log('write failed:', err.message);
112
- }
113
- }
114
-
115
- command(type, params = {}, timeoutMs = 60_000) {
116
- if (!this.child) return Promise.reject(new Error(`${this.label} is not running`));
117
- const id = `rpc-${this.nextId++}`;
118
- return new Promise((resolve, reject) => {
119
- const timer = setTimeout(() => {
120
- this.pending.delete(id);
121
- reject(new Error(`${this.label} ${type} timed out after ${timeoutMs}ms`));
122
- }, timeoutMs);
123
- this.pending.set(id, {
124
- resolve: (rec) => {
125
- clearTimeout(timer);
126
- if (!rec.success) reject(new Error(`${this.label} ${type} failed: ${rec.error ?? 'unknown error'}`));
127
- else resolve(rec.data);
128
- },
129
- reject: (err) => {
130
- clearTimeout(timer);
131
- reject(err);
132
- },
133
- });
134
- this.write({ id, type, ...params });
135
- });
136
- }
137
-
138
- waitSettled(timeoutMs = 600_000) {
139
- return new Promise((resolve, reject) => {
140
- const timer = !timeoutMs ? null : setTimeout(() => {
141
- const i = this.settledWaiters.indexOf(done);
142
- if (i >= 0) this.settledWaiters.splice(i, 1);
143
- reject(new Error(`${this.label} run did not settle within ${timeoutMs}ms`));
144
- }, timeoutMs);
145
- const done = (settled) => {
146
- if (timer) clearTimeout(timer);
147
- if (settled === false) reject(new Error(`${this.label} pi rpc exited before the run settled`));
148
- else resolve();
149
- };
150
- this.settledWaiters.push(done);
151
- });
152
- }
153
-
154
- state() {
155
- return this.command('get_state', {}, 60_000);
156
- }
157
-
158
- stats(timeoutMs = 30_000) {
159
- return this.command('get_session_stats', {}, timeoutMs);
160
- }
161
-
162
- async context() {
163
- return PiRpc.contextOf(await this.stats());
164
- }
165
-
166
- static contextOf(stats) {
167
- const c = stats?.contextUsage;
168
- return c && c.percent != null ? { used: c.tokens ?? null, size: c.contextWindow ?? null, percent: +c.percent.toFixed(1) } : null;
169
- }
170
-
171
- compact(timeoutMs = 600_000) {
172
- return this.command('compact', {}, timeoutMs);
173
- }
174
-
175
- abort(timeoutMs = 30_000) {
176
- return this.command('abort', {}, timeoutMs);
177
- }
178
-
179
- newSession() {
180
- return this.command('new_session', {}, 60_000);
181
- }
182
-
183
- switchSession(sessionPath) {
184
- return this.command('switch_session', { sessionPath }, 60_000);
185
- }
186
-
187
- setModel(provider, modelId) {
188
- return this.command('set_model', { provider, modelId }, 60_000);
189
- }
190
-
191
- setThinking(level) {
192
- return this.command('set_thinking_level', { level }, 60_000);
193
- }
194
-
195
- models() {
196
- return this.command('get_available_models', {}, 60_000);
197
- }
198
-
199
- thinkingLevels() {
200
- return this.command('get_available_thinking_levels', {}, 30_000);
201
- }
202
-
203
- messages() {
204
- return this.command('get_messages', {}, 60_000);
205
- }
206
- }
1
+ import { spawn } from 'node:child_process';
2
+ import { killTree } from '../base/index.mjs';
3
+
4
+ const defaultLog = (...a) => process.stderr.write(`[pi-rpc] ${a.join(' ')}\n`);
5
+
6
+ export class PiRpc {
7
+ constructor({ label = 'pi', log = defaultLog } = {}) {
8
+ this.label = label;
9
+ this.log = log;
10
+ this.child = null;
11
+ this.buf = '';
12
+ this.nextId = 1;
13
+ this.pending = new Map();
14
+ this.listeners = new Set();
15
+ this.settledWaiters = [];
16
+ this.streaming = false;
17
+ this.stderrTail = '';
18
+ this.lastError = null;
19
+ this.onClose = null;
20
+ }
21
+
22
+ get running() {
23
+ return Boolean(this.child);
24
+ }
25
+
26
+ start({ cmd, args, cwd, env }) {
27
+ if (this.child) throw new Error(`${this.label} is already running`);
28
+ const child = spawn(cmd, args, { cwd, env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, detached: process.platform !== 'win32' });
29
+ this.child = child;
30
+ this.buf = '';
31
+
32
+ child.stdout.setEncoding('utf8');
33
+ child.stdout.on('data', (chunk) => {
34
+ this.buf += chunk;
35
+ let i;
36
+ while ((i = this.buf.indexOf('\n')) !== -1) {
37
+ const line = this.buf.slice(0, i).trim();
38
+ this.buf = this.buf.slice(i + 1);
39
+ if (line) this._onLine(line);
40
+ }
41
+ });
42
+ child.stderr.setEncoding('utf8');
43
+ child.stderr.on('data', (d) => {
44
+ this.stderrTail = (this.stderrTail + d).slice(-2000);
45
+ });
46
+ child.on('error', (err) => {
47
+ this.lastError = err.message;
48
+ });
49
+ child.on('close', (code) => {
50
+ this.log(`pi exited (code=${code})`);
51
+ if (this.child === child) this.child = null;
52
+ this.streaming = false;
53
+ for (const { reject } of this.pending.values()) reject(new Error(`${this.label} pi rpc exited`));
54
+ this.pending.clear();
55
+ for (const w of this.settledWaiters.splice(0)) w(false);
56
+ this.onClose?.(code);
57
+ });
58
+ return child;
59
+ }
60
+
61
+ stop() {
62
+ const child = this.child;
63
+ if (!child) return;
64
+ try {
65
+ child.stdin.end();
66
+ killTree(child);
67
+ } catch {
68
+ }
69
+ }
70
+
71
+ addListener(fn) {
72
+ this.listeners.add(fn);
73
+ return () => this.listeners.delete(fn);
74
+ }
75
+
76
+ _onLine(line) {
77
+ let rec;
78
+ try {
79
+ rec = JSON.parse(line);
80
+ } catch {
81
+ return;
82
+ }
83
+ this.handle(rec);
84
+ }
85
+
86
+ handle(rec) {
87
+ if (rec.type === 'response' && rec.id != null && this.pending.has(rec.id)) {
88
+ const { resolve } = this.pending.get(rec.id);
89
+ this.pending.delete(rec.id);
90
+ resolve(rec);
91
+ return;
92
+ }
93
+ if (rec.type === 'agent_start') this.streaming = true;
94
+ if (rec.type === 'agent_settled') {
95
+ this.streaming = false;
96
+ for (const w of this.settledWaiters.splice(0)) w(true);
97
+ }
98
+ for (const fn of this.listeners) {
99
+ try {
100
+ fn(rec);
101
+ } catch (err) {
102
+ this.log(`a listener failed: ${err.message}`);
103
+ }
104
+ }
105
+ }
106
+
107
+ write(obj) {
108
+ try {
109
+ this.child?.stdin.write(JSON.stringify(obj) + '\n');
110
+ } catch (err) {
111
+ this.log('write failed:', err.message);
112
+ }
113
+ }
114
+
115
+ command(type, params = {}, timeoutMs = 60_000) {
116
+ if (!this.child) return Promise.reject(new Error(`${this.label} is not running`));
117
+ const id = `rpc-${this.nextId++}`;
118
+ return new Promise((resolve, reject) => {
119
+ const timer = setTimeout(() => {
120
+ this.pending.delete(id);
121
+ reject(new Error(`${this.label} ${type} timed out after ${timeoutMs}ms`));
122
+ }, timeoutMs);
123
+ this.pending.set(id, {
124
+ resolve: (rec) => {
125
+ clearTimeout(timer);
126
+ if (!rec.success) reject(new Error(`${this.label} ${type} failed: ${rec.error ?? 'unknown error'}`));
127
+ else resolve(rec.data);
128
+ },
129
+ reject: (err) => {
130
+ clearTimeout(timer);
131
+ reject(err);
132
+ },
133
+ });
134
+ this.write({ id, type, ...params });
135
+ });
136
+ }
137
+
138
+ waitSettled(timeoutMs = 600_000) {
139
+ return new Promise((resolve, reject) => {
140
+ const timer = !timeoutMs ? null : setTimeout(() => {
141
+ const i = this.settledWaiters.indexOf(done);
142
+ if (i >= 0) this.settledWaiters.splice(i, 1);
143
+ reject(new Error(`${this.label} run did not settle within ${timeoutMs}ms`));
144
+ }, timeoutMs);
145
+ const done = (settled) => {
146
+ if (timer) clearTimeout(timer);
147
+ if (settled === false) reject(new Error(`${this.label} pi rpc exited before the run settled`));
148
+ else resolve();
149
+ };
150
+ this.settledWaiters.push(done);
151
+ });
152
+ }
153
+
154
+ state() {
155
+ return this.command('get_state', {}, 60_000);
156
+ }
157
+
158
+ stats(timeoutMs = 30_000) {
159
+ return this.command('get_session_stats', {}, timeoutMs);
160
+ }
161
+
162
+ async context() {
163
+ return PiRpc.contextOf(await this.stats());
164
+ }
165
+
166
+ static contextOf(stats) {
167
+ const c = stats?.contextUsage;
168
+ return c && c.percent != null ? { used: c.tokens ?? null, size: c.contextWindow ?? null, percent: +c.percent.toFixed(1) } : null;
169
+ }
170
+
171
+ compact(timeoutMs = 600_000) {
172
+ return this.command('compact', {}, timeoutMs);
173
+ }
174
+
175
+ abort(timeoutMs = 30_000) {
176
+ return this.command('abort', {}, timeoutMs);
177
+ }
178
+
179
+ newSession() {
180
+ return this.command('new_session', {}, 60_000);
181
+ }
182
+
183
+ switchSession(sessionPath) {
184
+ return this.command('switch_session', { sessionPath }, 60_000);
185
+ }
186
+
187
+ setModel(provider, modelId) {
188
+ return this.command('set_model', { provider, modelId }, 60_000);
189
+ }
190
+
191
+ setThinking(level) {
192
+ return this.command('set_thinking_level', { level }, 60_000);
193
+ }
194
+
195
+ models() {
196
+ return this.command('get_available_models', {}, 60_000);
197
+ }
198
+
199
+ thinkingLevels() {
200
+ return this.command('get_available_thinking_levels', {}, 30_000);
201
+ }
202
+
203
+ messages() {
204
+ return this.command('get_messages', {}, 60_000);
205
+ }
206
+ }
@@ -1,6 +1,6 @@
1
1
  import { CANCEL_GRACE_MS, CONFIG, idleRunMs } from '../../env/index.mjs';
2
2
  import { getProvider } from '../../providers/index.mjs';
3
- import { entry, maybeCompact, modelName, noteSession, runMetrics, saved } from '../support/index.mjs';
3
+ import { entry, modelName, noteSession, runMetrics, saved } from '../support/index.mjs';
4
4
  import { StopHealth } from './health.mjs';
5
5
  import { forceStopProcess, handleProcessClose, initProcess, shutdownProcess, spawnProcess } from './process.mjs';
6
6
  import { PromptQueue } from './prompt-queue.mjs';
@@ -20,14 +20,14 @@ export class AcpClient {
20
20
  this.shortId = spec.shortId ?? name;
21
21
  this.role = spec.role ?? CONFIG?.roles?.[spec.type ?? name] ?? null;
22
22
  this.onSession = spec.onSession ?? null;
23
- this.compactAt = spec.compactAt ?? null;
24
23
  this.assertProcessLimit = opts.assertProcessLimit ?? spec.assertProcessLimit ?? (() => {});
24
+ this.ensureProcessSlot = opts.ensureProcessSlot ?? spec.ensureProcessSlot ?? null;
25
25
  this.withStartLock = opts.withStartLock ?? spec.withStartLock ?? ((_key, fn) => fn());
26
26
  this.onCompact = null;
27
- this._compacting = false;
28
27
  this.lastActive = Date.now();
29
28
  this.stopping = false;
30
29
  this._shuttingDown = false;
30
+ this._initializing = false;
31
31
  this._lastDriverUsageAt = 0;
32
32
 
33
33
  this.transport = new AcpTransport({
@@ -66,7 +66,6 @@ export class AcpClient {
66
66
  name,
67
67
  getRun: () => this.run,
68
68
  getContextSize: () => this.configuredContextSize(),
69
- isCompacting: () => this._compacting,
70
69
  onAutoCompact: (info) => this.onCompact?.(info),
71
70
  });
72
71
 
@@ -271,6 +270,9 @@ export class AcpClient {
271
270
  get preferEffort() {
272
271
  return this.sessions.preferEffort;
273
272
  }
273
+ set preferEffort(v) {
274
+ this.sessions.preferEffort = v;
275
+ }
274
276
  chooseModel(value) {
275
277
  return this.sessions.chooseModel(value);
276
278
  }
@@ -311,15 +313,11 @@ export class AcpClient {
311
313
  return this.startPrompt(text, opts).done;
312
314
  }
313
315
 
314
- _maybeCompact() {
315
- return maybeCompact(this);
316
- }
317
-
318
316
  setProgressSink(fn) {
319
317
  this.tracker.sink = fn;
320
318
  }
321
319
 
322
- startPrompt(text, { timeoutMs = idleRunMs(), cwd, reset, sessionId, callDepth = 1, callChain = null, meta = null, display = null } = {}) {
320
+ startPrompt(text, { timeoutMs = idleRunMs(this.preferEffort), cwd, reset, sessionId, callDepth = 1, callChain = null, meta = null, display = null } = {}) {
323
321
  const jobId = `${this.name}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
324
322
  const { done, ahead } = this.line.submit(
325
323
  jobId,
@@ -39,26 +39,35 @@ export async function initProcess(client) {
39
39
  if (client.child && client.initPromise) return client.initPromise;
40
40
  // Serialize starts per CLI type to prevent concurrent startup races (observed in mcode).
41
41
  client.initPromise = client.withStartLock(client.type, async () => {
42
- let lastErr;
43
- for (let attempt = 1; attempt <= START_ATTEMPTS; attempt += 1) {
44
- try {
45
- client._spawn();
46
- const init = await client._request('initialize', {
47
- protocolVersion: 1,
48
- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
49
- });
50
- client.agentInfo = init?.agentInfo ?? null;
51
- client.capabilities = init?.agentCapabilities ?? null;
52
- return client.capabilities;
53
- } catch (err) {
54
- lastErr = err;
55
- if (!/ACP exited/.test(err.message) || attempt === START_ATTEMPTS) break;
56
- log(`[${client.name}] died while starting (attempt ${attempt}/${START_ATTEMPTS}); retrying`);
57
- await new Promise((r) => setTimeout(r, attempt * 1500));
42
+ client._initializing = true;
43
+ try {
44
+ let lastErr;
45
+ for (let attempt = 1; attempt <= START_ATTEMPTS; attempt += 1) {
46
+ try {
47
+ if (typeof client.ensureProcessSlot === 'function') {
48
+ await client.ensureProcessSlot(client, () => client._spawn());
49
+ } else {
50
+ client._spawn();
51
+ }
52
+ const init = await client._request('initialize', {
53
+ protocolVersion: 1,
54
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false } },
55
+ });
56
+ client.agentInfo = init?.agentInfo ?? null;
57
+ client.capabilities = init?.agentCapabilities ?? null;
58
+ return client.capabilities;
59
+ } catch (err) {
60
+ lastErr = err;
61
+ if (!/ACP exited/.test(err.message) || attempt === START_ATTEMPTS) break;
62
+ log(`[${client.name}] died while starting (attempt ${attempt}/${START_ATTEMPTS}); retrying`);
63
+ await new Promise((r) => setTimeout(r, attempt * 1500));
64
+ }
58
65
  }
66
+ const tail = (client.stderrTail ?? []).join(' | ');
67
+ throw new Error(`${client.name} could not start: ${lastErr.message}${tail ? ` (${tail})` : ''}`);
68
+ } finally {
69
+ client._initializing = false;
59
70
  }
60
- const tail = (client.stderrTail ?? []).join(' | ');
61
- throw new Error(`${client.name} could not start: ${lastErr.message}${tail ? ` (${tail})` : ''}`);
62
71
  }).catch((err) => {
63
72
  client.initPromise = null;
64
73
  client.lastError = err.message;