@mycompbox/compbox-cli 1.21.12 → 1.21.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.js CHANGED
@@ -1831,7 +1831,7 @@ var SessionEventType;
1831
1831
  })(SessionEventType || (SessionEventType = {}));
1832
1832
 
1833
1833
  // ../shared/dist/types/mailbox.js
1834
- var START_EXECUTION_KINDS = ["plan", "orchestrate", "refine"];
1834
+ var START_EXECUTION_KINDS = ["plan", "orchestrate", "refine", "follow_up"];
1835
1835
  function normalizeGitRemote(raw) {
1836
1836
  const input = (raw ?? "").trim();
1837
1837
  if (input === "")
@@ -5978,6 +5978,18 @@ var skillPackManifestSchema = external_exports.object({
5978
5978
  dependencies: external_exports.record(external_exports.string()).optional().describe("Other skill pack dependencies (pack-name: version)")
5979
5979
  });
5980
5980
 
5981
+ // ../shared/dist/model-catalog.js
5982
+ var CONVERSATION_CHAT_MODELS = [
5983
+ { id: "claude-haiku-5-5", label: "Haiku 5.5" },
5984
+ { id: "claude-sonnet-5-5", label: "Sonnet 5.5" },
5985
+ { id: "claude-opus-5-5", label: "Opus 5.5" },
5986
+ { id: "claude-fable-5-1", label: "Fable 5.1" }
5987
+ ];
5988
+ var CONVERSATION_CHAT_MODEL_IDS = CONVERSATION_CHAT_MODELS.map((m) => m.id);
5989
+ function isConversationChatModel(value) {
5990
+ return typeof value === "string" && CONVERSATION_CHAT_MODEL_IDS.includes(value);
5991
+ }
5992
+
5981
5993
  // ../shared/dist/pxpipe/config.js
5982
5994
  var PXPIPE_DEFAULT_PROXY_URL = "http://127.0.0.1:47821";
5983
5995
  function currentEnv(env) {
@@ -6284,6 +6296,11 @@ function looksLikeCompletionAttempt(text) {
6284
6296
  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```';
6285
6297
 
6286
6298
  // ../shared/dist/interview-conversation.js
6299
+ function contentText(content) {
6300
+ if (typeof content === "string")
6301
+ return content;
6302
+ return content.flatMap((b) => b.type === "text" && typeof b.text === "string" ? [b.text] : []).join("\n\n");
6303
+ }
6287
6304
  function requestLockReason(saved) {
6288
6305
  if (!saved)
6289
6306
  return null;
@@ -6337,6 +6354,10 @@ What a good request covers:
6337
6354
  ${definition.map(renderSection).join("\n")}
6338
6355
  Optional topics may be skipped when the person has nothing to add. Never invent or pad facts.
6339
6356
 
6357
+ What you can and can't do:
6358
+ - The ONLY thing you can change is the request's own text (title and topics), by replying with the completion JSON below. You can't move it to another project, approve or reject it, make a blueprint, start a build, or change tasks, parts or anything else in CompBox.
6359
+ - Never say or imply you did any of those things (no "Done", "Moved", "Approved"). If they ask, say plainly that you can't do that from here and tell them where they can: the idea's page for approving and making the blueprint, "Move to project" on the classic page for a personal idea, or an admin.
6360
+
6340
6361
  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:
6341
6362
  \`\`\`json
6342
6363
  {"done": true, ${shape}}
@@ -6360,7 +6381,7 @@ function toConversationMessages(turns) {
6360
6381
  return messages;
6361
6382
  }
6362
6383
  function renderConversationPrompt(messages) {
6363
- const lines = messages.map((m) => `${m.role === "assistant" ? "You" : "Them"}: ${m.content}`);
6384
+ const lines = messages.map((m) => `${m.role === "assistant" ? "You" : "Them"}: ${contentText(m.content)}`);
6364
6385
  return `The conversation so far:
6365
6386
 
6366
6387
  ${lines.join("\n\n")}
@@ -6395,10 +6416,11 @@ async function runConversationStep(input, deps) {
6395
6416
  let createdHere = false;
6396
6417
  let qualityRounds = 0;
6397
6418
  let repairs = 0;
6419
+ let kind = "chat";
6398
6420
  for (; ; ) {
6399
6421
  let reply;
6400
6422
  try {
6401
- reply = await deps.reply(system, messages);
6423
+ reply = await deps.reply(system, messages, kind);
6402
6424
  } catch (error) {
6403
6425
  if (savedNow)
6404
6426
  return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created), ...savedNow };
@@ -6411,12 +6433,22 @@ Send another message (for example "try again") when you're ready and I'll pick u
6411
6433
  };
6412
6434
  }
6413
6435
  const draft = extractCompletionJson(reply);
6436
+ if (!draft && !looksLikeCompletionAttempt(reply)) {
6437
+ const text = reply.trim();
6438
+ if (savedNow) {
6439
+ return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created, text || void 0), ...savedNow };
6440
+ }
6441
+ if (!text)
6442
+ return { kind: "error", text: "I didn't get a reply that time. Send another message and I'll try again." };
6443
+ return { kind: "message", text };
6444
+ }
6414
6445
  if (draft) {
6415
6446
  if (lockReason) {
6416
6447
  const why = lockReason === "ownership" ? "Only the request's creator can change it, and I'm not its creator." : "That request is locked and can't be changed.";
6417
6448
  messages.push({ role: "assistant", content: reply }, { role: "user", content: `${why} Reply to me in plain text instead.` });
6418
6449
  if (++repairs > JSON_REPAIRS)
6419
6450
  return { kind: "error", text: lockedRequestMessage(lockReason) };
6451
+ kind = "repair";
6420
6452
  continue;
6421
6453
  }
6422
6454
  let saved;
@@ -6441,22 +6473,14 @@ Reply "try again" and I'll retry.` };
6441
6473
 
6442
6474
  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.`
6443
6475
  });
6476
+ kind = "save";
6444
6477
  continue;
6445
6478
  }
6446
- if (looksLikeCompletionAttempt(reply)) {
6447
- if (++repairs > JSON_REPAIRS) {
6448
- 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.` };
6449
- }
6450
- messages.push({ role: "assistant", content: reply }, { role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
6451
- continue;
6479
+ if (++repairs > JSON_REPAIRS) {
6480
+ 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.` };
6452
6481
  }
6453
- const text = reply.trim();
6454
- if (savedNow) {
6455
- return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created, text || void 0), ...savedNow };
6456
- }
6457
- if (!text)
6458
- return { kind: "error", text: "I didn't get a reply that time. Send another message and I'll try again." };
6459
- return { kind: "message", text };
6482
+ messages.push({ role: "assistant", content: reply }, { role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
6483
+ kind = "repair";
6460
6484
  }
6461
6485
  }
6462
6486
  function savedContextFromRecord(record, access) {
@@ -6750,6 +6774,77 @@ function formatNeedsInputText(req) {
6750
6774
  return out.join("\n");
6751
6775
  }
6752
6776
 
6777
+ // ../shared/dist/run-progress.js
6778
+ var isoTimestamp = external_exports.string().datetime({ offset: true });
6779
+ var runKindSchema = external_exports.enum(["planning", "build"]);
6780
+ var runStageStatusSchema = external_exports.enum(["pending", "active", "completed", "failed", "skipped"]);
6781
+ var runStateSchema = external_exports.enum([
6782
+ "pending",
6783
+ "active",
6784
+ "completed",
6785
+ "failed",
6786
+ "cancelled",
6787
+ "stalled"
6788
+ ]);
6789
+ var runProgressStageSchema = external_exports.object({
6790
+ /** Stable machine key for the stage, unique within the run. */
6791
+ key: external_exports.string().min(1),
6792
+ /** Human-readable label shown in the UI. */
6793
+ label: external_exports.string().min(1),
6794
+ /** Current status of the stage. */
6795
+ status: runStageStatusSchema,
6796
+ /** Optional short detail line (for example "3 of 7 tasks"). */
6797
+ detail: external_exports.string().nullable(),
6798
+ /** When the stage started, or null if it has not started yet. */
6799
+ startedAt: isoTimestamp.nullable(),
6800
+ /** When the stage finished, or null if it has not finished yet. */
6801
+ completedAt: isoTimestamp.nullable()
6802
+ });
6803
+ var runEtaSchema = external_exports.object({
6804
+ /** Estimated seconds left, or null when no estimate can be made. */
6805
+ secondsRemaining: external_exports.number().int().nonnegative().nullable(),
6806
+ /** How much to trust the estimate, based mostly on sample size. */
6807
+ confidence: external_exports.enum(["low", "medium", "high"]),
6808
+ /** Number of past runs the estimate is based on. */
6809
+ sampleSize: external_exports.number().int().nonnegative(),
6810
+ /** True when the run has already taken longer than the estimate. */
6811
+ overrun: external_exports.boolean()
6812
+ });
6813
+ var runProgressBaseSchema = external_exports.object({
6814
+ // --- Identity ---
6815
+ /** Which kind of run this is. */
6816
+ runKind: runKindSchema,
6817
+ // --- Stages ---
6818
+ /** Ordered list of the run's stages. */
6819
+ stages: external_exports.array(runProgressStageSchema),
6820
+ /** Key of the stage currently running, or null if none is running. */
6821
+ currentStageKey: external_exports.string().min(1).nullable(),
6822
+ // --- Counts ---
6823
+ /** Units of work finished (stages for planning, tasks for build). */
6824
+ completed: external_exports.number().int().nonnegative(),
6825
+ /** Total units of work in the run. */
6826
+ total: external_exports.number().int().nonnegative(),
6827
+ // --- State ---
6828
+ /** Overall state of the run. */
6829
+ state: runStateSchema,
6830
+ /** Why the run failed or stalled, or null otherwise. */
6831
+ failureReason: external_exports.string().nullable(),
6832
+ // --- Timing ---
6833
+ /** When the run started. */
6834
+ startedAt: isoTimestamp,
6835
+ /** When progress was last reported. */
6836
+ updatedAt: isoTimestamp,
6837
+ /** Estimated time remaining, or null when there is no estimate. */
6838
+ eta: runEtaSchema.nullable()
6839
+ });
6840
+ var runProgressSchema = runProgressBaseSchema.refine((p) => p.completed <= p.total, {
6841
+ message: "completed must not be greater than total",
6842
+ path: ["completed"]
6843
+ }).refine((p) => p.currentStageKey === null || p.stages.some((s) => s.key === p.currentStageKey), {
6844
+ message: "currentStageKey must match one of the stage keys",
6845
+ path: ["currentStageKey"]
6846
+ });
6847
+
6753
6848
  // src/utils/config-store.ts
6754
6849
  var DEFAULT_BUILD_STALL_MINUTES = 30;
6755
6850
  var DEFAULT_BUILD_MAX_HOURS = 12;
@@ -7228,7 +7323,7 @@ var cached;
7228
7323
  function resolveCliVersion() {
7229
7324
  if (cached !== void 0) return cached;
7230
7325
  if (true) {
7231
- cached = "1.21.12";
7326
+ cached = "1.21.15";
7232
7327
  return cached;
7233
7328
  }
7234
7329
  const require2 = createRequire(import.meta.url);
@@ -7544,13 +7639,16 @@ var MailboxClient = class {
7544
7639
  }
7545
7640
  return { cancelJobIds: parseCancelJobIds(res.data), ownerNotes: parseOwnerNotes(res.data) };
7546
7641
  }
7547
- /** Posts an agent turn (a question/status update) to a job's interview log. */
7548
- async postTurn(machineToken, jobId, content) {
7642
+ /**
7643
+ * Posts an agent turn (a question/status update) to a job's interview log.
7644
+ * `metrics` (ENG-392) carries how long the turn took; omitted when absent.
7645
+ */
7646
+ async postTurn(machineToken, jobId, content, metrics) {
7549
7647
  let res;
7550
7648
  try {
7551
7649
  res = await this.http.post(
7552
7650
  `/api/v1/jobs/${jobId}/turns`,
7553
- { content },
7651
+ metrics ? { content, metrics } : { content },
7554
7652
  { headers: { Authorization: `Bearer ${machineToken}` } }
7555
7653
  );
7556
7654
  } catch (error) {
@@ -7562,6 +7660,15 @@ var MailboxClient = class {
7562
7660
  const data = res.data;
7563
7661
  return data.data;
7564
7662
  }
7663
+ /**
7664
+ * Posts one slice of in-progress reply text for a claimed job (ENG-388).
7665
+ * `seq` orders slices within the job. The server publishes the slice to the
7666
+ * job's owner and stores nothing, so callers should treat this as
7667
+ * best-effort; see JobStreamPublisher, which batches and swallows failures.
7668
+ */
7669
+ async postStreamDelta(machineToken, jobId, seq, delta) {
7670
+ await this.send("post", `/api/v1/jobs/${jobId}/stream`, machineToken, { seq, delta }, "stream-delta");
7671
+ }
7565
7672
  /**
7566
7673
  * Marks a claimed job done or failed, with an optional structured result.
7567
7674
  * `waiting` (ENG-333) parks a usage-limited job to resume later: `resumeAt`
@@ -9109,7 +9216,8 @@ import Anthropic from "@anthropic-ai/sdk";
9109
9216
  import { execFile as execFile2, spawn as spawn7, spawnSync } from "node:child_process";
9110
9217
  import { randomUUID } from "node:crypto";
9111
9218
  import { mkdirSync as mkdirSync9 } from "node:fs";
9112
- import { homedir as homedir7 } from "node:os";
9219
+ import { mkdir as mkdir2, mkdtemp, realpath, rm, writeFile as writeFile2 } from "node:fs/promises";
9220
+ import { homedir as homedir7, tmpdir as tmpdir2 } from "node:os";
9113
9221
  import { join as join16 } from "node:path";
9114
9222
 
9115
9223
  // src/utils/run-timings.ts
@@ -9683,6 +9791,108 @@ function startProgressWatcher(options) {
9683
9791
  };
9684
9792
  }
9685
9793
 
9794
+ // src/utils/claude-stream.ts
9795
+ import { StringDecoder } from "node:string_decoder";
9796
+ function isObject(v) {
9797
+ return typeof v === "object" && v !== null && !Array.isArray(v);
9798
+ }
9799
+ function assistantText(message) {
9800
+ if (!isObject(message) || !Array.isArray(message.content)) return "";
9801
+ let out = "";
9802
+ for (const block of message.content) {
9803
+ if (isObject(block) && block.type === "text" && typeof block.text === "string") {
9804
+ out += block.text;
9805
+ }
9806
+ }
9807
+ return out;
9808
+ }
9809
+ function parseClaudeStream() {
9810
+ const decoder = new StringDecoder("utf8");
9811
+ let buffer = "";
9812
+ let accumulated = "";
9813
+ let sawPartial = false;
9814
+ let finalText = null;
9815
+ let sessionId = null;
9816
+ let done = false;
9817
+ let isError = false;
9818
+ const handleLine = (line, deltas) => {
9819
+ const trimmed = line.trim();
9820
+ if (!trimmed) return;
9821
+ let evt;
9822
+ try {
9823
+ evt = JSON.parse(trimmed);
9824
+ } catch {
9825
+ return;
9826
+ }
9827
+ if (!isObject(evt)) return;
9828
+ if (typeof evt.session_id === "string") sessionId = evt.session_id;
9829
+ switch (evt.type) {
9830
+ case "stream_event": {
9831
+ const inner = evt.event;
9832
+ if (!isObject(inner) || inner.type !== "content_block_delta") return;
9833
+ const delta = inner.delta;
9834
+ if (isObject(delta) && delta.type === "text_delta" && typeof delta.text === "string") {
9835
+ sawPartial = true;
9836
+ if (delta.text) {
9837
+ accumulated += delta.text;
9838
+ deltas.push(delta.text);
9839
+ }
9840
+ }
9841
+ return;
9842
+ }
9843
+ case "assistant": {
9844
+ if (sawPartial) return;
9845
+ const text = assistantText(evt.message);
9846
+ if (text) {
9847
+ accumulated += text;
9848
+ deltas.push(text);
9849
+ }
9850
+ return;
9851
+ }
9852
+ case "result": {
9853
+ done = true;
9854
+ isError = evt.is_error === true;
9855
+ if (typeof evt.result === "string") finalText = evt.result;
9856
+ return;
9857
+ }
9858
+ default:
9859
+ return;
9860
+ }
9861
+ };
9862
+ const snapshot = () => ({
9863
+ text: finalText ?? accumulated,
9864
+ sessionId,
9865
+ done,
9866
+ isError
9867
+ });
9868
+ return {
9869
+ push(chunk) {
9870
+ buffer += typeof chunk === "string" ? chunk : decoder.write(chunk);
9871
+ const deltas = [];
9872
+ let nl;
9873
+ while ((nl = buffer.indexOf("\n")) !== -1) {
9874
+ const line = buffer.slice(0, nl);
9875
+ buffer = buffer.slice(nl + 1);
9876
+ handleLine(line, deltas);
9877
+ }
9878
+ return deltas;
9879
+ },
9880
+ finish() {
9881
+ const deltas = [];
9882
+ buffer += decoder.end();
9883
+ if (buffer) {
9884
+ const line = buffer;
9885
+ buffer = "";
9886
+ handleLine(line, deltas);
9887
+ }
9888
+ return { deltas, result: snapshot() };
9889
+ },
9890
+ get result() {
9891
+ return snapshot();
9892
+ }
9893
+ };
9894
+ }
9895
+
9686
9896
  // src/utils/usage-limit.ts
9687
9897
  var TAIL_CHARS = 4096;
9688
9898
  var CLI_LIMIT_PATTERNS = [
@@ -11480,6 +11690,25 @@ function createWrapUp(deps) {
11480
11690
 
11481
11691
  // src/utils/agent-invoker.ts
11482
11692
  var ANTHROPIC_MODEL = "claude-fable-5";
11693
+ var CHAT_MODEL = "claude-haiku-5-5";
11694
+ var SAVE_MODEL = ANTHROPIC_MODEL;
11695
+ function modelForTurn(kind, chosenChatModel = null) {
11696
+ if (kind !== "chat") return SAVE_MODEL;
11697
+ return chosenChatModel ?? CHAT_MODEL;
11698
+ }
11699
+ function chosenChatModelOf(payload) {
11700
+ let p = payload;
11701
+ if (typeof p === "string") {
11702
+ try {
11703
+ p = JSON.parse(p);
11704
+ } catch {
11705
+ return null;
11706
+ }
11707
+ }
11708
+ if (typeof p !== "object" || p === null) return null;
11709
+ const model = p.model;
11710
+ return isConversationChatModel(model) ? model : null;
11711
+ }
11483
11712
  var CLAUDE_CLI_TURN_TIMEOUT_MS = 4 * 60 * 1e3;
11484
11713
  function anthropicClientOptions(apiKey, routing) {
11485
11714
  return routing.mode === "proxy" ? { apiKey, baseURL: routing.anthropicBaseUrl } : { apiKey };
@@ -11489,6 +11718,9 @@ function claudeSpawnEnv(base, routing) {
11489
11718
  }
11490
11719
  var SUPPORTED_IMAGE_MEDIA_TYPES = ["image/jpeg", "image/png", "image/gif", "image/webp"];
11491
11720
  var MAX_IMAGE_BYTES_PER_TURN = 20 * 1024 * 1024;
11721
+ var defaultWarn = (message) => {
11722
+ console.warn(` \u26A0 ${message}`);
11723
+ };
11492
11724
  function normalizeImageMediaType(mime) {
11493
11725
  const base = (mime.split(";")[0] ?? "").trim().toLowerCase();
11494
11726
  return SUPPORTED_IMAGE_MEDIA_TYPES.includes(base) ? base : null;
@@ -11496,18 +11728,164 @@ function normalizeImageMediaType(mime) {
11496
11728
  function isSupportedImageMediaType(mime) {
11497
11729
  return normalizeImageMediaType(mime) !== null;
11498
11730
  }
11499
- function imageAttachmentCount(attachments) {
11500
- if (!attachments || attachments.length === 0) return 0;
11501
- return attachments.filter((a) => isSupportedImageMediaType(a.mimeType)).length;
11731
+ async function apiUserTurnContent(turn, warn = defaultWarn, fetchImpl = fetch) {
11732
+ const all = turn.attachments ?? [];
11733
+ if (all.length === 0) return turn.content;
11734
+ const { fetched } = await fetchAttachments(selectAttachments(all, warn), warn, fetchImpl);
11735
+ const text = appendMissingAttachmentNote(turn.content, all.length - fetched.length);
11736
+ if (fetched.length === 0) return text;
11737
+ return [
11738
+ ...fetched.map((f, i) => attachmentBlock(f, i + 1)),
11739
+ { type: "text", text }
11740
+ ];
11741
+ }
11742
+ var PDF_MEDIA_TYPE = "application/pdf";
11743
+ var TEXT_DOCUMENT_MEDIA_TYPES = [
11744
+ "text/plain",
11745
+ "text/csv",
11746
+ "text/markdown",
11747
+ "application/json"
11748
+ ];
11749
+ var MAX_ATTACHMENTS_PER_TURN = 8;
11750
+ var MAX_ATTACHMENT_BYTES_PER_TURN = 32 * 1024 * 1024;
11751
+ function baseMime(mime) {
11752
+ return (mime.split(";")[0] ?? "").trim().toLowerCase();
11753
+ }
11754
+ function attachmentKind(mime) {
11755
+ if (isSupportedImageMediaType(mime)) return "image";
11756
+ const base = baseMime(mime);
11757
+ if (base === PDF_MEDIA_TYPE) return "pdf";
11758
+ if (TEXT_DOCUMENT_MEDIA_TYPES.includes(base)) return "text";
11759
+ return null;
11502
11760
  }
11503
- function appendAttachmentNote(text, imageCount) {
11504
- if (imageCount <= 0) return text;
11505
- const noun = imageCount === 1 ? "image" : "images";
11506
- const note = `[${String(imageCount)} ${noun} attached \u2014 not shown in subscription mode; vision is handled when the daemon runs in API mode]`;
11761
+ function selectAttachments(attachments, warn = defaultWarn) {
11762
+ if (!attachments || attachments.length === 0) return [];
11763
+ const selected = [];
11764
+ let declaredBytes = 0;
11765
+ for (const att of attachments) {
11766
+ if (attachmentKind(att.mimeType) === null) {
11767
+ warn(`Skipping attachment ${att.id}: unsupported type ${att.mimeType}.`);
11768
+ continue;
11769
+ }
11770
+ if (selected.length >= MAX_ATTACHMENTS_PER_TURN) {
11771
+ warn(
11772
+ `Skipping attachment ${att.id}: more than ${String(MAX_ATTACHMENTS_PER_TURN)} on one message.`
11773
+ );
11774
+ continue;
11775
+ }
11776
+ const size = typeof att.sizeBytes === "number" && att.sizeBytes > 0 ? att.sizeBytes : 0;
11777
+ if (declaredBytes + size > MAX_ATTACHMENT_BYTES_PER_TURN) {
11778
+ warn(`Skipping attachment ${att.id}: exceeds the per-message size budget.`);
11779
+ continue;
11780
+ }
11781
+ declaredBytes += size;
11782
+ selected.push(att);
11783
+ }
11784
+ return selected;
11785
+ }
11786
+ async function fetchAttachments(attachments, warn = defaultWarn, fetchImpl = fetch) {
11787
+ const fetched = [];
11788
+ const failed = [];
11789
+ let totalBytes = 0;
11790
+ for (const att of attachments) {
11791
+ const kind = attachmentKind(att.mimeType);
11792
+ if (!kind) {
11793
+ failed.push(att);
11794
+ continue;
11795
+ }
11796
+ try {
11797
+ const res = await fetchImpl(att.signedUrl);
11798
+ if (!res.ok) throw new Error(`fetch failed (HTTP ${String(res.status)})`);
11799
+ const bytes = Buffer.from(await res.arrayBuffer());
11800
+ if (bytes.byteLength === 0) throw new Error("empty response body");
11801
+ if (totalBytes + bytes.byteLength > MAX_ATTACHMENT_BYTES_PER_TURN) {
11802
+ throw new Error("exceeds the per-message size budget");
11803
+ }
11804
+ totalBytes += bytes.byteLength;
11805
+ fetched.push({ attachment: att, kind, bytes });
11806
+ } catch (error) {
11807
+ const message = error instanceof Error ? error.message : "unknown error";
11808
+ warn(`Skipping attachment ${att.id}: ${message}.`);
11809
+ failed.push(att);
11810
+ }
11811
+ }
11812
+ return { fetched, failed };
11813
+ }
11814
+ function attachmentBlock(f, n) {
11815
+ if (f.kind === "image") {
11816
+ const mediaType = normalizeImageMediaType(f.attachment.mimeType) ?? "image/png";
11817
+ return {
11818
+ type: "image",
11819
+ source: { type: "base64", media_type: mediaType, data: f.bytes.toString("base64") }
11820
+ };
11821
+ }
11822
+ if (f.kind === "pdf") {
11823
+ return {
11824
+ type: "document",
11825
+ source: { type: "base64", media_type: PDF_MEDIA_TYPE, data: f.bytes.toString("base64") }
11826
+ };
11827
+ }
11828
+ const label = `attachment ${String(n)} (${baseMime(f.attachment.mimeType)})`;
11829
+ return {
11830
+ type: "text",
11831
+ text: `<<<BEGIN ${label}>>>
11832
+ ${f.bytes.toString("utf8")}
11833
+ <<<END ${label}>>>`
11834
+ };
11835
+ }
11836
+ function appendMissingAttachmentNote(text, count) {
11837
+ if (count <= 0) return text;
11838
+ const noun = count === 1 ? "attachment" : "attachments";
11839
+ const note = `[${String(count)} ${noun} could not be loaded and ${count === 1 ? "is" : "are"} not shown]`;
11507
11840
  return text.trim().length > 0 ? `${text}
11508
11841
 
11509
11842
  ${note}` : note;
11510
11843
  }
11844
+ var EXTENSION_BY_MIME = {
11845
+ "image/png": "png",
11846
+ "image/jpeg": "jpg",
11847
+ "image/gif": "gif",
11848
+ "image/webp": "webp",
11849
+ "application/pdf": "pdf",
11850
+ "text/plain": "txt",
11851
+ "text/csv": "csv",
11852
+ "text/markdown": "md",
11853
+ "application/json": "json"
11854
+ };
11855
+ async function materializeAttachments(dir, attachments, fetchImpl = fetch, warn = defaultWarn) {
11856
+ const all = attachments ?? [];
11857
+ if (all.length === 0) return { files: [], failed: 0 };
11858
+ const { fetched } = await fetchAttachments(selectAttachments(all, warn), warn, fetchImpl);
11859
+ const files = [];
11860
+ if (fetched.length > 0) await mkdir2(dir, { recursive: true });
11861
+ for (const f of fetched) {
11862
+ const mimeType = baseMime(f.attachment.mimeType);
11863
+ const path3 = join16(
11864
+ dir,
11865
+ `attachment-${String(files.length + 1)}.${EXTENSION_BY_MIME[mimeType] ?? "bin"}`
11866
+ );
11867
+ try {
11868
+ await writeFile2(path3, f.bytes);
11869
+ files.push({ path: path3, mimeType });
11870
+ } catch (error) {
11871
+ const message = error instanceof Error ? error.message : "unknown error";
11872
+ warn(`Skipping attachment ${f.attachment.id}: could not save it (${message}).`);
11873
+ }
11874
+ }
11875
+ return { files, failed: all.length - files.length };
11876
+ }
11877
+ function appendAttachmentPaths(text, files, failed) {
11878
+ let out = text;
11879
+ if (files.length > 0) {
11880
+ const list = files.map((f) => `- ${f.path} (${f.mimeType})`).join("\n");
11881
+ const note = `[Attached files \u2014 open them with the Read tool:
11882
+ ${list}]`;
11883
+ out = out.trim().length > 0 ? `${out}
11884
+
11885
+ ${note}` : note;
11886
+ }
11887
+ return appendMissingAttachmentNote(out, failed);
11888
+ }
11511
11889
  function usageLimitMessage(resumeAt) {
11512
11890
  return resumeAt ? `The AI usage limit was reached. The run will continue after it resets at ${resumeAt.toISOString()}.` : "The AI usage limit was reached. The run will continue after it resets.";
11513
11891
  }
@@ -11559,86 +11937,157 @@ function claudeCliSessionCwd() {
11559
11937
  }
11560
11938
  return dir;
11561
11939
  }
11940
+ function claudeToolArgs(attachmentsDir) {
11941
+ if (!attachmentsDir) return ["--tools", ""];
11942
+ return [
11943
+ "--tools",
11944
+ "Read",
11945
+ "--add-dir",
11946
+ attachmentsDir,
11947
+ "--allowedTools",
11948
+ `Read(/${attachmentsDir}/**)`
11949
+ ];
11950
+ }
11951
+ function rejectsPartialMessagesFlag(stderr) {
11952
+ return stderr.includes("--include-partial-messages") && /unknown|unrecognized|invalid|unexpected|not supported/i.test(stderr);
11953
+ }
11562
11954
  function runClaudeCliTurn(prompt, opts) {
11563
11955
  return new Promise((resolve4, reject) => {
11564
11956
  const model = opts.model === void 0 ? ANTHROPIC_MODEL : opts.model;
11565
- const args = [
11566
- "-p",
11567
- prompt,
11568
- ...model ? ["--model", model] : [],
11569
- "--output-format",
11570
- "json",
11571
- "--tools",
11572
- "",
11573
- "--permission-mode",
11574
- "dontAsk",
11575
- "--safe-mode",
11576
- "--system-prompt",
11577
- opts.systemPrompt
11578
- ];
11579
- if (opts.resumeSessionId) {
11580
- args.push("--resume", opts.resumeSessionId);
11581
- }
11957
+ const onText = opts.onText;
11958
+ const streaming = typeof onText === "function";
11959
+ const buildArgs = (withPartial) => {
11960
+ const args = [
11961
+ "-p",
11962
+ prompt,
11963
+ ...model ? ["--model", model] : [],
11964
+ "--output-format",
11965
+ ...streaming ? ["stream-json", "--verbose", ...withPartial ? ["--include-partial-messages"] : []] : ["json"],
11966
+ ...claudeToolArgs(opts.attachmentsDir),
11967
+ "--permission-mode",
11968
+ "dontAsk",
11969
+ "--safe-mode",
11970
+ "--system-prompt",
11971
+ opts.systemPrompt
11972
+ ];
11973
+ if (opts.resumeSessionId) {
11974
+ args.push("--resume", opts.resumeSessionId);
11975
+ }
11976
+ return args;
11977
+ };
11582
11978
  const command = resolveClaudeBinary() ?? "claude";
11583
11979
  const pxpipeEnv = claudeSpawnEnv(process.env, opts.routing);
11584
- const child = spawn7(command, args, {
11585
- cwd: claudeCliSessionCwd(),
11586
- stdio: ["ignore", "pipe", "pipe"],
11587
- env: { ...pxpipeEnv, PATH: claudeChildEnvPath(pxpipeEnv.PATH) }
11588
- });
11589
- let stdout2 = "";
11590
- let stderr = "";
11591
- let settled = false;
11592
- const timer = setTimeout(() => {
11593
- if (settled) return;
11594
- settled = true;
11595
- child.kill("SIGKILL");
11596
- reject(new Error(`claude CLI timed out after ${String(CLAUDE_CLI_TURN_TIMEOUT_MS / 1e3)}s`));
11597
- }, CLAUDE_CLI_TURN_TIMEOUT_MS);
11598
- child.stdout.on("data", (chunk) => {
11599
- stdout2 += chunk.toString("utf-8");
11600
- });
11601
- child.stderr.on("data", (chunk) => {
11602
- stderr += chunk.toString("utf-8");
11603
- });
11604
- child.on("error", (error) => {
11605
- if (settled) return;
11606
- settled = true;
11607
- clearTimeout(timer);
11608
- if (error.code === "ENOENT") {
11609
- reject(new Error(claudeNotFoundMessage()));
11610
- return;
11611
- }
11612
- reject(error);
11613
- });
11614
- child.on("close", (code) => {
11615
- if (settled) return;
11616
- settled = true;
11617
- clearTimeout(timer);
11618
- if (code !== 0) {
11619
- reject(new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`));
11620
- return;
11621
- }
11622
- let parsed;
11623
- try {
11624
- parsed = JSON.parse(stdout2);
11625
- } catch {
11626
- reject(new Error(`claude CLI returned non-JSON output: ${stdout2.slice(0, 500)}`));
11627
- return;
11628
- }
11629
- const shaped = parsed;
11630
- if (shaped.is_error) {
11631
- reject(new Error(shaped.result ?? "claude CLI reported an error"));
11632
- return;
11633
- }
11634
- if (typeof shaped.result !== "string" || typeof shaped.session_id !== "string") {
11980
+ const attempt = (withPartial) => {
11981
+ const child = spawn7(command, buildArgs(withPartial), {
11982
+ cwd: claudeCliSessionCwd(),
11983
+ stdio: ["ignore", "pipe", "pipe"],
11984
+ env: { ...pxpipeEnv, PATH: claudeChildEnvPath(pxpipeEnv.PATH) }
11985
+ });
11986
+ let stdout2 = "";
11987
+ let stderr = "";
11988
+ let settled = false;
11989
+ let sawStdout = false;
11990
+ const stream = streaming ? parseClaudeStream() : null;
11991
+ const emit = (deltas) => {
11992
+ if (!onText || settled) return;
11993
+ for (const delta of deltas) {
11994
+ try {
11995
+ onText(delta);
11996
+ } catch {
11997
+ }
11998
+ }
11999
+ };
12000
+ const timer = setTimeout(() => {
12001
+ if (settled) return;
12002
+ settled = true;
12003
+ child.kill("SIGKILL");
11635
12004
  reject(
11636
- new Error("claude CLI returned an unexpected JSON shape (missing result/session_id).")
12005
+ new Error(`claude CLI timed out after ${String(CLAUDE_CLI_TURN_TIMEOUT_MS / 1e3)}s`)
11637
12006
  );
11638
- return;
11639
- }
11640
- resolve4({ text: shaped.result, sessionId: shaped.session_id });
11641
- });
12007
+ }, CLAUDE_CLI_TURN_TIMEOUT_MS);
12008
+ child.stdout.on("data", (chunk) => {
12009
+ if (chunk.length > 0) sawStdout = true;
12010
+ if (stream) {
12011
+ emit(stream.push(chunk));
12012
+ return;
12013
+ }
12014
+ stdout2 += chunk.toString("utf-8");
12015
+ });
12016
+ child.stderr.on("data", (chunk) => {
12017
+ stderr += chunk.toString("utf-8");
12018
+ });
12019
+ child.on("error", (error) => {
12020
+ if (settled) return;
12021
+ settled = true;
12022
+ clearTimeout(timer);
12023
+ if (error.code === "ENOENT") {
12024
+ reject(new Error(claudeNotFoundMessage()));
12025
+ return;
12026
+ }
12027
+ reject(error);
12028
+ });
12029
+ child.on("close", (code) => {
12030
+ if (settled) return;
12031
+ if (stream) {
12032
+ const { deltas, result } = stream.finish();
12033
+ emit(deltas);
12034
+ settled = true;
12035
+ clearTimeout(timer);
12036
+ if (code !== 0) {
12037
+ if (withPartial && !sawStdout && rejectsPartialMessagesFlag(stderr)) {
12038
+ attempt(false);
12039
+ return;
12040
+ }
12041
+ reject(
12042
+ new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`)
12043
+ );
12044
+ return;
12045
+ }
12046
+ if (result.isError) {
12047
+ reject(new Error(result.text || "claude CLI reported an error"));
12048
+ return;
12049
+ }
12050
+ if (!result.done || result.sessionId === null) {
12051
+ reject(
12052
+ new Error(
12053
+ "claude CLI stream ended without a result event (missing result/session_id)."
12054
+ )
12055
+ );
12056
+ return;
12057
+ }
12058
+ resolve4({ text: result.text, sessionId: result.sessionId });
12059
+ return;
12060
+ }
12061
+ settled = true;
12062
+ clearTimeout(timer);
12063
+ if (code !== 0) {
12064
+ reject(
12065
+ new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`)
12066
+ );
12067
+ return;
12068
+ }
12069
+ let parsed;
12070
+ try {
12071
+ parsed = JSON.parse(stdout2);
12072
+ } catch {
12073
+ reject(new Error(`claude CLI returned non-JSON output: ${stdout2.slice(0, 500)}`));
12074
+ return;
12075
+ }
12076
+ const shaped = parsed;
12077
+ if (shaped.is_error) {
12078
+ reject(new Error(shaped.result ?? "claude CLI reported an error"));
12079
+ return;
12080
+ }
12081
+ if (typeof shaped.result !== "string" || typeof shaped.session_id !== "string") {
12082
+ reject(
12083
+ new Error("claude CLI returned an unexpected JSON shape (missing result/session_id).")
12084
+ );
12085
+ return;
12086
+ }
12087
+ resolve4({ text: shaped.result, sessionId: shaped.session_id });
12088
+ });
12089
+ };
12090
+ attempt(streaming);
11642
12091
  });
11643
12092
  }
11644
12093
  async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId, discussed) {
@@ -11661,6 +12110,30 @@ function needsDefaultModel(error) {
11661
12110
  message
11662
12111
  );
11663
12112
  }
12113
+ var MAX_CONVERSATION_SESSIONS = 50;
12114
+ var conversationSessions = /* @__PURE__ */ new Map();
12115
+ function rememberConversationSession(jobId, session) {
12116
+ conversationSessions.delete(jobId);
12117
+ conversationSessions.set(jobId, session);
12118
+ while (conversationSessions.size > MAX_CONVERSATION_SESSIONS) {
12119
+ const oldest = conversationSessions.keys().next().value;
12120
+ if (oldest === void 0) break;
12121
+ conversationSessions.delete(oldest);
12122
+ }
12123
+ }
12124
+ function sessionMessageKey(m) {
12125
+ return `${m.role}\0${contentText(m.content)}`;
12126
+ }
12127
+ function extendsSession(seen, next) {
12128
+ if (next.length <= seen.length) return false;
12129
+ return seen.every((key, i) => next[i] === key);
12130
+ }
12131
+ function renderResumePrompt(fresh) {
12132
+ const lines = fresh.map((m) => `${m.role === "assistant" ? "You" : "Them"}: ${contentText(m.content)}`);
12133
+ return `${lines.join("\n\n")}
12134
+
12135
+ Write your next reply to them.`;
12136
+ }
11664
12137
  function savedRequestIdOf(job) {
11665
12138
  const result = job.result;
11666
12139
  if (typeof result?.epicRequestId === "string") return result.epicRequestId;
@@ -11682,48 +12155,138 @@ Send another message (for example "try again") and I'll pick up where we left of
11682
12155
  }
11683
12156
  }
11684
12157
  async function takeConversationStep(job, ctx) {
12158
+ const timer = startTurnTimer();
11685
12159
  const routing = await resolveRouting();
11686
12160
  const requestId = savedRequestIdOf(job);
11687
12161
  const discussed = requestId !== null && parseSeedPayload(job.payload)?.targetEpicRequestId === requestId;
11688
12162
  const saved = requestId ? await loadSavedRequest(ctx.apiBaseUrl, ctx.userApiToken, requestId, discussed) : null;
11689
- const turns = job.turns.map((t) => ({
11690
- role: t.role,
11691
- content: t.role === "user" ? appendAttachmentNote(t.content, imageAttachmentCount(t.attachments)) : t.content
11692
- }));
11693
12163
  const anthropic = ctx.anthropicApiKey ? new Anthropic(anthropicClientOptions(ctx.anthropicApiKey, routing)) : null;
11694
- let cliModel = ANTHROPIC_MODEL;
12164
+ const hasAttachments = job.turns.some(
12165
+ (t) => t.role === "user" && (t.attachments?.length ?? 0) > 0
12166
+ );
12167
+ const attachmentsDir = !anthropic && hasAttachments ? await realpath(await mkdtemp(join16(tmpdir2(), "compbox-attachments-"))) : void 0;
12168
+ try {
12169
+ return await converseWithAttachments(job, ctx, {
12170
+ routing,
12171
+ saved,
12172
+ anthropic,
12173
+ attachmentsDir,
12174
+ timer
12175
+ });
12176
+ } finally {
12177
+ if (attachmentsDir) await rm(attachmentsDir, { recursive: true, force: true });
12178
+ }
12179
+ }
12180
+ function startTurnTimer(now = () => performance.now()) {
12181
+ const startedAt = now();
12182
+ let firstTextAt = null;
12183
+ const elapsed = (at) => Math.max(0, Math.round(at - startedAt));
12184
+ return {
12185
+ markFirstText() {
12186
+ firstTextAt ??= now();
12187
+ },
12188
+ finish(model) {
12189
+ const metrics = {
12190
+ firstTokenMs: firstTextAt === null ? null : elapsed(firstTextAt),
12191
+ totalMs: elapsed(now())
12192
+ };
12193
+ if (model) metrics.model = model;
12194
+ return metrics;
12195
+ }
12196
+ };
12197
+ }
12198
+ async function converseWithAttachments(job, ctx, step) {
12199
+ const { routing, saved, anthropic, attachmentsDir } = step;
12200
+ const timer = step.timer ?? startTurnTimer();
12201
+ let replyModel = null;
12202
+ let usedFiles = false;
12203
+ const turns = [];
12204
+ for (const [index, t] of job.turns.entries()) {
12205
+ if (t.role !== "user") {
12206
+ turns.push({ role: t.role, content: t.content });
12207
+ } else if (anthropic) {
12208
+ turns.push({ role: t.role, content: await apiUserTurnContent(t) });
12209
+ } else if (attachmentsDir && (t.attachments?.length ?? 0) > 0) {
12210
+ const { files, failed } = await materializeAttachments(
12211
+ join16(attachmentsDir, `turn-${String(index + 1)}`),
12212
+ t.attachments
12213
+ );
12214
+ if (files.length > 0) usedFiles = true;
12215
+ turns.push({ role: t.role, content: appendAttachmentPaths(t.content, files, failed) });
12216
+ } else {
12217
+ turns.push({ role: t.role, content: t.content });
12218
+ }
12219
+ }
12220
+ const readDir = usedFiles ? attachmentsDir : void 0;
12221
+ let useDefaultModel = false;
12222
+ const chosenChatModel = chosenChatModelOf(job.payload);
11695
12223
  const outcome = await runConversationStep(
11696
12224
  { turns, saved },
11697
12225
  {
11698
- reply: async (system, messages) => {
12226
+ reply: async (system, messages, kind) => {
12227
+ const model = modelForTurn(kind, chosenChatModel);
11699
12228
  if (anthropic) {
11700
12229
  const response = await anthropic.messages.create({
11701
- model: ANTHROPIC_MODEL,
12230
+ model,
11702
12231
  max_tokens: 4096,
11703
12232
  system,
11704
12233
  messages
11705
12234
  });
11706
12235
  const text = response.content.find((b) => b.type === "text");
11707
- return text?.type === "text" ? text.text : "";
12236
+ const reply = text?.type === "text" ? text.text : "";
12237
+ replyModel = response.model || model;
12238
+ if (reply) timer.markFirstText();
12239
+ return reply;
11708
12240
  }
11709
- const prompt = renderConversationPrompt(messages);
11710
- try {
11711
- return (await runClaudeCliTurn(prompt, {
11712
- systemPrompt: system,
11713
- resumeSessionId: void 0,
11714
- routing,
11715
- model: cliModel
11716
- })).text;
11717
- } catch (error) {
11718
- if (cliModel === null || !needsDefaultModel(error)) throw error;
11719
- cliModel = null;
11720
- return (await runClaudeCliTurn(prompt, {
11721
- systemPrompt: system,
11722
- resumeSessionId: void 0,
11723
- routing,
11724
- model: null
11725
- })).text;
12241
+ const sent = messages.map(sessionMessageKey);
12242
+ const runFresh = async () => {
12243
+ const prompt = renderConversationPrompt(messages);
12244
+ try {
12245
+ return await runClaudeCliTurn(prompt, {
12246
+ systemPrompt: system,
12247
+ resumeSessionId: void 0,
12248
+ routing,
12249
+ model: useDefaultModel ? null : model,
12250
+ attachmentsDir: readDir
12251
+ });
12252
+ } catch (error) {
12253
+ if (useDefaultModel || !needsDefaultModel(error)) throw error;
12254
+ useDefaultModel = true;
12255
+ return await runClaudeCliTurn(prompt, {
12256
+ systemPrompt: system,
12257
+ resumeSessionId: void 0,
12258
+ routing,
12259
+ model: null,
12260
+ attachmentsDir: readDir
12261
+ });
12262
+ }
12263
+ };
12264
+ const session = conversationSessions.get(job.id);
12265
+ let turn = null;
12266
+ if (session && extendsSession(session.sent, sent)) {
12267
+ try {
12268
+ turn = await runClaudeCliTurn(renderResumePrompt(messages.slice(session.sent.length)), {
12269
+ systemPrompt: system,
12270
+ resumeSessionId: session.sessionId,
12271
+ routing,
12272
+ model: useDefaultModel ? null : model,
12273
+ attachmentsDir: readDir
12274
+ });
12275
+ } catch {
12276
+ turn = null;
12277
+ }
11726
12278
  }
12279
+ if (!turn) {
12280
+ conversationSessions.delete(job.id);
12281
+ turn = await runFresh();
12282
+ }
12283
+ rememberConversationSession(job.id, {
12284
+ sessionId: turn.sessionId,
12285
+ sent: [...sent, sessionMessageKey({ role: "assistant", content: turn.text })]
12286
+ });
12287
+ replyModel = useDefaultModel ? null : model;
12288
+ if (turn.text) timer.markFirstText();
12289
+ return turn.text;
11727
12290
  },
11728
12291
  save: async (existingId, draft) => {
11729
12292
  const submitted = await submitAndScore(ctx, existingId, draft);
@@ -11734,7 +12297,7 @@ async function takeConversationStep(job, ctx) {
11734
12297
  if (outcome.kind === "saved") {
11735
12298
  await ctx.mailboxClient.markRequestSaved(ctx.machineToken, job.id, outcome.saved.id);
11736
12299
  }
11737
- await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text);
12300
+ await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text, timer.finish(replyModel));
11738
12301
  return { status: "yield" };
11739
12302
  }
11740
12303
  var PLANNER_RUN_TIMEOUT_MS = 30 * 60 * 1e3;
@@ -12427,9 +12990,11 @@ var ORCHESTRATOR_FINAL_TURN_MAX_CHARS = 4e3;
12427
12990
  function buildOrchestratorArgs(epicId, sessionId, ownerReply, baseBranch, fastMode, extra) {
12428
12991
  return [
12429
12992
  "-p",
12430
- `@orchestrator execute epic ${epicId} --non-interactive` + (ownerReply ? `
12993
+ `@orchestrator execute epic ${epicId} --non-interactive` + (ownerReply || extra?.replyAttachmentsNote ? `
12431
12994
 
12432
- ${freshRunReplyContext(ownerReply)}` : "") + (extra?.ownerNote ? `
12995
+ ${freshRunReplyContext(ownerReply ?? "", extra?.replyAttachmentsNote)}` : "") + (extra?.followUp ? `
12996
+
12997
+ ${followUpContext(extra.followUp)}` : "") + (extra?.ownerNote ? `
12433
12998
 
12434
12999
  ${ownerNoteContext(extra.ownerNote)}` : "") + (extra?.deferred && extra.deferred.length > 0 ? `
12435
13000
 
@@ -12465,6 +13030,13 @@ function deferredFeaturesText(deferred) {
12465
13030
  function ownerNoteContext(note) {
12466
13031
  return ["The owner restarted this build with this note:", quoteOwnerReply(note)].join("\n\n");
12467
13032
  }
13033
+ function followUpContext(message) {
13034
+ return [
13035
+ "This epic's build already finished. Its owner sent this follow-up:",
13036
+ quoteOwnerReply(message, "a follow-up to the finished build"),
13037
+ "Act on it against the epic's blueprint: change features, tasks or code as needed, and report what you changed. If it is unclear, ask with a single COMPBOX_NEEDS_INPUT marker."
13038
+ ].join("\n\n");
13039
+ }
12468
13040
  function buildOrchestratorContinueArgs(sessionId, prompt, baseBranch, fastMode) {
12469
13041
  return [
12470
13042
  "-p",
@@ -12481,6 +13053,24 @@ function buildOrchestratorContinueArgs(sessionId, prompt, baseBranch, fastMode)
12481
13053
  ...fastModeArgs(fastMode)
12482
13054
  ];
12483
13055
  }
13056
+ function parseReplyAttachments(raw) {
13057
+ if (!Array.isArray(raw)) return [];
13058
+ const out = [];
13059
+ for (const item of raw) {
13060
+ if (typeof item !== "object" || item === null) continue;
13061
+ const a = item;
13062
+ if (typeof a.id !== "string" || typeof a.mimeType !== "string" || typeof a.signedUrl !== "string")
13063
+ continue;
13064
+ if (a.signedUrl.trim() === "") continue;
13065
+ out.push({
13066
+ id: a.id,
13067
+ mimeType: a.mimeType,
13068
+ sizeBytes: typeof a.sizeBytes === "number" && Number.isFinite(a.sizeBytes) ? a.sizeBytes : 0,
13069
+ signedUrl: a.signedUrl
13070
+ });
13071
+ }
13072
+ return out;
13073
+ }
12484
13074
  var MAX_REPLY_CHARS = 8e3;
12485
13075
  var REPLY_OPEN = "<<<OWNER_REPLY";
12486
13076
  var REPLY_CLOSE = "OWNER_REPLY>>>";
@@ -12488,16 +13078,24 @@ function parseReplyResume(job) {
12488
13078
  const raw = job.resume;
12489
13079
  if (typeof raw !== "object" || raw === null) return null;
12490
13080
  const r = raw;
12491
- if (typeof r.reply !== "string" || r.reply.trim() === "") return null;
13081
+ if (typeof r.reply !== "string") return null;
13082
+ const attachments = parseReplyAttachments(r.attachments);
13083
+ if (r.reply.trim() === "" && attachments.length === 0) return null;
12492
13084
  const str = (v) => typeof v === "string" && v.trim() !== "" ? v : null;
12493
13085
  const result = typeof job.result === "object" && job.result !== null ? job.result : {};
12494
13086
  return {
12495
13087
  sessionId: str(r.sessionId),
12496
13088
  runDir: str(r.runDir),
12497
13089
  reply: r.reply,
12498
- branch: str(result.branch)
13090
+ branch: str(result.branch),
13091
+ attachments
12499
13092
  };
12500
13093
  }
13094
+ function replyAttachmentsNote(files, failed) {
13095
+ if (files.length === 0 && failed <= 0) return "";
13096
+ const head = "The owner attached files to the reply.";
13097
+ return appendAttachmentPaths(head, files, failed);
13098
+ }
12501
13099
  function quoteOwnerReply(reply, kind = "an answer to your question") {
12502
13100
  let body = reply.slice(0, MAX_REPLY_CHARS);
12503
13101
  for (; ; ) {
@@ -12524,10 +13122,11 @@ function ownerNotePrompt(epicId, notes, deferred = []) {
12524
13122
  ...deferred.length > 0 ? [deferredFeaturesText(deferred)] : []
12525
13123
  ].join("\n\n");
12526
13124
  }
12527
- function replyResumePrompt(epicId, reply) {
13125
+ function replyResumePrompt(epicId, reply, attachmentsNote = "") {
12528
13126
  return [
12529
13127
  `The owner answered your question:`,
12530
13128
  quoteOwnerReply(reply),
13129
+ ...attachmentsNote ? [attachmentsNote] : [],
12531
13130
  `Continue executing epic ${epicId} in non-interactive mode from where you stopped.`,
12532
13131
  "If the answer is not enough, ask again with a single COMPBOX_NEEDS_INPUT marker."
12533
13132
  ].join("\n\n");
@@ -12535,10 +13134,11 @@ function replyResumePrompt(epicId, reply) {
12535
13134
  function buildReplyResumeArgs(sessionId, prompt, baseBranch, fastMode) {
12536
13135
  return buildOrchestratorContinueArgs(sessionId, prompt, baseBranch, fastMode);
12537
13136
  }
12538
- function freshRunReplyContext(reply) {
13137
+ function freshRunReplyContext(reply, attachmentsNote = "") {
12539
13138
  return [
12540
13139
  "This build stopped earlier to ask its owner a question. The owner answered:",
12541
13140
  quoteOwnerReply(reply),
13141
+ ...attachmentsNote ? [attachmentsNote] : [],
12542
13142
  "Use the answer where the earlier run stopped. If it is not enough, ask again with a single COMPBOX_NEEDS_INPUT marker."
12543
13143
  ].join("\n\n");
12544
13144
  }
@@ -12593,7 +13193,9 @@ function mergePullRequestsRequest(prs) {
12593
13193
  return {
12594
13194
  question: `${count} your review and merge before the build can continue.`,
12595
13195
  why: "The rest of the build builds on this work, so continuing now would redo it or conflict with it.",
12596
- steps: prs.map((pr, i) => `${String(i + 1)}. Merge #${String(pr.number)}${pr.title ? ` ${pr.title}` : ""}: ${pr.htmlUrl}`),
13196
+ steps: prs.map(
13197
+ (pr, i) => `${String(i + 1)}. Merge #${String(pr.number)}${pr.title ? ` ${pr.title}` : ""}: ${pr.htmlUrl}`
13198
+ ),
12597
13199
  afterAnswer: `The build continues by itself once they're merged. You can also press "All merged \u2014 continue".`,
12598
13200
  kind: "merge_prs",
12599
13201
  prNumbers: prs.map((pr) => pr.number)
@@ -12768,18 +13370,45 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
12768
13370
  }
12769
13371
  const runDir = workspace?.dir ?? projectDir;
12770
13372
  if (workspace) deps.activeRunDirs?.add(workspace.dir);
13373
+ let replyAttachmentsDir;
13374
+ let attachmentsNote = "";
13375
+ const replyAttachments = resume?.attachments ?? [];
13376
+ if (replyAttachments.length > 0) {
13377
+ try {
13378
+ replyAttachmentsDir = await realpath(
13379
+ await mkdtemp(join16(tmpdir2(), "compbox-reply-attachments-"))
13380
+ );
13381
+ const { files, failed } = await materializeAttachments(
13382
+ replyAttachmentsDir,
13383
+ replyAttachments,
13384
+ deps.fetchImpl ?? fetch
13385
+ );
13386
+ attachmentsNote = replyAttachmentsNote(files, failed);
13387
+ } catch {
13388
+ attachmentsNote = replyAttachmentsNote([], replyAttachments.length);
13389
+ }
13390
+ }
12771
13391
  const routing = await resolveRoutingImpl();
12772
13392
  const command = resolveClaudeBinary() ?? "claude";
12773
13393
  const sessionId = ctx.fix ? void 0 : resumeSessionId ?? (deps.newSessionId ?? randomUUID)();
12774
13394
  const runArgs = ctx.fix ? buildFixArgs(ctx.fix, workspace?.baseBranch, ctx.fastMode) : resumeSessionId && resume ? buildReplyResumeArgs(
12775
13395
  resumeSessionId,
12776
- replyResumePrompt(ctx.epicId, resume.reply),
13396
+ replyResumePrompt(ctx.epicId, resume.reply, attachmentsNote),
12777
13397
  workspace?.baseBranch,
12778
13398
  ctx.fastMode
12779
- ) : buildOrchestratorArgs(ctx.epicId, sessionId, resume?.reply, workspace?.baseBranch, ctx.fastMode, {
12780
- ...ctx.ownerNote && { ownerNote: ctx.ownerNote },
12781
- ...ctx.deferredFeatures && { deferred: ctx.deferredFeatures }
12782
- });
13399
+ ) : buildOrchestratorArgs(
13400
+ ctx.epicId,
13401
+ sessionId,
13402
+ resume?.reply,
13403
+ workspace?.baseBranch,
13404
+ ctx.fastMode,
13405
+ {
13406
+ ...ctx.ownerNote && { ownerNote: ctx.ownerNote },
13407
+ ...ctx.deferredFeatures && { deferred: ctx.deferredFeatures },
13408
+ ...ctx.followUp && { followUp: ctx.followUp },
13409
+ ...attachmentsNote && { replyAttachmentsNote: attachmentsNote }
13410
+ }
13411
+ );
12783
13412
  const args = ctx.keyRun ? keyRunArgs(runArgs) : runArgs;
12784
13413
  const routedEnv = claudeSpawnEnv(process.env, routing);
12785
13414
  const baseEnv = {
@@ -12808,11 +13437,12 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
12808
13437
  } catch {
12809
13438
  }
12810
13439
  try {
12811
- if (!resumeSessionId) await ctx.mailboxClient.postTurn(
12812
- ctx.machineToken,
12813
- ctx.jobId,
12814
- (ctx.fix ? `Started a fix run on the pull request's branch ${ctx.fix.branch}${ctx.fix.pullRequestUrl ? ` (${ctx.fix.pullRequestUrl})` : ""}. New commits are pushed to the same branch, so the existing pull request updates.` : `Started the orchestrator for epic ${ctx.epicId} (headless, non-interactive). This executes the full epic \u2014 every phase and feature \u2014 and may take a long time.` + (workspace ? workspace.continued ? ` Continuing the earlier unfinished work on ${workspace.branch}, which ends as a pull request into ${workspace.baseBranch}.` : ` Working on a new branch, ${workspace.branch}, which will end as a pull request into ${workspace.baseBranch}.` : "")) + (workspaceNotes.length > 0 ? ` Note: ${workspaceNotes.join(" ")}` : "")
12815
- );
13440
+ if (!resumeSessionId)
13441
+ await ctx.mailboxClient.postTurn(
13442
+ ctx.machineToken,
13443
+ ctx.jobId,
13444
+ (ctx.fix ? `Started a fix run on the pull request's branch ${ctx.fix.branch}${ctx.fix.pullRequestUrl ? ` (${ctx.fix.pullRequestUrl})` : ""}. New commits are pushed to the same branch, so the existing pull request updates.` : `Started the orchestrator for epic ${ctx.epicId} (headless, non-interactive). This executes the full epic \u2014 every phase and feature \u2014 and may take a long time.` + (workspace ? workspace.continued ? ` Continuing the earlier unfinished work on ${workspace.branch}, which ends as a pull request into ${workspace.baseBranch}.` : ` Working on a new branch, ${workspace.branch}, which will end as a pull request into ${workspace.baseBranch}.` : "")) + (workspaceNotes.length > 0 ? ` Note: ${workspaceNotes.join(" ")}` : "")
13445
+ );
12816
13446
  } catch {
12817
13447
  }
12818
13448
  const stopped = { reason: null };
@@ -13055,7 +13685,10 @@ ${stderr}`;
13055
13685
  let stalls = 0;
13056
13686
  while (sessionId && unfinished(progress) && continues < maxContinues && !ctx.signal?.aborted) {
13057
13687
  if (progress.waitingPullRequests && progress.waitingPullRequests.length > 0) {
13058
- outcome = needsInputRunResult(ctx.epicId, mergePullRequestsRequest(progress.waitingPullRequests));
13688
+ outcome = needsInputRunResult(
13689
+ ctx.epicId,
13690
+ mergePullRequestsRequest(progress.waitingPullRequests)
13691
+ );
13059
13692
  break;
13060
13693
  }
13061
13694
  if (deadline - Date.now() <= 6e4) {
@@ -13111,7 +13744,9 @@ ${stderr}`;
13111
13744
  outcome.result = {
13112
13745
  ...outcome.result,
13113
13746
  fastMode: { requested: true, used: fastModeUsed },
13114
- ...fastModeUsed === false ? { fastModeNote: "Fast mode was requested but isn't available on this computer's Claude account, so the run used standard speed." } : {}
13747
+ ...fastModeUsed === false ? {
13748
+ fastModeNote: "Fast mode was requested but isn't available on this computer's Claude account, so the run used standard speed."
13749
+ } : {}
13115
13750
  };
13116
13751
  }
13117
13752
  const keepRunCopy = needsInput !== null && !ctx.keyRun && !ctx.fix && sessionId !== void 0;
@@ -13190,6 +13825,8 @@ ${stderr}`;
13190
13825
  }
13191
13826
  }
13192
13827
  if (workspace) deps.activeRunDirs?.delete(workspace.dir);
13828
+ if (replyAttachmentsDir)
13829
+ await rm(replyAttachmentsDir, { recursive: true, force: true }).catch(() => void 0);
13193
13830
  const timings = buildJobTimings({
13194
13831
  install: workspace?.install,
13195
13832
  runs: runDurations,
@@ -13373,7 +14010,7 @@ async function invokeConnectRepo(payload, deps = {}) {
13373
14010
  const readOrigin = deps.readOrigin ?? readOriginRemote;
13374
14011
  const listDirs = deps.listDirs ?? listProjectDirs;
13375
14012
  const addDir = deps.addDir ?? ((path3) => addProjectDir(path3));
13376
- const mkdir2 = deps.mkdir ?? ((path3) => void mkdirSync10(path3, { recursive: true }));
14013
+ const mkdir3 = deps.mkdir ?? ((path3) => void mkdirSync10(path3, { recursive: true }));
13377
14014
  const p = parsePayload(payload);
13378
14015
  if (!p) {
13379
14016
  return { status: "failed", result: { error: "The job was missing the project repository. Try again from the project page." } };
@@ -13410,7 +14047,7 @@ async function invokeConnectRepo(payload, deps = {}) {
13410
14047
  result: { path: entry2.path, remote, outcome: "adopted", message: `Found an existing copy of ${name} at ${entry2.path} and set it up.` }
13411
14048
  };
13412
14049
  }
13413
- mkdir2(dirname6(target));
14050
+ mkdir3(dirname6(target));
13414
14051
  const errors = [];
13415
14052
  let cloned = false;
13416
14053
  for (const url of cloneUrls(remote)) {
@@ -13468,13 +14105,16 @@ var POLL_WAIT_MS = 0;
13468
14105
  var IDLE_POLL_INTERVAL_MS = 15e3;
13469
14106
  var ACTIVE_POLL_INTERVAL_MS = 2e3;
13470
14107
  var ACTIVE_WINDOW_MS = 6e4;
14108
+ var CONVERSATION_LIVE_POLL_MS = 750;
14109
+ var CONVERSATION_LIVE_WINDOW_MS = 2 * 6e4;
13471
14110
  var CONVERSATION_POLL_INTERVAL_MS = 3e3;
13472
14111
  var CONVERSATION_WINDOW_MS = 10 * 6e4;
13473
14112
  function idleDelay(now, lastJobAt, lastConversationAt = 0) {
14113
+ const sinceReply = lastConversationAt > 0 ? now - lastConversationAt : Infinity;
14114
+ if (sinceReply < CONVERSATION_LIVE_WINDOW_MS) return CONVERSATION_LIVE_POLL_MS;
13474
14115
  const warm = lastJobAt > 0 && now - lastJobAt < ACTIVE_WINDOW_MS;
13475
14116
  if (warm) return ACTIVE_POLL_INTERVAL_MS;
13476
- const talking = lastConversationAt > 0 && now - lastConversationAt < CONVERSATION_WINDOW_MS;
13477
- return talking ? CONVERSATION_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
14117
+ return sinceReply < CONVERSATION_WINDOW_MS ? CONVERSATION_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
13478
14118
  }
13479
14119
  var DEFAULT_MAX_PARALLEL_JOBS = 3;
13480
14120
  var MAX_JOBS_ENV = "COMPBOX_MAX_JOBS";
@@ -13686,6 +14326,16 @@ function parseStartExecutionPayload(payload) {
13686
14326
  ...useAiKey && { useAiKey }
13687
14327
  };
13688
14328
  }
14329
+ if (p.kind === "follow_up" && typeof p.epicId === "string" && p.epicId.length > 0 && typeof p.parentJobId === "string" && p.parentJobId.length > 0) {
14330
+ return {
14331
+ kind: "follow_up",
14332
+ epicId: p.epicId,
14333
+ parentJobId: p.parentJobId,
14334
+ ...typeof p.epicRequestId === "string" && p.epicRequestId.length > 0 && { epicRequestId: p.epicRequestId },
14335
+ ...projectRemote && { projectRemote },
14336
+ ...useAiKey && { useAiKey }
14337
+ };
14338
+ }
13689
14339
  return null;
13690
14340
  }
13691
14341
  async function handleStartExecution(ctx, job) {
@@ -13694,7 +14344,7 @@ async function handleStartExecution(ctx, job) {
13694
14344
  await completeWithFailure(
13695
14345
  ctx,
13696
14346
  job,
13697
- 'The start_execution job payload was missing or malformed (expected {kind:"plan",epicRequestId}, {kind:"orchestrate",epicId} or {kind:"refine",epicId,notes?}).'
14347
+ 'The start_execution job payload was missing or malformed (expected {kind:"plan",epicRequestId}, {kind:"orchestrate",epicId}, {kind:"refine",epicId,notes?} or {kind:"follow_up",epicId,parentJobId}).'
13698
14348
  );
13699
14349
  return;
13700
14350
  }
@@ -13789,6 +14439,15 @@ async function handleStartExecution(ctx, job) {
13789
14439
  );
13790
14440
  return;
13791
14441
  }
14442
+ let followUp;
14443
+ if (payload.kind === "follow_up") {
14444
+ followUp = job.turns.find((t) => t.role === "user" && t.content.trim() !== "")?.content;
14445
+ if (!followUp) {
14446
+ await completeWithFailure(ctx, job, "This follow-up has no message to act on. Send the message again.");
14447
+ return;
14448
+ }
14449
+ }
14450
+ const orch = payload.kind === "orchestrate" ? payload : void 0;
13792
14451
  const userApiToken = ctx.userApiToken;
13793
14452
  if (!userApiToken) {
13794
14453
  await completeWithFailure(
@@ -13809,7 +14468,7 @@ async function handleStartExecution(ctx, job) {
13809
14468
  const resume = parseReplyResume(job);
13810
14469
  console.log(
13811
14470
  chalk9.gray(
13812
- resume ? " Resuming the orchestrator with the owner's reply (start_execution / orchestrate)..." : " Running the orchestrator headless (start_execution / orchestrate)..."
14471
+ resume ? " Resuming the orchestrator with the owner's reply (start_execution / orchestrate)..." : followUp ? " Running the orchestrator on the owner's follow-up (start_execution / follow_up)..." : " Running the orchestrator headless (start_execution / orchestrate)..."
13813
14472
  )
13814
14473
  );
13815
14474
  await runInvokerAndComplete(ctx, job, async () => {
@@ -13822,11 +14481,12 @@ async function handleStartExecution(ctx, job) {
13822
14481
  epicId: payload.epicId,
13823
14482
  projectDir: jobProjectDir,
13824
14483
  ...keyRun && { keyRun },
13825
- ...payload.fix && { fix: payload.fix },
13826
- ...payload.fastMode === true && { fastMode: true },
13827
- ...payload.ownerNote && { ownerNote: payload.ownerNote },
13828
- ...payload.deferredFeatures && { deferredFeatures: payload.deferredFeatures },
13829
- ...payload.freshBranch === true && { freshBranch: true },
14484
+ ...orch?.fix && { fix: orch.fix },
14485
+ ...orch?.fastMode === true && { fastMode: true },
14486
+ ...orch?.ownerNote && { ownerNote: orch.ownerNote },
14487
+ ...orch?.deferredFeatures && { deferredFeatures: orch.deferredFeatures },
14488
+ ...orch?.freshBranch === true && { freshBranch: true },
14489
+ ...followUp && { followUp },
13830
14490
  ...resume && { resume },
13831
14491
  // ENG-345: cloud facts for the preflight (absent on older servers).
13832
14492
  cloud: parseCloudFacts(job.cloud),
@@ -13847,7 +14507,7 @@ async function handleStartExecution(ctx, job) {
13847
14507
  })
13848
14508
  }
13849
14509
  );
13850
- return payload.fix ? outcome : applyMergePolicy(mergePolicy, outcome, merge);
14510
+ return orch?.fix ? outcome : applyMergePolicy(mergePolicy, outcome, merge);
13851
14511
  });
13852
14512
  }
13853
14513
  var ACTIVE_RUN_DIRS = /* @__PURE__ */ new Set();