@wrongstack/core 0.313.0 → 0.313.1

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 (182) hide show
  1. package/dist/chronicle/index.js +84 -6391
  2. package/dist/chronicle/project-server.js +84 -4868
  3. package/dist/chunk-2BUUIMQB.js +225 -0
  4. package/dist/chunk-2FK4WTFF.js +207 -0
  5. package/dist/chunk-2FQL4PDC.js +292 -0
  6. package/dist/chunk-2KKODIQU.js +2256 -0
  7. package/dist/chunk-2YU4WVBW.js +134 -0
  8. package/dist/chunk-3E244UDA.js +356 -0
  9. package/dist/chunk-3XPVB7BA.js +135 -0
  10. package/dist/chunk-4LJJYBAU.js +388 -0
  11. package/dist/chunk-4VWO3ZXL.js +342 -0
  12. package/dist/chunk-4XV6IR37.js +187 -0
  13. package/dist/chunk-4ZHTKJHM.js +183 -0
  14. package/dist/chunk-52RTVH4M.js +361 -0
  15. package/dist/chunk-57GEWK5X.js +26 -0
  16. package/dist/chunk-5DSMEVA4.js +931 -0
  17. package/dist/chunk-5RP3QTRL.js +1223 -0
  18. package/dist/chunk-5S437PRC.js +50 -0
  19. package/dist/chunk-5XDUGTKN.js +511 -0
  20. package/dist/chunk-62V2AFVG.js +422 -0
  21. package/dist/chunk-65RDIOR2.js +2470 -0
  22. package/dist/chunk-6AKOTGLM.js +597 -0
  23. package/dist/chunk-7ZHZE5EO.js +28 -0
  24. package/dist/chunk-A455ATZB.js +140 -0
  25. package/dist/chunk-AD7ZFZCS.js +46 -0
  26. package/dist/chunk-AI4LLQ2U.js +856 -0
  27. package/dist/chunk-ASX6AW36.js +789 -0
  28. package/dist/chunk-AT4V4XGI.js +3522 -0
  29. package/dist/chunk-AWNQ6ED6.js +311 -0
  30. package/dist/chunk-B4AMLZPB.js +9 -0
  31. package/dist/chunk-BAKVJLEV.js +417 -0
  32. package/dist/chunk-BJHVULHO.js +55 -0
  33. package/dist/chunk-CB2HFKTP.js +9 -0
  34. package/dist/chunk-CE4ZOCOI.js +1640 -0
  35. package/dist/chunk-CQQL4ZOQ.js +151 -0
  36. package/dist/chunk-DEIQMBD2.js +65 -0
  37. package/dist/chunk-E6I5RXVK.js +58 -0
  38. package/dist/chunk-EFEHDQGY.js +1589 -0
  39. package/dist/chunk-EODDVJBM.js +82 -0
  40. package/dist/chunk-EPC3GZD4.js +308 -0
  41. package/dist/chunk-FAYRX2AD.js +13 -0
  42. package/dist/chunk-FFSX2QDQ.js +362 -0
  43. package/dist/chunk-FHAMQS7Q.js +5856 -0
  44. package/dist/chunk-FIV4IJL7.js +2263 -0
  45. package/dist/chunk-FNXVT7HF.js +52 -0
  46. package/dist/chunk-FSWCWSTS.js +395 -0
  47. package/dist/chunk-FW5LDDMJ.js +16464 -0
  48. package/dist/chunk-FXQLIX3K.js +211 -0
  49. package/dist/chunk-G5AAKEEZ.js +228 -0
  50. package/dist/chunk-G5S3S5ZN.js +38 -0
  51. package/dist/chunk-GAZEWQEZ.js +231 -0
  52. package/dist/chunk-GFJOMSHG.js +125 -0
  53. package/dist/chunk-GFXZTHNI.js +158 -0
  54. package/dist/chunk-GM54GJBU.js +960 -0
  55. package/dist/chunk-GPQ3NJPR.js +900 -0
  56. package/dist/chunk-GTCU6DZ3.js +1 -0
  57. package/dist/chunk-H5E77KUJ.js +15 -0
  58. package/dist/chunk-H72H4XDU.js +1023 -0
  59. package/dist/chunk-HA4ZYA6T.js +178 -0
  60. package/dist/chunk-I45KAW2N.js +5020 -0
  61. package/dist/chunk-IQ35HMQL.js +1396 -0
  62. package/dist/chunk-IYFBFX34.js +86 -0
  63. package/dist/chunk-JJPMWPB6.js +109 -0
  64. package/dist/chunk-JTHKOYWU.js +663 -0
  65. package/dist/chunk-JVGPR3TS.js +365 -0
  66. package/dist/chunk-JVKB2TBL.js +48 -0
  67. package/dist/chunk-JX7VBZDK.js +31 -0
  68. package/dist/chunk-K3G6JBUC.js +5232 -0
  69. package/dist/chunk-K4YUNKU7.js +589 -0
  70. package/dist/chunk-KBZGE6LN.js +710 -0
  71. package/dist/chunk-KDQJCT2J.js +45 -0
  72. package/dist/chunk-KI4L2DUL.js +560 -0
  73. package/dist/chunk-KJ2ZTQSL.js +47 -0
  74. package/dist/chunk-KSJ5UTP7.js +154 -0
  75. package/dist/chunk-LHOA5DWA.js +28 -0
  76. package/dist/chunk-LX5QWLBL.js +27 -0
  77. package/dist/chunk-LZDDLNCZ.js +279 -0
  78. package/dist/chunk-M2WF6AXG.js +115 -0
  79. package/dist/chunk-M7BS2K6U.js +1 -0
  80. package/dist/chunk-NDBIPFNY.js +102 -0
  81. package/dist/chunk-NEMIWEXC.js +1199 -0
  82. package/dist/chunk-NFAYHPRH.js +323 -0
  83. package/dist/chunk-O37BQ65S.js +21 -0
  84. package/dist/chunk-O74MJHXU.js +187 -0
  85. package/dist/chunk-OJZEX73F.js +112 -0
  86. package/dist/chunk-PAAWLLZX.js +74 -0
  87. package/dist/chunk-PFXFQQRT.js +339 -0
  88. package/dist/chunk-PFZO3C6H.js +14 -0
  89. package/dist/chunk-PHH7LD45.js +113 -0
  90. package/dist/chunk-QRTG4XTI.js +188 -0
  91. package/dist/chunk-QVOVMXJR.js +1351 -0
  92. package/dist/chunk-RCQYT2I4.js +757 -0
  93. package/dist/chunk-RD6DEE36.js +1178 -0
  94. package/dist/chunk-RJIZEJ42.js +30 -0
  95. package/dist/chunk-RPOA7IAE.js +150 -0
  96. package/dist/chunk-SN2DQRL6.js +1172 -0
  97. package/dist/chunk-SQJVFEBV.js +41 -0
  98. package/dist/chunk-SQP64RCS.js +5391 -0
  99. package/dist/chunk-SVT4RNTR.js +49 -0
  100. package/dist/chunk-SWUFN7XM.js +43 -0
  101. package/dist/chunk-SXMVYC5H.js +174 -0
  102. package/dist/chunk-SZ6AYUIZ.js +23 -0
  103. package/dist/chunk-T3KGZBU5.js +3171 -0
  104. package/dist/chunk-TBRL2RCC.js +9 -0
  105. package/dist/chunk-TRT2HRWZ.js +18 -0
  106. package/dist/chunk-TYW2GI5I.js +1077 -0
  107. package/dist/chunk-UIWONWVG.js +4959 -0
  108. package/dist/chunk-VB3H5WWB.js +151 -0
  109. package/dist/chunk-W4A6QA3D.js +258 -0
  110. package/dist/chunk-WBPVKEEE.js +227 -0
  111. package/dist/chunk-WEBMSQP2.js +123 -0
  112. package/dist/chunk-WOEZV3Q4.js +333 -0
  113. package/dist/chunk-WQQON3SV.js +473 -0
  114. package/dist/chunk-WQTOVMGV.js +119 -0
  115. package/dist/chunk-WZO23AWO.js +2779 -0
  116. package/dist/chunk-XBDP4QPW.js +7 -0
  117. package/dist/chunk-XEBHSJLT.js +103 -0
  118. package/dist/chunk-XQ2ECNK3.js +1 -0
  119. package/dist/chunk-XQ2XGIBF.js +2086 -0
  120. package/dist/chunk-Y2GE5TSI.js +355 -0
  121. package/dist/chunk-YBUJCZ57.js +351 -0
  122. package/dist/chunk-YNCVSFGF.js +149 -0
  123. package/dist/chunk-YUPMXOGP.js +282 -0
  124. package/dist/chunk-YY6APYUM.js +49 -0
  125. package/dist/chunk-Z2IJUO45.js +691 -0
  126. package/dist/chunk-ZEHUCJHY.js +129 -0
  127. package/dist/chunk-ZYU2YOJ6.js +1496 -0
  128. package/dist/chunk-ZZ4V3WIZ.js +163 -0
  129. package/dist/coordination/agents/index.js +145 -6260
  130. package/dist/coordination/index.js +365 -34324
  131. package/dist/coordination/mailbox-project-server.js +48 -3276
  132. package/dist/coordination/provider-status-tracker.d.ts +4 -0
  133. package/dist/core/agent.d.ts +14 -1
  134. package/dist/core/index.js +267 -12480
  135. package/dist/core/model-ref.js +5 -23
  136. package/dist/core/provider-runner.d.ts +36 -1
  137. package/dist/design/index.js +50 -1087
  138. package/dist/execution/index.d.ts +1 -1
  139. package/dist/execution/index.js +1599 -21888
  140. package/dist/execution/prompt-enhancer.js +16 -535
  141. package/dist/execution/retry-policy.d.ts +31 -1
  142. package/dist/extension/index.js +7 -311
  143. package/dist/goal/index.js +33 -3435
  144. package/dist/hooks/index.js +14 -1138
  145. package/dist/hq/index.js +112 -5139
  146. package/dist/hq/protocol.js +21 -668
  147. package/dist/index.js +1410 -92656
  148. package/dist/infrastructure/index.js +64 -4811
  149. package/dist/kernel/events/provider-events.d.ts +15 -0
  150. package/dist/kernel/index.js +14 -992
  151. package/dist/models/index.js +40 -1117
  152. package/dist/notifications/index.js +3 -108
  153. package/dist/observability/index.js +17 -279
  154. package/dist/plugin/index.js +584 -14835
  155. package/dist/prompts/index.js +14 -948
  156. package/dist/registry/index.js +9 -822
  157. package/dist/registry-R23UBE7H.js +14 -0
  158. package/dist/replay/index.js +6 -84
  159. package/dist/review-finding-store-DKAV3AS6.js +21 -0
  160. package/dist/review-report-store-OWY3EC3N.js +19 -0
  161. package/dist/security/index.js +114 -2202
  162. package/dist/session-catalog/index.js +36 -2103
  163. package/dist/session-catalog/project-server.js +42 -1435
  164. package/dist/skills/index.js +35 -1578
  165. package/dist/storage/index.js +182 -15600
  166. package/dist/tasking/index.js +10 -676
  167. package/dist/tools/index.js +52 -9590
  168. package/dist/types/config/autonomy.d.ts +5 -0
  169. package/dist/types/config/ui.d.ts +1 -1
  170. package/dist/types/errors.d.ts +18 -0
  171. package/dist/types/index.js +121 -1342
  172. package/dist/types/provider-runner.d.ts +8 -0
  173. package/dist/types/session-markers.js +8 -144
  174. package/dist/utils/error.js +3 -4
  175. package/dist/utils/expect-defined.js +3 -9
  176. package/dist/utils/heap-watchdog.js +6 -706
  177. package/dist/utils/index.js +269 -5685
  178. package/dist/utils/sage-output-block.js +5 -42
  179. package/dist/wiring/proxy-rewrite.d.ts +18 -0
  180. package/dist/wiring/proxy-rewrite.js +18 -121
  181. package/dist/worktree/index.js +6 -887
  182. package/package.json +4 -4
@@ -0,0 +1,154 @@
1
+ // src/types/session-markers.ts
2
+ var SESSION_MARKER_EVENT_TYPES = /* @__PURE__ */ new Set([
3
+ "mode_changed",
4
+ "compaction",
5
+ "checkpoint",
6
+ "skill_activated",
7
+ "skill_deactivated",
8
+ "agent_spawned",
9
+ "agent_stopped",
10
+ "agent_error",
11
+ "error",
12
+ "provider_retry",
13
+ "provider_error",
14
+ "message_truncated"
15
+ ]);
16
+ var CHAT_MARKER_SOURCES = new Set(
17
+ [...SESSION_MARKER_EVENT_TYPES].filter((type) => type !== "checkpoint")
18
+ );
19
+ function sessionEventToMarker(ev) {
20
+ switch (ev.type) {
21
+ case "compaction": {
22
+ const before = (ev.before / 1e3).toFixed(0);
23
+ const after = (ev.after / 1e3).toFixed(0);
24
+ const level = ev.level ? ` (${ev.level})` : "";
25
+ const reductions = ev.reductions && ev.reductions.length > 0 ? ` [${ev.reductions.map((r) => `${r.phase}: \u2212${r.saved}`).join(", ")}]` : "";
26
+ return {
27
+ ts: ev.ts,
28
+ source: ev.type,
29
+ level: "info",
30
+ text: `\u27F2 context compacted${level}: ${before}K \u2192 ${after}K tokens${reductions}`
31
+ };
32
+ }
33
+ case "error":
34
+ return {
35
+ ts: ev.ts,
36
+ source: ev.type,
37
+ level: "error",
38
+ text: ev.phase ? `[${ev.phase}] ${ev.message}` : ev.message
39
+ };
40
+ case "provider_retry": {
41
+ const secs = (ev.delayMs / 1e3).toFixed(ev.delayMs >= 1e3 ? 1 : 2);
42
+ return {
43
+ ts: ev.ts,
44
+ source: ev.type,
45
+ level: "warn",
46
+ text: ev.status ? `\u27F3 retry ${ev.attempt} (HTTP ${ev.status}) after ${secs}s \u2014 ${ev.description}` : `\u27F3 retry ${ev.attempt} after ${secs}s \u2014 ${ev.description}`
47
+ };
48
+ }
49
+ case "provider_error":
50
+ return {
51
+ ts: ev.ts,
52
+ source: ev.type,
53
+ level: "error",
54
+ text: ev.status ? `provider error (HTTP ${ev.status}, ${ev.retryable ? "retryable" : "fatal"}): ${ev.description}` : `provider error (${ev.retryable ? "retryable" : "fatal"}): ${ev.description}`
55
+ };
56
+ case "checkpoint":
57
+ return {
58
+ ts: ev.ts,
59
+ source: ev.type,
60
+ level: "info",
61
+ text: `\u2713 checkpoint #${ev.promptIndex}: "${ev.promptPreview.slice(0, 60)}"`
62
+ };
63
+ case "agent_spawned":
64
+ return {
65
+ ts: ev.ts,
66
+ source: ev.type,
67
+ level: "info",
68
+ text: `spawned as ${ev.role}`,
69
+ agentId: ev.agentId
70
+ };
71
+ case "agent_stopped":
72
+ return {
73
+ ts: ev.ts,
74
+ source: ev.type,
75
+ level: "info",
76
+ text: "stopped",
77
+ agentId: ev.agentId
78
+ };
79
+ case "agent_error":
80
+ return {
81
+ ts: ev.ts,
82
+ source: ev.type,
83
+ level: "error",
84
+ text: `error: ${ev.error.slice(0, 80)}`,
85
+ agentId: ev.agentId
86
+ };
87
+ case "mode_changed":
88
+ return {
89
+ ts: ev.ts,
90
+ source: ev.type,
91
+ level: "info",
92
+ text: `mode: ${ev.from} \u2192 ${ev.to}`
93
+ };
94
+ case "skill_activated":
95
+ return {
96
+ ts: ev.ts,
97
+ source: ev.type,
98
+ level: "info",
99
+ text: `skill activated: ${ev.skillName}`
100
+ };
101
+ case "skill_deactivated":
102
+ return {
103
+ ts: ev.ts,
104
+ source: ev.type,
105
+ level: "info",
106
+ text: `skill deactivated: ${ev.skillName}`
107
+ };
108
+ case "message_truncated":
109
+ return {
110
+ ts: ev.ts,
111
+ source: ev.type,
112
+ level: "warn",
113
+ text: ev.after < ev.before ? `message truncated: ${ev.before} \u2192 ${ev.after} tokens` : `message truncated at ${ev.after} tokens`
114
+ };
115
+ default:
116
+ return null;
117
+ }
118
+ }
119
+ function projectSessionMarkers(events, sources = SESSION_MARKER_EVENT_TYPES) {
120
+ const markers = [];
121
+ for (const ev of events) {
122
+ if (!sources.has(ev.type)) continue;
123
+ const marker = sessionEventToMarker(ev);
124
+ if (marker) markers.push(marker);
125
+ }
126
+ return markers;
127
+ }
128
+ var SYSTEM_INJECTION_PREFIXES = [
129
+ "[MAILBOX]",
130
+ "[MAILBOX BTW]",
131
+ "[BY THE WAY \u2014",
132
+ "[QUEUED MESSAGES \u2014",
133
+ "[FLEET PULSE]",
134
+ "[loop-detector]",
135
+ "[SESSION RESUME FILE VALIDATION]",
136
+ "[SESSION RESUME INTERRUPTED WORK]"
137
+ ];
138
+ function isSystemInjectedMessage(text) {
139
+ const trimmed = text.trimStart();
140
+ for (const prefix of SYSTEM_INJECTION_PREFIXES) {
141
+ if (trimmed.startsWith(prefix)) return true;
142
+ }
143
+ return false;
144
+ }
145
+
146
+ export {
147
+ SESSION_MARKER_EVENT_TYPES,
148
+ CHAT_MARKER_SOURCES,
149
+ sessionEventToMarker,
150
+ projectSessionMarkers,
151
+ SYSTEM_INJECTION_PREFIXES,
152
+ isSystemInjectedMessage
153
+ };
154
+ //# sourceMappingURL=chunk-KSJ5UTP7.js.map
@@ -0,0 +1,28 @@
1
+ // src/utils/win32-cmd.ts
2
+ var WIN32_CMD_META = /[&|<>"%\r\n\0]/;
3
+ function buildWin32CmdShimInvocation(command, args = []) {
4
+ assertSafeWin32CmdArgs([command, ...args]);
5
+ const line = ["call", quoteWin32CmdArg(command), ...args.map(quoteWin32CmdArg)].join(" ");
6
+ return {
7
+ command: process.env["COMSPEC"] ?? "cmd.exe",
8
+ args: ["/d", "/c", line],
9
+ windowsVerbatimArguments: true
10
+ };
11
+ }
12
+ function assertSafeWin32CmdArgs(args) {
13
+ for (const arg of args) {
14
+ if (typeof arg === "string" && WIN32_CMD_META.test(arg)) {
15
+ throw new Error(
16
+ 'win32 cmd shim spawn: argument contains a shell metacharacter (one of & | < > ", or a newline) that could enable command injection through the .cmd/.bat wrapper - refusing to run. Offending argument: ' + JSON.stringify(arg)
17
+ );
18
+ }
19
+ }
20
+ }
21
+ function quoteWin32CmdArg(arg) {
22
+ return `"${arg}"`;
23
+ }
24
+
25
+ export {
26
+ buildWin32CmdShimInvocation
27
+ };
28
+ //# sourceMappingURL=chunk-LHOA5DWA.js.map
@@ -0,0 +1,27 @@
1
+ // src/utils/sqlite-warning.ts
2
+ var SQLITE_EXPERIMENTAL_WARNING_RE = /sqlite is an experimental feature/i;
3
+ function isSqliteExperimentalWarning(warning, rest) {
4
+ const message = typeof warning === "string" ? warning : warning instanceof Error ? warning.message : "";
5
+ const typeOrOptions = rest[0];
6
+ const warningType = typeof warning === "string" ? typeof typeOrOptions === "string" ? typeOrOptions : typeof typeOrOptions === "object" && typeOrOptions !== null && "type" in typeOrOptions && typeof typeOrOptions.type === "string" ? typeOrOptions.type : "" : warning instanceof Error ? warning.name : "";
7
+ const warningCode = typeof warning === "string" ? typeof typeOrOptions === "object" && typeOrOptions !== null && "code" in typeOrOptions && typeof typeOrOptions.code === "string" ? typeOrOptions.code : typeof rest[1] === "string" ? rest[1] : "" : warning instanceof Error && "code" in warning && typeof warning.code === "string" ? warning.code : "";
8
+ return SQLITE_EXPERIMENTAL_WARNING_RE.test(message) && (warningType === "ExperimentalWarning" || warningCode === "ExperimentalWarning");
9
+ }
10
+ function withSqliteExperimentalWarningSuppressed(run) {
11
+ const originalEmitWarning = process.emitWarning;
12
+ const forwardWarning = originalEmitWarning.bind(process);
13
+ process.emitWarning = ((warning, ...rest) => {
14
+ if (isSqliteExperimentalWarning(warning, rest)) return;
15
+ forwardWarning(warning, ...rest);
16
+ });
17
+ try {
18
+ return run();
19
+ } finally {
20
+ process.emitWarning = originalEmitWarning;
21
+ }
22
+ }
23
+
24
+ export {
25
+ withSqliteExperimentalWarningSuppressed
26
+ };
27
+ //# sourceMappingURL=chunk-LX5QWLBL.js.map
@@ -0,0 +1,279 @@
1
+ import {
2
+ color
3
+ } from "./chunk-4VWO3ZXL.js";
4
+ import {
5
+ atomicWrite
6
+ } from "./chunk-7ZHZE5EO.js";
7
+ import {
8
+ resolveWstackPaths
9
+ } from "./chunk-YNCVSFGF.js";
10
+ import {
11
+ ERROR_CODES,
12
+ FsError
13
+ } from "./chunk-WOEZV3Q4.js";
14
+ import {
15
+ toErrorMessage
16
+ } from "./chunk-TBRL2RCC.js";
17
+
18
+ // src/storage/goal-store.ts
19
+ import * as fsp from "node:fs/promises";
20
+ var MAX_JOURNAL_ENTRIES = 500;
21
+ function goalFilePath(projectRoot) {
22
+ return resolveWstackPaths({ projectRoot }).projectGoal;
23
+ }
24
+ async function loadGoal(filePath, events, warn) {
25
+ const t0 = Date.now();
26
+ let raw;
27
+ try {
28
+ raw = await fsp.readFile(filePath, "utf8");
29
+ } catch (err) {
30
+ const code = err.code;
31
+ if (code === "ENOENT") {
32
+ events?.emit("storage.read", {
33
+ sessionId: "~boot~",
34
+ store: "goal",
35
+ filePath,
36
+ operation: "load",
37
+ outcome: "success",
38
+ durationMs: Date.now() - t0
39
+ });
40
+ return null;
41
+ }
42
+ events?.emit("storage.error", {
43
+ sessionId: "~boot~",
44
+ store: "goal",
45
+ filePath,
46
+ operation: "load",
47
+ error: toErrorMessage(err),
48
+ recoverable: false
49
+ });
50
+ throw err;
51
+ }
52
+ try {
53
+ const parsed = JSON.parse(raw);
54
+ if (parsed?.version !== 1 || typeof parsed.goal !== "string" || !Array.isArray(parsed.journal)) {
55
+ (warn ?? ((msg) => console.warn(JSON.stringify({ level: "warn", event: "goal_store.invalid_schema", path: filePath, message: msg, timestamp: (/* @__PURE__ */ new Date()).toISOString() }))))(
56
+ "invalid schema \u2014 consider deleting and re-creating"
57
+ );
58
+ events?.emit("storage.read", {
59
+ sessionId: "~boot~",
60
+ store: "goal",
61
+ filePath,
62
+ operation: "load",
63
+ outcome: "failure",
64
+ durationMs: Date.now() - t0,
65
+ error: "invalid_schema"
66
+ });
67
+ return null;
68
+ }
69
+ events?.emit("storage.read", {
70
+ sessionId: "~boot~",
71
+ store: "goal",
72
+ filePath,
73
+ operation: "load",
74
+ outcome: "success",
75
+ durationMs: Date.now() - t0
76
+ });
77
+ return parsed;
78
+ } catch {
79
+ (warn ?? ((msg) => console.warn(JSON.stringify({ level: "warn", event: "goal_store.parse_failed", path: filePath, message: msg, timestamp: (/* @__PURE__ */ new Date()).toISOString() }))))(
80
+ "JSON parse failed \u2014 consider deleting and re-creating"
81
+ );
82
+ events?.emit("storage.read", {
83
+ sessionId: "~boot~",
84
+ store: "goal",
85
+ filePath,
86
+ operation: "load",
87
+ outcome: "failure",
88
+ durationMs: Date.now() - t0,
89
+ error: "parse_failed"
90
+ });
91
+ return null;
92
+ }
93
+ }
94
+ async function saveGoal(filePath, goal, events) {
95
+ const t0 = Date.now();
96
+ try {
97
+ await atomicWrite(filePath, JSON.stringify(goal, null, 2), { mode: 384 });
98
+ events?.emit("storage.write", {
99
+ sessionId: "~boot~",
100
+ store: "goal",
101
+ filePath,
102
+ operation: "save",
103
+ outcome: "success",
104
+ durationMs: Date.now() - t0
105
+ });
106
+ } catch (err) {
107
+ events?.emit("storage.error", {
108
+ sessionId: "~boot~",
109
+ store: "goal",
110
+ filePath,
111
+ operation: "save",
112
+ error: toErrorMessage(err),
113
+ recoverable: false
114
+ });
115
+ throw new FsError({
116
+ message: toErrorMessage(err),
117
+ code: ERROR_CODES.FS_ATOMIC_WRITE_FAILED,
118
+ path: filePath,
119
+ cause: err
120
+ });
121
+ }
122
+ }
123
+ function emptyGoal(goal) {
124
+ const now = (/* @__PURE__ */ new Date()).toISOString();
125
+ return {
126
+ version: 1,
127
+ goal,
128
+ setAt: now,
129
+ lastActivityAt: now,
130
+ iterations: 0,
131
+ engineState: "idle",
132
+ goalState: "active",
133
+ todoAttempts: {},
134
+ journal: []
135
+ };
136
+ }
137
+ function setProgress(goal, progress, note) {
138
+ const clamped = Math.min(100, Math.max(0, progress));
139
+ return {
140
+ ...goal,
141
+ progress: clamped,
142
+ progressNote: note ?? clamped + "% complete"
143
+ };
144
+ }
145
+ function appendJournal(goal, entry) {
146
+ const iteration = goal.iterations + 1;
147
+ const at = (/* @__PURE__ */ new Date()).toISOString();
148
+ const full = { ...entry, iteration, at };
149
+ const journal = [...goal.journal, full];
150
+ const trimmed = journal.length > MAX_JOURNAL_ENTRIES ? journal.slice(journal.length - MAX_JOURNAL_ENTRIES) : journal;
151
+ return {
152
+ ...goal,
153
+ iterations: iteration,
154
+ lastActivityAt: at,
155
+ journal: trimmed
156
+ };
157
+ }
158
+ function summarizeUsage(goal) {
159
+ let totalCostUsd = 0;
160
+ let totalInputTokens = 0;
161
+ let totalOutputTokens = 0;
162
+ let iterationsWithUsage = 0;
163
+ for (const e of goal.journal) {
164
+ if (typeof e.costUsd === "number") totalCostUsd += e.costUsd;
165
+ if (e.tokens) {
166
+ totalInputTokens += e.tokens.input;
167
+ totalOutputTokens += e.tokens.output;
168
+ }
169
+ if (typeof e.costUsd === "number" || e.tokens) iterationsWithUsage++;
170
+ }
171
+ return { totalCostUsd, totalInputTokens, totalOutputTokens, iterationsWithUsage };
172
+ }
173
+ var DOLLAR = "$";
174
+ function formatGoal(goal, journalLimit = 10) {
175
+ const lines = [];
176
+ const displayGoal = goal.refinedGoal || goal.goal;
177
+ lines.push(color.bold("Goal") + ": " + displayGoal);
178
+ if (goal.refinedGoal && goal.refinedGoal !== goal.goal) {
179
+ const snippet = goal.goal.length > 60 ? goal.goal.slice(0, 60) + "\u2026" : goal.goal;
180
+ lines.push(color.dim(' (original: "' + snippet + '")'));
181
+ }
182
+ if (typeof goal.progress === "number") {
183
+ const pct = Math.min(100, Math.max(0, Math.round(goal.progress)));
184
+ const filled = Math.round(pct / 5);
185
+ const empty = 20 - filled;
186
+ const bar = color.green("\u2588".repeat(filled)) + color.dim("\u2591".repeat(empty));
187
+ lines.push("Progress: " + bar + " " + color.bold(pct + "%"));
188
+ if (goal.progressNote) {
189
+ lines.push(" " + color.dim(goal.progressNote));
190
+ }
191
+ if (goal.progressTrend) {
192
+ const trendIcon = goal.progressTrend === "accelerating" ? "\u{1F680}" : goal.progressTrend === "stalling" ? "\u26A0\uFE0F" : "\u27A1\uFE0F";
193
+ lines.push(" Trend: " + trendIcon + " " + goal.progressTrend);
194
+ }
195
+ }
196
+ if (goal.deliverables && goal.deliverables.length > 0) {
197
+ lines.push("");
198
+ lines.push(color.bold("Deliverables:"));
199
+ for (const d of goal.deliverables) {
200
+ const done = /^\[[x✓]\]|✅|\(done\)/i.test(d);
201
+ const marker = done ? color.green("\u2713") : color.dim("\u25CB");
202
+ lines.push(" " + marker + " " + d);
203
+ }
204
+ }
205
+ lines.push("");
206
+ lines.push("Set: " + goal.setAt);
207
+ lines.push("Last activity: " + goal.lastActivityAt);
208
+ lines.push("Iterations: " + goal.iterations);
209
+ const stateLabel = goal.goalState ?? "active";
210
+ lines.push("State: " + stateLabel + (goal.iterations > 0 ? " (iteration #" + goal.iterations + ")" : ""));
211
+ lines.push("Engine: " + goal.engineState);
212
+ const usage = summarizeUsage(goal);
213
+ if (usage.iterationsWithUsage > 0) {
214
+ const spent = "Spent: " + DOLLAR + usage.totalCostUsd.toFixed(4) + " (in " + usage.totalInputTokens + " / out " + usage.totalOutputTokens + " tokens across " + usage.iterationsWithUsage + " iterations)";
215
+ lines.push(spent);
216
+ }
217
+ if (goal.journal.length > 0) {
218
+ lines.push("");
219
+ lines.push("Recent journal (last " + Math.min(journalLimit, goal.journal.length) + "):");
220
+ const tail = goal.journal.slice(-journalLimit);
221
+ for (const e of tail) {
222
+ const mark = e.status === "success" ? "\u2713" : e.status === "failure" ? "\u2717" : e.status === "aborted" ? "\u2298" : "\xB7";
223
+ const note = e.note ? " \u2014 " + e.note : "";
224
+ const cost = typeof e.costUsd === "number" ? " (" + DOLLAR + e.costUsd.toFixed(4) + ")" : "";
225
+ lines.push(" #" + e.iteration + " " + mark + " [" + e.source + "] " + e.task + cost + note);
226
+ }
227
+ }
228
+ return lines.join("\n");
229
+ }
230
+ function parseProgressFromText(text) {
231
+ const re = /\[progress:\s*(\d{1,3})%\]\s*(?:[—-]\s*(.+))?/i;
232
+ const m = text.match(re);
233
+ if (!m) return null;
234
+ const progress = Math.min(100, Math.max(0, Number.parseInt(m[1] ?? "0", 10)));
235
+ const note = m[2]?.trim() || void 0;
236
+ return note === void 0 ? { progress } : { progress, note };
237
+ }
238
+ function recordProgress(goal, progress, note) {
239
+ const clamped = Math.min(100, Math.max(0, progress));
240
+ const history = [...goal.progressHistory ?? [], { at: (/* @__PURE__ */ new Date()).toISOString(), progress: clamped, note }];
241
+ const trimmed = history.length > 200 ? history.slice(-200) : history;
242
+ return {
243
+ ...goal,
244
+ progress: clamped,
245
+ progressNote: note ?? `${clamped}% complete`,
246
+ progressHistory: trimmed,
247
+ progressTrend: computeTrend(trimmed)
248
+ };
249
+ }
250
+ var MAX_PROGRESS_HISTORY = 200;
251
+ function computeTrend(history) {
252
+ if (history.length < 3) return void 0;
253
+ const recent = history.slice(-5);
254
+ const deltas = [];
255
+ for (let i = 1; i < recent.length; i++) {
256
+ deltas.push((recent[i]?.progress ?? 0) - (recent[i - 1]?.progress ?? 0));
257
+ }
258
+ if (deltas.length < 2) return void 0;
259
+ const avgDelta = deltas.reduce((a, b) => a + b, 0) / deltas.length;
260
+ if (avgDelta > 2) return "accelerating";
261
+ if (avgDelta < -1) return "stalling";
262
+ return "steady";
263
+ }
264
+
265
+ export {
266
+ MAX_JOURNAL_ENTRIES,
267
+ goalFilePath,
268
+ loadGoal,
269
+ saveGoal,
270
+ emptyGoal,
271
+ setProgress,
272
+ appendJournal,
273
+ summarizeUsage,
274
+ formatGoal,
275
+ parseProgressFromText,
276
+ recordProgress,
277
+ MAX_PROGRESS_HISTORY
278
+ };
279
+ //# sourceMappingURL=chunk-LZDDLNCZ.js.map
@@ -0,0 +1,115 @@
1
+ import {
2
+ expectDefined
3
+ } from "./chunk-PFZO3C6H.js";
4
+
5
+ // src/utils/message-invariants.ts
6
+ function repairToolUseAdjacency(messages) {
7
+ const removedToolUses = [];
8
+ const removedToolResults = [];
9
+ let removedMessages = 0;
10
+ let changed = false;
11
+ const out = [];
12
+ for (let i = 0; i < messages.length; i++) {
13
+ const original = expectDefined(messages[i]);
14
+ let msg = original;
15
+ if (hasToolUse(msg)) {
16
+ const nextIds = toolResultIds(messages[i + 1]);
17
+ const filtered = mapContent(msg, (blocks) => {
18
+ const next = [];
19
+ for (const block of blocks) {
20
+ if (block.type === "tool_use" && !nextIds.has(block.id)) {
21
+ removedToolUses.push(block.id);
22
+ changed = true;
23
+ continue;
24
+ }
25
+ next.push(block);
26
+ }
27
+ return next;
28
+ });
29
+ msg = filtered ?? msg;
30
+ }
31
+ if (hasToolResult(msg)) {
32
+ const allowed = toolUseIds(out[out.length - 1]);
33
+ const filtered = mapContent(msg, (blocks) => {
34
+ const next = [];
35
+ for (const block of blocks) {
36
+ if (block.type === "tool_result" && !allowed.has(block.tool_use_id)) {
37
+ removedToolResults.push(block.tool_use_id);
38
+ changed = true;
39
+ continue;
40
+ }
41
+ next.push(block);
42
+ }
43
+ return next;
44
+ });
45
+ msg = filtered ?? msg;
46
+ }
47
+ if (isEmptyMessage(msg)) {
48
+ removedMessages++;
49
+ changed = true;
50
+ continue;
51
+ }
52
+ out.push(msg);
53
+ }
54
+ return {
55
+ messages: changed ? out : messages,
56
+ report: { changed, removedToolUses, removedToolResults, removedMessages }
57
+ };
58
+ }
59
+ function hasToolUse(msg) {
60
+ return contentBlocks(msg).some((b) => b.type === "tool_use");
61
+ }
62
+ function hasToolResult(msg) {
63
+ return contentBlocks(msg).some((b) => b.type === "tool_result");
64
+ }
65
+ function toolUseIds(msg) {
66
+ const ids = /* @__PURE__ */ new Set();
67
+ if (msg?.role !== "assistant") return ids;
68
+ for (const block of contentBlocks(msg)) {
69
+ if (block.type === "tool_use") ids.add(block.id);
70
+ }
71
+ return ids;
72
+ }
73
+ function toolResultIds(msg) {
74
+ const ids = /* @__PURE__ */ new Set();
75
+ if (msg?.role !== "user") return ids;
76
+ for (const block of contentBlocks(msg)) {
77
+ if (block.type === "tool_result") ids.add(block.tool_use_id);
78
+ }
79
+ return ids;
80
+ }
81
+ function contentBlocks(msg) {
82
+ return msg && Array.isArray(msg.content) ? msg.content : [];
83
+ }
84
+ function mapContent(msg, fn) {
85
+ if (!Array.isArray(msg.content)) return msg;
86
+ const next = fn(msg.content);
87
+ if (next.length === msg.content.length && next.every((b, idx) => b === msg.content[idx])) {
88
+ return msg;
89
+ }
90
+ return { ...msg, content: next };
91
+ }
92
+ function hasMeaningfulContent(content) {
93
+ if (typeof content === "string") return content.trim().length > 0;
94
+ for (const block of content) {
95
+ if (block.type === "text") {
96
+ if (block.text.trim().length > 0) return true;
97
+ continue;
98
+ }
99
+ if (block.type === "thinking") {
100
+ if (block.thinking.trim().length > 0 || block.signature) return true;
101
+ continue;
102
+ }
103
+ return true;
104
+ }
105
+ return false;
106
+ }
107
+ function isEmptyMessage(msg) {
108
+ return !hasMeaningfulContent(msg.content);
109
+ }
110
+
111
+ export {
112
+ repairToolUseAdjacency,
113
+ hasMeaningfulContent
114
+ };
115
+ //# sourceMappingURL=chunk-M2WF6AXG.js.map
@@ -0,0 +1 @@
1
+ //# sourceMappingURL=chunk-M7BS2K6U.js.map