@sideboard-ai/core 0.1.135 → 0.1.139

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/{agents-RTQFF7PY.js → agents-665S7Z3R.js} +5 -5
  2. package/dist/{agents-O3AJMI2Y.js → agents-OC3XM7UE.js} +5 -5
  3. package/dist/{chunk-KBBXNS2V.js → chunk-23KCPND2.js} +49 -6
  4. package/dist/{chunk-2ESCEK2Q.js → chunk-5XH5M6RA.js} +244 -5
  5. package/dist/{chunk-57GIFU3X.js → chunk-7SYFWPOZ.js} +5 -5
  6. package/dist/{chunk-N62K3KXX.js → chunk-CDJISVKN.js} +79 -6
  7. package/dist/{chunk-QAV3HGVS.js → chunk-DJJ3DTT4.js} +1 -1
  8. package/dist/{chunk-HQQNLDVC.js → chunk-DKXZCIB2.js} +1 -1
  9. package/dist/{chunk-XUEI4GCF.js → chunk-E2RE7P2S.js} +286 -5
  10. package/dist/{chunk-J5IBSVB3.js → chunk-EUXOHTUK.js} +42 -25
  11. package/dist/{chunk-RDULVW3E.js → chunk-HLIHBGVO.js} +2 -2
  12. package/dist/{chunk-K7EX47QG.js → chunk-RTX3AY42.js} +5 -5
  13. package/dist/{chunk-LOKXPQ4U.js → chunk-SSBM4GZX.js} +2 -2
  14. package/dist/{chunk-PM3C2J6K.js → chunk-TUGKX5BD.js} +42 -25
  15. package/dist/{chunk-Z5LYMW7M.js → chunk-YZQEJOAU.js} +189 -248
  16. package/dist/{chunk-XIKEUCNC.js → chunk-ZCLHAOFR.js} +211 -299
  17. package/dist/{coordinator-prompt-FYMWE33S.js → coordinator-prompt-43O6EPA2.js} +3 -3
  18. package/dist/{coordinator-prompt-Y737IIFR.js → coordinator-prompt-4TXU6Q3R.js} +3 -3
  19. package/dist/{global-workspace-6KH6BSKL.js → global-workspace-VIU57E3Y.js} +4 -4
  20. package/dist/{global-workspace-ZFKNLBZA.js → global-workspace-ZDYKHQ4O.js} +4 -4
  21. package/dist/index.cjs +1019 -670
  22. package/dist/index.d.cts +41 -3
  23. package/dist/index.d.ts +41 -3
  24. package/dist/index.js +83 -24
  25. package/dist/mcp/run-stdio.cjs +831 -544
  26. package/dist/mcp/run-stdio.js +55 -16
  27. package/dist/{orchestrator-3YDPPZHZ.js → orchestrator-WEFXUHFX.js} +7 -7
  28. package/dist/{orchestrator-2BRAPJ47.js → orchestrator-ZCMYSDTC.js} +7 -7
  29. package/dist/{thread-store-FADXSMEJ.js → thread-store-57ZLHR3A.js} +1 -1
  30. package/dist/{thread-store-CRLQJ2HM.js → thread-store-WGASXXXR.js} +1 -1
  31. package/dist/{workspaces-3RRF3LVF.js → workspaces-4HYGNH4B.js} +5 -5
  32. package/dist/{workspaces-AYI5DHK4.js → workspaces-ALCTB65T.js} +5 -5
  33. package/dist/{worktree-MX7XBX6Z.js → worktree-GXD2NGOZ.js} +2 -2
  34. package/dist/{worktree-BC6XDMQK.js → worktree-NSNZODAM.js} +2 -2
  35. package/package.json +1 -1
@@ -31,13 +31,13 @@ import {
31
31
  summarizeTurnStderr,
32
32
  toolDescription,
33
33
  turnFailChatText
34
- } from "./chunk-KBBXNS2V.js";
34
+ } from "./chunk-23KCPND2.js";
35
35
  import {
36
36
  addWorkspace,
37
37
  ensureWorkspace,
38
38
  removeWorkspace,
39
39
  syncWorkspacesFromThreads
40
- } from "./chunk-RDULVW3E.js";
40
+ } from "./chunk-HLIHBGVO.js";
41
41
  import {
42
42
  extractPresentedPlan,
43
43
  readPlanFile,
@@ -48,6 +48,7 @@ import {
48
48
  } from "./chunk-KLBOWJ74.js";
49
49
  import {
50
50
  assertOrchestratorCapableAgent,
51
+ attachmentsFromWorktreePaths,
51
52
  coerceOrchestratorAgent,
52
53
  createGlobalChat,
53
54
  healOrchestrationSoccerTitles,
@@ -57,15 +58,18 @@ import {
57
58
  isOrchestratorCapableAgent,
58
59
  isOrchestratorThread,
59
60
  isSlackCoordinatorThread,
60
- orchestratorSessionPoisonedByBuiltins
61
- } from "./chunk-2ESCEK2Q.js";
61
+ orchestratorSessionPoisonedByBuiltins,
62
+ persistPendingFileAttachments,
63
+ stageAbsolutePathsAsAttachments,
64
+ stageBuffersAsAttachments
65
+ } from "./chunk-5XH5M6RA.js";
62
66
  import {
63
67
  SLACK_REPLY_FORMATTING,
64
68
  coordinatorSystemPrompt,
65
69
  coordinatorTurnReminder,
66
70
  enrichWorkspacesWithGithub,
67
71
  ensureGlobalCoordinatorCwd
68
- } from "./chunk-K7EX47QG.js";
72
+ } from "./chunk-RTX3AY42.js";
69
73
  import {
70
74
  addPrStackLayer,
71
75
  allocateTeamName,
@@ -110,11 +114,10 @@ import {
110
114
  withRepoGitLock,
111
115
  worktreeDisplayLabelForGroup,
112
116
  worktreeNameFromPath
113
- } from "./chunk-QAV3HGVS.js";
117
+ } from "./chunk-DJJ3DTT4.js";
114
118
  import {
115
119
  ATTACHMENTS_DIR,
116
- LEGACY_ATTACHMENTS_DIR,
117
- attachmentsGitignoreBody
120
+ LEGACY_ATTACHMENTS_DIR
118
121
  } from "./chunk-B3SJXYIJ.js";
119
122
  import {
120
123
  appendMessage,
@@ -127,7 +130,7 @@ import {
127
130
  updateThread,
128
131
  withThreadLock,
129
132
  writeThread
130
- } from "./chunk-J5IBSVB3.js";
133
+ } from "./chunk-EUXOHTUK.js";
131
134
  import {
132
135
  clearStaleIndexLocks,
133
136
  enrichPathWithNpmGlobalBin,
@@ -384,7 +387,7 @@ async function continueSourceThread(threadId, prompt) {
384
387
  await continueOnReply(threadId, prompt);
385
388
  return;
386
389
  }
387
- const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-2BRAPJ47.js");
390
+ const { getOrchestrator: getOrchestrator2 } = await import("./orchestrator-ZCMYSDTC.js");
388
391
  await getOrchestrator2().send(threadId, prompt);
389
392
  } catch {
390
393
  }
@@ -644,7 +647,7 @@ async function pollSlackOutboundWatches(opts) {
644
647
  }
645
648
 
646
649
  // src/orchestrator/orchestrator.ts
647
- import { existsSync as existsSync16 } from "fs";
650
+ import { existsSync as existsSync15 } from "fs";
648
651
 
649
652
  // src/agents/spawn.ts
650
653
  import { createInterface } from "readline";
@@ -725,9 +728,9 @@ async function spawnAgentTurn(thread, input, onEvent) {
725
728
  `Cannot spawn ${thread.agent}: thread ${thread.id} has no worktreePath`
726
729
  );
727
730
  }
728
- const { isGlobalThread: isGlobalThread2 } = await import("./global-workspace-6KH6BSKL.js");
731
+ const { isGlobalThread: isGlobalThread2 } = await import("./global-workspace-VIU57E3Y.js");
729
732
  if (isGlobalThread2(thread)) {
730
- const { ensureGlobalCoordinatorCwd: ensureGlobalCoordinatorCwd2 } = await import("./coordinator-prompt-Y737IIFR.js");
733
+ const { ensureGlobalCoordinatorCwd: ensureGlobalCoordinatorCwd2 } = await import("./coordinator-prompt-4TXU6Q3R.js");
731
734
  ensureGlobalCoordinatorCwd2(
732
735
  isOrchestratorThread(thread) ? { orchestratorThreadId: thread.id } : void 0
733
736
  );
@@ -974,6 +977,49 @@ import { dirname, join as join4 } from "path";
974
977
  // src/threads/chat-tabs.ts
975
978
  import { randomUUID } from "crypto";
976
979
 
980
+ // src/composer/context-estimate.ts
981
+ var CHARS_PER_CONTEXT_TOKEN = 4;
982
+ function estimateMessageChars(message) {
983
+ let n = message.text.length + 16;
984
+ for (const part of message.parts ?? []) {
985
+ n += estimatePartChars(part);
986
+ }
987
+ return n;
988
+ }
989
+ function estimatePartChars(part) {
990
+ switch (part.type) {
991
+ case "text":
992
+ case "thinking":
993
+ return part.text.length;
994
+ case "tool": {
995
+ const input = part.input ? JSON.stringify(part.input) : "";
996
+ return part.name.length + (part.description?.length ?? 0) + (part.detail?.length ?? 0) + (part.result?.length ?? 0) + input.length + 32;
997
+ }
998
+ default:
999
+ return 0;
1000
+ }
1001
+ }
1002
+ function estimateThreadChars(messages) {
1003
+ return messages.reduce((sum, m) => sum + estimateMessageChars(m), 0);
1004
+ }
1005
+ function estimateOccupancyTokens(messages) {
1006
+ return Math.ceil(estimateThreadChars(messages) / CHARS_PER_CONTEXT_TOKEN);
1007
+ }
1008
+ function applyForwardOccupancy(messages) {
1009
+ const tokens = estimateOccupancyTokens(messages);
1010
+ if (tokens <= 0) return messages;
1011
+ for (let i = messages.length - 1; i >= 0; i--) {
1012
+ const m = messages[i];
1013
+ if (m?.role !== "agent" || !m.usage) continue;
1014
+ const current = contextTokens(m.usage);
1015
+ if (tokens >= current) return messages;
1016
+ const next = messages.slice();
1017
+ next[i] = { ...m, usage: { ...m.usage, lastRequestTokens: tokens } };
1018
+ return next;
1019
+ }
1020
+ return messages;
1021
+ }
1022
+
977
1023
  // src/composer/summarize.ts
978
1024
  var MAX_TRANSCRIPT_CHARS = 12e4;
979
1025
  var MAX_SUMMARY_CHARS = 6e3;
@@ -1082,29 +1128,6 @@ var CONTEXT_KEEP_RECENT_CHARS = 24e3;
1082
1128
  var CONTEXT_KEEP_RECENT_MESSAGES = 12;
1083
1129
  var CONTEXT_MIN_MESSAGES = 10;
1084
1130
  var SESSION_RESET_OCCUPANCY_TOKENS = 75e4;
1085
- function estimateMessageChars(message) {
1086
- let n = message.text.length + 16;
1087
- for (const part of message.parts ?? []) {
1088
- n += estimatePartChars(part);
1089
- }
1090
- return n;
1091
- }
1092
- function estimatePartChars(part) {
1093
- switch (part.type) {
1094
- case "text":
1095
- case "thinking":
1096
- return part.text.length;
1097
- case "tool": {
1098
- const input = part.input ? JSON.stringify(part.input) : "";
1099
- return part.name.length + (part.description?.length ?? 0) + (part.detail?.length ?? 0) + (part.result?.length ?? 0) + input.length + 32;
1100
- }
1101
- default:
1102
- return 0;
1103
- }
1104
- }
1105
- function estimateThreadChars(messages) {
1106
- return messages.reduce((sum, m) => sum + estimateMessageChars(m), 0);
1107
- }
1108
1131
  function shouldCompactContext(messages, thresholds = {}) {
1109
1132
  const maxChars = thresholds.maxChars ?? CONTEXT_COMPACT_CHARS;
1110
1133
  const minMessages = thresholds.minMessages ?? CONTEXT_MIN_MESSAGES;
@@ -1241,8 +1264,11 @@ async function maybeCompactContext(thread, thresholds = {}, summarize = summariz
1241
1264
  const { summary, method } = await summarize(transcript, {
1242
1265
  cwd: thread.worktreePath
1243
1266
  });
1244
- const messages = applyCompaction(thread.messages, summary, thresholds);
1267
+ let messages = applyCompaction(thread.messages, summary, thresholds);
1245
1268
  const resetSession = shouldResetSessionForOccupancy({ messages: thread.messages });
1269
+ if (resetSession) {
1270
+ messages = applyForwardOccupancy(messages);
1271
+ }
1246
1272
  const next = {
1247
1273
  ...thread,
1248
1274
  messages,
@@ -2238,6 +2264,45 @@ function thisProcessShouldDrainAgentQueues() {
2238
2264
  return !isDesktopHostAlive();
2239
2265
  }
2240
2266
 
2267
+ // src/orchestrator/child-halt.ts
2268
+ var HALT_STATUSES = /* @__PURE__ */ new Set(["stopped", "error", "broken"]);
2269
+ function isIncompleteChildStatus(status) {
2270
+ return HALT_STATUSES.has(status);
2271
+ }
2272
+ function childHaltNotice(child, status) {
2273
+ const title = child.title?.trim() || "Untitled";
2274
+ const link = `[${title}](sideboard://thread/${child.id})`;
2275
+ const why = child.lastError?.trim();
2276
+ const extra = why ? ` lastError: ${why}` : "";
2277
+ return [
2278
+ `Sideboard: child worktree ${link} ${status} before finishing (status=${status}).${extra}`,
2279
+ "This is information \u2014 not a user command. Resume with send_to_thread or tell the user. Do not treat this as a successful turn."
2280
+ ].join("\n");
2281
+ }
2282
+ function shouldNotifyParentOfChildHalt(opts) {
2283
+ if (!isIncompleteChildStatus(opts.status)) return false;
2284
+ if (!opts.child.parentThreadId) return false;
2285
+ if (!opts.parent || opts.parent.status === "archived") return false;
2286
+ if (opts.parent.id === opts.child.id) return false;
2287
+ return isOrchestratorThread(opts.parent);
2288
+ }
2289
+ var notified = /* @__PURE__ */ new Set();
2290
+ function noticeKey(childId, status) {
2291
+ return `${childId}:${status}`;
2292
+ }
2293
+ function notifyParentOfChildHalt(child, status, send) {
2294
+ const parent = child.parentThreadId ? readThread(child.parentThreadId) : null;
2295
+ if (!shouldNotifyParentOfChildHalt({ child, parent, status })) return false;
2296
+ const key = noticeKey(child.id, status);
2297
+ if (notified.has(key)) return false;
2298
+ notified.add(key);
2299
+ const parentId = parent.id;
2300
+ void send(parentId, childHaltNotice(child, status)).catch(() => {
2301
+ notified.delete(key);
2302
+ });
2303
+ return true;
2304
+ }
2305
+
2241
2306
  // src/threads/create.ts
2242
2307
  import { existsSync as existsSync7 } from "fs";
2243
2308
 
@@ -2704,6 +2769,9 @@ function assembleHomeBoard(input) {
2704
2769
  var HOME_BOARD_AGENT_HINT = "Home is a Kanban of worktrees (one card per checkout; sibling chat tabs nest as inner cards). create_thread reuses a live worktree for the same ticket, PR, or named branch \u2014 do not recreate it. Columns are the path to merge: New (no PR) \u2192 Draft (draft PR) \u2192 Review (open PR) \u2192 Merged. Archive removes the card to Settings \u2192 History. Queued/running are activity on the card, not columns. Orchestration chats stay in the sidebar. Do not invent status.";
2705
2770
 
2706
2771
  // src/threads/create.ts
2772
+ function persistCreateAttachments(worktreePath, attachments) {
2773
+ return persistPendingFileAttachments(worktreePath, attachments ?? []);
2774
+ }
2707
2775
  async function createThread(input, _onSetupLine) {
2708
2776
  const repoPath = await resolveRepoRoot(input.repoPath);
2709
2777
  if (!existsSync7(repoPath)) {
@@ -2723,7 +2791,16 @@ async function createThread(input, _onSetupLine) {
2723
2791
  repoPath: canonicalizeRepoPath(t.repoPath)
2724
2792
  }))
2725
2793
  );
2726
- if (existing) return readThread(existing.id) ?? existing;
2794
+ if (existing) {
2795
+ const thread2 = readThread(existing.id) ?? existing;
2796
+ if (!input.attachments?.length) return thread2;
2797
+ return updateThread(thread2.id, {
2798
+ attachments: persistCreateAttachments(thread2.worktreePath, [
2799
+ ...thread2.attachments,
2800
+ ...input.attachments
2801
+ ])
2802
+ });
2803
+ }
2727
2804
  }
2728
2805
  const resolved = resolveNewThreadOptions({
2729
2806
  agent: input.agent,
@@ -2771,7 +2848,7 @@ async function createThread(input, _onSetupLine) {
2771
2848
  effort: resolved.effort,
2772
2849
  fast: resolved.fast,
2773
2850
  planMode: Boolean(input.planMode),
2774
- attachments: input.attachments ?? [],
2851
+ attachments: persistCreateAttachments(repoPath, input.attachments),
2775
2852
  sourceIsFork: false,
2776
2853
  parentThreadId: input.parentThreadId ?? null,
2777
2854
  status: "idle",
@@ -2850,7 +2927,7 @@ async function createThread(input, _onSetupLine) {
2850
2927
  effort: resolved.effort,
2851
2928
  fast: resolved.fast,
2852
2929
  planMode: Boolean(input.planMode),
2853
- attachments,
2930
+ attachments: persistCreateAttachments(worktreePath, attachments),
2854
2931
  sourceIsFork,
2855
2932
  parentThreadId: input.parentThreadId ?? null,
2856
2933
  status: "idle",
@@ -2862,7 +2939,7 @@ async function createThread(input, _onSetupLine) {
2862
2939
  return readThread(thread.id) ?? thread;
2863
2940
  }
2864
2941
  async function listLinearIssues(agent, repoPath) {
2865
- const { getAdapter: getAdapter2 } = await import("./agents-O3AJMI2Y.js");
2942
+ const { getAdapter: getAdapter2 } = await import("./agents-OC3XM7UE.js");
2866
2943
  await requireAgent(agent, { requireLinear: true });
2867
2944
  const adapter = getAdapter2(agent);
2868
2945
  if (!adapter.listLinearIssues) {
@@ -3259,7 +3336,7 @@ async function adoptThread(input) {
3259
3336
  messages: input.messages ?? []
3260
3337
  });
3261
3338
  writeThread(thread);
3262
- const { ensureWorkspace: ensureWorkspace2 } = await import("./workspaces-3RRF3LVF.js");
3339
+ const { ensureWorkspace: ensureWorkspace2 } = await import("./workspaces-4HYGNH4B.js");
3263
3340
  await ensureWorkspace2(repoPath);
3264
3341
  return thread;
3265
3342
  }
@@ -4809,193 +4886,9 @@ function expandComposerPrompt(worktreePath, prompt, opts) {
4809
4886
  };
4810
4887
  }
4811
4888
 
4812
- // src/composer/stage-files.ts
4813
- import { copyFileSync as copyFileSync3, existsSync as existsSync13, mkdirSync as mkdirSync4, readFileSync as readFileSync10, statSync as statSync4, writeFileSync as writeFileSync5 } from "fs";
4814
- import { basename as basename3, extname, join as join12 } from "path";
4815
- import { randomUUID as randomUUID4 } from "crypto";
4816
- var IMAGE_EXTENSIONS2 = /* @__PURE__ */ new Set([
4817
- "png",
4818
- "jpg",
4819
- "jpeg",
4820
- "gif",
4821
- "webp",
4822
- "svg",
4823
- "bmp",
4824
- "ico"
4825
- ]);
4826
- var IMAGE_MIME_BY_EXT = {
4827
- png: "image/png",
4828
- jpg: "image/jpeg",
4829
- jpeg: "image/jpeg",
4830
- gif: "image/gif",
4831
- webp: "image/webp",
4832
- svg: "image/svg+xml",
4833
- bmp: "image/bmp",
4834
- ico: "image/x-icon"
4835
- };
4836
- var MAX_INLINE_BYTES = 4e5;
4837
- var MAX_PREVIEW_BYTES = 5e6;
4838
- function fileExtension(filePath) {
4839
- const base = basename3(filePath).toLowerCase();
4840
- return base.includes(".") ? base.split(".").pop() || "" : "";
4841
- }
4842
- function isImageFilePath(filePath) {
4843
- return IMAGE_EXTENSIONS2.has(fileExtension(filePath));
4844
- }
4845
- function imageMimeType(filePath) {
4846
- return IMAGE_MIME_BY_EXT[fileExtension(filePath)] || "image/png";
4847
- }
4848
- function ensureAttachmentsDir(worktreePath) {
4849
- const dir = join12(worktreePath, ATTACHMENTS_DIR);
4850
- mkdirSync4(dir, { recursive: true });
4851
- const gi = join12(dir, ".gitignore");
4852
- if (!existsSync13(gi)) {
4853
- writeFileSync5(gi, attachmentsGitignoreBody(), "utf8");
4854
- }
4855
- return dir;
4856
- }
4857
- function uniqueAttachmentName(dir, originalName) {
4858
- const safe = originalName.replace(/[/\\]/g, "_") || "file";
4859
- if (!existsSync13(join12(dir, safe))) return safe;
4860
- const ext = extname(safe);
4861
- const stem = ext ? safe.slice(0, -ext.length) : safe;
4862
- for (let i = 1; i < 1e4; i++) {
4863
- const candidate = `${stem}-${i}${ext}`;
4864
- if (!existsSync13(join12(dir, candidate))) return candidate;
4865
- }
4866
- return `${stem}-${randomUUID4()}${ext}`;
4867
- }
4868
- function previewDataUrlFromBuf(filePath, buf) {
4869
- if (!isImageFilePath(filePath)) return void 0;
4870
- if (buf.length > MAX_PREVIEW_BYTES) return void 0;
4871
- return `data:${imageMimeType(filePath)};base64,${buf.toString("base64")}`;
4872
- }
4873
- function attachmentFromBuffer(name, buf, opts) {
4874
- const previewDataUrl = previewDataUrlFromBuf(name, buf);
4875
- if (isImageFilePath(name)) {
4876
- const pathHint = opts.path ? `\`${opts.path}\`` : opts.sourceLabel || name;
4877
- return {
4878
- id: randomUUID4(),
4879
- name,
4880
- kind: "file",
4881
- path: opts.path,
4882
- previewDataUrl,
4883
- content: [
4884
- `Image attached: ${pathHint}`,
4885
- opts.path ? `Use the Read tool on \`${opts.path}\` to view this image.` : "The image is shown in the composer; copy it into the worktree if you need to inspect pixels."
4886
- ].join("\n")
4887
- };
4888
- }
4889
- if (buf.length > MAX_INLINE_BYTES) {
4890
- return {
4891
- id: randomUUID4(),
4892
- name,
4893
- kind: "file",
4894
- path: opts.path,
4895
- content: opts.path ? `(file too large to attach inline: \`${opts.path}\`, ${buf.length} bytes \u2014 use the Read tool)` : `(file too large to attach inline: ${opts.sourceLabel || name}, ${buf.length} bytes)`
4896
- };
4897
- }
4898
- if (buf.includes(0)) {
4899
- return {
4900
- id: randomUUID4(),
4901
- name,
4902
- kind: "file",
4903
- path: opts.path,
4904
- content: opts.path ? `(binary file at \`${opts.path}\` \u2014 use tools to inspect)` : `(binary file attached by path only: ${opts.sourceLabel || name})`
4905
- };
4906
- }
4907
- return {
4908
- id: randomUUID4(),
4909
- name,
4910
- kind: "file",
4911
- path: opts.path,
4912
- content: buf.toString("utf8")
4913
- };
4914
- }
4915
- function stageAbsolutePathsAsAttachments(worktreePath, absolutePaths) {
4916
- if (absolutePaths.length === 0) return [];
4917
- const dir = ensureAttachmentsDir(worktreePath);
4918
- const out = [];
4919
- for (const abs of absolutePaths) {
4920
- const originalName = basename3(abs);
4921
- try {
4922
- const st = statSync4(abs);
4923
- if (!st.isFile()) continue;
4924
- const name = uniqueAttachmentName(dir, originalName);
4925
- const destAbs = join12(dir, name);
4926
- copyFileSync3(abs, destAbs);
4927
- const rel = `${ATTACHMENTS_DIR}/${name}`;
4928
- const buf = readFileSync10(destAbs);
4929
- out.push(attachmentFromBuffer(name, buf, { path: rel, sourceLabel: abs }));
4930
- } catch (err) {
4931
- out.push({
4932
- id: randomUUID4(),
4933
- name: originalName,
4934
- kind: "file",
4935
- content: `(could not attach ${abs}: ${err instanceof Error ? err.message : String(err)})`
4936
- });
4937
- }
4938
- }
4939
- return out;
4940
- }
4941
- function stageBuffersAsAttachments(worktreePath, buffers2) {
4942
- if (buffers2.length === 0) return [];
4943
- const dir = ensureAttachmentsDir(worktreePath);
4944
- const out = [];
4945
- for (const item of buffers2) {
4946
- const originalName = (item.name || "file").replace(/[/\\]/g, "_") || "file";
4947
- try {
4948
- const buf = Buffer.from(item.dataBase64, "base64");
4949
- const name = uniqueAttachmentName(dir, originalName);
4950
- const destAbs = join12(dir, name);
4951
- writeFileSync5(destAbs, buf);
4952
- const rel = `${ATTACHMENTS_DIR}/${name}`;
4953
- out.push(attachmentFromBuffer(name, buf, { path: rel }));
4954
- } catch (err) {
4955
- out.push({
4956
- id: randomUUID4(),
4957
- name: originalName,
4958
- kind: "file",
4959
- content: `(could not attach ${originalName}: ${err instanceof Error ? err.message : String(err)})`
4960
- });
4961
- }
4962
- }
4963
- return out;
4964
- }
4965
- function attachmentsFromWorktreePaths(worktreePath, relativePaths) {
4966
- const out = [];
4967
- for (const rel of relativePaths) {
4968
- if (!rel || rel.includes("..") || rel.startsWith("/")) {
4969
- out.push({
4970
- id: randomUUID4(),
4971
- name: basename3(rel) || "file",
4972
- kind: "file",
4973
- content: `(invalid path: ${rel})`
4974
- });
4975
- continue;
4976
- }
4977
- const name = basename3(rel);
4978
- try {
4979
- const abs = join12(worktreePath, rel);
4980
- const st = statSync4(abs);
4981
- if (!st.isFile()) continue;
4982
- const buf = readFileSync10(abs);
4983
- out.push(attachmentFromBuffer(name, buf, { path: rel, sourceLabel: abs }));
4984
- } catch (err) {
4985
- out.push({
4986
- id: randomUUID4(),
4987
- name,
4988
- kind: "file",
4989
- content: `(could not read ${rel}: ${err instanceof Error ? err.message : String(err)})`
4990
- });
4991
- }
4992
- }
4993
- return out;
4994
- }
4995
-
4996
4889
  // src/agents/instructions.ts
4997
- import { existsSync as existsSync14, readFileSync as readFileSync11, statSync as statSync5 } from "fs";
4998
- import { join as join13 } from "path";
4890
+ import { existsSync as existsSync13, readFileSync as readFileSync10, statSync as statSync4 } from "fs";
4891
+ import { join as join12 } from "path";
4999
4892
  function normPath(p) {
5000
4893
  return p.replace(/\/+$/, "");
5001
4894
  }
@@ -5170,9 +5063,9 @@ async function syncThreadBranchFromGit(threadId) {
5170
5063
  }
5171
5064
 
5172
5065
  // src/store/schedules.ts
5173
- import { randomUUID as randomUUID5 } from "crypto";
5174
- import { existsSync as existsSync15, readFileSync as readFileSync12 } from "fs";
5175
- import { join as join14 } from "path";
5066
+ import { randomUUID as randomUUID4 } from "crypto";
5067
+ import { existsSync as existsSync14, readFileSync as readFileSync11 } from "fs";
5068
+ import { join as join13 } from "path";
5176
5069
  import { Cron } from "croner";
5177
5070
  var DURATION_RE = /^(\d+)(s|m|h|d)$/i;
5178
5071
  var UNIT_MS = {
@@ -5182,7 +5075,7 @@ var UNIT_MS = {
5182
5075
  d: 864e5
5183
5076
  };
5184
5077
  function schedulesPath() {
5185
- return join14(appDataDir(), "schedules.json");
5078
+ return join13(appDataDir(), "schedules.json");
5186
5079
  }
5187
5080
  function parseDurationMs(every) {
5188
5081
  const m = every.trim().match(DURATION_RE);
@@ -5282,9 +5175,9 @@ function normalizeTask(raw) {
5282
5175
  }
5283
5176
  function readAll() {
5284
5177
  const path = schedulesPath();
5285
- if (!existsSync15(path)) return [];
5178
+ if (!existsSync14(path)) return [];
5286
5179
  try {
5287
- const parsed = JSON.parse(readFileSync12(path, "utf8"));
5180
+ const parsed = JSON.parse(readFileSync11(path, "utf8"));
5288
5181
  if (!Array.isArray(parsed)) return [];
5289
5182
  return parsed.map((row) => {
5290
5183
  try {
@@ -5309,7 +5202,7 @@ function buildTask(input, now) {
5309
5202
  const ts = nowIso(now);
5310
5203
  const agent = input.agent ? coerceOrchestratorAgent(input.agent) : null;
5311
5204
  return {
5312
- id: randomUUID5(),
5205
+ id: randomUUID4(),
5313
5206
  name: input.name?.trim() || defaultScheduleName(prompt),
5314
5207
  prompt,
5315
5208
  enabled: input.enabled !== false,
@@ -5407,7 +5300,7 @@ function formatScheduledPrompt(name, prompt) {
5407
5300
  ${prompt}`;
5408
5301
  }
5409
5302
  async function defaultDeps() {
5410
- const { getOrchestrator: getOrchestrator2, startOrchestration: startOrchestration2 } = await import("./orchestrator-2BRAPJ47.js");
5303
+ const { getOrchestrator: getOrchestrator2, startOrchestration: startOrchestration2 } = await import("./orchestrator-ZCMYSDTC.js");
5411
5304
  const orch = getOrchestrator2();
5412
5305
  return {
5413
5306
  findThread: (id) => findThreadByRef(id),
@@ -5613,7 +5506,7 @@ var Orchestrator = class {
5613
5506
  }
5614
5507
  continue;
5615
5508
  }
5616
- if (!existsSync16(thread.worktreePath)) {
5509
+ if (!existsSync15(thread.worktreePath)) {
5617
5510
  setStatus(thread.id, "broken", "Worktree missing on disk");
5618
5511
  this.emit({ type: "status_changed", threadId: thread.id, status: "broken" });
5619
5512
  continue;
@@ -5650,6 +5543,9 @@ var Orchestrator = class {
5650
5543
  * MCP-created review threads don't stay `queued` after the MCP child exits.
5651
5544
  */
5652
5545
  adoptPersistedQueues() {
5546
+ if (thisProcessShouldDrainAgentQueues()) {
5547
+ this.healStaleRunningTurns();
5548
+ }
5653
5549
  for (const thread of listThreads()) {
5654
5550
  if (thread.status === "stopped" || thread.status === "archived") continue;
5655
5551
  const pid = thread.agentPid;
@@ -5670,6 +5566,32 @@ var Orchestrator = class {
5670
5566
  }
5671
5567
  }
5672
5568
  }
5569
+ /**
5570
+ * Mid-session: a worktree can sit at `running` after the agent process dies
5571
+ * (Cursor/CLI crash, OOM) while wait_for_turn still reports stillRunning.
5572
+ * Reclaim those and wake the parent orchestration chat.
5573
+ */
5574
+ healStaleRunningTurns() {
5575
+ for (const thread of listThreads()) {
5576
+ if (thread.status === "archived") continue;
5577
+ const handle = this.activeTurns.get(thread.id);
5578
+ if (handle) {
5579
+ const pid = handle.pid;
5580
+ if (typeof pid === "number" && pid > 0 && !isPidAlive(pid)) {
5581
+ handle.kill();
5582
+ }
5583
+ continue;
5584
+ }
5585
+ if (!this.shouldReclaimRunningThread(thread)) continue;
5586
+ setStatus(thread.id, "stopped", "Process died (agent exited)");
5587
+ this.emit({ type: "status_changed", threadId: thread.id, status: "stopped" });
5588
+ this.emit({ type: "turn_finished", threadId: thread.id, exitCode: 1 });
5589
+ const latest = readThread(thread.id);
5590
+ if (latest) {
5591
+ notifyParentOfChildHalt(latest, "stopped", (id, prompt) => this.send(id, prompt));
5592
+ }
5593
+ }
5594
+ }
5673
5595
  clearQuotaResumeTimer(threadId) {
5674
5596
  const timer = this.quotaResumeTimers.get(threadId);
5675
5597
  if (timer) clearTimeout(timer);
@@ -6387,6 +6309,12 @@ var Orchestrator = class {
6387
6309
  assistantText: chatText,
6388
6310
  partsCount: parts.length
6389
6311
  });
6312
+ if (!this.crashContinued.has(threadId)) {
6313
+ const failed = readThread(threadId);
6314
+ if (failed) {
6315
+ notifyParentOfChildHalt(failed, "error", (id, prompt2) => this.send(id, prompt2));
6316
+ }
6317
+ }
6390
6318
  }
6391
6319
  }
6392
6320
  } catch (err) {
@@ -6411,6 +6339,12 @@ var Orchestrator = class {
6411
6339
  assistantText: "",
6412
6340
  partsCount: 0
6413
6341
  });
6342
+ if (!this.crashContinued.has(threadId)) {
6343
+ const failed = readThread(threadId);
6344
+ if (failed) {
6345
+ notifyParentOfChildHalt(failed, "error", (id, prompt2) => this.send(id, prompt2));
6346
+ }
6347
+ }
6414
6348
  }
6415
6349
  } finally {
6416
6350
  this.startingTurns.delete(threadId);
@@ -6466,6 +6400,9 @@ var Orchestrator = class {
6466
6400
  const stopped = writeLiveStatus(thread.id, "stopped") ?? readThread(thread.id) ?? thread;
6467
6401
  if (stopped.status === "stopped") {
6468
6402
  this.emit({ type: "status_changed", threadId: thread.id, status: "stopped" });
6403
+ if (inFlight && opts?.notifyParent !== false) {
6404
+ notifyParentOfChildHalt(stopped, "stopped", (id, prompt) => this.send(id, prompt));
6405
+ }
6469
6406
  }
6470
6407
  return stopped;
6471
6408
  }
@@ -6710,21 +6647,25 @@ var Orchestrator = class {
6710
6647
  fn();
6711
6648
  };
6712
6649
  const off = this.on((event) => {
6713
- if (event.type === "turn_finished" && event.threadId === thread.id) {
6650
+ if (!("threadId" in event) || event.threadId !== thread.id) return;
6651
+ if (event.type === "turn_finished" || event.type === "error") {
6714
6652
  const latest = readThread(thread.id);
6715
6653
  if (!latest) {
6716
6654
  finish(() => reject(new Error(`Thread not found: ${thread.id}`)));
6717
6655
  return;
6718
6656
  }
6719
6657
  finish(() => resolve(latest));
6658
+ return;
6720
6659
  }
6721
- if (event.type === "error" && event.threadId === thread.id) {
6660
+ if (event.type === "status_changed") {
6722
6661
  const latest = readThread(thread.id);
6723
6662
  if (!latest) {
6724
6663
  finish(() => reject(new Error(`Thread not found: ${thread.id}`)));
6725
6664
  return;
6726
6665
  }
6727
- finish(() => resolve(latest));
6666
+ if (!["running", "queued"].includes(latest.status)) {
6667
+ finish(() => resolve(latest));
6668
+ }
6728
6669
  }
6729
6670
  });
6730
6671
  timer = setInterval(() => {
@@ -6759,7 +6700,7 @@ var Orchestrator = class {
6759
6700
  const thread = this.requireThread(threadRef);
6760
6701
  const lastAgent = [...thread.messages].reverse().find((m) => m.role === "agent");
6761
6702
  const lastError = thread.lastError ?? null;
6762
- const text = (lastAgent?.text ?? "").trim() || (thread.status === "error" ? lastError ?? "" : "");
6703
+ const text = (lastAgent?.text ?? "").trim() || (thread.status === "error" || thread.status === "stopped" || thread.status === "broken" ? lastError ?? "" : "");
6763
6704
  const stillRunning = thread.status === "running" || thread.status === "queued";
6764
6705
  const live = stillRunning ? readTurnLive(thread.id) : null;
6765
6706
  const queuedHint = thread.status === "queued" && !live?.summary ? "Queued \u2014 waiting for a concurrency slot" : null;
@@ -7218,7 +7159,7 @@ var Orchestrator = class {
7218
7159
  }
7219
7160
  async archiveUnlocked(threadRef) {
7220
7161
  const thread = this.requireThread(threadRef);
7221
- this.stop(thread.id);
7162
+ this.stop(thread.id, { notifyParent: false });
7222
7163
  this.releaseOrchestratorCaffeinate(thread);
7223
7164
  if (isGlobalThread(thread)) {
7224
7165
  const archived2 = setStatus(thread.id, "archived");
@@ -7246,7 +7187,7 @@ var Orchestrator = class {
7246
7187
  this.emit({ type: "status_changed", threadId: archived.id, status: "archived" });
7247
7188
  if (thread.repoPath && !isGlobalRepoPath(thread.repoPath)) {
7248
7189
  try {
7249
- const { ensureWorkspace: ensureWorkspace2 } = await import("./workspaces-3RRF3LVF.js");
7190
+ const { ensureWorkspace: ensureWorkspace2 } = await import("./workspaces-4HYGNH4B.js");
7250
7191
  await ensureWorkspace2(thread.repoPath);
7251
7192
  } catch {
7252
7193
  }
@@ -7259,7 +7200,7 @@ var Orchestrator = class {
7259
7200
  }
7260
7201
  async purgeUnlocked(threadRef, opts) {
7261
7202
  const thread = this.requireThread(threadRef);
7262
- this.stop(thread.id);
7203
+ this.stop(thread.id, { notifyParent: false });
7263
7204
  this.releaseOrchestratorCaffeinate(thread);
7264
7205
  if (isGlobalThread(thread)) {
7265
7206
  deleteThreadRecord(thread.id);
@@ -7294,13 +7235,13 @@ var Orchestrator = class {
7294
7235
  this.emit({ type: "status_changed", threadId: restored2.id, status: restored2.status });
7295
7236
  return restored2;
7296
7237
  }
7297
- if (!existsSync16(thread.worktreePath)) {
7238
+ if (!existsSync15(thread.worktreePath)) {
7298
7239
  if (isCowboyThread(thread) || isPrimaryCheckoutThread(thread)) {
7299
7240
  throw new Error(
7300
7241
  `Cowboy checkout missing: ${thread.worktreePath}. Re-add the project folder, then restore.`
7301
7242
  );
7302
7243
  }
7303
- const { createThreadWorktree: createThreadWorktree2 } = await import("./worktree-BC6XDMQK.js");
7244
+ const { createThreadWorktree: createThreadWorktree2 } = await import("./worktree-NSNZODAM.js");
7304
7245
  const slug = thread.worktreePath.split("/").pop();
7305
7246
  const dest = thread.worktreePath;
7306
7247
  await withRepoGitLock(thread.repoPath, async () => {
@@ -7408,7 +7349,7 @@ async function startOrchestration(opts) {
7408
7349
  sourceRef: "default",
7409
7350
  ...createOpts
7410
7351
  }).catch(async () => {
7411
- const { resolveDefaultBranch: resolveDefaultBranch2, resolveRepoRoot: resolveRepoRoot2 } = await import("./worktree-BC6XDMQK.js");
7352
+ const { resolveDefaultBranch: resolveDefaultBranch2, resolveRepoRoot: resolveRepoRoot2 } = await import("./worktree-NSNZODAM.js");
7412
7353
  const repo = await resolveRepoRoot2(repoPath);
7413
7354
  const def = await resolveDefaultBranch2(repo);
7414
7355
  return orch.createThread({
@@ -7418,7 +7359,7 @@ async function startOrchestration(opts) {
7418
7359
  repoPath: repo
7419
7360
  });
7420
7361
  });
7421
- const { updateThread: upd } = await import("./thread-store-FADXSMEJ.js");
7362
+ const { updateThread: upd } = await import("./thread-store-57ZLHR3A.js");
7422
7363
  const updated = upd(thread.id, {
7423
7364
  sourceType: "orchestration",
7424
7365
  sourceRef: goal