@mycompbox/compbox-cli 1.19.0 → 1.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.tsbuildinfo +1 -1
- package/commands/configure.d.ts +2 -0
- package/commands/configure.d.ts.map +1 -1
- package/commands/configure.js +34 -55
- package/commands/configure.js.map +1 -1
- package/commands/deploy.d.ts +22 -0
- package/commands/deploy.d.ts.map +1 -0
- package/commands/deploy.js +96 -0
- package/commands/deploy.js.map +1 -0
- package/commands/doctor.d.ts +14 -12
- package/commands/doctor.d.ts.map +1 -1
- package/commands/doctor.js +35 -19
- package/commands/doctor.js.map +1 -1
- package/commands/repo.d.ts +24 -0
- package/commands/repo.d.ts.map +1 -0
- package/commands/repo.js +81 -0
- package/commands/repo.js.map +1 -0
- package/commands/run.d.ts +12 -16
- package/commands/run.d.ts.map +1 -1
- package/commands/run.js +117 -55
- package/commands/run.js.map +1 -1
- package/commands/workspace.d.ts +56 -0
- package/commands/workspace.d.ts.map +1 -0
- package/commands/workspace.js +177 -0
- package/commands/workspace.js.map +1 -0
- package/index.js +1022 -514
- package/index.js.map +1 -1
- package/package.json +1 -1
- package/utils/agent-invoker.d.ts +62 -45
- package/utils/agent-invoker.d.ts.map +1 -1
- package/utils/agent-invoker.js +172 -335
- package/utils/agent-invoker.js.map +1 -1
- package/utils/config-store.d.ts +30 -58
- package/utils/config-store.d.ts.map +1 -1
- package/utils/config-store.js +27 -47
- package/utils/config-store.js.map +1 -1
- package/utils/mailbox-client.d.ts +33 -1
- package/utils/mailbox-client.d.ts.map +1 -1
- package/utils/mailbox-client.js +46 -2
- package/utils/mailbox-client.js.map +1 -1
- package/utils/run-workspace.d.ts +40 -4
- package/utils/run-workspace.d.ts.map +1 -1
- package/utils/run-workspace.js +141 -35
- package/utils/run-workspace.js.map +1 -1
package/utils/agent-invoker.js
CHANGED
|
@@ -2,40 +2,26 @@
|
|
|
2
2
|
* Agent invoker (ENG-E23 / ENG-122-2) — the daemon's "heart": actually runs a
|
|
3
3
|
* claimed job instead of immediately reporting it as unimplemented.
|
|
4
4
|
*
|
|
5
|
-
*
|
|
6
|
-
* (
|
|
7
|
-
*
|
|
5
|
+
* Request conversations (`epic_request` jobs) run one AI reply per claim
|
|
6
|
+
* (invokeEpicRequestStep, on the shared runConversationStep): the reply is
|
|
7
|
+
* posted, the job is left waiting on the person, and the server hands it back
|
|
8
|
+
* when they write again. Nothing waits in between, so a conversation never
|
|
9
|
+
* times out and stays open after the request is saved. Two ways to reply:
|
|
8
10
|
* - `api`: Anthropic Messages API, directly (Anthropic API key, billed
|
|
9
|
-
* per-token).
|
|
11
|
+
* per-token).
|
|
10
12
|
* - `claude-subscription`: shells out to the local `claude` CLI
|
|
11
13
|
* non-interactively, using whichever account is already logged in on
|
|
12
14
|
* this machine (personal Pro/Max or a company Team seat) — no API key
|
|
13
|
-
* ever touches CompBox.
|
|
15
|
+
* ever touches CompBox.
|
|
14
16
|
*
|
|
15
|
-
*
|
|
16
|
-
* - The interview is driven by the shared, declarative INTERVIEW_DEFINITION
|
|
17
|
-
* (@mycompbox/shared, ENG-143) so the machine/mailbox interview reaches the
|
|
18
|
-
* SAME depth as the CLI request-formulator: it covers all seven sections
|
|
19
|
-
* (problem, solution, impact, success metrics, target audience, technical
|
|
20
|
-
* context, alternatives) rather than only the 3 required fields. The system
|
|
21
|
-
* prompt is rendered from that definition (buildInterviewSystemPrompt), and
|
|
22
|
-
* the completion object carries the required fields plus any optional ones
|
|
23
|
-
* the employee provided; there is no shortened variant left in this path.
|
|
24
|
-
*
|
|
25
|
-
* Turn relay: the mailbox has no "wait for a new turn" primitive for a
|
|
26
|
-
* machine caller (next-job's "resume active job" path returns immediately
|
|
27
|
-
* with whatever the job's current state is — see jobService.ts tryClaimOnce).
|
|
28
|
-
* So after posting an agent question, this module polls next-job on a short
|
|
29
|
-
* client-side interval until it observes a new trailing user turn, with a
|
|
30
|
-
* bounded overall timeout so an abandoned interview eventually fails cleanly
|
|
31
|
-
* instead of polling forever.
|
|
17
|
+
* `start_execution` jobs run the planner/orchestrator headless (below).
|
|
32
18
|
*/
|
|
33
19
|
import Anthropic from '@anthropic-ai/sdk';
|
|
34
20
|
import { spawn, spawnSync } from 'node:child_process';
|
|
35
21
|
import { mkdirSync } from 'node:fs';
|
|
36
22
|
import { homedir } from 'node:os';
|
|
37
23
|
import { join } from 'node:path';
|
|
38
|
-
import { resolveRouting,
|
|
24
|
+
import { resolveRouting, extractCompletionJson, looksLikeCompletionAttempt, meetsComplianceTarget, buildAuditFeedback, COMPLETION_REPAIR_INSTRUCTION, renderConversationPrompt, runConversationStep, savedContextFromRecord, } from '@mycompbox/shared';
|
|
39
25
|
// Completion parsing lives in @mycompbox/shared so CompBox's server-side
|
|
40
26
|
// (API-key) interview finishes the same way; re-exported for existing callers.
|
|
41
27
|
export { extractCompletionJson, looksLikeCompletionAttempt, meetsComplianceTarget, buildAuditFeedback, COMPLETION_REPAIR_INSTRUCTION, };
|
|
@@ -47,22 +33,8 @@ import { keyRunArgs, keyRunEnv, parseClaudeJsonResult } from './key-run.js';
|
|
|
47
33
|
// quality loss. Opus/Sonnet are deliberately NOT used here — pxpipe passes
|
|
48
34
|
// Opus through uncompressed, defeating the token savings.
|
|
49
35
|
const ANTHROPIC_MODEL = 'claude-fable-5';
|
|
50
|
-
// Turn budget for the interview loop. Raised from 8: a full 7-section interview
|
|
51
|
-
// (problem / solution / impact + success metrics / audience / technical context /
|
|
52
|
-
// alternatives) plus follow-ups AND audit-quality rounds needs more headroom
|
|
53
|
-
// than 8 (deep interviews were being cut off mid-way — bug #3).
|
|
54
|
-
const MAX_INTERVIEW_TURNS = 18;
|
|
55
|
-
// Audit-quality gate (bug #2): the interview must reach the `pass` tier
|
|
56
|
-
// (>=90, zero critical issues) before it may finish. After the model says
|
|
57
|
-
// "done", we submit, read the server-computed compliance score, and if it is
|
|
58
|
-
// not yet `pass` we feed the failing rules back and keep going. This bounds how
|
|
59
|
-
// many re-submit/re-audit rounds we allow before finalizing with the best draft
|
|
60
|
-
// (so we never loop forever, and never strand the request at a failing score).
|
|
61
|
-
const MAX_QUALITY_ROUNDS = 4;
|
|
62
|
-
const REPLY_POLL_INTERVAL_MS = 3_000;
|
|
63
|
-
const REPLY_TIMEOUT_MS = 10 * 60 * 1_000; // 10 minutes
|
|
64
36
|
/** Per-turn wall-clock budget for a single `claude -p` child process. */
|
|
65
|
-
const CLAUDE_CLI_TURN_TIMEOUT_MS =
|
|
37
|
+
const CLAUDE_CLI_TURN_TIMEOUT_MS = 4 * 60 * 1_000; // 4 minutes: a full write-up can take a while
|
|
66
38
|
/**
|
|
67
39
|
* pxpipe routing (ENG-136). Anthropic SDK options carrying the proxy `baseURL`
|
|
68
40
|
* when routed through pxpipe, otherwise just the API key. Pure — unit tested.
|
|
@@ -228,13 +200,6 @@ export function appendAttachmentNote(text, imageCount) {
|
|
|
228
200
|
const note = `[${String(imageCount)} ${noun} attached — not shown in subscription mode; vision is handled when the daemon runs in API mode]`;
|
|
229
201
|
return text.trim().length > 0 ? `${text}\n\n${note}` : note;
|
|
230
202
|
}
|
|
231
|
-
/**
|
|
232
|
-
* The interview system prompt, rendered from the shared, declarative
|
|
233
|
-
* INTERVIEW_DEFINITION (ENG-143). This is the single wiring point that gives
|
|
234
|
-
* the machine/mailbox interview the same section depth as the CLI
|
|
235
|
-
* request-formulator — there is no shortened hardcoded variant anymore.
|
|
236
|
-
*/
|
|
237
|
-
const SYSTEM_PROMPT = buildInterviewSystemPrompt();
|
|
238
203
|
/**
|
|
239
204
|
* ENG-149 — parse a claimed job's `payload` as an interview-CONTINUATION seed
|
|
240
205
|
* (the ENG-148 dispatch shape), or return null for a normal fresh-start job
|
|
@@ -263,17 +228,6 @@ export function parseSeedPayload(payload) {
|
|
|
263
228
|
priorTranscript,
|
|
264
229
|
};
|
|
265
230
|
}
|
|
266
|
-
/**
|
|
267
|
-
* ENG-149 — the interview system prompt for a job: a seed-aware RESUME/ENRICH
|
|
268
|
-
* prompt for a continuation, otherwise the module-level fresh-start prompt.
|
|
269
|
-
*/
|
|
270
|
-
export function resolveSystemPrompt(seed) {
|
|
271
|
-
return seed
|
|
272
|
-
? buildInterviewSystemPrompt(INTERVIEW_DEFINITION, {
|
|
273
|
-
priorTranscript: seed.priorTranscript,
|
|
274
|
-
})
|
|
275
|
-
: SYSTEM_PROMPT;
|
|
276
|
-
}
|
|
277
231
|
/**
|
|
278
232
|
* Submit the current draft and read back the server-computed compliance score
|
|
279
233
|
* (bug #2 — audit-aware finishing). Fresh interview: the FIRST submit
|
|
@@ -290,162 +244,6 @@ export async function submitAndScore(ctx, currentErId, draft) {
|
|
|
290
244
|
const created = await createPersonalEpicRequest(ctx.apiBaseUrl, ctx.userApiToken, draft);
|
|
291
245
|
return { erId: created.id, compliance: created.compliance };
|
|
292
246
|
}
|
|
293
|
-
/** How many times to ask the model to fix a malformed completion before failing. */
|
|
294
|
-
const MAX_JSON_REPAIRS = 3;
|
|
295
|
-
function sleep(ms) {
|
|
296
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
297
|
-
}
|
|
298
|
-
/**
|
|
299
|
-
* Polls next-job (the "resume active job" path) until a new trailing user
|
|
300
|
-
* turn appears, or the timeout elapses. Returns the updated job, or null on
|
|
301
|
-
* timeout.
|
|
302
|
-
*/
|
|
303
|
-
async function waitForUserReply(client, machineToken, jobId, turnsSoFar) {
|
|
304
|
-
const deadline = Date.now() + REPLY_TIMEOUT_MS;
|
|
305
|
-
while (Date.now() < deadline) {
|
|
306
|
-
await sleep(REPLY_POLL_INTERVAL_MS);
|
|
307
|
-
const job = await client.nextJob(machineToken, 0);
|
|
308
|
-
if (job?.id !== jobId)
|
|
309
|
-
continue;
|
|
310
|
-
const last = job.turns[job.turns.length - 1];
|
|
311
|
-
if (job.turns.length > turnsSoFar && last?.role === 'user') {
|
|
312
|
-
return job;
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
return null;
|
|
316
|
-
}
|
|
317
|
-
/**
|
|
318
|
-
* Runs the epic_request interview end-to-end: converses with the user via
|
|
319
|
-
* post-turn/next-job until it has a title + the 3 required structured-desc
|
|
320
|
-
* fields, then creates a personal-scope epic request via the real API
|
|
321
|
-
* (POST /api/v1/me/epic-requests) using the user's own stored token.
|
|
322
|
-
*/
|
|
323
|
-
export async function invokeEpicRequestViaApi(job, ctx) {
|
|
324
|
-
// pxpipe (ENG-136): route API-mode calls through the proxy when enabled+healthy.
|
|
325
|
-
const routing = await resolveRouting();
|
|
326
|
-
const anthropic = new Anthropic(anthropicClientOptions(ctx.anthropicApiKey, routing));
|
|
327
|
-
// ENG-149: a continuation job carries a seed → resume/enrich prompt + update
|
|
328
|
-
// the target ER in place; a fresh job → normal prompt + create a new ER.
|
|
329
|
-
const seed = parseSeedPayload(job.payload);
|
|
330
|
-
const systemPrompt = resolveSystemPrompt(seed);
|
|
331
|
-
// Audit-gate state (bug #2): the ER we are building (a continuation starts with
|
|
332
|
-
// its target), and how many re-submit/re-audit rounds we've spent.
|
|
333
|
-
let currentErId = seed?.targetEpicRequestId ?? null;
|
|
334
|
-
let qualityRounds = 0;
|
|
335
|
-
// Malformed-completion recovery: a model can emit "done" JSON we can't parse.
|
|
336
|
-
let jsonRepairs = 0;
|
|
337
|
-
const messages = [];
|
|
338
|
-
// Seed the conversation with any turns already on the job (e.g. a resumed
|
|
339
|
-
// daemon restart), so we don't re-ask questions already answered. A seeded
|
|
340
|
-
// USER turn may carry image attachments (ENG-153) — fetch + attach them as
|
|
341
|
-
// vision blocks; agent turns and image-free user turns are unchanged.
|
|
342
|
-
for (const turn of job.turns) {
|
|
343
|
-
if (turn.role === 'agent') {
|
|
344
|
-
messages.push({ role: 'assistant', content: turn.content });
|
|
345
|
-
}
|
|
346
|
-
else {
|
|
347
|
-
messages.push({ role: 'user', content: await apiUserTurnContent(turn) });
|
|
348
|
-
}
|
|
349
|
-
}
|
|
350
|
-
let turnsSoFar = job.turns.length;
|
|
351
|
-
for (let i = 0; i < MAX_INTERVIEW_TURNS; i++) {
|
|
352
|
-
let reply;
|
|
353
|
-
try {
|
|
354
|
-
const response = await anthropic.messages.create({
|
|
355
|
-
model: ANTHROPIC_MODEL,
|
|
356
|
-
max_tokens: 1024,
|
|
357
|
-
system: systemPrompt,
|
|
358
|
-
messages: messages.length > 0 ? messages : [{ role: 'user', content: 'Let\'s get started.' }],
|
|
359
|
-
});
|
|
360
|
-
const textBlock = response.content.find((b) => b.type === 'text');
|
|
361
|
-
reply = textBlock?.type === 'text' ? textBlock.text : '';
|
|
362
|
-
}
|
|
363
|
-
catch (error) {
|
|
364
|
-
const message = error instanceof Error ? error.message : 'Anthropic API request failed';
|
|
365
|
-
return { status: 'failed', result: { error: `Agent invocation failed: ${message}` } };
|
|
366
|
-
}
|
|
367
|
-
const draft = extractCompletionJson(reply);
|
|
368
|
-
if (draft) {
|
|
369
|
-
let submitted;
|
|
370
|
-
try {
|
|
371
|
-
submitted = await submitAndScore(ctx, currentErId, draft);
|
|
372
|
-
}
|
|
373
|
-
catch (error) {
|
|
374
|
-
const message = error instanceof Error ? error.message : 'Failed to save the epic request';
|
|
375
|
-
return { status: 'failed', result: { error: message } };
|
|
376
|
-
}
|
|
377
|
-
currentErId = submitted.erId;
|
|
378
|
-
const compliance = submitted.compliance;
|
|
379
|
-
// Finish only once the request passes the audit (>=90, no criticals), or
|
|
380
|
-
// when the quality-round budget is spent — best-effort, never stranded.
|
|
381
|
-
if (meetsComplianceTarget(compliance) || qualityRounds >= MAX_QUALITY_ROUNDS) {
|
|
382
|
-
return { status: 'done', result: { epicRequestId: currentErId } };
|
|
383
|
-
}
|
|
384
|
-
// Not good enough: feed the failing rules back (a model-facing round, no
|
|
385
|
-
// user turn) and loop — the model re-emits a richer completion or asks the
|
|
386
|
-
// employee a targeted question next iteration. (compliance is non-null here:
|
|
387
|
-
// meetsComplianceTarget(null) is true, so a null score would have finished.)
|
|
388
|
-
qualityRounds++;
|
|
389
|
-
if (compliance !== null) {
|
|
390
|
-
messages.push({ role: 'assistant', content: reply });
|
|
391
|
-
messages.push({ role: 'user', content: buildAuditFeedback(compliance) });
|
|
392
|
-
}
|
|
393
|
-
continue;
|
|
394
|
-
}
|
|
395
|
-
// The model TRIED to finish but the JSON was unusable (bug: malformed
|
|
396
|
-
// completion relayed to the employee as a question, looping forever). Correct
|
|
397
|
-
// the model instead of posting raw JSON — bounded, then fail cleanly.
|
|
398
|
-
if (looksLikeCompletionAttempt(reply)) {
|
|
399
|
-
if (jsonRepairs >= MAX_JSON_REPAIRS) {
|
|
400
|
-
return {
|
|
401
|
-
status: 'failed',
|
|
402
|
-
result: {
|
|
403
|
-
error: 'The interview produced malformed completion data and could not be finalized after several attempts.',
|
|
404
|
-
},
|
|
405
|
-
};
|
|
406
|
-
}
|
|
407
|
-
jsonRepairs++;
|
|
408
|
-
messages.push({ role: 'assistant', content: reply });
|
|
409
|
-
messages.push({ role: 'user', content: COMPLETION_REPAIR_INSTRUCTION });
|
|
410
|
-
continue;
|
|
411
|
-
}
|
|
412
|
-
// Not done yet — `reply` is the next question. Post it and wait for the answer.
|
|
413
|
-
messages.push({ role: 'assistant', content: reply });
|
|
414
|
-
let updated;
|
|
415
|
-
try {
|
|
416
|
-
updated = await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, reply);
|
|
417
|
-
}
|
|
418
|
-
catch (error) {
|
|
419
|
-
const message = error instanceof Error ? error.message : 'post-turn failed';
|
|
420
|
-
return { status: 'failed', result: { error: message } };
|
|
421
|
-
}
|
|
422
|
-
turnsSoFar = updated.turns.length;
|
|
423
|
-
const answered = await waitForUserReply(ctx.mailboxClient, ctx.machineToken, job.id, turnsSoFar);
|
|
424
|
-
if (!answered) {
|
|
425
|
-
return {
|
|
426
|
-
status: 'failed',
|
|
427
|
-
result: { error: 'Timed out waiting for a reply — no response within 10 minutes.' },
|
|
428
|
-
};
|
|
429
|
-
}
|
|
430
|
-
const lastTurn = answered.turns[answered.turns.length - 1];
|
|
431
|
-
// ENG-153: the employee's reply may include image attachments — attach them
|
|
432
|
-
// as vision blocks (image-free replies stay a plain string, as before).
|
|
433
|
-
messages.push({
|
|
434
|
-
role: 'user',
|
|
435
|
-
content: lastTurn ? await apiUserTurnContent(lastTurn) : '',
|
|
436
|
-
});
|
|
437
|
-
turnsSoFar = answered.turns.length;
|
|
438
|
-
}
|
|
439
|
-
// Turn budget exhausted. If we already produced an ER (fresh create or a
|
|
440
|
-
// continuation's target), finalize with it best-effort rather than losing the
|
|
441
|
-
// work (bug #3); only fail outright if nothing was ever submitted.
|
|
442
|
-
return currentErId
|
|
443
|
-
? { status: 'done', result: { epicRequestId: currentErId } }
|
|
444
|
-
: {
|
|
445
|
-
status: 'failed',
|
|
446
|
-
result: { error: `Interview did not converge after ${String(MAX_INTERVIEW_TURNS)} turns.` },
|
|
447
|
-
};
|
|
448
|
-
}
|
|
449
247
|
/**
|
|
450
248
|
* Fixed working directory for every `claude` CLI invocation made by the
|
|
451
249
|
* subscription-mode invoker. Two reasons this must be a stable, dedicated
|
|
@@ -503,11 +301,11 @@ function claudeCliSessionCwd() {
|
|
|
503
301
|
*/
|
|
504
302
|
function runClaudeCliTurn(prompt, opts) {
|
|
505
303
|
return new Promise((resolve, reject) => {
|
|
304
|
+
const model = opts.model === undefined ? ANTHROPIC_MODEL : opts.model;
|
|
506
305
|
const args = [
|
|
507
306
|
'-p',
|
|
508
307
|
prompt,
|
|
509
|
-
'--model',
|
|
510
|
-
ANTHROPIC_MODEL,
|
|
308
|
+
...(model ? ['--model', model] : []),
|
|
511
309
|
'--output-format',
|
|
512
310
|
'json',
|
|
513
311
|
'--tools',
|
|
@@ -595,123 +393,91 @@ function runClaudeCliTurn(prompt, opts) {
|
|
|
595
393
|
});
|
|
596
394
|
});
|
|
597
395
|
}
|
|
396
|
+
// ---------------------------------------------------------------------
|
|
397
|
+
// Request conversations (always open): one AI reply per claim.
|
|
398
|
+
// ---------------------------------------------------------------------
|
|
399
|
+
/** The request this conversation already saved, read with the person's token. */
|
|
400
|
+
async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId) {
|
|
401
|
+
const res = await fetch(`${apiBaseUrl.replace(/\/+$/, '')}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`, { headers: { Authorization: `Bearer ${userApiToken}` } });
|
|
402
|
+
if (!res.ok)
|
|
403
|
+
return null;
|
|
404
|
+
const body = (await res.json().catch(() => null));
|
|
405
|
+
return savedContextFromRecord(body?.data);
|
|
406
|
+
}
|
|
598
407
|
/**
|
|
599
|
-
*
|
|
600
|
-
*
|
|
601
|
-
|
|
602
|
-
|
|
408
|
+
* True when the person's Claude plan can't use the requested model (for
|
|
409
|
+
* example Fable needs usage credits on some plans): retry on their default.
|
|
410
|
+
*/
|
|
411
|
+
export function needsDefaultModel(error) {
|
|
412
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
413
|
+
return /requires usage credits|switch to another model|model.*not available|not have access to/i.test(message);
|
|
414
|
+
}
|
|
415
|
+
function savedRequestIdOf(job) {
|
|
416
|
+
const result = job.result;
|
|
417
|
+
if (typeof result?.epicRequestId === 'string')
|
|
418
|
+
return result.epicRequestId;
|
|
419
|
+
return parseSeedPayload(job.payload)?.targetEpicRequestId ?? null;
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Takes one step of a request conversation on this computer: the AI's reply to
|
|
423
|
+
* the person's latest message, which may save or update their request. Then
|
|
424
|
+
* the job is left waiting on the person (never completed), so the chat stays
|
|
425
|
+
* open: there is no reply timeout, and the computer is free for other work in
|
|
426
|
+
* the meantime. The server hands the job back when they write again.
|
|
427
|
+
*
|
|
428
|
+
* `anthropicApiKey` set → the Anthropic API; otherwise the local `claude` CLI
|
|
429
|
+
* on the person's own Claude sign-in.
|
|
603
430
|
*/
|
|
604
|
-
export async function
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
431
|
+
export async function invokeEpicRequestStep(job, ctx) {
|
|
432
|
+
try {
|
|
433
|
+
return await takeConversationStep(job, ctx);
|
|
434
|
+
}
|
|
435
|
+
catch (error) {
|
|
436
|
+
// Leave the conversation waiting on the person rather than retrying a
|
|
437
|
+
// broken step over and over; their next message tries again.
|
|
438
|
+
const reason = error instanceof Error ? error.message : 'something went wrong';
|
|
439
|
+
await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, `I couldn't continue: ${reason}\n\nSend another message (for example "try again") and I'll pick up where we left off.`);
|
|
440
|
+
return { status: 'yield' };
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
async function takeConversationStep(job, ctx) {
|
|
608
444
|
const routing = await resolveRouting();
|
|
609
|
-
|
|
610
|
-
const
|
|
611
|
-
const
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
: // ENG-153 (A4): subscription mode has no inline-image channel, so a
|
|
626
|
-
// user turn's images degrade to an explicit textual note.
|
|
627
|
-
`They replied: ${appendAttachmentNote(t.content, imageAttachmentCount(t.attachments))}`)
|
|
628
|
-
.join('\n') +
|
|
629
|
-
'\n\nContinue the interview from exactly where this left off — ask the next question, or if you already have everything, respond with the completion JSON.'
|
|
630
|
-
: "Let's begin the interview.";
|
|
631
|
-
for (let i = 0; i < MAX_INTERVIEW_TURNS; i++) {
|
|
632
|
-
let turn;
|
|
633
|
-
try {
|
|
634
|
-
turn = await runClaudeCliTurn(nextPrompt, {
|
|
635
|
-
systemPrompt,
|
|
636
|
-
resumeSessionId: sessionId,
|
|
637
|
-
routing,
|
|
638
|
-
});
|
|
639
|
-
}
|
|
640
|
-
catch (error) {
|
|
641
|
-
const message = error instanceof Error ? error.message : 'claude CLI invocation failed';
|
|
642
|
-
return { status: 'failed', result: { error: `Agent invocation failed: ${message}` } };
|
|
643
|
-
}
|
|
644
|
-
sessionId = turn.sessionId;
|
|
645
|
-
const draft = extractCompletionJson(turn.text);
|
|
646
|
-
if (draft) {
|
|
647
|
-
let submitted;
|
|
445
|
+
const requestId = savedRequestIdOf(job);
|
|
446
|
+
const saved = requestId ? await loadSavedRequest(ctx.apiBaseUrl, ctx.userApiToken, requestId) : null;
|
|
447
|
+
const turns = job.turns.map((t) => ({
|
|
448
|
+
role: t.role,
|
|
449
|
+
content: t.role === 'user' ? appendAttachmentNote(t.content, imageAttachmentCount(t.attachments)) : t.content,
|
|
450
|
+
}));
|
|
451
|
+
const anthropic = ctx.anthropicApiKey ? new Anthropic(anthropicClientOptions(ctx.anthropicApiKey, routing)) : null;
|
|
452
|
+
let cliModel = ANTHROPIC_MODEL;
|
|
453
|
+
const outcome = await runConversationStep({ turns, saved }, {
|
|
454
|
+
reply: async (system, messages) => {
|
|
455
|
+
if (anthropic) {
|
|
456
|
+
const response = await anthropic.messages.create({ model: ANTHROPIC_MODEL, max_tokens: 4096, system, messages });
|
|
457
|
+
const text = response.content.find((b) => b.type === 'text');
|
|
458
|
+
return text?.type === 'text' ? text.text : '';
|
|
459
|
+
}
|
|
460
|
+
const prompt = renderConversationPrompt(messages);
|
|
648
461
|
try {
|
|
649
|
-
|
|
462
|
+
return (await runClaudeCliTurn(prompt, { systemPrompt: system, resumeSessionId: undefined, routing, model: cliModel })).text;
|
|
650
463
|
}
|
|
651
464
|
catch (error) {
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
const compliance = submitted.compliance;
|
|
657
|
-
if (meetsComplianceTarget(compliance) || qualityRounds >= MAX_QUALITY_ROUNDS) {
|
|
658
|
-
return { status: 'done', result: { epicRequestId: currentErId } };
|
|
659
|
-
}
|
|
660
|
-
// Feed the failing rules back into the SAME resumed session (no user turn);
|
|
661
|
-
// the model re-emits a richer completion or asks a targeted question next.
|
|
662
|
-
// (compliance is non-null here — see the api-mode note above.)
|
|
663
|
-
qualityRounds++;
|
|
664
|
-
if (compliance !== null) {
|
|
665
|
-
nextPrompt = buildAuditFeedback(compliance);
|
|
465
|
+
if (cliModel === null || !needsDefaultModel(error))
|
|
466
|
+
throw error;
|
|
467
|
+
cliModel = null;
|
|
468
|
+
return (await runClaudeCliTurn(prompt, { systemPrompt: system, resumeSessionId: undefined, routing, model: null })).text;
|
|
666
469
|
}
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
result: {
|
|
676
|
-
error: 'The interview produced malformed completion data and could not be finalized after several attempts.',
|
|
677
|
-
},
|
|
678
|
-
};
|
|
679
|
-
}
|
|
680
|
-
jsonRepairs++;
|
|
681
|
-
nextPrompt = COMPLETION_REPAIR_INSTRUCTION;
|
|
682
|
-
continue;
|
|
683
|
-
}
|
|
684
|
-
// Not done yet — turn.text is the next question. Post it and wait for the answer.
|
|
685
|
-
let updated;
|
|
686
|
-
try {
|
|
687
|
-
updated = await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, turn.text);
|
|
688
|
-
}
|
|
689
|
-
catch (error) {
|
|
690
|
-
const message = error instanceof Error ? error.message : 'post-turn failed';
|
|
691
|
-
return { status: 'failed', result: { error: message } };
|
|
692
|
-
}
|
|
693
|
-
turnsSoFar = updated.turns.length;
|
|
694
|
-
const answered = await waitForUserReply(ctx.mailboxClient, ctx.machineToken, job.id, turnsSoFar);
|
|
695
|
-
if (!answered) {
|
|
696
|
-
return {
|
|
697
|
-
status: 'failed',
|
|
698
|
-
result: { error: 'Timed out waiting for a reply — no response within 10 minutes.' },
|
|
699
|
-
};
|
|
700
|
-
}
|
|
701
|
-
const lastTurn = answered.turns[answered.turns.length - 1];
|
|
702
|
-
// ENG-153 (A4): note any attached images textually (subscription-mode degradation).
|
|
703
|
-
nextPrompt = lastTurn
|
|
704
|
-
? appendAttachmentNote(lastTurn.content, imageAttachmentCount(lastTurn.attachments))
|
|
705
|
-
: '';
|
|
706
|
-
turnsSoFar = answered.turns.length;
|
|
470
|
+
},
|
|
471
|
+
save: async (existingId, draft) => {
|
|
472
|
+
const submitted = await submitAndScore(ctx, existingId, draft);
|
|
473
|
+
return { id: submitted.erId, title: draft.title, compliance: submitted.compliance };
|
|
474
|
+
},
|
|
475
|
+
});
|
|
476
|
+
if (outcome.kind === 'saved') {
|
|
477
|
+
await ctx.mailboxClient.markRequestSaved(ctx.machineToken, job.id, outcome.saved.id);
|
|
707
478
|
}
|
|
708
|
-
|
|
709
|
-
return
|
|
710
|
-
? { status: 'done', result: { epicRequestId: currentErId } }
|
|
711
|
-
: {
|
|
712
|
-
status: 'failed',
|
|
713
|
-
result: { error: `Interview did not converge after ${String(MAX_INTERVIEW_TURNS)} turns.` },
|
|
714
|
-
};
|
|
479
|
+
await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text);
|
|
480
|
+
return { status: 'yield' };
|
|
715
481
|
}
|
|
716
482
|
// ---------------------------------------------------------------------
|
|
717
483
|
// start_execution / kind:'plan' (ENG-164) — run the local @planner headless
|
|
@@ -789,15 +555,29 @@ export function buildPlannerArgs(epicRequestId) {
|
|
|
789
555
|
'bypassPermissions',
|
|
790
556
|
];
|
|
791
557
|
}
|
|
792
|
-
/**
|
|
558
|
+
/**
|
|
559
|
+
* Defensive failure when an invoker is handed no folder. The daemon routes every
|
|
560
|
+
* job to its repository's registered folder before calling an invoker, so this
|
|
561
|
+
* only fires if a caller skipped that step. There is no default folder.
|
|
562
|
+
*/
|
|
793
563
|
export function projectDirNotConfiguredMessage() {
|
|
794
564
|
return [
|
|
795
|
-
|
|
796
|
-
'
|
|
797
|
-
' - `compbox
|
|
798
|
-
'
|
|
799
|
-
|
|
800
|
-
|
|
565
|
+
"This run has no project folder on this computer, so it can't run.",
|
|
566
|
+
'Each run works only in the folder registered for its project\'s repository:',
|
|
567
|
+
' - `compbox machines dirs add <path-to-your-checkout>` (or re-run `compbox configure`)',
|
|
568
|
+
'CompBox never falls back to a default folder.',
|
|
569
|
+
].join('\n');
|
|
570
|
+
}
|
|
571
|
+
/**
|
|
572
|
+
* Actionable failure when a dispatched job carries no repository (`projectRemote`).
|
|
573
|
+
* A machine has NO default folder, so the job is refused rather than run in some
|
|
574
|
+
* other folder — which is how a build once landed in the wrong project.
|
|
575
|
+
*/
|
|
576
|
+
export function noProjectRemoteMessage() {
|
|
577
|
+
return [
|
|
578
|
+
"This run isn't linked to a project repository, so this computer won't run it.",
|
|
579
|
+
"Update CompBox (`brew upgrade compbox`) or connect the project's repository in its Settings → Repository, then send the run again.",
|
|
580
|
+
'CompBox only runs work in the folder registered for its project\'s repository — never in a default folder.',
|
|
801
581
|
].join('\n');
|
|
802
582
|
}
|
|
803
583
|
/**
|
|
@@ -821,11 +601,11 @@ export function unregisteredRemoteMessage(remote) {
|
|
|
821
601
|
/** Actionable failure when the configured path is not a git repository. */
|
|
822
602
|
export function projectDirNotGitRepoMessage(dir) {
|
|
823
603
|
return [
|
|
824
|
-
`The
|
|
825
|
-
'The planner runs the local `claude` CLI in this
|
|
604
|
+
`The project folder registered for this run's repository is not a git repository: ${dir}`,
|
|
605
|
+
'The planner runs the local `claude` CLI in this folder so the repo\'s .mcp.json (CompBox MCP)',
|
|
826
606
|
'and CLAUDE.md (@agent routing) load — both require a real checkout.',
|
|
827
|
-
'
|
|
828
|
-
'
|
|
607
|
+
'Register the right checkout with `compbox machines dirs add <path>` (or re-run `compbox configure`),',
|
|
608
|
+
'then re-run the job.',
|
|
829
609
|
].join('\n');
|
|
830
610
|
}
|
|
831
611
|
/** Parse the first balanced top-level `{...}` JSON objects out of arbitrary text (string-aware). */
|
|
@@ -1115,6 +895,12 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
|
|
|
1115
895
|
export const ORCHESTRATOR_RUN_TIMEOUT_MS = 3 * 60 * 60 * 1_000;
|
|
1116
896
|
/** Keep-alive cadence while the orchestrator child runs (H4) — same as the planner path. */
|
|
1117
897
|
export const ORCHESTRATOR_HEARTBEAT_INTERVAL_MS = PLANNER_HEARTBEAT_INTERVAL_MS;
|
|
898
|
+
/**
|
|
899
|
+
* Appended to the headless orchestrate prompt (orchestrator.md H3): a print-mode
|
|
900
|
+
* run ends when the agent stops, so anything left in the background is lost. A
|
|
901
|
+
* run once exited "waiting for the architect review" after one task.
|
|
902
|
+
*/
|
|
903
|
+
export const HEADLESS_ORCHESTRATE_REMINDER = 'This is a non-interactive run: do NOT start sub-agents or reviews in the background and do not end your turn to wait for them. Run every step in this process and keep going until every feature is done or a hard gate stops the run.';
|
|
1118
904
|
/** Max chars of orchestrator output relayed in the final mailbox turn (bound turn size). */
|
|
1119
905
|
const ORCHESTRATOR_FINAL_TURN_MAX_CHARS = 4_000;
|
|
1120
906
|
/**
|
|
@@ -1132,6 +918,9 @@ export function buildOrchestratorArgs(epicId) {
|
|
|
1132
918
|
return [
|
|
1133
919
|
'-p',
|
|
1134
920
|
`@orchestrator execute epic ${epicId} --non-interactive`,
|
|
921
|
+
// H3 reminder: never background work in a print-mode run.
|
|
922
|
+
'--append-system-prompt',
|
|
923
|
+
HEADLESS_ORCHESTRATE_REMINDER,
|
|
1135
924
|
// H1: unattended permission mode so print-mode tool use never blocks on an
|
|
1136
925
|
// interactive "allow?" prompt (this path grants the full MCP surface).
|
|
1137
926
|
'--permission-mode',
|
|
@@ -1144,7 +933,7 @@ export function orchestrateNotGitRepoMessage(dir) {
|
|
|
1144
933
|
`The configured CompBox project directory is not a git repository: ${dir}`,
|
|
1145
934
|
'The orchestrator runs the local `claude` CLI in this directory so the repo\'s .mcp.json (CompBox MCP)',
|
|
1146
935
|
'and CLAUDE.md (@agent routing) load, and it drives builds/tests through git worktrees — all require a real checkout.',
|
|
1147
|
-
'
|
|
936
|
+
'Register the right checkout with `compbox machines dirs add <path>` and re-run the job.',
|
|
1148
937
|
].join('\n');
|
|
1149
938
|
}
|
|
1150
939
|
/** Actionable failure when `git worktree` is unavailable in the project dir. */
|
|
@@ -1205,8 +994,24 @@ export function defaultToolchainPresent(_dir) {
|
|
|
1205
994
|
}
|
|
1206
995
|
return false;
|
|
1207
996
|
}
|
|
997
|
+
/**
|
|
998
|
+
* The job result for a headless run that exited cleanly but left features
|
|
999
|
+
* unfinished. Pure — exported for unit testing.
|
|
1000
|
+
*/
|
|
1001
|
+
export function buildIncompleteRunResult(epicId, progress) {
|
|
1002
|
+
return {
|
|
1003
|
+
needsAttention: true,
|
|
1004
|
+
epicId,
|
|
1005
|
+
completedFeatures: progress.completedFeatures,
|
|
1006
|
+
totalFeatures: progress.totalFeatures,
|
|
1007
|
+
message: `The run stopped before finishing: ${String(progress.completedFeatures)} of ${String(progress.totalFeatures)} features done. Send the build again to continue.`,
|
|
1008
|
+
};
|
|
1009
|
+
}
|
|
1208
1010
|
/** Plain-language summary of where a run's code ended up. */
|
|
1209
1011
|
export function describeRunBranch(finish) {
|
|
1012
|
+
if (finish.needsAttention) {
|
|
1013
|
+
return `Needs attention: the run's work was kept in ${finish.keptWorktree ?? 'its run folder'} (branch ${finish.branch}) because it couldn't all be committed.`;
|
|
1014
|
+
}
|
|
1210
1015
|
if (finish.prUrl)
|
|
1211
1016
|
return `Pull request: ${finish.prUrl}`;
|
|
1212
1017
|
if (finish.compareUrl)
|
|
@@ -1409,6 +1214,26 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
|
|
|
1409
1214
|
finish({ status: 'done', result: { epicId: ctx.epicId } });
|
|
1410
1215
|
});
|
|
1411
1216
|
});
|
|
1217
|
+
// A clean exit isn't proof the epic is finished: a headless run can end its
|
|
1218
|
+
// turn early (e.g. "waiting" on a background review). Check CompBox, and flag
|
|
1219
|
+
// the run for attention when features are still outstanding.
|
|
1220
|
+
if (outcome.status === 'done') {
|
|
1221
|
+
const readProgress = deps.epicProgress ??
|
|
1222
|
+
(async () => {
|
|
1223
|
+
try {
|
|
1224
|
+
const job = await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, `The orchestrator finished. Checking epic ${ctx.epicId}'s progress in CompBox…`);
|
|
1225
|
+
return job.progress ?? null;
|
|
1226
|
+
}
|
|
1227
|
+
catch {
|
|
1228
|
+
return null;
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
const progress = await readProgress();
|
|
1232
|
+
if (progress && progress.totalFeatures > 0 && progress.completedFeatures < progress.totalFeatures) {
|
|
1233
|
+
outcome.status = 'failed';
|
|
1234
|
+
outcome.result = buildIncompleteRunResult(ctx.epicId, progress);
|
|
1235
|
+
}
|
|
1236
|
+
}
|
|
1412
1237
|
// Commit what's left, push the branch and open the pull request (draft when
|
|
1413
1238
|
// the run stopped early), then attach where the code is to the job result.
|
|
1414
1239
|
let branchLine = '';
|
|
@@ -1435,7 +1260,19 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
|
|
|
1435
1260
|
...(finished.prUrl ? { prUrl: finished.prUrl } : {}),
|
|
1436
1261
|
...(finished.compareUrl ? { compareUrl: finished.compareUrl } : {}),
|
|
1437
1262
|
...(finished.notes.length > 0 ? { branchNotes: finished.notes } : {}),
|
|
1263
|
+
...(finished.keptWorktree ? { keptWorktree: finished.keptWorktree } : {}),
|
|
1438
1264
|
};
|
|
1265
|
+
// Work that isn't safely on a branch is never "done": the worktree was kept
|
|
1266
|
+
// and the person needs to look at it.
|
|
1267
|
+
if (finished.needsAttention) {
|
|
1268
|
+
outcome.status = 'failed';
|
|
1269
|
+
outcome.result = {
|
|
1270
|
+
...outcome.result,
|
|
1271
|
+
needsAttention: true,
|
|
1272
|
+
message: `The run's work couldn't be saved to its branch, so it was kept in ${finished.keptWorktree ?? 'its run folder'}.` +
|
|
1273
|
+
(typeof outcome.result.message === 'string' ? ` ${outcome.result.message}` : ''),
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1439
1276
|
}
|
|
1440
1277
|
// H4: relay a FINAL turn summarizing the outcome (best-effort).
|
|
1441
1278
|
try {
|