@mycompbox/compbox-cli 1.21.14 → 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
@@ -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) {
@@ -6404,10 +6416,11 @@ async function runConversationStep(input, deps) {
6404
6416
  let createdHere = false;
6405
6417
  let qualityRounds = 0;
6406
6418
  let repairs = 0;
6419
+ let kind = "chat";
6407
6420
  for (; ; ) {
6408
6421
  let reply;
6409
6422
  try {
6410
- reply = await deps.reply(system, messages);
6423
+ reply = await deps.reply(system, messages, kind);
6411
6424
  } catch (error) {
6412
6425
  if (savedNow)
6413
6426
  return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created), ...savedNow };
@@ -6420,12 +6433,22 @@ Send another message (for example "try again") when you're ready and I'll pick u
6420
6433
  };
6421
6434
  }
6422
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
+ }
6423
6445
  if (draft) {
6424
6446
  if (lockReason) {
6425
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.";
6426
6448
  messages.push({ role: "assistant", content: reply }, { role: "user", content: `${why} Reply to me in plain text instead.` });
6427
6449
  if (++repairs > JSON_REPAIRS)
6428
6450
  return { kind: "error", text: lockedRequestMessage(lockReason) };
6451
+ kind = "repair";
6429
6452
  continue;
6430
6453
  }
6431
6454
  let saved;
@@ -6450,22 +6473,14 @@ Reply "try again" and I'll retry.` };
6450
6473
 
6451
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.`
6452
6475
  });
6476
+ kind = "save";
6453
6477
  continue;
6454
6478
  }
6455
- if (looksLikeCompletionAttempt(reply)) {
6456
- if (++repairs > JSON_REPAIRS) {
6457
- 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.` };
6458
- }
6459
- messages.push({ role: "assistant", content: reply }, { role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
6460
- continue;
6461
- }
6462
- const text = reply.trim();
6463
- if (savedNow) {
6464
- return { kind: "saved", text: savedMessage(savedNow.saved, savedNow.created, text || void 0), ...savedNow };
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.` };
6465
6481
  }
6466
- if (!text)
6467
- return { kind: "error", text: "I didn't get a reply that time. Send another message and I'll try again." };
6468
- return { kind: "message", text };
6482
+ messages.push({ role: "assistant", content: reply }, { role: "user", content: COMPLETION_REPAIR_INSTRUCTION });
6483
+ kind = "repair";
6469
6484
  }
6470
6485
  }
6471
6486
  function savedContextFromRecord(record, access) {
@@ -7308,7 +7323,7 @@ var cached;
7308
7323
  function resolveCliVersion() {
7309
7324
  if (cached !== void 0) return cached;
7310
7325
  if (true) {
7311
- cached = "1.21.14";
7326
+ cached = "1.21.15";
7312
7327
  return cached;
7313
7328
  }
7314
7329
  const require2 = createRequire(import.meta.url);
@@ -7624,13 +7639,16 @@ var MailboxClient = class {
7624
7639
  }
7625
7640
  return { cancelJobIds: parseCancelJobIds(res.data), ownerNotes: parseOwnerNotes(res.data) };
7626
7641
  }
7627
- /** Posts an agent turn (a question/status update) to a job's interview log. */
7628
- 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) {
7629
7647
  let res;
7630
7648
  try {
7631
7649
  res = await this.http.post(
7632
7650
  `/api/v1/jobs/${jobId}/turns`,
7633
- { content },
7651
+ metrics ? { content, metrics } : { content },
7634
7652
  { headers: { Authorization: `Bearer ${machineToken}` } }
7635
7653
  );
7636
7654
  } catch (error) {
@@ -7642,6 +7660,15 @@ var MailboxClient = class {
7642
7660
  const data = res.data;
7643
7661
  return data.data;
7644
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
+ }
7645
7672
  /**
7646
7673
  * Marks a claimed job done or failed, with an optional structured result.
7647
7674
  * `waiting` (ENG-333) parks a usage-limited job to resume later: `resumeAt`
@@ -9764,6 +9791,108 @@ function startProgressWatcher(options) {
9764
9791
  };
9765
9792
  }
9766
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
+
9767
9896
  // src/utils/usage-limit.ts
9768
9897
  var TAIL_CHARS = 4096;
9769
9898
  var CLI_LIMIT_PATTERNS = [
@@ -11561,6 +11690,25 @@ function createWrapUp(deps) {
11561
11690
 
11562
11691
  // src/utils/agent-invoker.ts
11563
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
+ }
11564
11712
  var CLAUDE_CLI_TURN_TIMEOUT_MS = 4 * 60 * 1e3;
11565
11713
  function anthropicClientOptions(apiKey, routing) {
11566
11714
  return routing.mode === "proxy" ? { apiKey, baseURL: routing.anthropicBaseUrl } : { apiKey };
@@ -11620,7 +11768,9 @@ function selectAttachments(attachments, warn = defaultWarn) {
11620
11768
  continue;
11621
11769
  }
11622
11770
  if (selected.length >= MAX_ATTACHMENTS_PER_TURN) {
11623
- warn(`Skipping attachment ${att.id}: more than ${String(MAX_ATTACHMENTS_PER_TURN)} on one message.`);
11771
+ warn(
11772
+ `Skipping attachment ${att.id}: more than ${String(MAX_ATTACHMENTS_PER_TURN)} on one message.`
11773
+ );
11624
11774
  continue;
11625
11775
  }
11626
11776
  const size = typeof att.sizeBytes === "number" && att.sizeBytes > 0 ? att.sizeBytes : 0;
@@ -11710,7 +11860,10 @@ async function materializeAttachments(dir, attachments, fetchImpl = fetch, warn
11710
11860
  if (fetched.length > 0) await mkdir2(dir, { recursive: true });
11711
11861
  for (const f of fetched) {
11712
11862
  const mimeType = baseMime(f.attachment.mimeType);
11713
- const path3 = join16(dir, `attachment-${String(files.length + 1)}.${EXTENSION_BY_MIME[mimeType] ?? "bin"}`);
11863
+ const path3 = join16(
11864
+ dir,
11865
+ `attachment-${String(files.length + 1)}.${EXTENSION_BY_MIME[mimeType] ?? "bin"}`
11866
+ );
11714
11867
  try {
11715
11868
  await writeFile2(path3, f.bytes);
11716
11869
  files.push({ path: path3, mimeType });
@@ -11795,85 +11948,146 @@ function claudeToolArgs(attachmentsDir) {
11795
11948
  `Read(/${attachmentsDir}/**)`
11796
11949
  ];
11797
11950
  }
11951
+ function rejectsPartialMessagesFlag(stderr) {
11952
+ return stderr.includes("--include-partial-messages") && /unknown|unrecognized|invalid|unexpected|not supported/i.test(stderr);
11953
+ }
11798
11954
  function runClaudeCliTurn(prompt, opts) {
11799
11955
  return new Promise((resolve4, reject) => {
11800
11956
  const model = opts.model === void 0 ? ANTHROPIC_MODEL : opts.model;
11801
- const args = [
11802
- "-p",
11803
- prompt,
11804
- ...model ? ["--model", model] : [],
11805
- "--output-format",
11806
- "json",
11807
- ...claudeToolArgs(opts.attachmentsDir),
11808
- "--permission-mode",
11809
- "dontAsk",
11810
- "--safe-mode",
11811
- "--system-prompt",
11812
- opts.systemPrompt
11813
- ];
11814
- if (opts.resumeSessionId) {
11815
- args.push("--resume", opts.resumeSessionId);
11816
- }
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
+ };
11817
11978
  const command = resolveClaudeBinary() ?? "claude";
11818
11979
  const pxpipeEnv = claudeSpawnEnv(process.env, opts.routing);
11819
- const child = spawn7(command, args, {
11820
- cwd: claudeCliSessionCwd(),
11821
- stdio: ["ignore", "pipe", "pipe"],
11822
- env: { ...pxpipeEnv, PATH: claudeChildEnvPath(pxpipeEnv.PATH) }
11823
- });
11824
- let stdout2 = "";
11825
- let stderr = "";
11826
- let settled = false;
11827
- const timer = setTimeout(() => {
11828
- if (settled) return;
11829
- settled = true;
11830
- child.kill("SIGKILL");
11831
- reject(new Error(`claude CLI timed out after ${String(CLAUDE_CLI_TURN_TIMEOUT_MS / 1e3)}s`));
11832
- }, CLAUDE_CLI_TURN_TIMEOUT_MS);
11833
- child.stdout.on("data", (chunk) => {
11834
- stdout2 += chunk.toString("utf-8");
11835
- });
11836
- child.stderr.on("data", (chunk) => {
11837
- stderr += chunk.toString("utf-8");
11838
- });
11839
- child.on("error", (error) => {
11840
- if (settled) return;
11841
- settled = true;
11842
- clearTimeout(timer);
11843
- if (error.code === "ENOENT") {
11844
- reject(new Error(claudeNotFoundMessage()));
11845
- return;
11846
- }
11847
- reject(error);
11848
- });
11849
- child.on("close", (code) => {
11850
- if (settled) return;
11851
- settled = true;
11852
- clearTimeout(timer);
11853
- if (code !== 0) {
11854
- reject(new Error(stderr.trim() || `claude CLI exited with code ${String(code ?? "null")}`));
11855
- return;
11856
- }
11857
- let parsed;
11858
- try {
11859
- parsed = JSON.parse(stdout2);
11860
- } catch {
11861
- reject(new Error(`claude CLI returned non-JSON output: ${stdout2.slice(0, 500)}`));
11862
- return;
11863
- }
11864
- const shaped = parsed;
11865
- if (shaped.is_error) {
11866
- reject(new Error(shaped.result ?? "claude CLI reported an error"));
11867
- return;
11868
- }
11869
- 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");
11870
12004
  reject(
11871
- 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`)
11872
12006
  );
11873
- return;
11874
- }
11875
- resolve4({ text: shaped.result, sessionId: shaped.session_id });
11876
- });
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);
11877
12091
  });
11878
12092
  }
11879
12093
  async function loadSavedRequest(apiBaseUrl, userApiToken, epicRequestId, discussed) {
@@ -11896,6 +12110,30 @@ function needsDefaultModel(error) {
11896
12110
  message
11897
12111
  );
11898
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
+ }
11899
12137
  function savedRequestIdOf(job) {
11900
12138
  const result = job.result;
11901
12139
  if (typeof result?.epicRequestId === "string") return result.epicRequestId;
@@ -11917,6 +12155,7 @@ Send another message (for example "try again") and I'll pick up where we left of
11917
12155
  }
11918
12156
  }
11919
12157
  async function takeConversationStep(job, ctx) {
12158
+ const timer = startTurnTimer();
11920
12159
  const routing = await resolveRouting();
11921
12160
  const requestId = savedRequestIdOf(job);
11922
12161
  const discussed = requestId !== null && parseSeedPayload(job.payload)?.targetEpicRequestId === requestId;
@@ -11931,14 +12170,35 @@ async function takeConversationStep(job, ctx) {
11931
12170
  routing,
11932
12171
  saved,
11933
12172
  anthropic,
11934
- attachmentsDir
12173
+ attachmentsDir,
12174
+ timer
11935
12175
  });
11936
12176
  } finally {
11937
12177
  if (attachmentsDir) await rm(attachmentsDir, { recursive: true, force: true });
11938
12178
  }
11939
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
+ }
11940
12198
  async function converseWithAttachments(job, ctx, step) {
11941
12199
  const { routing, saved, anthropic, attachmentsDir } = step;
12200
+ const timer = step.timer ?? startTurnTimer();
12201
+ let replyModel = null;
11942
12202
  let usedFiles = false;
11943
12203
  const turns = [];
11944
12204
  for (const [index, t] of job.turns.entries()) {
@@ -11958,41 +12218,75 @@ async function converseWithAttachments(job, ctx, step) {
11958
12218
  }
11959
12219
  }
11960
12220
  const readDir = usedFiles ? attachmentsDir : void 0;
11961
- let cliModel = ANTHROPIC_MODEL;
12221
+ let useDefaultModel = false;
12222
+ const chosenChatModel = chosenChatModelOf(job.payload);
11962
12223
  const outcome = await runConversationStep(
11963
12224
  { turns, saved },
11964
12225
  {
11965
- reply: async (system, messages) => {
12226
+ reply: async (system, messages, kind) => {
12227
+ const model = modelForTurn(kind, chosenChatModel);
11966
12228
  if (anthropic) {
11967
12229
  const response = await anthropic.messages.create({
11968
- model: ANTHROPIC_MODEL,
12230
+ model,
11969
12231
  max_tokens: 4096,
11970
12232
  system,
11971
12233
  messages
11972
12234
  });
11973
12235
  const text = response.content.find((b) => b.type === "text");
11974
- 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;
11975
12240
  }
11976
- const prompt = renderConversationPrompt(messages);
11977
- try {
11978
- return (await runClaudeCliTurn(prompt, {
11979
- systemPrompt: system,
11980
- resumeSessionId: void 0,
11981
- routing,
11982
- model: cliModel,
11983
- attachmentsDir: readDir
11984
- })).text;
11985
- } catch (error) {
11986
- if (cliModel === null || !needsDefaultModel(error)) throw error;
11987
- cliModel = null;
11988
- return (await runClaudeCliTurn(prompt, {
11989
- systemPrompt: system,
11990
- resumeSessionId: void 0,
11991
- routing,
11992
- model: null,
11993
- attachmentsDir: readDir
11994
- })).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
+ }
12278
+ }
12279
+ if (!turn) {
12280
+ conversationSessions.delete(job.id);
12281
+ turn = await runFresh();
11995
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;
11996
12290
  },
11997
12291
  save: async (existingId, draft) => {
11998
12292
  const submitted = await submitAndScore(ctx, existingId, draft);
@@ -12003,7 +12297,7 @@ async function converseWithAttachments(job, ctx, step) {
12003
12297
  if (outcome.kind === "saved") {
12004
12298
  await ctx.mailboxClient.markRequestSaved(ctx.machineToken, job.id, outcome.saved.id);
12005
12299
  }
12006
- await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text);
12300
+ await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text, timer.finish(replyModel));
12007
12301
  return { status: "yield" };
12008
12302
  }
12009
12303
  var PLANNER_RUN_TIMEOUT_MS = 30 * 60 * 1e3;
@@ -12765,7 +13059,8 @@ function parseReplyAttachments(raw) {
12765
13059
  for (const item of raw) {
12766
13060
  if (typeof item !== "object" || item === null) continue;
12767
13061
  const a = item;
12768
- if (typeof a.id !== "string" || typeof a.mimeType !== "string" || typeof a.signedUrl !== "string") continue;
13062
+ if (typeof a.id !== "string" || typeof a.mimeType !== "string" || typeof a.signedUrl !== "string")
13063
+ continue;
12769
13064
  if (a.signedUrl.trim() === "") continue;
12770
13065
  out.push({
12771
13066
  id: a.id,
@@ -12898,7 +13193,9 @@ function mergePullRequestsRequest(prs) {
12898
13193
  return {
12899
13194
  question: `${count} your review and merge before the build can continue.`,
12900
13195
  why: "The rest of the build builds on this work, so continuing now would redo it or conflict with it.",
12901
- 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
+ ),
12902
13199
  afterAnswer: `The build continues by itself once they're merged. You can also press "All merged \u2014 continue".`,
12903
13200
  kind: "merge_prs",
12904
13201
  prNumbers: prs.map((pr) => pr.number)
@@ -13078,7 +13375,9 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13078
13375
  const replyAttachments = resume?.attachments ?? [];
13079
13376
  if (replyAttachments.length > 0) {
13080
13377
  try {
13081
- replyAttachmentsDir = await realpath(await mkdtemp(join16(tmpdir2(), "compbox-reply-attachments-")));
13378
+ replyAttachmentsDir = await realpath(
13379
+ await mkdtemp(join16(tmpdir2(), "compbox-reply-attachments-"))
13380
+ );
13082
13381
  const { files, failed } = await materializeAttachments(
13083
13382
  replyAttachmentsDir,
13084
13383
  replyAttachments,
@@ -13097,12 +13396,19 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13097
13396
  replyResumePrompt(ctx.epicId, resume.reply, attachmentsNote),
13098
13397
  workspace?.baseBranch,
13099
13398
  ctx.fastMode
13100
- ) : buildOrchestratorArgs(ctx.epicId, sessionId, resume?.reply, workspace?.baseBranch, ctx.fastMode, {
13101
- ...ctx.ownerNote && { ownerNote: ctx.ownerNote },
13102
- ...ctx.deferredFeatures && { deferred: ctx.deferredFeatures },
13103
- ...ctx.followUp && { followUp: ctx.followUp },
13104
- ...attachmentsNote && { replyAttachmentsNote: attachmentsNote }
13105
- });
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
+ );
13106
13412
  const args = ctx.keyRun ? keyRunArgs(runArgs) : runArgs;
13107
13413
  const routedEnv = claudeSpawnEnv(process.env, routing);
13108
13414
  const baseEnv = {
@@ -13131,11 +13437,12 @@ async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
13131
13437
  } catch {
13132
13438
  }
13133
13439
  try {
13134
- if (!resumeSessionId) await ctx.mailboxClient.postTurn(
13135
- ctx.machineToken,
13136
- ctx.jobId,
13137
- (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(" ")}` : "")
13138
- );
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
+ );
13139
13446
  } catch {
13140
13447
  }
13141
13448
  const stopped = { reason: null };
@@ -13378,7 +13685,10 @@ ${stderr}`;
13378
13685
  let stalls = 0;
13379
13686
  while (sessionId && unfinished(progress) && continues < maxContinues && !ctx.signal?.aborted) {
13380
13687
  if (progress.waitingPullRequests && progress.waitingPullRequests.length > 0) {
13381
- outcome = needsInputRunResult(ctx.epicId, mergePullRequestsRequest(progress.waitingPullRequests));
13688
+ outcome = needsInputRunResult(
13689
+ ctx.epicId,
13690
+ mergePullRequestsRequest(progress.waitingPullRequests)
13691
+ );
13382
13692
  break;
13383
13693
  }
13384
13694
  if (deadline - Date.now() <= 6e4) {
@@ -13434,7 +13744,9 @@ ${stderr}`;
13434
13744
  outcome.result = {
13435
13745
  ...outcome.result,
13436
13746
  fastMode: { requested: true, used: fastModeUsed },
13437
- ...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
+ } : {}
13438
13750
  };
13439
13751
  }
13440
13752
  const keepRunCopy = needsInput !== null && !ctx.keyRun && !ctx.fix && sessionId !== void 0;
@@ -13513,7 +13825,8 @@ ${stderr}`;
13513
13825
  }
13514
13826
  }
13515
13827
  if (workspace) deps.activeRunDirs?.delete(workspace.dir);
13516
- if (replyAttachmentsDir) await rm(replyAttachmentsDir, { recursive: true, force: true }).catch(() => void 0);
13828
+ if (replyAttachmentsDir)
13829
+ await rm(replyAttachmentsDir, { recursive: true, force: true }).catch(() => void 0);
13517
13830
  const timings = buildJobTimings({
13518
13831
  install: workspace?.install,
13519
13832
  runs: runDurations,
@@ -13792,13 +14105,16 @@ var POLL_WAIT_MS = 0;
13792
14105
  var IDLE_POLL_INTERVAL_MS = 15e3;
13793
14106
  var ACTIVE_POLL_INTERVAL_MS = 2e3;
13794
14107
  var ACTIVE_WINDOW_MS = 6e4;
14108
+ var CONVERSATION_LIVE_POLL_MS = 750;
14109
+ var CONVERSATION_LIVE_WINDOW_MS = 2 * 6e4;
13795
14110
  var CONVERSATION_POLL_INTERVAL_MS = 3e3;
13796
14111
  var CONVERSATION_WINDOW_MS = 10 * 6e4;
13797
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;
13798
14115
  const warm = lastJobAt > 0 && now - lastJobAt < ACTIVE_WINDOW_MS;
13799
14116
  if (warm) return ACTIVE_POLL_INTERVAL_MS;
13800
- const talking = lastConversationAt > 0 && now - lastConversationAt < CONVERSATION_WINDOW_MS;
13801
- return talking ? CONVERSATION_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
14117
+ return sinceReply < CONVERSATION_WINDOW_MS ? CONVERSATION_POLL_INTERVAL_MS : IDLE_POLL_INTERVAL_MS;
13802
14118
  }
13803
14119
  var DEFAULT_MAX_PARALLEL_JOBS = 3;
13804
14120
  var MAX_JOBS_ENV = "COMPBOX_MAX_JOBS";