@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.
Files changed (44) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/commands/configure.d.ts +2 -0
  3. package/commands/configure.d.ts.map +1 -1
  4. package/commands/configure.js +34 -55
  5. package/commands/configure.js.map +1 -1
  6. package/commands/deploy.d.ts +22 -0
  7. package/commands/deploy.d.ts.map +1 -0
  8. package/commands/deploy.js +96 -0
  9. package/commands/deploy.js.map +1 -0
  10. package/commands/doctor.d.ts +14 -12
  11. package/commands/doctor.d.ts.map +1 -1
  12. package/commands/doctor.js +35 -19
  13. package/commands/doctor.js.map +1 -1
  14. package/commands/repo.d.ts +24 -0
  15. package/commands/repo.d.ts.map +1 -0
  16. package/commands/repo.js +81 -0
  17. package/commands/repo.js.map +1 -0
  18. package/commands/run.d.ts +12 -16
  19. package/commands/run.d.ts.map +1 -1
  20. package/commands/run.js +117 -55
  21. package/commands/run.js.map +1 -1
  22. package/commands/workspace.d.ts +56 -0
  23. package/commands/workspace.d.ts.map +1 -0
  24. package/commands/workspace.js +177 -0
  25. package/commands/workspace.js.map +1 -0
  26. package/index.js +1022 -514
  27. package/index.js.map +1 -1
  28. package/package.json +1 -1
  29. package/utils/agent-invoker.d.ts +62 -45
  30. package/utils/agent-invoker.d.ts.map +1 -1
  31. package/utils/agent-invoker.js +172 -335
  32. package/utils/agent-invoker.js.map +1 -1
  33. package/utils/config-store.d.ts +30 -58
  34. package/utils/config-store.d.ts.map +1 -1
  35. package/utils/config-store.js +27 -47
  36. package/utils/config-store.js.map +1 -1
  37. package/utils/mailbox-client.d.ts +33 -1
  38. package/utils/mailbox-client.d.ts.map +1 -1
  39. package/utils/mailbox-client.js +46 -2
  40. package/utils/mailbox-client.js.map +1 -1
  41. package/utils/run-workspace.d.ts +40 -4
  42. package/utils/run-workspace.d.ts.map +1 -1
  43. package/utils/run-workspace.js +141 -35
  44. package/utils/run-workspace.js.map +1 -1
package/index.js CHANGED
@@ -7,7 +7,7 @@ var __export = (target, all) => {
7
7
 
8
8
  // src/index.ts
9
9
  import { createRequire } from "node:module";
10
- import { Command as Command12 } from "commander";
10
+ import { Command as Command15 } from "commander";
11
11
 
12
12
  // src/commands/install.ts
13
13
  import { Command } from "commander";
@@ -5555,76 +5555,10 @@ var INTERVIEW_DEFINITION = [
5555
5555
  fields: ["alternatives"]
5556
5556
  }
5557
5557
  ];
5558
- var INTERVIEW_FIELD_MIN_WORDS = {
5559
- problemStatement: 60,
5560
- proposedSolution: 100,
5561
- impactAssessment: 40,
5562
- description: 150
5563
- };
5564
- function buildInterviewSystemPrompt(definition = INTERVIEW_DEFINITION, seedContext) {
5565
- const requiredSections = definition.filter((s) => s.required);
5566
- const optionalSections = definition.filter((s) => !s.required);
5567
- const renderSection = (s) => {
5568
- const tag = s.required ? "REQUIRED" : "OPTIONAL \u2014 ask, but the user may decline";
5569
- const followUps = s.followUps.map((q) => ` - ${q}`).join("\n");
5570
- return `- ${s.title} (${tag}) [json keys: ${s.fields.join(", ")}]
5571
- ${s.purpose}
5572
- ${followUps}`;
5573
- };
5574
- const completionKeys = [
5575
- "title",
5576
- ...interviewFieldKeysFor(definition),
5577
- "description"
5578
- ];
5579
- const completionShape = completionKeys.map((k) => `"${k}": "..."`).join(", ");
5580
- const base = `You are the CompBox request-formulator, interviewing an employee to turn their idea into a well-formed Epic Request. Ask exactly ONE short, focused question at a time \u2014 never multiple questions in one message, never preamble or explanation.
5581
-
5582
- Work through these interview sections in order. Cover EVERY required section; for optional sections, ask about them too, but if the employee has nothing to add or declines, move on and leave that field out (never invent or pad it):
5583
-
5584
- REQUIRED sections (an Epic Request cannot omit these):
5585
- ${requiredSections.map(renderSection).join("\n")}
5586
-
5587
- OPTIONAL-BUT-RECOMMENDED sections (ask about each; omit the field if the employee has nothing):
5588
- ${optionalSections.map(renderSection).join("\n")}
5589
-
5590
- The employee's answers may be short or casual \u2014 that's fine, but when you write the final fields below, EXPAND them into complete, well-written prose using everything they told you across the whole conversation, not just a compressed one-liner. Each required field is scored by an automated quality rubric with hard minimums, so undershooting length is a real failure, not just a style nitpick:
5591
- - problemStatement: at least ${String(INTERVIEW_FIELD_MIN_WORDS.problemStatement)} words.
5592
- - proposedSolution: at least ${String(INTERVIEW_FIELD_MIN_WORDS.proposedSolution)} words.
5593
- - impactAssessment: at least ${String(INTERVIEW_FIELD_MIN_WORDS.impactAssessment)} words.
5594
- - description: at least ${String(INTERVIEW_FIELD_MIN_WORDS.description)} words. This is a SEPARATE plain-text field (not shown to the employee) that stands alone as a full narrative summary of the whole request \u2014 restate the problem, the proposed solution, and the expected impact in flowing prose, as if writing the request from scratch for someone who hasn't seen the conversation.
5595
-
5596
- Once you have gathered the required sections (and covered the optional ones), respond with ONLY a fenced JSON code block (no other text) in exactly this shape. Include a key for every optional field you gathered; omit any optional field the employee had nothing for:
5597
- \`\`\`json
5598
- {"done": true, ${completionShape}}
5599
- \`\`\`
5600
-
5601
- Until then, respond with ONLY your next question as plain text \u2014 no JSON, no labels, no numbering.`;
5602
- if (!seedContext || seedContext.priorTranscript.length === 0) {
5603
- return base;
5604
- }
5605
- return `${renderContinuationHeader(seedContext.priorTranscript)}
5606
-
5607
- ${base}`;
5608
- }
5609
- function renderContinuationHeader(priorTranscript) {
5610
- const transcript = priorTranscript.map((t) => `${t.role === "agent" ? "You" : "Employee"}: ${t.content}`).join("\n");
5611
- return `\u26A0\uFE0F CONTINUATION \u2014 this is NOT a fresh interview. You already interviewed this employee; below is that prior conversation, and an Epic Request already exists from it. Your job now is to ENRICH that same request, not restart it.
5612
-
5613
- Prior conversation:
5614
- ${transcript}
5615
-
5616
- How to continue:
5617
- - Read the prior conversation first. Do NOT re-ask anything already answered there.
5618
- - Use the section list below only as a checklist of what a complete request needs. Identify which sections are MISSING or THIN, and ask focused questions to fill ONLY those gaps \u2014 still one short question at a time.
5619
- - If the prior conversation already covers everything well, go straight to the completion JSON.
5620
- - When you emit the final completion JSON, MERGE the prior answers with whatever new detail you gathered \u2014 restate and expand every field using the WHOLE conversation (old + new). Never drop or shorten content that was already captured; the goal is a richer request than before, meeting the same length minimums.
5621
-
5622
- `;
5623
- }
5624
- function interviewFieldKeysFor(definition) {
5558
+ function interviewFieldKeys() {
5625
5559
  const seen = /* @__PURE__ */ new Set();
5626
5560
  const out = [];
5627
- for (const section of definition) {
5561
+ for (const section of INTERVIEW_DEFINITION) {
5628
5562
  for (const f of section.fields) {
5629
5563
  if (!seen.has(f)) {
5630
5564
  seen.add(f);
@@ -5634,6 +5568,12 @@ function interviewFieldKeysFor(definition) {
5634
5568
  }
5635
5569
  return out;
5636
5570
  }
5571
+ var INTERVIEW_FIELD_MIN_WORDS = {
5572
+ problemStatement: 60,
5573
+ proposedSolution: 100,
5574
+ impactAssessment: 40,
5575
+ description: 150
5576
+ };
5637
5577
 
5638
5578
  // ../shared/dist/interview-completion.js
5639
5579
  var TARGET_COMPLIANCE_TIER = "pass";
@@ -5759,6 +5699,284 @@ function looksLikeCompletionAttempt(text) {
5759
5699
  }
5760
5700
  var COMPLETION_REPAIR_INSTRUCTION = 'Your last message looked like a completion but I could NOT parse it as a valid JSON object with all required fields. Re-emit ONLY a single valid JSON object inside a ```json code fence \u2014 no other text \u2014 with every string value properly escaped (escape any internal double-quotes as \\" and any line breaks as \\n), and make sure title, problemStatement, proposedSolution, impactAssessment, and description are all present and non-empty:\n```json\n{"done": true, "title": "...", "problemStatement": "...", "proposedSolution": "...", "impactAssessment": "...", "description": "..."}\n```';
5761
5701
 
5702
+ // ../shared/dist/interview-conversation.js
5703
+ var CONVERSATION_QUALITY_ROUNDS = 2;
5704
+ var JSON_REPAIRS = 3;
5705
+ var STARTER = "Hi! I'd like to propose something.";
5706
+ var NUDGE = "(Please continue.)";
5707
+ function renderSection(s) {
5708
+ const tag = s.required ? "needed" : "nice to have";
5709
+ return `- ${s.title} (${tag}): ${s.purpose} For example: ${s.followUps.slice(0, 2).join(" ")}`;
5710
+ }
5711
+ function renderSaved(saved) {
5712
+ const fieldLines = Object.entries(saved.fields).filter((entry) => typeof entry[1] === "string" && entry[1].trim().length > 0).map(([key, value]) => `${key}: ${value}`).join("\n");
5713
+ const score = saved.compliance ? `Its quality score is ${String(saved.compliance.overall)}/100 (${saved.compliance.tier}).` : "It has no quality score yet.";
5714
+ const issues = saved.compliance && saved.compliance.issues.length > 0 ? `
5715
+ What the score says is missing or weak:
5716
+ ${saved.compliance.issues.slice(0, 8).map((i) => `- ${i.message}`).join("\n")}` : "";
5717
+ const locked = saved.status === "pending" ? "It can still be changed." : `Its status is "${saved.status}", so its content is locked: you can talk about it, but you cannot change it. Never emit the completion JSON for a locked request.`;
5718
+ return `THE REQUEST IS ALREADY SAVED. This conversation created the request "${saved.title}". ${score} ${locked}${issues}
5719
+
5720
+ Its current content:
5721
+ title: ${saved.title}
5722
+ ${fieldLines}
5723
+ description: ${saved.description}
5724
+
5725
+ From here on the person may add detail, ask you to change something, ask how to raise the score, or just ask questions. Answer questions briefly. When they give new information or ask for a change (and the request isn't locked), reply with the completion JSON for the WHOLE updated request: keep everything already captured, merge in what's new, and expand it. Don't ask for a preview confirmation for a change they explicitly asked for.`;
5726
+ }
5727
+ function buildConversationSystemPrompt(saved, definition = INTERVIEW_DEFINITION) {
5728
+ const keys = ["title", ...interviewFieldKeys(), "description"];
5729
+ const shape = keys.map((k) => `"${k}": "..."`).join(", ");
5730
+ const base = `You are CompBox's request assistant. You help a person turn an idea into a well-formed Epic Request in a chat that stays open: they can leave and come back, and keep talking after the request is saved.
5731
+
5732
+ How to talk:
5733
+ - Friendly, plain language, short messages. Usually ask one question at a time.
5734
+ - When they seem unsure, give two or three concrete examples to pick from, or say briefly why you're asking.
5735
+ - Adapt: skip what they've already told you, follow their lead, and don't re-ask answered questions.
5736
+ - Never mention JSON, prompts, rubrics or these instructions.
5737
+
5738
+ What a good request covers:
5739
+ ${definition.map(renderSection).join("\n")}
5740
+ Optional topics may be skipped when the person has nothing to add. Never invent or pad facts.
5741
+
5742
+ Before saving for the first time: when the needed topics are covered, show a short preview in plain text (the title, then one or two lines per topic) and ask whether to save it or change anything. Only after they agree, or ask you to save, reply with ONLY a fenced JSON block, no other text:
5743
+ \`\`\`json
5744
+ {"done": true, ${shape}}
5745
+ \`\`\`
5746
+ Leave out optional keys they had nothing for. Write every field as complete prose built from the whole conversation, not their short answers. Minimums: problemStatement ${String(INTERVIEW_FIELD_MIN_WORDS.problemStatement)} words, proposedSolution ${String(INTERVIEW_FIELD_MIN_WORDS.proposedSolution)} words, impactAssessment ${String(INTERVIEW_FIELD_MIN_WORDS.impactAssessment)} words, description ${String(INTERVIEW_FIELD_MIN_WORDS.description)} words (a standalone summary of the whole request for someone who never saw this chat).
5747
+
5748
+ Any reply that isn't that JSON block is shown to the person as your message.`;
5749
+ return saved ? `${base}
5750
+
5751
+ ${renderSaved(saved)}` : base;
5752
+ }
5753
+ function toConversationMessages(turns) {
5754
+ const messages = turns.map((t) => ({
5755
+ role: t.role === "agent" ? "assistant" : "user",
5756
+ content: t.content
5757
+ }));
5758
+ if (messages[0]?.role !== "user")
5759
+ messages.unshift({ role: "user", content: STARTER });
5760
+ if (messages[messages.length - 1]?.role !== "user")
5761
+ messages.push({ role: "user", content: NUDGE });
5762
+ return messages;
5763
+ }
5764
+ function renderConversationPrompt(messages) {
5765
+ const lines = messages.map((m) => `${m.role === "assistant" ? "You" : "Them"}: ${m.content}`);
5766
+ return `The conversation so far:
5767
+
5768
+ ${lines.join("\n\n")}
5769
+
5770
+ Write your next reply to them.`;
5771
+ }
5772
+ function savedMessage(saved, created, followUp) {
5773
+ const verb = created ? "Saved your request" : "Updated your request";
5774
+ const c = saved.compliance;
5775
+ let text;
5776
+ if (!c) {
5777
+ text = `${verb} "${saved.title}". You can keep talking here to add detail or change anything.`;
5778
+ } else if (meetsComplianceTarget(c)) {
5779
+ text = `${verb} "${saved.title}". It scores ${String(c.overall)}/100, ready for review. You can keep talking here to change anything.`;
5780
+ } else {
5781
+ const gaps = [...c.issues.filter((i) => i.tier === "critical"), ...c.issues.filter((i) => i.tier === "advisory")].slice(0, 4).map((i) => `- ${i.message}`).join("\n");
5782
+ text = `${verb} "${saved.title}". It scores ${String(c.overall)}/100; 90 is the target.${gaps ? ` To raise it:
5783
+ ${gaps}` : ""}
5784
+
5785
+ Tell me more here and I'll update it, or leave it as it is.`;
5786
+ }
5787
+ return followUp ? `${text}
5788
+
5789
+ ${followUp}` : text;
5790
+ }
5791
+ async function runConversationStep(input, deps) {
5792
+ const system = buildConversationSystemPrompt(input.saved);
5793
+ const messages = toConversationMessages(input.turns);
5794
+ const locked = input.saved !== null && input.saved.status !== "pending";
5795
+ let requestId = input.saved?.id ?? null;
5796
+ let savedNow = null;
5797
+ let createdHere = false;
5798
+ let qualityRounds = 0;
5799
+ let repairs = 0;
5800
+ for (; ; ) {
5801
+ let reply;
5802
+ try {
5803
+ reply = await deps.reply(system, messages);
5804
+ } catch (error) {
5805
+ if (savedNow)
5806
+ return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created), ...savedNow };
5807
+ const reason = error instanceof Error ? error.message : "Something went wrong reaching the AI.";
5808
+ return {
5809
+ kind: "error",
5810
+ text: `I couldn't reply just now: ${reason}
5811
+
5812
+ Send another message (for example "try again") when you're ready and I'll pick up where we left off.`
5813
+ };
5814
+ }
5815
+ const draft = extractCompletionJson(reply);
5816
+ if (draft) {
5817
+ if (locked) {
5818
+ messages.push({ role: "assistant", content: reply }, { role: "user", content: "That request is locked and can't be changed. Reply to me in plain text instead." });
5819
+ if (++repairs > JSON_REPAIRS)
5820
+ return { kind: "error", text: "This request is locked, so it can't be changed any more." };
5821
+ continue;
5822
+ }
5823
+ let saved;
5824
+ try {
5825
+ saved = await deps.save(requestId, draft);
5826
+ } catch (error) {
5827
+ const reason = error instanceof Error ? error.message : "the save failed";
5828
+ return { kind: "error", text: `I couldn't save the request: ${reason}
5829
+
5830
+ Reply "try again" and I'll retry.` };
5831
+ }
5832
+ createdHere ||= requestId === null;
5833
+ savedNow = { saved, created: createdHere };
5834
+ requestId = saved.id;
5835
+ if (meetsComplianceTarget(saved.compliance) || qualityRounds >= CONVERSATION_QUALITY_ROUNDS || !saved.compliance) {
5836
+ return { kind: "saved", text: savedMessage(saved, savedNow.created), ...savedNow };
5837
+ }
5838
+ qualityRounds++;
5839
+ messages.push({ role: "assistant", content: reply }, {
5840
+ role: "user",
5841
+ content: `${buildAuditFeedback(saved.compliance)}
5842
+
5843
+ The request IS already saved, and the person will be shown its score. If you ask them something, ask it as a way to improve the saved request; never say it hasn't been saved.`
5844
+ });
5845
+ continue;
5846
+ }
5847
+ if (looksLikeCompletionAttempt(reply)) {
5848
+ if (++repairs > JSON_REPAIRS) {
5849
+ return savedNow ? { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created), ...savedNow } : { kind: "error", text: `I had trouble writing up the request. Reply "try again" and I'll have another go.` };
5850
+ }
5851
+ messages.push({ role: "assistant", content: reply }, { role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
5852
+ continue;
5853
+ }
5854
+ const text = reply.trim();
5855
+ if (savedNow) {
5856
+ return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created, text || void 0), ...savedNow };
5857
+ }
5858
+ if (!text)
5859
+ return { kind: "error", text: "I didn't get a reply that time. Send another message and I'll try again." };
5860
+ return { kind: "message", text };
5861
+ }
5862
+ }
5863
+ function savedContextFromRecord(record) {
5864
+ if (typeof record !== "object" || record === null)
5865
+ return null;
5866
+ const r = record;
5867
+ if (typeof r.id !== "string" || typeof r.title !== "string")
5868
+ return null;
5869
+ let structured = r.structuredDesc;
5870
+ if (typeof structured === "string") {
5871
+ try {
5872
+ structured = JSON.parse(structured);
5873
+ } catch {
5874
+ structured = null;
5875
+ }
5876
+ }
5877
+ const fields = {};
5878
+ if (typeof structured === "object" && structured !== null) {
5879
+ for (const [key, value] of Object.entries(structured)) {
5880
+ if (typeof value === "string")
5881
+ fields[key] = value;
5882
+ }
5883
+ }
5884
+ let score = r.complianceScore;
5885
+ if (typeof score === "string") {
5886
+ try {
5887
+ score = JSON.parse(score);
5888
+ } catch {
5889
+ score = null;
5890
+ }
5891
+ }
5892
+ return {
5893
+ id: r.id,
5894
+ title: r.title,
5895
+ status: typeof r.status === "string" ? r.status : "pending",
5896
+ description: typeof r.description === "string" ? r.description : "",
5897
+ fields,
5898
+ compliance: complianceFromRecord(score)
5899
+ };
5900
+ }
5901
+ function complianceFromRecord(score) {
5902
+ if (typeof score !== "object" || score === null)
5903
+ return null;
5904
+ const s = score;
5905
+ if (typeof s.overall !== "number" || typeof s.tier !== "string")
5906
+ return null;
5907
+ const issues = Array.isArray(s.issues) ? s.issues.filter((i) => typeof i === "object" && i !== null).map((i) => ({
5908
+ message: typeof i.message === "string" ? i.message : typeof i.code === "string" ? i.code : "issue",
5909
+ tier: i.tier === "critical" ? "critical" : "advisory"
5910
+ })) : [];
5911
+ return { overall: s.overall, tier: s.tier, issues };
5912
+ }
5913
+
5914
+ // ../shared/dist/cloud-connect.js
5915
+ var GITHUB_OIDC_THUMBPRINTS = ["6938fd4d98bab03faadb97b34396831e3780aea1", "1c58a3a8518e8759bf075b76b750d4f2df264fcd"];
5916
+ var AWS_SETUP_FUNCTION = `import json, urllib.error, urllib.request
5917
+ import boto3
5918
+
5919
+ ISSUER = "token.actions.githubusercontent.com"
5920
+
5921
+
5922
+ def respond(event, ok, data=None, reason=""):
5923
+ body = json.dumps({
5924
+ "Status": "SUCCESS" if ok else "FAILED",
5925
+ "Reason": (reason or "See the function's CloudWatch logs")[:1000],
5926
+ "PhysicalResourceId": event.get("PhysicalResourceId") or event["LogicalResourceId"],
5927
+ "StackId": event["StackId"],
5928
+ "RequestId": event["RequestId"],
5929
+ "LogicalResourceId": event["LogicalResourceId"],
5930
+ "Data": data or {},
5931
+ }).encode()
5932
+ req = urllib.request.Request(event["ResponseURL"], data=body, method="PUT", headers={"Content-Type": ""})
5933
+ urllib.request.urlopen(req, timeout=30)
5934
+
5935
+
5936
+ def github_oidc():
5937
+ iam = boto3.client("iam")
5938
+ for p in iam.list_open_id_connect_providers()["OpenIDConnectProviderList"]:
5939
+ arn = p["Arn"]
5940
+ if arn.endswith("/" + ISSUER):
5941
+ if "sts.amazonaws.com" not in iam.get_open_id_connect_provider(OpenIDConnectProviderArn=arn)["ClientIDList"]:
5942
+ iam.add_client_id_to_open_id_connect_provider(OpenIDConnectProviderArn=arn, ClientID="sts.amazonaws.com")
5943
+ return arn
5944
+ return iam.create_open_id_connect_provider(
5945
+ Url="https://" + ISSUER, ClientIDList=["sts.amazonaws.com"], ThumbprintList=${JSON.stringify(GITHUB_OIDC_THUMBPRINTS)}
5946
+ )["OpenIDConnectProviderArn"]
5947
+
5948
+
5949
+ def notify(p):
5950
+ body = json.dumps({
5951
+ "token": p["Token"], "accountId": p["AccountId"], "region": p["Region"],
5952
+ "roleArn": p["RoleArn"], "stateBucket": p["Bucket"],
5953
+ }).encode()
5954
+ req = urllib.request.Request(p["Url"], data=body, method="POST", headers={"Content-Type": "application/json"})
5955
+ try:
5956
+ urllib.request.urlopen(req, timeout=30)
5957
+ except urllib.error.HTTPError as e:
5958
+ raise RuntimeError("CompBox said: " + e.read().decode(errors="replace")[:500])
5959
+
5960
+
5961
+ def handler(event, context):
5962
+ try:
5963
+ props = event["ResourceProperties"]
5964
+ if event["RequestType"] == "Delete":
5965
+ return respond(event, True)
5966
+ if props["Action"] == "oidc":
5967
+ return respond(event, True, {"Arn": github_oidc()})
5968
+ try:
5969
+ notify(props)
5970
+ except Exception:
5971
+ # The connect link expires; a later stack update shouldn't fail on it.
5972
+ if event["RequestType"] != "Update":
5973
+ raise
5974
+ respond(event, True)
5975
+ except Exception as e:
5976
+ print(e)
5977
+ respond(event, False, reason=str(e))
5978
+ `;
5979
+
5762
5980
  // src/utils/config-store.ts
5763
5981
  var CONFIG_DIR_ENV = "COMPBOX_CONFIG_DIR";
5764
5982
  var PROJECT_DIR_ENV = "COMPBOX_PROJECT_DIR";
@@ -5817,28 +6035,22 @@ function applyPxpipeEnv(config, env = process.env) {
5817
6035
  env.PXPIPE_ENABLED = "false";
5818
6036
  }
5819
6037
  }
5820
- function resolveProjectDir(opts) {
5821
- const env = opts.env ?? process.env;
5822
- const candidates = [opts.flag, env[PROJECT_DIR_ENV], opts.config?.projectDir];
5823
- for (const candidate of candidates) {
6038
+ function resolveProjectDirForJob(projectRemote, opts) {
6039
+ const remote = normalizeGitRemote(projectRemote ?? "");
6040
+ if (remote.length === 0) {
6041
+ return { status: "no-remote" };
6042
+ }
6043
+ const entry = (opts.config?.projectDirs ?? []).find((e) => e.remote === remote);
6044
+ return entry ? { status: "registered", path: entry.path } : { status: "unregistered", remote };
6045
+ }
6046
+ function unusedLegacyProjectDir(config, env = process.env) {
6047
+ for (const candidate of [config?.projectDir, env[PROJECT_DIR_ENV]]) {
5824
6048
  if (typeof candidate === "string" && candidate.trim().length > 0) {
5825
6049
  return candidate.trim();
5826
6050
  }
5827
6051
  }
5828
6052
  return void 0;
5829
6053
  }
5830
- function resolveProjectDirForJob(projectRemote, opts) {
5831
- const remote = normalizeGitRemote(projectRemote ?? "");
5832
- if (remote.length > 0) {
5833
- const entry = (opts.config?.projectDirs ?? []).find((e) => e.remote === remote);
5834
- if (entry) {
5835
- return { status: "registered", path: entry.path };
5836
- }
5837
- return { status: "unregistered", remote };
5838
- }
5839
- const fallback = resolveProjectDir({ flag: opts.flag, env: opts.env, config: opts.config });
5840
- return fallback !== void 0 ? { status: "fallback", path: fallback } : { status: "unresolved" };
5841
- }
5842
6054
  function isGitRepoDir(dir) {
5843
6055
  try {
5844
6056
  return existsSync4(join4(dir, ".git")) && statSync(dir).isDirectory();
@@ -6360,12 +6572,18 @@ var MailboxClient = class {
6360
6572
  * here. Cloud Run bills vCPU for the wall-clock life of a request, so a held
6361
6573
  * connection kept one instance permanently awake at ~$64/month.
6362
6574
  */
6363
- async nextJob(machineToken, waitMs = 0) {
6575
+ /**
6576
+ * `runningIds`: jobs this daemon is already running, so the server hands out
6577
+ * new work instead of resuming one of them.
6578
+ */
6579
+ async nextJob(machineToken, waitMs = 0, runningIds = []) {
6364
6580
  let res;
6365
6581
  try {
6366
6582
  res = await this.http.get("/api/v1/machines/next-job", {
6367
6583
  headers: { Authorization: `Bearer ${machineToken}` },
6368
- params: { waitMs }
6584
+ // steps=1: this daemon runs request conversations one reply at a time,
6585
+ // so it never wants back a job that is waiting on the person.
6586
+ params: { waitMs, steps: "1", ...runningIds.length > 0 && { running: runningIds.join(",") } }
6369
6587
  });
6370
6588
  } catch (error) {
6371
6589
  throw toMailboxError(error, "next-job request failed");
@@ -6478,6 +6696,42 @@ var MailboxClient = class {
6478
6696
  const data = res.data;
6479
6697
  return data.data;
6480
6698
  }
6699
+ /**
6700
+ * Tells CompBox that a request conversation saved its epic request. The
6701
+ * conversation stays open; this only links the job to the request.
6702
+ */
6703
+ async markRequestSaved(machineToken, jobId, epicRequestId) {
6704
+ let res;
6705
+ try {
6706
+ res = await this.http.post(`/api/v1/jobs/${jobId}/saved`, { epicRequestId }, {
6707
+ headers: { Authorization: `Bearer ${machineToken}` }
6708
+ });
6709
+ } catch (error) {
6710
+ throw toMailboxError(error, "saved request failed");
6711
+ }
6712
+ if (res.status < 200 || res.status >= 300) {
6713
+ throw errorFromResponse(res, "saved failed");
6714
+ }
6715
+ }
6716
+ /**
6717
+ * Asks CompBox to open the run's pull request through the CompBox GitHub
6718
+ * app. Throws when the project isn't connected through the app (409), so
6719
+ * the caller can open it another way.
6720
+ */
6721
+ async openPullRequest(machineToken, jobId, input) {
6722
+ let res;
6723
+ try {
6724
+ res = await this.http.post(`/api/v1/jobs/${jobId}/pull-request`, input, {
6725
+ headers: { Authorization: `Bearer ${machineToken}` }
6726
+ });
6727
+ } catch (error) {
6728
+ throw toMailboxError(error, "pull-request request failed");
6729
+ }
6730
+ if (res.status < 200 || res.status >= 300) {
6731
+ throw errorFromResponse(res, "pull-request failed");
6732
+ }
6733
+ return res.data.data;
6734
+ }
6481
6735
  /** Reports what a run on the person's API key spent. */
6482
6736
  async reportAiUsage(machineToken, jobId, usage) {
6483
6737
  let res;
@@ -6746,6 +7000,7 @@ function installAutostart() {
6746
7000
  }
6747
7001
 
6748
7002
  // src/commands/configure.ts
7003
+ var PROJECT_FOLDER_QUESTION = "Add a project folder (a git checkout) \u2014 leave blank when done:";
6749
7004
  function parseAiMode(value) {
6750
7005
  if (value === "claude-subscription" || value === "api-key") {
6751
7006
  return value;
@@ -6840,78 +7095,47 @@ Device pairing failed: ${message}`));
6840
7095
  console.log(chalk7.gray(`
6841
7096
  Device already paired as "${config.machineName ?? config.machineId}".`));
6842
7097
  }
6843
- const defaultDir = isGitRepoDir(process.cwd()) ? process.cwd() : void 0;
6844
- console.log("\n" + chalk7.bold("Project folder:"));
7098
+ const legacyDir = config.projectDir?.trim();
7099
+ const registeredPaths = () => new Set(listProjectDirs().map((e) => e.path));
7100
+ const firstDefault = [process.cwd(), legacyDir].find(
7101
+ (dir) => typeof dir === "string" && dir.length > 0 && isGitRepoDir(dir) && !registeredPaths().has(dir)
7102
+ );
7103
+ console.log("\n" + chalk7.bold("Project folders:"));
6845
7104
  console.log(
6846
7105
  chalk7.gray(
6847
- " The folder with your code (a git project) where the AI plans, edits and commits.\n Leave blank to skip; add folders per project later with `compbox machines dirs add`."
7106
+ " Each project runs only in the folder you register for its repository (a git checkout\n with an origin remote). Add one folder per project. Leave blank when you are done."
6848
7107
  )
6849
7108
  );
6850
- const projectDirQuestion = "Which project folder should the AI work in?";
6851
- const MAX_PROJECT_DIR_ATTEMPTS = 5;
6852
- let projectDirPersisted = false;
6853
- let projectDirSkipped = false;
6854
- for (let attempt = 0; attempt < MAX_PROJECT_DIR_ATTEMPTS; attempt += 1) {
6855
- const answer = (await promptText(
6856
- projectDirQuestion,
6857
- defaultDir !== void 0 ? { defaultValue: defaultDir } : {}
6858
- )).trim();
6859
- if (answer.length === 0) {
6860
- projectDirSkipped = true;
6861
- break;
6862
- }
6863
- if (isGitRepoDir(answer)) {
6864
- updateConfig({ projectDir: answer });
6865
- console.log(chalk7.green(`\u2714 Project directory set to ${answer}`));
6866
- console.log(
6867
- chalk7.gray(" Dispatched plan/orchestrate runs will operate in this repository.")
6868
- );
6869
- projectDirPersisted = true;
6870
- break;
6871
- }
6872
- console.warn(
6873
- chalk7.yellow(
6874
- `\u26A0 ${answer} is not a git repository. Enter a path to a git checkout, or leave blank to skip.`
7109
+ if (legacyDir) {
7110
+ console.log(
7111
+ chalk7.gray(
7112
+ ` Note: this computer no longer uses a single default folder (${legacyDir}). Register it here if you still want runs for its repository to use it.`
6875
7113
  )
6876
7114
  );
6877
7115
  }
6878
- if (!projectDirPersisted) {
6879
- if (!projectDirSkipped) {
6880
- console.warn(
6881
- chalk7.yellow("\u26A0 No valid git repository entered \u2014 skipping the project directory for now.")
6882
- );
7116
+ const MAX_PROJECT_DIR_PROMPTS = 10;
7117
+ for (let attempt = 0; attempt < MAX_PROJECT_DIR_PROMPTS; attempt += 1) {
7118
+ const offerDefault = attempt === 0 && firstDefault !== void 0;
7119
+ const answer = (await promptText(PROJECT_FOLDER_QUESTION, offerDefault ? { defaultValue: firstDefault } : {})).trim();
7120
+ if (answer.length === 0) break;
7121
+ try {
7122
+ const entry = addProjectDir(answer);
7123
+ console.log(chalk7.green(`\u2714 Registered ${entry.remote} \u2192 ${entry.path}`));
7124
+ } catch (error) {
7125
+ const message = error instanceof Error ? error.message : "unknown error";
7126
+ console.warn(chalk7.yellow(`\u26A0 ${message} Enter another folder, or leave blank to finish.`));
6883
7127
  }
7128
+ }
7129
+ const registered = listProjectDirs();
7130
+ if (registered.length === 0) {
6884
7131
  console.log(
6885
7132
  chalk7.yellow(
6886
- "\n\u26A0 No project directory set \u2014 dispatched plan/orchestrate jobs will fail until one is configured."
7133
+ "\n\u26A0 No project folders registered \u2014 runs sent to this computer will be refused until you add one."
6887
7134
  )
6888
7135
  );
6889
- console.log(
6890
- chalk7.gray(
6891
- " Set it later with `compbox run --project-dir <path>`, the COMPBOX_PROJECT_DIR env var, or by re-running `compbox configure`."
6892
- )
6893
- );
6894
- }
6895
- if (isGitRepoDir(process.cwd())) {
6896
- const registerAllowlist = await promptConfirm(
6897
- "Register this repository (its origin remote \u2192 this path) so dispatched runs targeting it route to this machine?",
6898
- true
6899
- );
6900
- if (registerAllowlist) {
6901
- try {
6902
- const entry = addProjectDir(process.cwd());
6903
- console.log(chalk7.green(`\u2714 Registered ${entry.remote} \u2192 ${entry.path}`));
6904
- console.log(
6905
- chalk7.gray(" Manage the allowlist later with `compbox machines dirs list/add/rm`.")
6906
- );
6907
- } catch (error) {
6908
- const message = error instanceof Error ? error.message : "unknown error";
6909
- console.warn(chalk7.yellow(`\u26A0 Could not register this repository: ${message}`));
6910
- console.warn(
6911
- chalk7.gray(" You can register it later with `compbox machines dirs add`.")
6912
- );
6913
- }
6914
- }
7136
+ console.log(chalk7.gray(" Add one later with `compbox machines dirs add <path-to-checkout>`."));
7137
+ } else {
7138
+ console.log(chalk7.gray(` ${String(registered.length)} project folder(s) registered. Manage them with \`compbox machines dirs list/add/rm\`.`));
6915
7139
  }
6916
7140
  const mcpConfigPath = options.mcpConfig ?? defaultMcpConfigPath();
6917
7141
  const result = patchMcpConfig(mcpConfigPath, {
@@ -7520,26 +7744,40 @@ ${reRun}`
7520
7744
  };
7521
7745
  }
7522
7746
  function projectDirCheck(config) {
7523
- const name = "Project directory configured";
7524
- const dir = resolveProjectDir({ config });
7525
- if (dir === void 0) {
7747
+ const name = "Project folders registered";
7748
+ const entries = config.projectDirs ?? [];
7749
+ if (entries.length === 0) {
7526
7750
  return {
7527
7751
  name,
7528
7752
  passed: false,
7529
- detail: "No CompBox project repository is configured \u2014 run `compbox configure` to set one (start_execution/plan jobs fail until it is set)."
7753
+ detail: "No project folders are registered \u2014 runs sent to this computer are refused until you add one with `compbox machines dirs add <path>` (or `compbox configure`)."
7530
7754
  };
7531
7755
  }
7532
- if (!isGitRepoDir(dir)) {
7756
+ const broken = entries.filter((e) => !isGitRepoDir(e.path));
7757
+ if (broken.length > 0) {
7533
7758
  return {
7534
7759
  name,
7535
7760
  passed: false,
7536
- detail: `configured path is not a git repo: ${dir} \u2014 run \`compbox configure\` to point it at a CompBox repo checkout.`
7761
+ detail: `registered folder is not a git repo: ${broken.map((e) => `${e.remote} \u2192 ${e.path}`).join(", ")} \u2014 re-register it with \`compbox machines dirs add <path>\`.`
7537
7762
  };
7538
7763
  }
7539
7764
  return {
7540
7765
  name,
7541
7766
  passed: true,
7542
- detail: `Project repository configured at ${dir}.`
7767
+ detail: entries.map((e) => `${e.remote} \u2192 ${e.path}`).join("; ")
7768
+ };
7769
+ }
7770
+ function legacyProjectDirCheck(config, env = process.env) {
7771
+ const name = "Old default folder";
7772
+ const dir = unusedLegacyProjectDir(config, env);
7773
+ if (dir === void 0) {
7774
+ return { name, passed: true, skipped: true, detail: "not set" };
7775
+ }
7776
+ return {
7777
+ name,
7778
+ passed: true,
7779
+ warning: true,
7780
+ detail: `${dir} is set as a default folder but is no longer used \u2014 runs go only to the folder registered for their project's repository. Register it with \`compbox machines dirs add ${dir}\` if you still want it.`
7543
7781
  };
7544
7782
  }
7545
7783
  var doctorCommand = new Command7("doctor").description("Diagnose config, connectivity, machine pairing, MCP config, AI mode, and the service").option("--mcp-config <path>", "Path to the MCP config to check (default: ./.mcp.json)").action(async (options) => {
@@ -7692,6 +7930,7 @@ var doctorCommand = new Command7("doctor").description("Diagnose config, connect
7692
7930
  }
7693
7931
  results.push(await agentRuntimeCheck(config));
7694
7932
  results.push(projectDirCheck(config));
7933
+ results.push(legacyProjectDirCheck(config));
7695
7934
  if (process.platform === "darwin") {
7696
7935
  results.push(checkBrewService());
7697
7936
  }
@@ -7784,11 +8023,7 @@ function parseClaudeJsonResult(stdout2, fallbackModel) {
7784
8023
 
7785
8024
  // src/utils/agent-invoker.ts
7786
8025
  var ANTHROPIC_MODEL = "claude-fable-5";
7787
- var MAX_INTERVIEW_TURNS = 18;
7788
- var MAX_QUALITY_ROUNDS = 4;
7789
- var REPLY_POLL_INTERVAL_MS = 3e3;
7790
- var REPLY_TIMEOUT_MS = 10 * 60 * 1e3;
7791
- var CLAUDE_CLI_TURN_TIMEOUT_MS = 2 * 60 * 1e3;
8026
+ var CLAUDE_CLI_TURN_TIMEOUT_MS = 4 * 60 * 1e3;
7792
8027
  function anthropicClientOptions(apiKey, routing) {
7793
8028
  return routing.mode === "proxy" ? { apiKey, baseURL: routing.anthropicBaseUrl } : { apiKey };
7794
8029
  }
@@ -7801,11 +8036,7 @@ var SUPPORTED_IMAGE_MEDIA_TYPES = [
7801
8036
  "image/gif",
7802
8037
  "image/webp"
7803
8038
  ];
7804
- var MAX_IMAGES_PER_TURN = 8;
7805
8039
  var MAX_IMAGE_BYTES_PER_TURN = 20 * 1024 * 1024;
7806
- var defaultWarn = (message) => {
7807
- console.warn(` \u26A0 ${message}`);
7808
- };
7809
8040
  function normalizeImageMediaType(mime) {
7810
8041
  const base = (mime.split(";")[0] ?? "").trim().toLowerCase();
7811
8042
  return SUPPORTED_IMAGE_MEDIA_TYPES.includes(base) ? base : null;
@@ -7813,67 +8044,10 @@ function normalizeImageMediaType(mime) {
7813
8044
  function isSupportedImageMediaType(mime) {
7814
8045
  return normalizeImageMediaType(mime) !== null;
7815
8046
  }
7816
- function selectImageAttachments(attachments) {
7817
- if (!attachments || attachments.length === 0) return [];
7818
- const selected = [];
7819
- let declaredBytes = 0;
7820
- for (const att of attachments) {
7821
- if (selected.length >= MAX_IMAGES_PER_TURN) break;
7822
- if (!isSupportedImageMediaType(att.mimeType)) continue;
7823
- const size = typeof att.sizeBytes === "number" && att.sizeBytes > 0 ? att.sizeBytes : 0;
7824
- if (declaredBytes + size > MAX_IMAGE_BYTES_PER_TURN) continue;
7825
- declaredBytes += size;
7826
- selected.push(att);
7827
- }
7828
- return selected;
7829
- }
7830
8047
  function imageAttachmentCount(attachments) {
7831
8048
  if (!attachments || attachments.length === 0) return 0;
7832
8049
  return attachments.filter((a) => isSupportedImageMediaType(a.mimeType)).length;
7833
8050
  }
7834
- async function fetchImageBlocks(attachments, warn = defaultWarn, fetchImpl = fetch) {
7835
- const blocks = [];
7836
- let totalBytes = 0;
7837
- for (const att of attachments) {
7838
- const mediaType = normalizeImageMediaType(att.mimeType);
7839
- if (!mediaType) continue;
7840
- try {
7841
- const res = await fetchImpl(att.signedUrl);
7842
- if (!res.ok) {
7843
- warn(`Skipping image attachment ${att.id}: fetch failed (HTTP ${String(res.status)}).`);
7844
- continue;
7845
- }
7846
- const bytes = Buffer.from(await res.arrayBuffer());
7847
- if (bytes.byteLength === 0) {
7848
- warn(`Skipping image attachment ${att.id}: empty response body.`);
7849
- continue;
7850
- }
7851
- if (totalBytes + bytes.byteLength > MAX_IMAGE_BYTES_PER_TURN) {
7852
- warn(`Skipping image attachment ${att.id}: exceeds the per-turn image byte budget.`);
7853
- continue;
7854
- }
7855
- totalBytes += bytes.byteLength;
7856
- blocks.push({
7857
- type: "image",
7858
- source: { type: "base64", media_type: mediaType, data: bytes.toString("base64") }
7859
- });
7860
- } catch (error) {
7861
- const message = error instanceof Error ? error.message : "unknown error";
7862
- warn(`Skipping image attachment ${att.id}: ${message}.`);
7863
- }
7864
- }
7865
- return blocks;
7866
- }
7867
- function buildApiUserContent(text, imageBlocks) {
7868
- if (imageBlocks.length === 0) return text;
7869
- return [...imageBlocks, { type: "text", text }];
7870
- }
7871
- async function apiUserTurnContent(turn, warn = defaultWarn, fetchImpl = fetch) {
7872
- const selected = selectImageAttachments(turn.attachments);
7873
- if (selected.length === 0) return turn.content;
7874
- const blocks = await fetchImageBlocks(selected, warn, fetchImpl);
7875
- return buildApiUserContent(turn.content, blocks);
7876
- }
7877
8051
  function appendAttachmentNote(text, imageCount) {
7878
8052
  if (imageCount <= 0) return text;
7879
8053
  const noun = imageCount === 1 ? "image" : "images";
@@ -7882,7 +8056,6 @@ function appendAttachmentNote(text, imageCount) {
7882
8056
 
7883
8057
  ${note}` : note;
7884
8058
  }
7885
- var SYSTEM_PROMPT = buildInterviewSystemPrompt();
7886
8059
  function parseSeedPayload(payload) {
7887
8060
  if (typeof payload !== "object" || payload === null) return null;
7888
8061
  const p = payload;
@@ -7898,11 +8071,6 @@ function parseSeedPayload(payload) {
7898
8071
  priorTranscript
7899
8072
  };
7900
8073
  }
7901
- function resolveSystemPrompt(seed) {
7902
- return seed ? buildInterviewSystemPrompt(INTERVIEW_DEFINITION, {
7903
- priorTranscript: seed.priorTranscript
7904
- }) : SYSTEM_PROMPT;
7905
- }
7906
8074
  async function submitAndScore(ctx, currentErId, draft) {
7907
8075
  if (currentErId) {
7908
8076
  const compliance = await updatePersonalEpicRequest(
@@ -7916,118 +8084,6 @@ async function submitAndScore(ctx, currentErId, draft) {
7916
8084
  const created = await createPersonalEpicRequest(ctx.apiBaseUrl, ctx.userApiToken, draft);
7917
8085
  return { erId: created.id, compliance: created.compliance };
7918
8086
  }
7919
- var MAX_JSON_REPAIRS = 3;
7920
- function sleep(ms) {
7921
- return new Promise((resolve3) => setTimeout(resolve3, ms));
7922
- }
7923
- async function waitForUserReply(client, machineToken, jobId, turnsSoFar) {
7924
- const deadline = Date.now() + REPLY_TIMEOUT_MS;
7925
- while (Date.now() < deadline) {
7926
- await sleep(REPLY_POLL_INTERVAL_MS);
7927
- const job = await client.nextJob(machineToken, 0);
7928
- if (job?.id !== jobId) continue;
7929
- const last = job.turns[job.turns.length - 1];
7930
- if (job.turns.length > turnsSoFar && last?.role === "user") {
7931
- return job;
7932
- }
7933
- }
7934
- return null;
7935
- }
7936
- async function invokeEpicRequestViaApi(job, ctx) {
7937
- const routing = await resolveRouting();
7938
- const anthropic = new Anthropic(anthropicClientOptions(ctx.anthropicApiKey, routing));
7939
- const seed = parseSeedPayload(job.payload);
7940
- const systemPrompt = resolveSystemPrompt(seed);
7941
- let currentErId = seed?.targetEpicRequestId ?? null;
7942
- let qualityRounds = 0;
7943
- let jsonRepairs = 0;
7944
- const messages = [];
7945
- for (const turn of job.turns) {
7946
- if (turn.role === "agent") {
7947
- messages.push({ role: "assistant", content: turn.content });
7948
- } else {
7949
- messages.push({ role: "user", content: await apiUserTurnContent(turn) });
7950
- }
7951
- }
7952
- let turnsSoFar = job.turns.length;
7953
- for (let i = 0; i < MAX_INTERVIEW_TURNS; i++) {
7954
- let reply;
7955
- try {
7956
- const response = await anthropic.messages.create({
7957
- model: ANTHROPIC_MODEL,
7958
- max_tokens: 1024,
7959
- system: systemPrompt,
7960
- messages: messages.length > 0 ? messages : [{ role: "user", content: "Let's get started." }]
7961
- });
7962
- const textBlock = response.content.find((b) => b.type === "text");
7963
- reply = textBlock?.type === "text" ? textBlock.text : "";
7964
- } catch (error) {
7965
- const message = error instanceof Error ? error.message : "Anthropic API request failed";
7966
- return { status: "failed", result: { error: `Agent invocation failed: ${message}` } };
7967
- }
7968
- const draft = extractCompletionJson(reply);
7969
- if (draft) {
7970
- let submitted;
7971
- try {
7972
- submitted = await submitAndScore(ctx, currentErId, draft);
7973
- } catch (error) {
7974
- const message = error instanceof Error ? error.message : "Failed to save the epic request";
7975
- return { status: "failed", result: { error: message } };
7976
- }
7977
- currentErId = submitted.erId;
7978
- const compliance = submitted.compliance;
7979
- if (meetsComplianceTarget(compliance) || qualityRounds >= MAX_QUALITY_ROUNDS) {
7980
- return { status: "done", result: { epicRequestId: currentErId } };
7981
- }
7982
- qualityRounds++;
7983
- if (compliance !== null) {
7984
- messages.push({ role: "assistant", content: reply });
7985
- messages.push({ role: "user", content: buildAuditFeedback(compliance) });
7986
- }
7987
- continue;
7988
- }
7989
- if (looksLikeCompletionAttempt(reply)) {
7990
- if (jsonRepairs >= MAX_JSON_REPAIRS) {
7991
- return {
7992
- status: "failed",
7993
- result: {
7994
- error: "The interview produced malformed completion data and could not be finalized after several attempts."
7995
- }
7996
- };
7997
- }
7998
- jsonRepairs++;
7999
- messages.push({ role: "assistant", content: reply });
8000
- messages.push({ role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
8001
- continue;
8002
- }
8003
- messages.push({ role: "assistant", content: reply });
8004
- let updated;
8005
- try {
8006
- updated = await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, reply);
8007
- } catch (error) {
8008
- const message = error instanceof Error ? error.message : "post-turn failed";
8009
- return { status: "failed", result: { error: message } };
8010
- }
8011
- turnsSoFar = updated.turns.length;
8012
- const answered = await waitForUserReply(ctx.mailboxClient, ctx.machineToken, job.id, turnsSoFar);
8013
- if (!answered) {
8014
- return {
8015
- status: "failed",
8016
- result: { error: "Timed out waiting for a reply \u2014 no response within 10 minutes." }
8017
- };
8018
- }
8019
- const lastTurn = answered.turns[answered.turns.length - 1];
8020
- messages.push({
8021
- role: "user",
8022
- content: lastTurn ? await apiUserTurnContent(lastTurn) : ""
8023
- });
8024
- turnsSoFar = answered.turns.length;
8025
- }
8026
- return currentErId ? { status: "done", result: { epicRequestId: currentErId } } : {
8027
- status: "failed",
8028
- result: { error: `Interview did not converge after ${String(MAX_INTERVIEW_TURNS)} turns.` }
8029
- };
8030
- }
8031
8087
  function claudeCliSessionCwd() {
8032
8088
  const dir = join9(homedir5(), ".compbox", "claude-sessions");
8033
8089
  try {
@@ -8038,11 +8094,11 @@ function claudeCliSessionCwd() {
8038
8094
  }
8039
8095
  function runClaudeCliTurn(prompt, opts) {
8040
8096
  return new Promise((resolve3, reject) => {
8097
+ const model = opts.model === void 0 ? ANTHROPIC_MODEL : opts.model;
8041
8098
  const args = [
8042
8099
  "-p",
8043
8100
  prompt,
8044
- "--model",
8045
- ANTHROPIC_MODEL,
8101
+ ...model ? ["--model", model] : [],
8046
8102
  "--output-format",
8047
8103
  "json",
8048
8104
  "--tools",
@@ -8116,91 +8172,78 @@ function runClaudeCliTurn(prompt, opts) {
8116
8172
  });
8117
8173
  });
8118
8174
  }
8119
- async function invokeEpicRequestViaSubscription(job, ctx) {
8120
- let sessionId;
8121
- let turnsSoFar = job.turns.length;
8175
+ async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId) {
8176
+ const res = await fetch(
8177
+ `${apiBaseUrl.replace(/\/+$/, "")}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`,
8178
+ { headers: { Authorization: `Bearer ${userApiToken}` } }
8179
+ );
8180
+ if (!res.ok) return null;
8181
+ const body = await res.json().catch(() => null);
8182
+ return savedContextFromRecord(body?.data);
8183
+ }
8184
+ function needsDefaultModel(error) {
8185
+ const message = error instanceof Error ? error.message : String(error);
8186
+ return /requires usage credits|switch to another model|model.*not available|not have access to/i.test(message);
8187
+ }
8188
+ function savedRequestIdOf(job) {
8189
+ const result = job.result;
8190
+ if (typeof result?.epicRequestId === "string") return result.epicRequestId;
8191
+ return parseSeedPayload(job.payload)?.targetEpicRequestId ?? null;
8192
+ }
8193
+ async function invokeEpicRequestStep(job, ctx) {
8194
+ try {
8195
+ return await takeConversationStep(job, ctx);
8196
+ } catch (error) {
8197
+ const reason = error instanceof Error ? error.message : "something went wrong";
8198
+ await ctx.mailboxClient.postTurn(
8199
+ ctx.machineToken,
8200
+ job.id,
8201
+ `I couldn't continue: ${reason}
8202
+
8203
+ Send another message (for example "try again") and I'll pick up where we left off.`
8204
+ );
8205
+ return { status: "yield" };
8206
+ }
8207
+ }
8208
+ async function takeConversationStep(job, ctx) {
8122
8209
  const routing = await resolveRouting();
8123
- const seed = parseSeedPayload(job.payload);
8124
- const systemPrompt = resolveSystemPrompt(seed);
8125
- let currentErId = seed?.targetEpicRequestId ?? null;
8126
- let qualityRounds = 0;
8127
- let jsonRepairs = 0;
8128
- let nextPrompt = job.turns.length > 0 ? job.turns.map(
8129
- (t) => t.role === "agent" ? `You asked: ${t.content}` : (
8130
- // ENG-153 (A4): subscription mode has no inline-image channel, so a
8131
- // user turn's images degrade to an explicit textual note.
8132
- `They replied: ${appendAttachmentNote(t.content, imageAttachmentCount(t.attachments))}`
8133
- )
8134
- ).join("\n") + "\n\nContinue the interview from exactly where this left off \u2014 ask the next question, or if you already have everything, respond with the completion JSON." : "Let's begin the interview.";
8135
- for (let i = 0; i < MAX_INTERVIEW_TURNS; i++) {
8136
- let turn;
8137
- try {
8138
- turn = await runClaudeCliTurn(nextPrompt, {
8139
- systemPrompt,
8140
- resumeSessionId: sessionId,
8141
- routing
8142
- });
8143
- } catch (error) {
8144
- const message = error instanceof Error ? error.message : "claude CLI invocation failed";
8145
- return { status: "failed", result: { error: `Agent invocation failed: ${message}` } };
8146
- }
8147
- sessionId = turn.sessionId;
8148
- const draft = extractCompletionJson(turn.text);
8149
- if (draft) {
8150
- let submitted;
8151
- try {
8152
- submitted = await submitAndScore(ctx, currentErId, draft);
8153
- } catch (error) {
8154
- const message = error instanceof Error ? error.message : "Failed to save the epic request";
8155
- return { status: "failed", result: { error: message } };
8156
- }
8157
- currentErId = submitted.erId;
8158
- const compliance = submitted.compliance;
8159
- if (meetsComplianceTarget(compliance) || qualityRounds >= MAX_QUALITY_ROUNDS) {
8160
- return { status: "done", result: { epicRequestId: currentErId } };
8161
- }
8162
- qualityRounds++;
8163
- if (compliance !== null) {
8164
- nextPrompt = buildAuditFeedback(compliance);
8165
- }
8166
- continue;
8167
- }
8168
- if (looksLikeCompletionAttempt(turn.text)) {
8169
- if (jsonRepairs >= MAX_JSON_REPAIRS) {
8170
- return {
8171
- status: "failed",
8172
- result: {
8173
- error: "The interview produced malformed completion data and could not be finalized after several attempts."
8174
- }
8175
- };
8210
+ const requestId = savedRequestIdOf(job);
8211
+ const saved = requestId ? await loadSavedRequest(ctx.apiBaseUrl, ctx.userApiToken, requestId) : null;
8212
+ const turns = job.turns.map((t) => ({
8213
+ role: t.role,
8214
+ content: t.role === "user" ? appendAttachmentNote(t.content, imageAttachmentCount(t.attachments)) : t.content
8215
+ }));
8216
+ const anthropic = ctx.anthropicApiKey ? new Anthropic(anthropicClientOptions(ctx.anthropicApiKey, routing)) : null;
8217
+ let cliModel = ANTHROPIC_MODEL;
8218
+ const outcome = await runConversationStep(
8219
+ { turns, saved },
8220
+ {
8221
+ reply: async (system, messages) => {
8222
+ if (anthropic) {
8223
+ const response = await anthropic.messages.create({ model: ANTHROPIC_MODEL, max_tokens: 4096, system, messages });
8224
+ const text = response.content.find((b) => b.type === "text");
8225
+ return text?.type === "text" ? text.text : "";
8226
+ }
8227
+ const prompt = renderConversationPrompt(messages);
8228
+ try {
8229
+ return (await runClaudeCliTurn(prompt, { systemPrompt: system, resumeSessionId: void 0, routing, model: cliModel })).text;
8230
+ } catch (error) {
8231
+ if (cliModel === null || !needsDefaultModel(error)) throw error;
8232
+ cliModel = null;
8233
+ return (await runClaudeCliTurn(prompt, { systemPrompt: system, resumeSessionId: void 0, routing, model: null })).text;
8234
+ }
8235
+ },
8236
+ save: async (existingId, draft) => {
8237
+ const submitted = await submitAndScore(ctx, existingId, draft);
8238
+ return { id: submitted.erId, title: draft.title, compliance: submitted.compliance };
8176
8239
  }
8177
- jsonRepairs++;
8178
- nextPrompt = COMPLETION_REPAIR_INSTRUCTION;
8179
- continue;
8180
- }
8181
- let updated;
8182
- try {
8183
- updated = await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, turn.text);
8184
- } catch (error) {
8185
- const message = error instanceof Error ? error.message : "post-turn failed";
8186
- return { status: "failed", result: { error: message } };
8187
8240
  }
8188
- turnsSoFar = updated.turns.length;
8189
- const answered = await waitForUserReply(ctx.mailboxClient, ctx.machineToken, job.id, turnsSoFar);
8190
- if (!answered) {
8191
- return {
8192
- status: "failed",
8193
- result: { error: "Timed out waiting for a reply \u2014 no response within 10 minutes." }
8194
- };
8195
- }
8196
- const lastTurn = answered.turns[answered.turns.length - 1];
8197
- nextPrompt = lastTurn ? appendAttachmentNote(lastTurn.content, imageAttachmentCount(lastTurn.attachments)) : "";
8198
- turnsSoFar = answered.turns.length;
8241
+ );
8242
+ if (outcome.kind === "saved") {
8243
+ await ctx.mailboxClient.markRequestSaved(ctx.machineToken, job.id, outcome.saved.id);
8199
8244
  }
8200
- return currentErId ? { status: "done", result: { epicRequestId: currentErId } } : {
8201
- status: "failed",
8202
- result: { error: `Interview did not converge after ${String(MAX_INTERVIEW_TURNS)} turns.` }
8203
- };
8245
+ await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text);
8246
+ return { status: "yield" };
8204
8247
  }
8205
8248
  var PLANNER_RUN_TIMEOUT_MS = 30 * 60 * 1e3;
8206
8249
  var PLANNER_HEARTBEAT_INTERVAL_MS = 20 * 1e3;
@@ -8230,12 +8273,17 @@ function buildPlannerArgs(epicRequestId) {
8230
8273
  }
8231
8274
  function projectDirNotConfiguredMessage() {
8232
8275
  return [
8233
- "No CompBox project repository is configured for this machine, so the planner has nowhere to run.",
8234
- "Set one of the following and re-run the job:",
8235
- " - `compbox configure` \u2014 the guided setup prompts for and persists the project directory (recommended)",
8236
- " - `compbox run --project-dir <path-to-your-checkout>` (persisted for future runs)",
8237
- " - the COMPBOX_PROJECT_DIR environment variable",
8238
- "The path must be a git checkout of the CompBox repo (it needs the repo's .mcp.json and CLAUDE.md)."
8276
+ "This run has no project folder on this computer, so it can't run.",
8277
+ "Each run works only in the folder registered for its project's repository:",
8278
+ " - `compbox machines dirs add <path-to-your-checkout>` (or re-run `compbox configure`)",
8279
+ "CompBox never falls back to a default folder."
8280
+ ].join("\n");
8281
+ }
8282
+ function noProjectRemoteMessage() {
8283
+ return [
8284
+ "This run isn't linked to a project repository, so this computer won't run it.",
8285
+ "Update CompBox (`brew upgrade compbox`) or connect the project's repository in its Settings \u2192 Repository, then send the run again.",
8286
+ "CompBox only runs work in the folder registered for its project's repository \u2014 never in a default folder."
8239
8287
  ].join("\n");
8240
8288
  }
8241
8289
  function unregisteredRemoteMessage(remote) {
@@ -8251,11 +8299,11 @@ function unregisteredRemoteMessage(remote) {
8251
8299
  }
8252
8300
  function projectDirNotGitRepoMessage(dir) {
8253
8301
  return [
8254
- `The configured CompBox project directory is not a git repository: ${dir}`,
8255
- "The planner runs the local `claude` CLI in this directory so the repo's .mcp.json (CompBox MCP)",
8302
+ `The project folder registered for this run's repository is not a git repository: ${dir}`,
8303
+ "The planner runs the local `claude` CLI in this folder so the repo's .mcp.json (CompBox MCP)",
8256
8304
  "and CLAUDE.md (@agent routing) load \u2014 both require a real checkout.",
8257
- "Re-run `compbox configure` to point it at a git checkout of the CompBox repo (or set --project-dir /",
8258
- "COMPBOX_PROJECT_DIR to one), then re-run the job."
8305
+ "Register the right checkout with `compbox machines dirs add <path>` (or re-run `compbox configure`),",
8306
+ "then re-run the job."
8259
8307
  ].join("\n");
8260
8308
  }
8261
8309
  function scanJsonObjects(text) {
@@ -8452,11 +8500,15 @@ ${stderr}`;
8452
8500
  }
8453
8501
  var ORCHESTRATOR_RUN_TIMEOUT_MS = 3 * 60 * 60 * 1e3;
8454
8502
  var ORCHESTRATOR_HEARTBEAT_INTERVAL_MS = PLANNER_HEARTBEAT_INTERVAL_MS;
8503
+ var 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.";
8455
8504
  var ORCHESTRATOR_FINAL_TURN_MAX_CHARS = 4e3;
8456
8505
  function buildOrchestratorArgs(epicId) {
8457
8506
  return [
8458
8507
  "-p",
8459
8508
  `@orchestrator execute epic ${epicId} --non-interactive`,
8509
+ // H3 reminder: never background work in a print-mode run.
8510
+ "--append-system-prompt",
8511
+ HEADLESS_ORCHESTRATE_REMINDER,
8460
8512
  // H1: unattended permission mode so print-mode tool use never blocks on an
8461
8513
  // interactive "allow?" prompt (this path grants the full MCP surface).
8462
8514
  "--permission-mode",
@@ -8468,7 +8520,7 @@ function orchestrateNotGitRepoMessage(dir) {
8468
8520
  `The configured CompBox project directory is not a git repository: ${dir}`,
8469
8521
  "The orchestrator runs the local `claude` CLI in this directory so the repo's .mcp.json (CompBox MCP)",
8470
8522
  "and CLAUDE.md (@agent routing) load, and it drives builds/tests through git worktrees \u2014 all require a real checkout.",
8471
- "Point --project-dir / COMPBOX_PROJECT_DIR at a git checkout of the CompBox repo and re-run the job."
8523
+ "Register the right checkout with `compbox machines dirs add <path>` and re-run the job."
8472
8524
  ].join("\n");
8473
8525
  }
8474
8526
  function worktreeUnavailableMessage(dir) {
@@ -8509,7 +8561,19 @@ function defaultToolchainPresent(_dir) {
8509
8561
  }
8510
8562
  return false;
8511
8563
  }
8564
+ function buildIncompleteRunResult(epicId, progress) {
8565
+ return {
8566
+ needsAttention: true,
8567
+ epicId,
8568
+ completedFeatures: progress.completedFeatures,
8569
+ totalFeatures: progress.totalFeatures,
8570
+ message: `The run stopped before finishing: ${String(progress.completedFeatures)} of ${String(progress.totalFeatures)} features done. Send the build again to continue.`
8571
+ };
8572
+ }
8512
8573
  function describeRunBranch(finish) {
8574
+ if (finish.needsAttention) {
8575
+ 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.`;
8576
+ }
8513
8577
  if (finish.prUrl) return `Pull request: ${finish.prUrl}`;
8514
8578
  if (finish.compareUrl) return `Branch ${finish.branch} was pushed. Open the pull request here: ${finish.compareUrl}`;
8515
8579
  if (finish.commits === 0) return "No code changes were made.";
@@ -8653,6 +8717,25 @@ ${stderr}`;
8653
8717
  finish({ status: "done", result: { epicId: ctx.epicId } });
8654
8718
  });
8655
8719
  });
8720
+ if (outcome.status === "done") {
8721
+ const readProgress = deps.epicProgress ?? (async () => {
8722
+ try {
8723
+ const job = await ctx.mailboxClient.postTurn(
8724
+ ctx.machineToken,
8725
+ ctx.jobId,
8726
+ `The orchestrator finished. Checking epic ${ctx.epicId}'s progress in CompBox\u2026`
8727
+ );
8728
+ return job.progress ?? null;
8729
+ } catch {
8730
+ return null;
8731
+ }
8732
+ });
8733
+ const progress = await readProgress();
8734
+ if (progress && progress.totalFeatures > 0 && progress.completedFeatures < progress.totalFeatures) {
8735
+ outcome.status = "failed";
8736
+ outcome.result = buildIncompleteRunResult(ctx.epicId, progress);
8737
+ }
8738
+ }
8656
8739
  let branchLine = "";
8657
8740
  if (deps.workspace && workspace) {
8658
8741
  const resultError = outcome.result;
@@ -8672,8 +8755,17 @@ ${stderr}`;
8672
8755
  pushed: finished.pushed,
8673
8756
  ...finished.prUrl ? { prUrl: finished.prUrl } : {},
8674
8757
  ...finished.compareUrl ? { compareUrl: finished.compareUrl } : {},
8675
- ...finished.notes.length > 0 ? { branchNotes: finished.notes } : {}
8758
+ ...finished.notes.length > 0 ? { branchNotes: finished.notes } : {},
8759
+ ...finished.keptWorktree ? { keptWorktree: finished.keptWorktree } : {}
8676
8760
  };
8761
+ if (finished.needsAttention) {
8762
+ outcome.status = "failed";
8763
+ outcome.result = {
8764
+ ...outcome.result,
8765
+ needsAttention: true,
8766
+ message: `The run's work couldn't be saved to its branch, so it was kept in ${finished.keptWorktree ?? "its run folder"}.` + (typeof outcome.result.message === "string" ? ` ${outcome.result.message}` : "")
8767
+ };
8768
+ }
8677
8769
  }
8678
8770
  try {
8679
8771
  const summary = (outcome.status === "done" ? `Execution complete \u2014 epic ${ctx.epicId} finished all phases.` : `Orchestrator run ended: ${JSON.stringify(outcome.result).slice(0, ORCHESTRATOR_FINAL_TURN_MAX_CHARS)}`) + (branchLine ? `
@@ -8834,6 +8926,17 @@ function githubCompareUrl(remoteUrl, baseBranch, branch) {
8834
8926
  if (!m) return null;
8835
8927
  return `https://github.com/${m[1] ?? ""}/${m[2] ?? ""}/compare/${encodeURIComponent(baseBranch)}...${encodeURIComponent(branch)}?expand=1`;
8836
8928
  }
8929
+ var repoQueues = /* @__PURE__ */ new Map();
8930
+ function withRepoLock(projectDir, task) {
8931
+ const previous = repoQueues.get(projectDir) ?? Promise.resolve();
8932
+ const result = previous.catch(() => void 0).then(task);
8933
+ const tail = result.catch(() => void 0);
8934
+ repoQueues.set(projectDir, tail);
8935
+ void tail.then(() => {
8936
+ if (repoQueues.get(projectDir) === tail) repoQueues.delete(projectDir);
8937
+ });
8938
+ return result;
8939
+ }
8837
8940
  var RunWorkspaceManager = class {
8838
8941
  run;
8839
8942
  now;
@@ -8841,7 +8944,9 @@ var RunWorkspaceManager = class {
8841
8944
  exists;
8842
8945
  copyFile;
8843
8946
  env;
8947
+ openPullRequest;
8844
8948
  constructor(deps = {}) {
8949
+ this.openPullRequest = deps.openPullRequest;
8845
8950
  this.run = deps.run ?? defaultCommandRunner;
8846
8951
  this.now = deps.now ?? (() => /* @__PURE__ */ new Date());
8847
8952
  this.runsRoot = deps.runsRoot ?? join10(getConfigDir(), "runs");
@@ -8857,6 +8962,31 @@ var RunWorkspaceManager = class {
8857
8962
  }
8858
8963
  /** Creates the branch + worktree for a run. Never touches the person's checkout. */
8859
8964
  async prepare(projectDir, epicId) {
8965
+ const created = await withRepoLock(projectDir, () => this.createWorktree(projectDir, epicId));
8966
+ if (!created.ok) return created;
8967
+ const { workspace, notes } = created;
8968
+ const { dir, branch } = workspace;
8969
+ const install = installCommand2(dir, this.exists);
8970
+ if (install) {
8971
+ const [command, args] = install;
8972
+ const res = await this.run(command, args, dir);
8973
+ if (res.status !== 0) {
8974
+ await withRepoLock(projectDir, async () => {
8975
+ await this.git(["worktree", "remove", "--force", dir], projectDir);
8976
+ await this.git(["branch", "-D", branch], projectDir);
8977
+ });
8978
+ return {
8979
+ ok: false,
8980
+ error: [
8981
+ `Installing the project's dependencies failed (${command} ${args.join(" ")}): ${firstLine(res.stderr) || firstLine(res.stdout) || "unknown error"}`,
8982
+ "The run was not started. Check that the same command works in your project folder."
8983
+ ].join("\n")
8984
+ };
8985
+ }
8986
+ }
8987
+ return { ok: true, workspace, notes };
8988
+ }
8989
+ async createWorktree(projectDir, epicId) {
8860
8990
  const notes = [];
8861
8991
  const remotes = (await this.git(["remote"], projectDir)).stdout.split("\n").map((r) => r.trim()).filter(Boolean);
8862
8992
  const remote = remotes.includes("origin") ? "origin" : remotes[0] ?? null;
@@ -8911,48 +9041,51 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
8911
9041
  notes.push(`Couldn't copy ${path3} into the run workspace.`);
8912
9042
  }
8913
9043
  }
8914
- const install = installCommand2(dir, this.exists);
8915
- if (install) {
8916
- const [command, args] = install;
8917
- const res = await this.run(command, args, dir);
8918
- if (res.status !== 0) {
8919
- await this.git(["worktree", "remove", "--force", dir], projectDir);
8920
- await this.git(["branch", "-D", branch], projectDir);
8921
- return {
8922
- ok: false,
8923
- error: [
8924
- `Installing the project's dependencies failed (${command} ${args.join(" ")}): ${firstLine(res.stderr) || firstLine(res.stdout) || "unknown error"}`,
8925
- "The run was not started. Check that the same command works in your project folder."
8926
- ].join("\n")
8927
- };
8928
- }
8929
- }
8930
9044
  return { ok: true, workspace: { dir, projectDir, branch, baseRef, baseBranch, remote }, notes };
8931
9045
  }
8932
9046
  /** Commits, pushes and opens the pull request; then cleans up the worktree. */
8933
- async finish(input) {
9047
+ finish(input) {
9048
+ return withRepoLock(input.workspace.projectDir, () => this.finishLocked(input));
9049
+ }
9050
+ async finishLocked(input) {
8934
9051
  const { workspace: ws } = input;
8935
9052
  const notes = [];
8936
- if ((await this.git(["status", "--porcelain"], ws.dir)).stdout.trim()) {
9053
+ const dirtyBefore = await this.isDirty(ws.dir);
9054
+ let commitFailed = false;
9055
+ if (dirtyBefore) {
8937
9056
  await this.git(["add", "-A"], ws.dir);
8938
9057
  const commit = await this.git(
8939
- ["commit", "-m", `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`],
9058
+ ["commit", "--no-verify", "-m", `chore(compbox): save work left uncommitted by the orchestrator (epic ${input.epicId})`],
8940
9059
  ws.dir
8941
9060
  );
8942
9061
  if (commit.status !== 0) {
8943
- notes.push(`Couldn't commit the remaining changes: ${firstLine(commit.stderr) || firstLine(commit.stdout)}`);
9062
+ commitFailed = true;
9063
+ notes.push(`Couldn't commit the remaining changes: ${firstLine(commit.stderr) || firstLine(commit.stdout) || "unknown error"}`);
8944
9064
  }
8945
9065
  }
8946
9066
  const commits = Number.parseInt((await this.git(["rev-list", "--count", `${ws.baseRef}..HEAD`], ws.dir)).stdout.trim(), 10) || 0;
8947
9067
  const base = { branch: ws.branch, commits, pushed: false, notes };
9068
+ if (commitFailed || dirtyBefore && await this.isDirty(ws.dir)) {
9069
+ notes.push(`The run's changes couldn't all be committed, so nothing was removed. They are safe in ${ws.dir} on branch ${ws.branch}.`);
9070
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
9071
+ }
8948
9072
  if (commits === 0) {
8949
- await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
8950
- await this.git(["branch", "-D", ws.branch], ws.projectDir);
8951
- notes.push("The run made no code changes, so there is nothing to review.");
8952
- return base;
9073
+ if (!dirtyBefore) {
9074
+ if (await this.removeWorktree(ws, notes)) {
9075
+ await this.git(["branch", "-D", ws.branch], ws.projectDir);
9076
+ } else {
9077
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
9078
+ }
9079
+ notes.push("The run made no code changes, so there is nothing to review.");
9080
+ return base;
9081
+ }
9082
+ notes.push(`The run's changes didn't end up in a commit, so nothing was removed. Check ${ws.dir} on branch ${ws.branch}.`);
9083
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
8953
9084
  }
8954
9085
  if (!ws.remote || this.env[RUN_PUSH_ENV] === "0") {
8955
- await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
9086
+ if (!await this.removeWorktree(ws, notes)) {
9087
+ return { ...base, keptWorktree: ws.dir, needsAttention: true };
9088
+ }
8956
9089
  notes.push(
8957
9090
  ws.remote ? `Pushing is turned off (${RUN_PUSH_ENV}=0). The work is on the local branch ${ws.branch}.` : `The repository has no remote, so the work is on the local branch ${ws.branch}.`
8958
9091
  );
@@ -8973,10 +9106,21 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
8973
9106
  "",
8974
9107
  `${String(commits)} commit${commits === 1 ? "" : "s"} on \`${ws.branch}\`, based on \`${ws.baseBranch}\`.`
8975
9108
  ].join("\n");
8976
- const prArgs = ["pr", "create", "--base", ws.baseBranch, "--head", ws.branch, "--title", title, "--body", body];
8977
- if (!input.completed) prArgs.push("--draft");
8978
- const pr = await this.run("gh", prArgs, ws.dir);
8979
- const prUrl = pr.status === 0 ? /https:\/\/\S+/.exec(pr.stdout)?.[0] : void 0;
9109
+ let prUrl;
9110
+ if (this.openPullRequest) {
9111
+ try {
9112
+ prUrl = (await this.openPullRequest({ branch: ws.branch, base: ws.baseBranch, title, body, draft: !input.completed })).url;
9113
+ } catch {
9114
+ prUrl = void 0;
9115
+ }
9116
+ }
9117
+ let pr = { status: 0, stdout: "", stderr: "" };
9118
+ if (!prUrl) {
9119
+ const prArgs = ["pr", "create", "--base", ws.baseBranch, "--head", ws.branch, "--title", title, "--body", body];
9120
+ if (!input.completed) prArgs.push("--draft");
9121
+ pr = await this.run("gh", prArgs, ws.dir);
9122
+ prUrl = pr.status === 0 ? /https:\/\/\S+/.exec(pr.stdout)?.[0] : void 0;
9123
+ }
8980
9124
  let compareUrl;
8981
9125
  if (!prUrl) {
8982
9126
  const remoteUrl = (await this.git(["remote", "get-url", ws.remote], ws.dir)).stdout.trim();
@@ -8985,8 +9129,32 @@ ${untracked.stdout}`.split("\n").map((p) => p.trim()).filter((p) => p && !p.ends
8985
9129
  `The branch was pushed, but the pull request couldn't be opened automatically${firstLine(pr.stderr) ? ` (${firstLine(pr.stderr)})` : ""}.` + (compareUrl ? " Use the link to open it." : ` Open a pull request for ${ws.branch} on your git host.`)
8986
9130
  );
8987
9131
  }
9132
+ const removed = await this.removeWorktree(ws, notes);
9133
+ return {
9134
+ ...base,
9135
+ pushed: true,
9136
+ ...prUrl ? { prUrl } : {},
9137
+ ...compareUrl ? { compareUrl } : {},
9138
+ ...removed ? {} : { keptWorktree: ws.dir, needsAttention: true }
9139
+ };
9140
+ }
9141
+ /** True when the worktree has uncommitted (or unreadable) state. */
9142
+ async isDirty(dir) {
9143
+ const status = await this.git(["status", "--porcelain"], dir);
9144
+ return status.status !== 0 || status.stdout.trim().length > 0;
9145
+ }
9146
+ /**
9147
+ * Removes a run's worktree — a separate step, run only once the worktree is
9148
+ * verified clean (everything is committed). Returns false, keeping the
9149
+ * worktree and noting why, when it still has changes.
9150
+ */
9151
+ async removeWorktree(ws, notes) {
9152
+ if (await this.isDirty(ws.dir)) {
9153
+ notes.push(`The run's folder still has uncommitted changes, so it was kept: ${ws.dir} (branch ${ws.branch}).`);
9154
+ return false;
9155
+ }
8988
9156
  await this.git(["worktree", "remove", "--force", ws.dir], ws.projectDir);
8989
- return { ...base, pushed: true, ...prUrl ? { prUrl } : {}, ...compareUrl ? { compareUrl } : {} };
9157
+ return true;
8990
9158
  }
8991
9159
  };
8992
9160
 
@@ -9142,9 +9310,20 @@ var POLL_WAIT_MS = 0;
9142
9310
  var IDLE_POLL_INTERVAL_MS = 15e3;
9143
9311
  var ACTIVE_POLL_INTERVAL_MS = 2e3;
9144
9312
  var ACTIVE_WINDOW_MS = 6e4;
9145
- function idleDelay(now, lastJobAt) {
9313
+ var CONVERSATION_POLL_INTERVAL_MS = 3e3;
9314
+ var CONVERSATION_WINDOW_MS = 10 * 6e4;
9315
+ function idleDelay(now, lastJobAt, lastConversationAt = 0) {
9146
9316
  const warm = lastJobAt > 0 && now - lastJobAt < ACTIVE_WINDOW_MS;
9147
- return warm ? ACTIVE_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
9317
+ if (warm) return ACTIVE_POLL_INTERVAL_MS;
9318
+ const talking = lastConversationAt > 0 && now - lastConversationAt < CONVERSATION_WINDOW_MS;
9319
+ return talking ? CONVERSATION_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
9320
+ }
9321
+ var DEFAULT_MAX_PARALLEL_JOBS = 3;
9322
+ var MAX_JOBS_ENV = "COMPBOX_MAX_JOBS";
9323
+ function maxParallelJobs(env = process.env) {
9324
+ const raw = Number.parseInt(env[MAX_JOBS_ENV] ?? "", 10);
9325
+ if (!Number.isFinite(raw) || raw < 1) return DEFAULT_MAX_PARALLEL_JOBS;
9326
+ return Math.min(raw, 10);
9148
9327
  }
9149
9328
  var BACKOFF_BASE_MS = 1e3;
9150
9329
  var BACKOFF_MAX_MS = 3e4;
@@ -9152,7 +9331,7 @@ var HEARTBEAT_INTERVAL_MS = 2e4;
9152
9331
  function runtimeHeartbeatDue(nowMs, lastRuntimeSentMs, intervalMs = HEARTBEAT_INTERVAL_MS) {
9153
9332
  return nowMs - lastRuntimeSentMs >= intervalMs;
9154
9333
  }
9155
- function sleep2(ms) {
9334
+ function sleep(ms) {
9156
9335
  return new Promise((resolve3) => setTimeout(resolve3, ms));
9157
9336
  }
9158
9337
  function backoffDelay(consecutiveErrors) {
@@ -9217,15 +9396,16 @@ async function handleStartExecution(ctx, job) {
9217
9396
  );
9218
9397
  return;
9219
9398
  }
9220
- const routed = resolveProjectDirForJob(payload.projectRemote, {
9221
- flag: ctx.projectDirFlag,
9222
- config: readConfig()
9223
- });
9399
+ const routed = resolveProjectDirForJob(payload.projectRemote, { config: readConfig() });
9224
9400
  if (routed.status === "unregistered") {
9225
9401
  await completeWithFailure(ctx, job, unregisteredRemoteMessage(routed.remote));
9226
9402
  return;
9227
9403
  }
9228
- const jobProjectDir = routed.status === "registered" || routed.status === "fallback" ? routed.path : void 0;
9404
+ if (routed.status === "no-remote") {
9405
+ await completeWithFailure(ctx, job, noProjectRemoteMessage());
9406
+ return;
9407
+ }
9408
+ const jobProjectDir = routed.path;
9229
9409
  let keyRun;
9230
9410
  if (payload.useAiKey) {
9231
9411
  try {
@@ -9298,8 +9478,11 @@ async function handleStartExecution(ctx, job) {
9298
9478
  // H4: keep this machine online during the long orchestrator run — the
9299
9479
  // poll loop (its own heartbeat) is blocked for the whole job.
9300
9480
  heartbeat: () => ctx.client.heartbeat(ctx.machineToken).catch(() => void 0),
9301
- // Own branch + worktree per run, finishing with a pull request.
9302
- workspace: new RunWorkspaceManager()
9481
+ // Own branch + worktree per run, finishing with a pull request (opened
9482
+ // through CompBox's GitHub app when the project is connected to it).
9483
+ workspace: new RunWorkspaceManager({
9484
+ openPullRequest: (input) => ctx.client.openPullRequest(ctx.machineToken, job.id, input)
9485
+ })
9303
9486
  }
9304
9487
  )
9305
9488
  );
@@ -9307,6 +9490,10 @@ async function handleStartExecution(ctx, job) {
9307
9490
  async function runInvokerAndComplete(ctx, job, invoke) {
9308
9491
  try {
9309
9492
  const outcome = await invoke();
9493
+ if (outcome.status === "yield") {
9494
+ console.log(chalk9.gray(` Job ${job.id}: replied; waiting for the person.`));
9495
+ return;
9496
+ }
9310
9497
  await ctx.client.completeJob(ctx.machineToken, job.id, outcome.status, outcome.result);
9311
9498
  console.log(
9312
9499
  outcome.status === "done" ? chalk9.green(` Job ${job.id} completed: ${JSON.stringify(outcome.result)}`) : chalk9.yellow(` Job ${job.id} failed: ${JSON.stringify(outcome.result)}`)
@@ -9331,37 +9518,22 @@ async function handleJob(ctx, job) {
9331
9518
  \u2192 Claimed job ${job.id} (type: ${job.type}, status: ${job.status})`)
9332
9519
  );
9333
9520
  const userApiToken = ctx.userApiToken;
9334
- const isEpicRequest = job.type === "epic_request" && !!userApiToken;
9335
- if (isEpicRequest && userApiToken) {
9521
+ if (job.type === "epic_request" && userApiToken) {
9522
+ let anthropicApiKey;
9336
9523
  if (ctx.aiMode === "api-key") {
9337
- const { value: anthropicApiKey } = await retrieveSecret(AI_KEY_ACCOUNT);
9338
- if (anthropicApiKey) {
9339
- console.log(chalk9.gray(" Running the request-formulator interview (api mode)..."));
9340
- await runInvokerAndComplete(
9341
- ctx,
9342
- job,
9343
- () => invokeEpicRequestViaApi(job, {
9344
- mailboxClient: ctx.client,
9345
- machineToken: ctx.machineToken,
9346
- apiBaseUrl: ctx.apiBaseUrl,
9347
- userApiToken,
9348
- anthropicApiKey
9349
- })
9350
- );
9351
- return;
9352
- }
9353
- } else if (ctx.aiMode === "claude-subscription") {
9354
- console.log(
9355
- chalk9.gray(" Running the request-formulator interview (claude-subscription mode, local `claude` CLI)...")
9356
- );
9524
+ anthropicApiKey = (await retrieveSecret(AI_KEY_ACCOUNT)).value ?? void 0;
9525
+ }
9526
+ if (ctx.aiMode === "claude-subscription" || anthropicApiKey) {
9527
+ console.log(chalk9.gray(` Replying in the request conversation (${anthropicApiKey ? "api mode" : "local claude CLI"})...`));
9357
9528
  await runInvokerAndComplete(
9358
9529
  ctx,
9359
9530
  job,
9360
- () => invokeEpicRequestViaSubscription(job, {
9531
+ () => invokeEpicRequestStep(job, {
9361
9532
  mailboxClient: ctx.client,
9362
9533
  machineToken: ctx.machineToken,
9363
9534
  apiBaseUrl: ctx.apiBaseUrl,
9364
- userApiToken
9535
+ userApiToken,
9536
+ ...anthropicApiKey && { anthropicApiKey }
9365
9537
  })
9366
9538
  );
9367
9539
  return;
@@ -9398,10 +9570,18 @@ var runCommand = new Command8("run").description("Start the Agent Runner daemon
9398
9570
  `Server-side hold per request, ms (default ${String(POLL_WAIT_MS)} \u2014 the server answers immediately and the daemon paces itself; raising this bills Cloud Run vCPU for the whole hold)`
9399
9571
  ).option(
9400
9572
  "--project-dir <path>",
9401
- "CompBox project repo the planner runs in for start_execution jobs (persisted; also settable via COMPBOX_PROJECT_DIR)"
9573
+ "Register a project folder (a git checkout) for its repository before starting \u2014 same as `compbox machines dirs add <path>`. There is no default folder."
9402
9574
  ).action(async (options) => {
9403
9575
  if (options.projectDir && options.projectDir.trim().length > 0) {
9404
- updateConfig({ projectDir: options.projectDir.trim() });
9576
+ try {
9577
+ const entry = addProjectDir(options.projectDir.trim());
9578
+ console.log(chalk9.green(`Registered ${entry.remote} \u2192 ${entry.path}`));
9579
+ } catch (error) {
9580
+ console.error(chalk9.red(`
9581
+ Couldn't register ${options.projectDir.trim()}: ${error instanceof Error ? error.message : String(error)}`));
9582
+ process.exit(1);
9583
+ return;
9584
+ }
9405
9585
  }
9406
9586
  const config = readConfig();
9407
9587
  applyPxpipeEnv(config);
@@ -9436,29 +9616,38 @@ var runCommand = new Command8("run").description("Start the Agent Runner daemon
9436
9616
  }
9437
9617
  const waitMs = options.waitMs ? Number.parseInt(options.waitMs, 10) : POLL_WAIT_MS;
9438
9618
  const client = new MailboxClient(config.apiBaseUrl);
9439
- const projectDir = resolveProjectDir({ flag: options.projectDir, config });
9440
9619
  const jobContext = {
9441
9620
  client,
9442
9621
  machineToken,
9443
9622
  apiBaseUrl: config.apiBaseUrl,
9444
9623
  aiMode: config.aiMode,
9445
- userApiToken: config.apiToken,
9446
- projectDir,
9447
- // ENG-179: preserve the raw flag so per-job fallback resolution reproduces
9448
- // flag→env→config precedence for jobs without a projectRemote.
9449
- projectDirFlag: options.projectDir
9624
+ userApiToken: config.apiToken
9450
9625
  };
9626
+ const folders = config.projectDirs ?? [];
9627
+ const legacyDir = unusedLegacyProjectDir(config);
9451
9628
  console.log(chalk9.bold("\nCompBox Agent Runner\n"));
9452
9629
  console.log(chalk9.gray(` Central: ${config.apiBaseUrl}`));
9453
9630
  console.log(chalk9.gray(` Machine: ${config.machineName ?? config.machineId}`));
9454
9631
  console.log(chalk9.gray(` AI mode: ${config.aiMode ?? "unset"}`));
9455
- console.log(chalk9.gray(` Project: ${projectDir ?? "(unset \u2014 run `compbox configure` to set it; start_execution/plan jobs fail until then)"}`));
9632
+ if (folders.length === 0) {
9633
+ console.log(chalk9.yellow(" Projects: none registered \u2014 runs are refused until you add one (`compbox machines dirs add <path>`)."));
9634
+ } else {
9635
+ for (const entry of folders) {
9636
+ console.log(chalk9.gray(` Project: ${entry.remote} \u2192 ${entry.path}`));
9637
+ }
9638
+ }
9639
+ if (legacyDir) {
9640
+ console.log(chalk9.yellow(` Note: the old default folder (${legacyDir}) is no longer used. Runs go only to a project's registered folder.`));
9641
+ }
9456
9642
  console.log(
9457
9643
  chalk9.gray(
9458
9644
  ` Polling for jobs (every ${String(Math.round(IDLE_POLL_INTERVAL_MS / 1e3))}s idle, ${String(Math.round(ACTIVE_POLL_INTERVAL_MS / 1e3))}s while a session is active)...
9459
9645
  `
9460
9646
  )
9461
9647
  );
9648
+ const maxJobs = maxParallelJobs();
9649
+ console.log(chalk9.gray(` Runs up to ${String(maxJobs)} job${maxJobs === 1 ? "" : "s"} at once (${MAX_JOBS_ENV} to change).
9650
+ `));
9462
9651
  const runtimeProbe = () => probeAgentRuntime();
9463
9652
  let agentRuntime = await safeProbeAgentRuntime(runtimeProbe, void 0);
9464
9653
  if (agentRuntime) {
@@ -9489,10 +9678,14 @@ Received ${signal}, shutting down...`));
9489
9678
  });
9490
9679
  let consecutiveErrors = 0;
9491
9680
  let lastJobAt = 0;
9681
+ let lastConversationAt = 0;
9682
+ const inFlight = /* @__PURE__ */ new Map();
9492
9683
  do {
9493
9684
  let job = null;
9494
9685
  try {
9495
- job = await client.nextJob(machineToken, waitMs);
9686
+ if (inFlight.size < maxJobs) {
9687
+ job = await client.nextJob(machineToken, waitMs, [...inFlight.keys()]);
9688
+ }
9496
9689
  consecutiveErrors = 0;
9497
9690
  } catch (error) {
9498
9691
  consecutiveErrors += 1;
@@ -9506,12 +9699,21 @@ Received ${signal}, shutting down...`));
9506
9699
  );
9507
9700
  console.error(chalk9.gray(` Reconnecting in ${String(Math.round(delay / 1e3))}s...`));
9508
9701
  if (options.once) break;
9509
- await sleep2(delay);
9702
+ await sleep(delay);
9510
9703
  continue;
9511
9704
  }
9705
+ if (job && inFlight.has(job.id)) job = null;
9512
9706
  if (job) {
9513
- await handleJob(jobContext, job);
9514
- lastJobAt = Date.now();
9707
+ const jobId = job.id;
9708
+ const isConversation = job.type === "epic_request";
9709
+ const work = handleJob(jobContext, job).catch((error) => {
9710
+ console.error(chalk9.red(` Job ${jobId} stopped unexpectedly: ${error instanceof Error ? error.message : String(error)}`));
9711
+ }).finally(() => {
9712
+ inFlight.delete(jobId);
9713
+ lastJobAt = Date.now();
9714
+ if (isConversation) lastConversationAt = lastJobAt;
9715
+ });
9716
+ inFlight.set(jobId, work);
9515
9717
  }
9516
9718
  if (runtimeHeartbeatDue(Date.now(), lastRuntimeSentAt)) {
9517
9719
  const cycle = await runHeartbeatCycle({
@@ -9528,9 +9730,12 @@ Received ${signal}, shutting down...`));
9528
9730
  lastRuntimeSentAt = Date.now();
9529
9731
  }
9530
9732
  }
9531
- if (options.once) break;
9733
+ if (options.once) {
9734
+ await Promise.all(inFlight.values());
9735
+ break;
9736
+ }
9532
9737
  if (!job) {
9533
- await sleep2(idleDelay(Date.now(), lastJobAt));
9738
+ await sleep(idleDelay(Date.now(), lastJobAt, lastConversationAt));
9534
9739
  }
9535
9740
  } while (running);
9536
9741
  console.log(chalk9.gray("Agent Runner stopped."));
@@ -9790,16 +9995,316 @@ machinesCommand.command("rm <id>").description("Remove (revoke) a paired machine
9790
9995
  }
9791
9996
  });
9792
9997
 
9998
+ // src/commands/repo.ts
9999
+ import { Command as Command12 } from "commander";
10000
+ import chalk13 from "chalk";
10001
+ function findProject(projects, query) {
10002
+ const q = query.trim().toLowerCase();
10003
+ return projects.find((p) => p.key.toLowerCase() === q) ?? projects.find((p) => p.name.toLowerCase() === q) ?? null;
10004
+ }
10005
+ async function listProjects(apiBaseUrl, apiToken) {
10006
+ const res = await fetch(`${apiBaseUrl.replace(/\/+$/, "")}/api/v1/teams?limit=100`, {
10007
+ headers: { Authorization: `Bearer ${apiToken}` }
10008
+ });
10009
+ if (!res.ok) throw new Error(`CompBox returned ${String(res.status)} listing projects`);
10010
+ const body = await res.json();
10011
+ return body.data ?? [];
10012
+ }
10013
+ var repoCommand = new Command12("repo").description("Set up projects' repositories on this computer");
10014
+ repoCommand.command("setup <project>").description("Clone (or adopt) a project's repository on this computer so its runs land there").option("--folder <path>", "Where to put it (default ~/CompBox/<repo>)").action(async (project, options) => {
10015
+ const config = readConfig();
10016
+ if (!config.apiBaseUrl || !config.apiToken) {
10017
+ console.error(chalk13.red("\nNot logged in. Run `compbox login` first."));
10018
+ process.exit(1);
10019
+ return;
10020
+ }
10021
+ let projects;
10022
+ try {
10023
+ projects = await listProjects(config.apiBaseUrl, config.apiToken);
10024
+ } catch (error) {
10025
+ console.error(chalk13.red(`
10026
+ ${error instanceof Error ? error.message : "Could not reach CompBox."}`));
10027
+ process.exit(1);
10028
+ return;
10029
+ }
10030
+ const match = findProject(projects, project);
10031
+ if (!match) {
10032
+ console.error(chalk13.red(`
10033
+ No project called "${project}". Your projects: ${projects.map((p) => p.key).join(", ") || "none"}.`));
10034
+ process.exit(1);
10035
+ return;
10036
+ }
10037
+ if (!match.gitRemote) {
10038
+ console.error(
10039
+ chalk13.red(`
10040
+ ${match.name} has no repository yet. Connect one on the project's Settings \u2192 Repository page first.`)
10041
+ );
10042
+ process.exit(1);
10043
+ return;
10044
+ }
10045
+ console.log(chalk13.gray(`
10046
+ Setting up ${match.name} (${match.gitRemote})...`));
10047
+ const outcome = await invokeConnectRepo({
10048
+ teamId: match.id,
10049
+ projectRemote: match.gitRemote,
10050
+ projectName: match.name,
10051
+ ...options.folder && { folder: options.folder }
10052
+ });
10053
+ const result = outcome.result;
10054
+ if (outcome.status === "done") {
10055
+ console.log(chalk13.green(`\u2713 ${typeof result.message === "string" ? result.message : "Set up."}`));
10056
+ console.log(chalk13.gray(" The CompBox app reports it to CompBox on its next check-in."));
10057
+ } else {
10058
+ console.error(chalk13.red(`\u2716 ${typeof result.error === "string" ? result.error : "Setting it up failed."}`));
10059
+ process.exit(1);
10060
+ }
10061
+ });
10062
+
10063
+ // src/commands/workspace.ts
10064
+ import { Command as Command13 } from "commander";
10065
+ import chalk14 from "chalk";
10066
+ import { spawnSync as spawnSync2 } from "node:child_process";
10067
+ import { mkdirSync as mkdirSync8, writeFileSync as writeFileSync5 } from "node:fs";
10068
+ import { homedir as homedir7 } from "node:os";
10069
+ import { join as join12 } from "node:path";
10070
+ function readWorkspaceEnv(env = process.env) {
10071
+ const apiUrl = env.COMPBOX_API_URL?.trim();
10072
+ const jobId = env.COMPBOX_JOB_ID?.trim();
10073
+ const token = env.COMPBOX_WORKSPACE_TOKEN?.trim();
10074
+ if (!apiUrl || !jobId || !token) return null;
10075
+ return { apiUrl: apiUrl.replace(/\/+$/, ""), jobId, token };
10076
+ }
10077
+ async function workspaceApi(env, path3, method, fetchFn) {
10078
+ const res = await fetchFn(`${env.apiUrl}/api/v1/cloud-runs/workspace/${path3}`, {
10079
+ method,
10080
+ headers: { Authorization: `Bearer ${env.token}`, ...method === "POST" && { "Content-Type": "application/json" } },
10081
+ ...method === "POST" && { body: "{}" }
10082
+ });
10083
+ if (!res.ok) {
10084
+ const body = await res.json().catch(() => null);
10085
+ throw new Error(body?.error?.message ?? `CompBox returned ${String(res.status)} for ${path3}`);
10086
+ }
10087
+ return (await res.json()).data;
10088
+ }
10089
+ var defaultRunner = (command, args, cwd) => {
10090
+ const res = spawnSync2(command, args, { cwd, encoding: "utf-8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
10091
+ if (res.status !== 0) {
10092
+ throw new Error(`${command} ${args[0] ?? ""} failed: ${(res.stderr || res.stdout || "").trim().split("\n").pop() ?? ""}`);
10093
+ }
10094
+ };
10095
+ function agentRoutingInstructions(agentsDir, compboxRoot = "/opt/compbox") {
10096
+ return `# CompBox cloud workspace
10097
+
10098
+ When a prompt starts with \`@<agent-name>\` (for example \`@planner\` or \`@orchestrator\`), read the agent file at \`${agentsDir}/<agent-name>.md\` in full and follow it exactly.
10099
+
10100
+ CompBox's own files live outside the project: any path an agent file mentions under \`.github/agents/\` or \`.github/skills/\` is at \`${compboxRoot}/.github/agents/\` or \`${compboxRoot}/.github/skills/\`. Never copy them into the project.
10101
+
10102
+ Never push to the default branch: work on the run's own branch.
10103
+ `;
10104
+ }
10105
+ async function runWorkspace(deps = {}) {
10106
+ const env = readWorkspaceEnv(deps.env);
10107
+ if (!env) {
10108
+ console.error(chalk14.red("Not a CompBox cloud workspace (COMPBOX_API_URL, COMPBOX_JOB_ID, COMPBOX_WORKSPACE_TOKEN)."));
10109
+ return 2;
10110
+ }
10111
+ const fetchFn = deps.fetchFn ?? fetch;
10112
+ const run = deps.run ?? defaultRunner;
10113
+ const home = deps.home ?? homedir7();
10114
+ const agentsDir = deps.agentsDir ?? "/opt/compbox/.github/agents/claude";
10115
+ const workDir = deps.workDir ?? "/workspace";
10116
+ const client = deps.client ?? new MailboxClient(env.apiUrl);
10117
+ const job = await client.nextJob(env.token, 0);
10118
+ if (job?.id !== env.jobId) {
10119
+ console.log("Nothing to do: the job has already finished.");
10120
+ return 0;
10121
+ }
10122
+ const fail = async (error) => {
10123
+ console.error(chalk14.red(error));
10124
+ await client.completeJob(env.token, job.id, "failed", { error }).catch(() => void 0);
10125
+ return 1;
10126
+ };
10127
+ const payload = job.payload ?? {};
10128
+ const repoDir = join12(workDir, "repo");
10129
+ let userApiToken;
10130
+ let keyRun;
10131
+ try {
10132
+ const git = await workspaceApi(env, "git-credentials", "GET", fetchFn);
10133
+ userApiToken = (await workspaceApi(env, "session", "POST", fetchFn)).userApiToken;
10134
+ const key = await client.getAiKey(env.token, job.id);
10135
+ keyRun = { apiKey: key.apiKey, model: key.model };
10136
+ run("git", ["config", "--global", "credential.helper", "!compbox workspace git-credential"]);
10137
+ run("git", ["config", "--global", "user.name", "CompBox"]);
10138
+ run("git", ["config", "--global", "user.email", "bot@mycompbox.com"]);
10139
+ mkdirSync8(workDir, { recursive: true });
10140
+ run("git", ["clone", "--branch", git.defaultBranch, git.cloneUrl, repoDir]);
10141
+ run("claude", [
10142
+ "mcp",
10143
+ "add",
10144
+ "--scope",
10145
+ "user",
10146
+ "-e",
10147
+ `API_BASE_URL=${env.apiUrl}`,
10148
+ "-e",
10149
+ `API_TOKEN=${userApiToken}`,
10150
+ "compbox",
10151
+ "--",
10152
+ "compbox-mcp"
10153
+ ]);
10154
+ mkdirSync8(join12(home, ".claude"), { recursive: true });
10155
+ writeFileSync5(join12(home, ".claude", "CLAUDE.md"), agentRoutingInstructions(agentsDir));
10156
+ } catch (error) {
10157
+ return fail(`Setting up the cloud workspace failed: ${error instanceof Error ? error.message : String(error)}`);
10158
+ }
10159
+ const heartbeat = () => client.heartbeat(env.token).then(() => void 0).catch(() => void 0);
10160
+ let outcome;
10161
+ if (payload.kind === "plan" && payload.epicRequestId) {
10162
+ outcome = await (deps.plan ?? invokeStartExecutionPlan)(
10163
+ {
10164
+ mailboxClient: client,
10165
+ machineToken: env.token,
10166
+ jobId: job.id,
10167
+ apiBaseUrl: env.apiUrl,
10168
+ userApiToken,
10169
+ epicRequestId: payload.epicRequestId,
10170
+ projectDir: repoDir,
10171
+ keyRun
10172
+ },
10173
+ { heartbeat }
10174
+ );
10175
+ } else if (payload.kind === "orchestrate" && payload.epicId) {
10176
+ outcome = await (deps.orchestrate ?? invokeStartExecutionOrchestrate)(
10177
+ {
10178
+ mailboxClient: client,
10179
+ machineToken: env.token,
10180
+ jobId: job.id,
10181
+ epicId: payload.epicId,
10182
+ projectDir: repoDir,
10183
+ keyRun
10184
+ },
10185
+ {
10186
+ heartbeat,
10187
+ workspace: new RunWorkspaceManager({
10188
+ openPullRequest: (input) => client.openPullRequest(env.token, job.id, input)
10189
+ })
10190
+ }
10191
+ );
10192
+ } else {
10193
+ return fail("The job is missing what to plan or build.");
10194
+ }
10195
+ await client.completeJob(env.token, job.id, outcome.status, outcome.result);
10196
+ console.log(outcome.status === "done" ? chalk14.green("Finished.") : chalk14.yellow(`Stopped: ${JSON.stringify(outcome.result)}`));
10197
+ return outcome.status === "done" ? 0 : 1;
10198
+ }
10199
+ async function gitCredential(action, deps = {}) {
10200
+ if (action !== "get") return;
10201
+ const env = readWorkspaceEnv(deps.env);
10202
+ if (!env) return;
10203
+ const git = await workspaceApi(env, "git-credentials", "GET", deps.fetchFn ?? fetch);
10204
+ (deps.write ?? ((s) => process.stdout.write(s)))(`username=${git.username}
10205
+ password=${git.token}
10206
+ `);
10207
+ }
10208
+ var workspaceCommand = new Command13("workspace").description("Run inside a CompBox cloud workspace (used by CompBox)");
10209
+ workspaceCommand.command("run").description("Run this workspace's one plan or build job").action(async () => {
10210
+ process.exitCode = await runWorkspace();
10211
+ });
10212
+ workspaceCommand.command("git-credential <action>").description("Git credential helper for the workspace repository").action(async (action) => {
10213
+ await gitCredential(action);
10214
+ });
10215
+
10216
+ // src/commands/deploy.ts
10217
+ import { Command as Command14 } from "commander";
10218
+ import chalk15 from "chalk";
10219
+ var SLACK_MS = 6e4;
10220
+ var WAIT_LIMIT_MS = 30 * 6e4;
10221
+ async function call(deps, path3, init = {}) {
10222
+ const res = await (deps.fetchFn ?? fetch)(`${deps.apiBaseUrl.replace(/\/+$/, "")}/api/v1${path3}`, {
10223
+ method: init.method ?? "GET",
10224
+ headers: {
10225
+ Authorization: `Bearer ${deps.apiToken}`,
10226
+ ...init.body !== void 0 && { "Content-Type": "application/json" }
10227
+ },
10228
+ ...init.body !== void 0 && { body: JSON.stringify(init.body) }
10229
+ });
10230
+ const body = await res.json().catch(() => null);
10231
+ if (!res.ok) throw new Error(body?.error?.message ?? body?.message ?? `CompBox returned ${String(res.status)}`);
10232
+ return body?.data;
10233
+ }
10234
+ async function deployProject(deps, teamId, environment, wait) {
10235
+ const log = deps.log ?? ((line) => {
10236
+ console.log(line);
10237
+ });
10238
+ const now = deps.now ?? Date.now;
10239
+ const sleep2 = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
10240
+ const startedAt = now();
10241
+ const queued = await call(deps, `/teams/${teamId}/deployments`, { method: "POST", body: { environment } });
10242
+ log(chalk15.gray(`Deploying to ${environment}...`));
10243
+ if (!wait) {
10244
+ log(`Started. When it's done it'll be at ${queued.url}`);
10245
+ return 0;
10246
+ }
10247
+ let last = "";
10248
+ while (now() - startedAt < WAIT_LIMIT_MS) {
10249
+ await sleep2(5e3);
10250
+ const list = await call(deps, `/teams/${teamId}/deployments`);
10251
+ const d = list.find((x) => x.environment === environment);
10252
+ const current = d?.runUrl && d.startedAt && Date.parse(d.startedAt) >= startedAt - SLACK_MS ? d : null;
10253
+ if (!current) continue;
10254
+ if (current.state !== last) {
10255
+ last = current.state;
10256
+ if (current.state === "in_progress") log(chalk15.gray(`Building and deploying (${current.runUrl ?? ""})...`));
10257
+ }
10258
+ if (current.state === "success") {
10259
+ log(chalk15.green(`
10260
+ Live: ${current.url}`));
10261
+ return 0;
10262
+ }
10263
+ if (current.state === "failure" || current.state === "cancelled") {
10264
+ log(chalk15.red(`
10265
+ The deploy ${current.state === "failure" ? "failed" : "was cancelled"}. Run log: ${current.runUrl ?? ""}`));
10266
+ return 1;
10267
+ }
10268
+ }
10269
+ log(chalk15.yellow(`
10270
+ Still running after 30 minutes. Follow it on GitHub; it'll be at ${queued.url}`));
10271
+ return 1;
10272
+ }
10273
+ var deployCommand = new Command14("deploy").description("Deploy a project (its default branch) and print the live address").argument("<project>", "The project's key (e.g. SHOP) or name").option("--env <environment>", "dev, stage or prod", "dev").option("--no-wait", "Start the deploy and don't wait for it").action(async (project, options) => {
10274
+ const config = readConfig();
10275
+ if (!config.apiBaseUrl || !config.apiToken) {
10276
+ console.error(chalk15.red("\nNot logged in. Run `compbox login` first."));
10277
+ process.exit(1);
10278
+ return;
10279
+ }
10280
+ const deps = { apiBaseUrl: config.apiBaseUrl, apiToken: config.apiToken };
10281
+ try {
10282
+ const projects = await listProjects(config.apiBaseUrl, config.apiToken);
10283
+ const match = findProject(projects, project);
10284
+ if (!match) {
10285
+ console.error(chalk15.red(`
10286
+ No project called "${project}". Your projects: ${projects.map((p) => p.key).join(", ") || "none"}.`));
10287
+ process.exit(1);
10288
+ return;
10289
+ }
10290
+ process.exitCode = await deployProject(deps, match.id, options.env, options.wait);
10291
+ } catch (error) {
10292
+ console.error(chalk15.red(`
10293
+ ${error instanceof Error ? error.message : String(error)}`));
10294
+ process.exit(1);
10295
+ }
10296
+ });
10297
+
9793
10298
  // src/index.ts
9794
10299
  function resolveCliVersion() {
9795
10300
  if (true) {
9796
- return "1.19.0";
10301
+ return "1.21.0";
9797
10302
  }
9798
10303
  const require2 = createRequire(import.meta.url);
9799
10304
  const pkg = require2("../package.json");
9800
10305
  return pkg.version;
9801
10306
  }
9802
- var program = new Command12();
10307
+ var program = new Command15();
9803
10308
  program.name("compbox").description("CompBox CLI \u2014 pair this machine, manage Skill Packs, and run the Agent Runner daemon").version(resolveCliVersion());
9804
10309
  program.addCommand(installCommand);
9805
10310
  program.addCommand(updateCommand);
@@ -9811,4 +10316,7 @@ program.addCommand(doctorCommand);
9811
10316
  program.addCommand(runCommand);
9812
10317
  program.addCommand(serviceCommand);
9813
10318
  program.addCommand(machinesCommand);
10319
+ program.addCommand(repoCommand);
10320
+ program.addCommand(workspaceCommand);
10321
+ program.addCommand(deployCommand);
9814
10322
  program.parse(process.argv);