fixate-on 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2574 @@
1
+ // @bun
2
+ var __esm = (fn, res, err) => () => {
3
+ if (fn)
4
+ try {
5
+ res = fn(fn = 0);
6
+ } catch (e) {
7
+ err = [e];
8
+ }
9
+ if (err)
10
+ throw err[0];
11
+ return res;
12
+ };
13
+
14
+ // src/tui-components.ts
15
+ function formatNumber(n) {
16
+ return n.toLocaleString("en-US");
17
+ }
18
+ function formatRelativeTime(timestamp, now = Date.now()) {
19
+ const diff = now - timestamp;
20
+ if (diff < 60000)
21
+ return "just now";
22
+ const minutes = Math.floor(diff / 60000);
23
+ if (minutes < 60)
24
+ return `${minutes}m ago`;
25
+ const hours = Math.floor(minutes / 60);
26
+ if (hours < 24)
27
+ return `${hours}h ago`;
28
+ const days = Math.floor(hours / 24);
29
+ return `${days}d ago`;
30
+ }
31
+ var PRODUCT_DISPLAY_NAME = "Fixate";
32
+
33
+ // src/status-label.ts
34
+ function isYieldPastPromise(stoppedAt, now, promiseMs = YIELD_PROMISE_MS, updatedAt) {
35
+ const since = stoppedAt && stoppedAt > 0 ? stoppedAt : updatedAt;
36
+ if (!since || since <= 0)
37
+ return false;
38
+ if (since > now)
39
+ return true;
40
+ return now - since >= promiseMs;
41
+ }
42
+ function isSelfResolvingStop(status, stopReason, stoppedAt, now = Date.now(), updatedAt) {
43
+ if (status !== "paused")
44
+ return false;
45
+ if (!SELF_RESOLVING_STOP_REASONS.has(stopReason ?? ""))
46
+ return false;
47
+ if (stopReason === USER_INTERVENTION_STOP_REASON && isYieldPastPromise(stoppedAt, now, YIELD_PROMISE_MS, updatedAt))
48
+ return false;
49
+ return true;
50
+ }
51
+ function isYieldingPause(status, stopReason) {
52
+ return status === "paused" && stopReason === USER_INTERVENTION_STOP_REASON;
53
+ }
54
+ function isLiveYield(status, stopReason, stoppedAt, now, updatedAt) {
55
+ if (!isYieldingPause(status, stopReason))
56
+ return false;
57
+ return !isYieldPastPromise(stoppedAt, now ?? Date.now(), YIELD_PROMISE_MS, updatedAt);
58
+ }
59
+ function statusTag(status, stopReason, stoppedAt, now, updatedAt) {
60
+ return isLiveYield(status, stopReason, stoppedAt, now, updatedAt) ? "paused: yielding" : status;
61
+ }
62
+ function stopReasonLabel(stopReason, status, stoppedAt, now, updatedAt) {
63
+ if (stopReason !== USER_INTERVENTION_STOP_REASON)
64
+ return stopReason;
65
+ if (status !== undefined && !isLiveYield(status, stopReason, stoppedAt, now, updatedAt)) {
66
+ return "yielding to your message; did not re-arm";
67
+ }
68
+ return "yielding to your message; re-arms automatically";
69
+ }
70
+ var USER_INTERVENTION_STOP_REASON = "user intervention", SELF_RESOLVING_STOP_REASONS, YIELD_PROMISE_MS;
71
+ var init_status_label = __esm(() => {
72
+ SELF_RESOLVING_STOP_REASONS = new Set([
73
+ "recovery",
74
+ "user intervention",
75
+ "queued"
76
+ ]);
77
+ YIELD_PROMISE_MS = 15 * 60000;
78
+ });
79
+
80
+ // src/accounting.ts
81
+ function chargedTokens(usage) {
82
+ if (!usage)
83
+ return 0;
84
+ return toNonNegativeInteger(usage.input) + toNonNegativeInteger(usage.cacheWrite) + toNonNegativeInteger(usage.output) + toNonNegativeInteger(usage.reasoning);
85
+ }
86
+ function emptyUsage() {
87
+ return {
88
+ input: 0,
89
+ output: 0,
90
+ reasoning: 0,
91
+ cacheRead: 0,
92
+ cacheWrite: 0,
93
+ cost: 0,
94
+ costKnown: false
95
+ };
96
+ }
97
+ function normalizeUsage(value) {
98
+ const source = typeof value === "object" && value !== null ? value : {};
99
+ const usage = emptyUsage();
100
+ for (const field of USAGE_TOKEN_FIELDS) {
101
+ usage[field] = toNonNegativeInteger(source[field]);
102
+ }
103
+ const rawCost = source.cost;
104
+ usage.cost = Number.isFinite(Number(rawCost)) && Number(rawCost) >= 0 ? Number(rawCost) : 0;
105
+ usage.costKnown = source.costKnown === true || usage.cost > 0;
106
+ return usage;
107
+ }
108
+ function normalizeMessageUsage(message) {
109
+ const msg = message;
110
+ const info = msg?.info;
111
+ const tokens = info?.tokens ?? msg?.tokens ?? msg?.usage ?? {};
112
+ const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
113
+ const rawCost = info?.cost ?? msg?.cost ?? tokens.cost;
114
+ return {
115
+ input: toNonNegativeInteger(tokens.input ?? tokens.input_tokens ?? tokens.prompt_tokens),
116
+ output: toNonNegativeInteger(tokens.output ?? tokens.output_tokens ?? tokens.completion_tokens),
117
+ reasoning: toNonNegativeInteger(tokens.reasoning ?? tokens.reasoning_tokens),
118
+ cacheRead: toNonNegativeInteger(cache.read ?? tokens.cacheRead ?? tokens.cache_read),
119
+ cacheWrite: toNonNegativeInteger(cache.write ?? tokens.cacheWrite ?? tokens.cache_write),
120
+ cost: Number.isFinite(Number(rawCost)) && Number(rawCost) >= 0 ? Number(rawCost) : 0,
121
+ costKnown: rawCost != null && Number.isFinite(Number(rawCost)) && Number(rawCost) >= 0
122
+ };
123
+ }
124
+ function addToUsageField(total, field, delta) {
125
+ const next = normalizeUsage(total);
126
+ const current = next[field];
127
+ if (typeof current === "number") {
128
+ next[field] = current + delta;
129
+ }
130
+ return next;
131
+ }
132
+ function addUsageDelta(total, current, previous, isNewStep = false) {
133
+ const next = normalizeUsage(total);
134
+ const cur = normalizeUsage(current);
135
+ const prev = normalizeUsage(previous);
136
+ const costIncreased = prev.cost > 0 && cur.cost > prev.cost;
137
+ const anyTokenFieldDecreased = STEP_DETECTION_FIELDS.some((field) => cur[field] < prev[field]);
138
+ const completedAnotherStep = isNewStep || costIncreased || anyTokenFieldDecreased;
139
+ for (const field of USAGE_TOKEN_FIELDS) {
140
+ next[field] += completedAnotherStep ? cur[field] : Math.max(0, cur[field] - prev[field]);
141
+ }
142
+ next.cost += Math.max(0, cur.cost - prev.cost);
143
+ next.costKnown ||= cur.costKnown;
144
+ return next;
145
+ }
146
+ function totalTokensForMessage(message) {
147
+ const msg = message;
148
+ const info = msg?.info;
149
+ const tokens = info?.tokens ?? msg?.tokens ?? msg?.usage ?? {};
150
+ const reportedTotal = toNonNegativeInteger(tokens.total);
151
+ if (reportedTotal > 0)
152
+ return reportedTotal;
153
+ return toNonNegativeInteger(tokens.input ?? tokens.input_tokens ?? tokens.prompt_tokens) + toNonNegativeInteger(tokens.output ?? tokens.output_tokens ?? tokens.completion_tokens) + toNonNegativeInteger(tokens.reasoning ?? tokens.reasoning_tokens) + cacheTokensForMessage(tokens);
154
+ }
155
+ function outputTokensForMessage(message) {
156
+ const msg = message;
157
+ const info = msg?.info;
158
+ const tokens = info?.tokens ?? msg?.tokens ?? msg?.usage ?? {};
159
+ const outputRaw = tokens.output ?? tokens.output_tokens ?? tokens.completion_tokens;
160
+ const output = toNonNegativeInteger(outputRaw);
161
+ if (outputRaw === undefined && (info?.tokens === undefined || info?.tokens === null) && (msg?.tokens === undefined || msg?.tokens === null) && (msg?.usage === undefined || msg?.usage === null))
162
+ return null;
163
+ return output;
164
+ }
165
+ function cacheTokensForMessage(tokens) {
166
+ const cache = typeof tokens.cache === "object" && tokens.cache !== null ? tokens.cache : {};
167
+ return toNonNegativeInteger(cache.read ?? tokens.cacheRead ?? tokens.cache_read) + toNonNegativeInteger(cache.write ?? tokens.cacheWrite ?? tokens.cache_write);
168
+ }
169
+ function toNonNegativeInteger(value, fallback = 0) {
170
+ if (value === null || value === undefined)
171
+ return fallback;
172
+ const parsed = Number(value);
173
+ return Number.isSafeInteger(parsed) && parsed >= 0 ? parsed : fallback;
174
+ }
175
+ var USAGE_TOKEN_FIELDS, STEP_DETECTION_FIELDS;
176
+ var init_accounting = __esm(() => {
177
+ USAGE_TOKEN_FIELDS = [
178
+ "input",
179
+ "output",
180
+ "reasoning",
181
+ "cacheRead",
182
+ "cacheWrite"
183
+ ];
184
+ STEP_DETECTION_FIELDS = [
185
+ "input",
186
+ "output",
187
+ "reasoning",
188
+ "cacheWrite"
189
+ ];
190
+ });
191
+
192
+ // src/tui-analytics.ts
193
+ function computeAnalytics(goal) {
194
+ const charged = chargedTokens(goal.usage);
195
+ const tokenBudget = goal.tokenBudget ?? null;
196
+ const budgetPercentage = tokenBudget !== null && tokenBudget > 0 ? Math.round(charged / tokenBudget * 100) : null;
197
+ const tokensPerTurn = goal.turnCount > 0 ? Math.round(charged / goal.turnCount) : 0;
198
+ const projectedTotalTokens = goal.turnCount > 0 && goal.maxTurns > 0 ? tokensPerTurn * goal.maxTurns : null;
199
+ const turnsRemaining = tokenBudget !== null && tokensPerTurn > 0 ? Math.max(0, Math.floor((tokenBudget - charged) / tokensPerTurn)) : null;
200
+ const costPerTurn = goal.usage.costKnown && goal.turnCount > 0 ? goal.usage.cost / goal.turnCount : 0;
201
+ const projectedTotalCost = goal.usage.costKnown && goal.turnCount > 0 ? costPerTurn * goal.maxTurns : null;
202
+ const elapsedMs = Date.now() - goal.createdAt;
203
+ const burnRate = elapsedMs >= 1000 ? Math.round(charged / (elapsedMs / 1000)) : 0;
204
+ return {
205
+ chargedTokens: charged,
206
+ tokenBudget,
207
+ budgetPercentage,
208
+ tokensPerTurn,
209
+ projectedTotalTokens,
210
+ turnsRemaining,
211
+ costPerTurn,
212
+ projectedTotalCost,
213
+ burnRate
214
+ };
215
+ }
216
+ function formatAnalyticsSummary(analytics) {
217
+ const parts = [];
218
+ parts.push(`Charged: ${formatNumber(analytics.chargedTokens)}`);
219
+ if (analytics.budgetPercentage !== null) {
220
+ parts.push(`Budget: ${analytics.budgetPercentage}%`);
221
+ }
222
+ if (analytics.tokensPerTurn > 0) {
223
+ parts.push(`${formatNumber(analytics.tokensPerTurn)}/turn`);
224
+ }
225
+ if (analytics.turnsRemaining !== null) {
226
+ parts.push(`${analytics.turnsRemaining} turns left`);
227
+ }
228
+ if (analytics.costPerTurn > 0) {
229
+ parts.push(`$${analytics.costPerTurn.toFixed(4)}/turn`);
230
+ }
231
+ if (analytics.burnRate > 0) {
232
+ parts.push(`${formatNumber(analytics.burnRate)} tok/s`);
233
+ }
234
+ return parts.join(" | ");
235
+ }
236
+ function formatBudgetWarning(analytics) {
237
+ if (analytics.budgetPercentage === null)
238
+ return null;
239
+ if (analytics.budgetPercentage < 80)
240
+ return null;
241
+ if (analytics.budgetPercentage >= 100) {
242
+ return `Budget ${analytics.budgetPercentage}% consumed - limit reached`;
243
+ }
244
+ if (analytics.projectedTotalTokens !== null && analytics.tokenBudget !== null && analytics.projectedTotalTokens > analytics.tokenBudget) {
245
+ return `Projected to exceed budget at current rate (${analytics.budgetPercentage}% used, ${analytics.turnsRemaining} turns left)`;
246
+ }
247
+ return `Budget at ${analytics.budgetPercentage}% - approaching limit`;
248
+ }
249
+ var init_tui_analytics = __esm(() => {
250
+ init_accounting();
251
+ });
252
+
253
+ // src/brake-format.ts
254
+ function brakeCeiling(limit) {
255
+ return limit > 0 ? limit : UNLIMITED;
256
+ }
257
+ function brakeCeilingFormatted(limit, format) {
258
+ return limit > 0 ? format(limit) : UNLIMITED;
259
+ }
260
+ var UNLIMITED = "unlimited";
261
+
262
+ // src/tui-views.ts
263
+ function wrapText(text, width, continuationIndent = "") {
264
+ const words = text.split(/\s+/).filter(Boolean);
265
+ if (words.length === 0)
266
+ return [text];
267
+ const lines = [];
268
+ let current = "";
269
+ for (const word of words) {
270
+ const candidate = current ? `${current} ${word}` : word;
271
+ if (current && candidate.length > width) {
272
+ lines.push(current);
273
+ current = continuationIndent + word;
274
+ } else {
275
+ current = candidate;
276
+ }
277
+ }
278
+ if (current)
279
+ lines.push(current);
280
+ return lines;
281
+ }
282
+ function isForeignGoal(goal, activeSessionID) {
283
+ return activeSessionID !== null && goal.sessionID !== activeSessionID;
284
+ }
285
+ function foreignSessionLabel(goal) {
286
+ return goal.sessionID;
287
+ }
288
+ function fallbackNotice(goals, activeSessionID) {
289
+ if (activeSessionID === null)
290
+ return null;
291
+ const foreign = goals.filter((g) => isForeignGoal(g, activeSessionID));
292
+ if (foreign.length === 0)
293
+ return null;
294
+ const mine = goals.length - foreign.length;
295
+ return mine === 0 ? `This session has no goals. Showing ${foreign.length} from other sessions.` : `Showing ${foreign.length} from other sessions alongside this session's ${mine}.`;
296
+ }
297
+ function goalListRow(goal, index, activeSessionID) {
298
+ const foreign = isForeignGoal(goal, activeSessionID);
299
+ return {
300
+ title: `${index + 1}. [${statusTag(goal.status, goal.stopReason, goal.stoppedAt, undefined, goal.updatedAt)}] ${goal.condition.substring(0, 60)}`,
301
+ description: (foreign ? `Another session (${foreignSessionLabel(goal)}) | ` : "") + `Tokens: ${goal.totalTokens}/${brakeCeiling(goal.maxTokens)} Turns: ${goal.turnCount}/${brakeCeiling(goal.maxTurns)}`
302
+ };
303
+ }
304
+ function dashboardGoalActions(store, targetSessionID, send) {
305
+ const withTarget = (verb) => () => {
306
+ const id = resolveFocusedGoalId(store, targetSessionID());
307
+ if (id)
308
+ send(`${verb} ${id}`);
309
+ };
310
+ return {
311
+ onPause: withTarget("pause"),
312
+ onResume: withTarget("resume"),
313
+ onClear: withTarget("clear")
314
+ };
315
+ }
316
+ function dashboardFooterText(targetGoalId, dashboardChord, pauseChord, resumeChord, clearChord, escLabel) {
317
+ const nav = `${dashboardChord} dashboard | ${escLabel} home`;
318
+ if (!targetGoalId)
319
+ return nav;
320
+ return `${pauseChord} pause | ${resumeChord} resume | ${clearChord} clear | ${nav}`;
321
+ }
322
+ function resolveFocusedGoalId(store, sessionID) {
323
+ if (sessionID === null)
324
+ return null;
325
+ const focused = store.getFocused(sessionID);
326
+ if (focused)
327
+ return focused.goalId;
328
+ const mine = store.getAllSnapshots().filter((g) => !isForeignGoal(g, sessionID));
329
+ return mine.length > 0 ? mine[mine.length - 1].goalId : null;
330
+ }
331
+ function goalCardLines(goal, activeSessionID) {
332
+ const lines = [];
333
+ lines.push({ text: `Objective: ${goal.condition}` });
334
+ lines.push({ text: ` Status: ${goal.status}` });
335
+ if (isForeignGoal(goal, activeSessionID)) {
336
+ lines.push({
337
+ subdued: true,
338
+ text: ` Session: ${foreignSessionLabel(goal)} (another session)`
339
+ });
340
+ }
341
+ if (goal.stopReason) {
342
+ lines.push({
343
+ subdued: true,
344
+ text: ` Stop: ${stopReasonLabel(goal.stopReason, goal.status, goal.stoppedAt, undefined, goal.updatedAt)}`
345
+ });
346
+ }
347
+ lines.push({ text: ` ${tokenGauge(goal.totalTokens, goal.maxTokens)}` });
348
+ lines.push({
349
+ text: ` Turns: ${goal.turnCount}/${brakeCeiling(goal.maxTurns)}`
350
+ });
351
+ return lines;
352
+ }
353
+ function tokenGauge(used, max) {
354
+ const pct = max > 0 ? Math.round(used / max * 100) : 0;
355
+ const compact = (n) => n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
356
+ return `Tokens: ${pct}% ${compact(used)} / ${brakeCeilingFormatted(max, compact)}`;
357
+ }
358
+ function formatGoalStatusDashboard(goals, activeSessionID = null) {
359
+ if (goals.length === 0) {
360
+ return [
361
+ {
362
+ title: PRODUCT_DISPLAY_NAME,
363
+ text: "No active goals. Use /goal <condition> to set one."
364
+ }
365
+ ];
366
+ }
367
+ const sections = [];
368
+ const notice = fallbackNotice(goals, activeSessionID);
369
+ if (notice) {
370
+ sections.push({ title: "Sessions shown", text: notice });
371
+ }
372
+ for (const goal of goals) {
373
+ const lines = [];
374
+ lines.push(...wrapText(` Objective: ${goal.condition}`, 96, " "));
375
+ lines.push(` Status: ${goal.status}`);
376
+ if (isForeignGoal(goal, activeSessionID)) {
377
+ lines.push(` Session: ${foreignSessionLabel(goal)} (another session)`);
378
+ }
379
+ if (goal.stopReason) {
380
+ lines.push(` Stop: ${stopReasonLabel(goal.stopReason, goal.status, goal.stoppedAt, undefined, goal.updatedAt)}`);
381
+ }
382
+ if (goal.blockedReason) {
383
+ lines.push(` Blocked: ${goal.blockedReason}`);
384
+ }
385
+ lines.push("");
386
+ lines.push(formatTokenGauge(goal.totalTokens, goal.maxTokens));
387
+ lines.push(` Turns: ${goal.turnCount} / ${brakeCeiling(goal.maxTurns)}`);
388
+ if (goal.usage.costKnown && goal.usage.cost > 0) {
389
+ lines.push(` Cost: $${goal.usage.cost.toFixed(4)}`);
390
+ }
391
+ const analytics = computeAnalytics(goal);
392
+ const analyticsLine = formatAnalyticsSummary(analytics);
393
+ if (analyticsLine) {
394
+ lines.push(` Analytics: ${analyticsLine}`);
395
+ }
396
+ const warning = formatBudgetWarning(analytics);
397
+ if (warning) {
398
+ lines.push(` ${warning}`);
399
+ }
400
+ if (goal.lastCheckpoint) {
401
+ lines.push("");
402
+ lines.push(` Checkpoint: ${goal.lastCheckpoint.summary}`);
403
+ lines.push(` ${formatRelativeTime(goal.lastCheckpoint.timestamp)}`);
404
+ }
405
+ if (goal.history.length > 0) {
406
+ lines.push("");
407
+ lines.push(formatHistoryList(goal.history));
408
+ }
409
+ sections.push({
410
+ title: `Goal: ${goal.goalId.substring(0, 8)}`,
411
+ text: lines.join(`
412
+ `)
413
+ });
414
+ }
415
+ return sections;
416
+ }
417
+ function formatTokenGauge(used, max) {
418
+ const percentage = max > 0 ? used / max * 100 : 0;
419
+ const maxLabel = max > 0 ? formatNumber(max) : "unlimited";
420
+ return ` Tokens: ${Math.round(percentage)}% ${formatNumber(used)} / ${maxLabel}`;
421
+ }
422
+ function isSignalHistoryEntry(entry) {
423
+ if (entry.type === "tracking")
424
+ return false;
425
+ if (entry.type !== "mutation")
426
+ return true;
427
+ return MUTATION_SIGNAL_PREFIXES.some((prefix) => entry.detail.startsWith(prefix));
428
+ }
429
+ function formatHistoryList(history) {
430
+ const signals = history.filter(isSignalHistoryEntry);
431
+ if (signals.length === 0) {
432
+ return " History: (no lifecycle events)";
433
+ }
434
+ const lines = [" History:"];
435
+ for (const entry of signals) {
436
+ const time = formatRelativeTime(entry.timestamp);
437
+ lines.push(` [${entry.type}] ${entry.detail} (${time})`);
438
+ }
439
+ return lines.join(`
440
+ `);
441
+ }
442
+ var MUTATION_SIGNAL_PREFIXES;
443
+ var init_tui_views = __esm(() => {
444
+ init_tui_analytics();
445
+ init_status_label();
446
+ MUTATION_SIGNAL_PREFIXES = [
447
+ "User ",
448
+ "Human ",
449
+ "Accepted proposal",
450
+ "Rejected proposal",
451
+ "Proposed term changes",
452
+ "Recorded claim",
453
+ "Loaded from persisted state",
454
+ "Paused because",
455
+ "Backgrounded",
456
+ "Queued goal",
457
+ "Started an ordered sequence",
458
+ "Pressure rung"
459
+ ];
460
+ });
461
+
462
+ // src/tui-state.ts
463
+ var GOAL_TUI_EVENT_TITLE = "fixate-on";
464
+ var VALID_GOAL_STATUSES = new Set([
465
+ "active",
466
+ "paused",
467
+ "blocked",
468
+ "budgetLimited",
469
+ "finalizing",
470
+ "complete"
471
+ ]);
472
+ var memoHistoryRef = null;
473
+ var memoHistoryLen = -1;
474
+ var memoHistoryFrozen = [];
475
+ function frozenHistory(history) {
476
+ if (history === memoHistoryRef && history.length === memoHistoryLen) {
477
+ return memoHistoryFrozen;
478
+ }
479
+ memoHistoryRef = history;
480
+ memoHistoryLen = history.length;
481
+ memoHistoryFrozen = deepFreeze(history.map((h) => ({
482
+ type: h.type,
483
+ detail: h.detail,
484
+ timestamp: h.timestamp
485
+ })));
486
+ return memoHistoryFrozen;
487
+ }
488
+ function serializeGoalForTui(state) {
489
+ const snapshot = {
490
+ goalId: state.goalId,
491
+ sessionID: state.sessionID,
492
+ condition: state.condition,
493
+ artifactPointers: state.artifactPointers ? [...state.artifactPointers] : [],
494
+ pendingProposal: state.pendingProposal ? { ...state.pendingProposal } : null,
495
+ claims: state.claims ? state.claims.map((c) => ({ ...c })) : [],
496
+ lastClaim: state.lastClaim ? { ...state.lastClaim } : null,
497
+ status: state.status,
498
+ revision: state.revision,
499
+ turnCount: state.turnCount,
500
+ totalTokens: state.totalTokens,
501
+ maxTokens: state.maxTokens,
502
+ maxTurns: state.maxTurns,
503
+ tokenBudget: state.tokenBudget,
504
+ usage: {
505
+ input: state.usage.input,
506
+ output: state.usage.output,
507
+ reasoning: state.usage.reasoning,
508
+ cacheRead: state.usage.cacheRead,
509
+ cacheWrite: state.usage.cacheWrite,
510
+ cost: state.usage.cost,
511
+ costKnown: state.usage.costKnown
512
+ },
513
+ stopReason: state.stopReason,
514
+ blockedReason: state.blockedReason,
515
+ pausedAt: state.pausedAt,
516
+ stoppedAt: state.stoppedAt,
517
+ createdAt: state.createdAt,
518
+ updatedAt: state.updatedAt,
519
+ finishedAt: state.finishedAt,
520
+ lastCheckpoint: state.lastCheckpoint ? {
521
+ summary: state.lastCheckpoint.summary,
522
+ timestamp: state.lastCheckpoint.timestamp
523
+ } : null,
524
+ history: frozenHistory(state.history)
525
+ };
526
+ return deepFreeze(snapshot);
527
+ }
528
+ function parseTuiSyncEvent(raw) {
529
+ if (!raw || typeof raw !== "string")
530
+ return null;
531
+ let parsed;
532
+ try {
533
+ parsed = JSON.parse(raw);
534
+ } catch {
535
+ return null;
536
+ }
537
+ return validateTuiEvent(parsed);
538
+ }
539
+ function validateTuiEvent(value) {
540
+ if (!value || typeof value !== "object")
541
+ return null;
542
+ const obj = value;
543
+ if (obj.title === GOAL_TUI_EVENT_TITLE && obj.payload && typeof obj.payload === "object") {
544
+ return validateTuiEvent(obj.payload);
545
+ }
546
+ const kind = obj.kind;
547
+ if (kind !== "create" && kind !== "transition" && kind !== "usage" && kind !== "remove") {
548
+ return null;
549
+ }
550
+ const sessionID = obj.sessionID;
551
+ if (typeof sessionID !== "string" || sessionID.length === 0)
552
+ return null;
553
+ const timestamp = obj.timestamp;
554
+ if (typeof timestamp !== "number" || !Number.isFinite(timestamp))
555
+ return null;
556
+ if (kind === "remove") {
557
+ const goalId = obj.goalId;
558
+ if (typeof goalId !== "string" || goalId.length === 0)
559
+ return null;
560
+ return { kind, sessionID, timestamp, goalId };
561
+ }
562
+ const snapshot = validateSnapshot(obj.snapshot);
563
+ if (!snapshot)
564
+ return null;
565
+ if (snapshot.sessionID !== sessionID)
566
+ return null;
567
+ if (kind === "transition") {
568
+ const transition = validateTransition(obj.transition);
569
+ if (!transition)
570
+ return null;
571
+ return { kind, sessionID, timestamp, snapshot, transition };
572
+ }
573
+ return { kind, sessionID, timestamp, snapshot };
574
+ }
575
+ function validateSnapshot(value) {
576
+ if (!value || typeof value !== "object")
577
+ return null;
578
+ const s = value;
579
+ if (typeof s.goalId !== "string" || typeof s.sessionID !== "string" || typeof s.condition !== "string" || typeof s.status !== "string" || !VALID_GOAL_STATUSES.has(s.status) || typeof s.revision !== "number" || typeof s.turnCount !== "number" || typeof s.totalTokens !== "number" || typeof s.maxTokens !== "number" || typeof s.maxTurns !== "number" || s.tokenBudget !== null && typeof s.tokenBudget !== "number" || typeof s.stopReason !== "string" || typeof s.pausedAt !== "number" || !Number.isFinite(s.pausedAt) || s.pausedAt < 0 || typeof s.stoppedAt !== "number" || !Number.isFinite(s.stoppedAt) || s.stoppedAt < 0 || typeof s.blockedReason !== "string" || typeof s.createdAt !== "number" || typeof s.updatedAt !== "number") {
580
+ return null;
581
+ }
582
+ if (s.finishedAt !== null && typeof s.finishedAt !== "number")
583
+ return null;
584
+ const usage = validateUsage(s.usage);
585
+ if (!usage)
586
+ return null;
587
+ const history = validateHistory(s.history);
588
+ if (history === null)
589
+ return null;
590
+ const checkpoint = validateCheckpoint(s.lastCheckpoint);
591
+ if (checkpoint === INVALID_CHECKPOINT)
592
+ return null;
593
+ const snapshot = {
594
+ goalId: s.goalId,
595
+ sessionID: s.sessionID,
596
+ condition: s.condition,
597
+ status: s.status,
598
+ revision: s.revision,
599
+ turnCount: s.turnCount,
600
+ totalTokens: s.totalTokens,
601
+ maxTokens: s.maxTokens,
602
+ maxTurns: s.maxTurns,
603
+ tokenBudget: s.tokenBudget === null ? null : s.tokenBudget,
604
+ usage,
605
+ stopReason: s.stopReason,
606
+ blockedReason: s.blockedReason,
607
+ pausedAt: s.pausedAt,
608
+ stoppedAt: s.stoppedAt,
609
+ createdAt: s.createdAt,
610
+ updatedAt: s.updatedAt,
611
+ finishedAt: s.finishedAt === null ? null : s.finishedAt,
612
+ lastCheckpoint: checkpoint,
613
+ history
614
+ };
615
+ return deepFreeze(snapshot);
616
+ }
617
+ function validateUsage(value) {
618
+ if (!value || typeof value !== "object")
619
+ return null;
620
+ const u = value;
621
+ if (typeof u.input !== "number" || typeof u.output !== "number" || typeof u.reasoning !== "number" || typeof u.cacheRead !== "number" || typeof u.cacheWrite !== "number" || typeof u.cost !== "number" || typeof u.costKnown !== "boolean") {
622
+ return null;
623
+ }
624
+ return {
625
+ input: u.input,
626
+ output: u.output,
627
+ reasoning: u.reasoning,
628
+ cacheRead: u.cacheRead,
629
+ cacheWrite: u.cacheWrite,
630
+ cost: u.cost,
631
+ costKnown: u.costKnown
632
+ };
633
+ }
634
+ function validateHistory(value) {
635
+ if (!Array.isArray(value))
636
+ return null;
637
+ const result = [];
638
+ for (const entry of value) {
639
+ if (!entry || typeof entry !== "object")
640
+ return null;
641
+ const e = entry;
642
+ if (typeof e.type !== "string" || typeof e.detail !== "string" || typeof e.timestamp !== "number") {
643
+ return null;
644
+ }
645
+ result.push({ type: e.type, detail: e.detail, timestamp: e.timestamp });
646
+ }
647
+ return result;
648
+ }
649
+ var INVALID_CHECKPOINT = Object.freeze({ summary: "", timestamp: -1 });
650
+ function validateCheckpoint(value) {
651
+ if (value === null)
652
+ return null;
653
+ if (!value || typeof value !== "object")
654
+ return INVALID_CHECKPOINT;
655
+ const c = value;
656
+ if (typeof c.summary !== "string" || typeof c.timestamp !== "number")
657
+ return INVALID_CHECKPOINT;
658
+ return { summary: c.summary, timestamp: c.timestamp };
659
+ }
660
+ function validateTransition(value) {
661
+ if (!value || typeof value !== "object")
662
+ return null;
663
+ const t = value;
664
+ if (typeof t.source !== "string" || typeof t.from !== "string" || typeof t.to !== "string" || typeof t.detail !== "string") {
665
+ return null;
666
+ }
667
+ return {
668
+ source: t.source,
669
+ from: t.from,
670
+ to: t.to,
671
+ detail: t.detail
672
+ };
673
+ }
674
+ function createSessionStore() {
675
+ return { goals: new Map, focusedId: null, order: [] };
676
+ }
677
+ function createTuiStateStore() {
678
+ const sessions = new Map;
679
+ const subscribers = new Set;
680
+ function getOrCreateSession(sessionID) {
681
+ let s = sessions.get(sessionID);
682
+ if (!s) {
683
+ s = createSessionStore();
684
+ sessions.set(sessionID, s);
685
+ }
686
+ return s;
687
+ }
688
+ function notify(event) {
689
+ for (const sub of subscribers) {
690
+ try {
691
+ sub(event);
692
+ } catch {}
693
+ }
694
+ }
695
+ function applyEvent(event) {
696
+ if (event.kind === "remove") {
697
+ const session = sessions.get(event.sessionID);
698
+ if (session && event.goalId) {
699
+ session.goals.delete(event.goalId);
700
+ session.order = session.order.filter((id) => id !== event.goalId);
701
+ if (session.focusedId === event.goalId) {
702
+ session.focusedId = session.order[session.order.length - 1] ?? null;
703
+ }
704
+ }
705
+ notify(event);
706
+ return;
707
+ }
708
+ if (!event.snapshot)
709
+ return;
710
+ const snapshot = deepFreeze(event.snapshot);
711
+ const session = getOrCreateSession(event.sessionID);
712
+ const existing = session.goals.get(snapshot.goalId);
713
+ if (existing && snapshot.revision < existing.revision) {
714
+ return;
715
+ }
716
+ if (!existing) {
717
+ session.order.push(snapshot.goalId);
718
+ }
719
+ session.goals.set(snapshot.goalId, snapshot);
720
+ session.focusedId = snapshot.goalId;
721
+ notify(event);
722
+ }
723
+ function getSnapshots(sessionID) {
724
+ const session = sessions.get(sessionID);
725
+ if (!session)
726
+ return [];
727
+ return session.order.map((id) => session.goals.get(id)).filter((s) => !!s);
728
+ }
729
+ function getAllSnapshots() {
730
+ const all = [];
731
+ for (const session of sessions.values()) {
732
+ for (const id of session.order) {
733
+ const snap = session.goals.get(id);
734
+ if (snap)
735
+ all.push(snap);
736
+ }
737
+ }
738
+ return all;
739
+ }
740
+ function getSnapshot(sessionID, goalId) {
741
+ const session = sessions.get(sessionID);
742
+ if (!session)
743
+ return;
744
+ return session.goals.get(goalId);
745
+ }
746
+ function getFocused(sessionID) {
747
+ const session = sessions.get(sessionID);
748
+ if (!session || !session.focusedId)
749
+ return;
750
+ return session.goals.get(session.focusedId);
751
+ }
752
+ function subscribe(fn) {
753
+ subscribers.add(fn);
754
+ return () => subscribers.delete(fn);
755
+ }
756
+ function clear() {
757
+ sessions.clear();
758
+ subscribers.clear();
759
+ }
760
+ return {
761
+ applyEvent,
762
+ getSnapshots,
763
+ getAllSnapshots,
764
+ getSnapshot,
765
+ getFocused,
766
+ subscribe,
767
+ clear
768
+ };
769
+ }
770
+ function createGoalBroadcaster(config) {
771
+ const { publish, onDeliveryFailure } = config;
772
+ async function emit(snapshot, kind, transition) {
773
+ const event = {
774
+ kind,
775
+ sessionID: snapshot.sessionID,
776
+ timestamp: Date.now(),
777
+ snapshot: serializeGoalForTui(snapshot),
778
+ ...transition ? { transition, previousStatus: transition.from } : {}
779
+ };
780
+ try {
781
+ await publish(snapshot.sessionID, event);
782
+ } catch (error) {
783
+ try {
784
+ onDeliveryFailure?.({
785
+ kind,
786
+ sessionID: snapshot.sessionID,
787
+ goalId: snapshot.goalId,
788
+ error
789
+ });
790
+ } catch {}
791
+ }
792
+ }
793
+ return {
794
+ onCommit: async (snapshot, transition) => {
795
+ await emit(snapshot, "transition", transition);
796
+ },
797
+ emitCreate: async (snapshot) => {
798
+ await emit(snapshot, "create");
799
+ },
800
+ emitRemove: async (sessionID, goalId) => {
801
+ const event = {
802
+ kind: "remove",
803
+ sessionID,
804
+ goalId,
805
+ timestamp: Date.now()
806
+ };
807
+ try {
808
+ await publish(sessionID, event);
809
+ } catch (error) {
810
+ try {
811
+ onDeliveryFailure?.({ kind: "remove", sessionID, goalId, error });
812
+ } catch {}
813
+ }
814
+ },
815
+ emitUsage: async (snapshot) => {
816
+ await emit(snapshot, "usage");
817
+ }
818
+ };
819
+ }
820
+ var BUFFER_MAX_EVENTS = 64;
821
+ var GOAL_TUI_METADATA_KEY = "fixate-on";
822
+ function createBufferingTransport() {
823
+ const buffers = new Map;
824
+ function get(sessionID) {
825
+ let buf = buffers.get(sessionID);
826
+ if (!buf) {
827
+ buf = [];
828
+ buffers.set(sessionID, buf);
829
+ }
830
+ return buf;
831
+ }
832
+ return {
833
+ publish: (_sessionID, event) => {
834
+ const sessionID = event.sessionID;
835
+ if (!sessionID)
836
+ return;
837
+ const buf = get(sessionID);
838
+ buf.push(event);
839
+ if (buf.length > BUFFER_MAX_EVENTS) {
840
+ buf.splice(0, buf.length - BUFFER_MAX_EVENTS);
841
+ }
842
+ },
843
+ drain: (sessionID) => {
844
+ const buf = buffers.get(sessionID);
845
+ if (!buf || buf.length === 0)
846
+ return [];
847
+ return buf.splice(0, buf.length);
848
+ },
849
+ peek: (sessionID) => {
850
+ const buf = buffers.get(sessionID);
851
+ return buf ? buf.slice() : [];
852
+ },
853
+ clear: () => {
854
+ buffers.clear();
855
+ }
856
+ };
857
+ }
858
+ function encodeGoalToolMetadata(events) {
859
+ if (!events || events.length === 0)
860
+ return;
861
+ return { [GOAL_TUI_METADATA_KEY]: { events } };
862
+ }
863
+ function decodeGoalToolMetadata(metadata) {
864
+ if (!metadata || typeof metadata !== "object")
865
+ return null;
866
+ const envelope = metadata[GOAL_TUI_METADATA_KEY];
867
+ if (!envelope || typeof envelope !== "object")
868
+ return null;
869
+ const events = envelope.events;
870
+ if (!Array.isArray(events))
871
+ return null;
872
+ const valid = [];
873
+ for (const raw of events) {
874
+ const event = validateTuiEvent(raw);
875
+ if (event)
876
+ valid.push(event);
877
+ }
878
+ return valid.length > 0 ? valid : null;
879
+ }
880
+ function deepFreeze(value) {
881
+ if (value === null || typeof value !== "object")
882
+ return value;
883
+ if (Object.isFrozen(value))
884
+ return value;
885
+ if (Array.isArray(value)) {
886
+ for (const item of value)
887
+ deepFreeze(item);
888
+ return Object.freeze(value);
889
+ }
890
+ for (const key of Object.keys(value)) {
891
+ deepFreeze(value[key]);
892
+ }
893
+ return Object.freeze(value);
894
+ }
895
+ // src/tui-disk-state.ts
896
+ import { resolve as resolve2 } from "path";
897
+
898
+ // src/fs-portable.ts
899
+ import {
900
+ lstat as fsLstat,
901
+ mkdir as fsMkdir,
902
+ rename as fsRename,
903
+ unlink as fsUnlink
904
+ } from "fs/promises";
905
+ var MAX_STATE_FILE_BYTES = 16 * 1024 * 1024;
906
+ async function portableReadBounded(filePath, maxBytes = MAX_STATE_FILE_BYTES) {
907
+ const { open } = await import("fs/promises");
908
+ const info = await fsLstat(filePath).catch(() => null);
909
+ if (!info || info.isSymbolicLink() || !info.isFile()) {
910
+ throw new Error(`refusing to read non-regular file: ${filePath}`);
911
+ }
912
+ const handle = await open(filePath, "r");
913
+ try {
914
+ const opened = await handle.stat();
915
+ const buf = Buffer.alloc(Math.min(opened.size, maxBytes));
916
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
917
+ return {
918
+ text: buf.subarray(0, bytesRead).toString("utf8"),
919
+ truncated: opened.size > maxBytes
920
+ };
921
+ } finally {
922
+ await handle.close();
923
+ }
924
+ }
925
+ async function portableWriteFile(filePath, data, mode = 384) {
926
+ const { dirname } = await import("path");
927
+ const { open } = await import("fs/promises");
928
+ const { randomUUID } = await import("crypto");
929
+ const { constants } = await import("fs");
930
+ await fsMkdir(dirname(filePath), { recursive: true, mode: 448 });
931
+ const temporaryPath = `${filePath}.tmp-${randomUUID()}`;
932
+ let installed = false;
933
+ let ownsTemporary = false;
934
+ let backupPath = null;
935
+ try {
936
+ const handle = await open(temporaryPath, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL, mode);
937
+ ownsTemporary = true;
938
+ try {
939
+ await handle.writeFile(data, "utf8");
940
+ await handle.chmod(mode);
941
+ await handle.sync();
942
+ } finally {
943
+ await handle.close();
944
+ }
945
+ const existing = await fsLstat(filePath).catch(() => {
946
+ return;
947
+ });
948
+ if (existing?.isSymbolicLink()) {
949
+ throw new Error(`refusing to replace symlinked state file: ${filePath}`);
950
+ }
951
+ if (existing && !existing.isFile()) {
952
+ throw new Error(`refusing to replace non-regular state file: ${filePath}`);
953
+ }
954
+ try {
955
+ await fsRename(temporaryPath, filePath);
956
+ installed = true;
957
+ } catch (renameError) {
958
+ if (!existing)
959
+ throw renameError;
960
+ backupPath = `${filePath}.bak-${randomUUID()}`;
961
+ await fsRename(filePath, backupPath);
962
+ try {
963
+ await fsRename(temporaryPath, filePath);
964
+ installed = true;
965
+ } catch (fallbackError) {
966
+ try {
967
+ await fsRename(backupPath, filePath);
968
+ } catch (restoreError) {
969
+ throw new Error(`snapshot replacement failed and prior snapshot restore failed; prior snapshot preserved at ${backupPath}: ${restoreError instanceof Error ? restoreError.message : String(restoreError)}`, { cause: fallbackError });
970
+ }
971
+ throw fallbackError;
972
+ }
973
+ await fsUnlink(backupPath).catch(() => {});
974
+ }
975
+ try {
976
+ const directory = await open(dirname(filePath), constants.O_RDONLY);
977
+ try {
978
+ await directory.sync();
979
+ } finally {
980
+ await directory.close();
981
+ }
982
+ } catch {}
983
+ installed = true;
984
+ } finally {
985
+ if (ownsTemporary && !installed) {
986
+ await fsUnlink(temporaryPath).catch(() => {});
987
+ }
988
+ }
989
+ }
990
+ async function portableFileExists(filePath) {
991
+ try {
992
+ const info = await fsLstat(filePath);
993
+ return info.isFile();
994
+ } catch {
995
+ return false;
996
+ }
997
+ }
998
+ async function portableFileSize(filePath) {
999
+ try {
1000
+ const info = await fsLstat(filePath);
1001
+ return info.isFile() ? info.size : -1;
1002
+ } catch {
1003
+ return -1;
1004
+ }
1005
+ }
1006
+
1007
+ // src/session-paths.ts
1008
+ import { lstatSync } from "fs";
1009
+ import { dirname, join, relative, resolve, sep } from "path";
1010
+ var SESSIONS_DIRNAME = "sessions";
1011
+ var DEFAULT_STATE_ROOT = ".opencode/goals";
1012
+ var STATE_FILENAME = "state.json";
1013
+ var LEDGER_SUFFIX = ".ledger.jsonl";
1014
+ var SESSION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
1015
+ function assertSafeSessionID(sessionID) {
1016
+ if (typeof sessionID !== "string" || !SESSION_ID_PATTERN.test(sessionID)) {
1017
+ const shown = typeof sessionID === "string" ? sessionID.slice(0, 64) : String(sessionID);
1018
+ throw new Error(`refusing to use ${JSON.stringify(shown)} as a session directory name: a session id must be 1-128 characters of A-Z, a-z, 0-9, '_' or '-'`);
1019
+ }
1020
+ return sessionID;
1021
+ }
1022
+ function sessionStatePaths(stateRoot, sessionID) {
1023
+ const sessionDir = join(stateRoot, SESSIONS_DIRNAME, assertSafeSessionID(sessionID));
1024
+ const statePath = join(sessionDir, STATE_FILENAME);
1025
+ return { sessionDir, statePath, ledgerPath: `${statePath}${LEDGER_SUFFIX}` };
1026
+ }
1027
+ function assertContainedInStateRoot(stateRoot, target) {
1028
+ const root = resolve(stateRoot);
1029
+ const rel = relative(root, target);
1030
+ if (rel.startsWith("..")) {
1031
+ throw new Error(`goal persistence path escapes the state root and is refused: ${target}`);
1032
+ }
1033
+ const rootParent = dirname(root);
1034
+ if (root !== rootParent) {
1035
+ let rootIsSymlink = false;
1036
+ try {
1037
+ rootIsSymlink = lstatSync(root).isSymbolicLink();
1038
+ } catch {}
1039
+ if (rootIsSymlink) {
1040
+ throw new Error(`refusing goal persistence: the state root itself is a symlink (${root}), so goal state would ` + "be written outside it. Point `stateRoot` at a real directory.");
1041
+ }
1042
+ }
1043
+ if (rel === "")
1044
+ return;
1045
+ let cursor = root;
1046
+ for (const segment of rel.split(sep).filter((s) => s.length > 0)) {
1047
+ cursor = join(cursor, segment);
1048
+ let info;
1049
+ try {
1050
+ info = lstatSync(cursor);
1051
+ } catch {
1052
+ break;
1053
+ }
1054
+ if (info.isSymbolicLink()) {
1055
+ throw new Error(`refusing goal persistence through a symlinked path segment: ${cursor}`);
1056
+ }
1057
+ }
1058
+ }
1059
+ async function ensureSessionDir(stateRoot, sessionID) {
1060
+ const { mkdir } = await import("fs/promises");
1061
+ const { sessionDir } = sessionStatePaths(stateRoot, sessionID);
1062
+ assertContainedInStateRoot(stateRoot, sessionDir);
1063
+ await mkdir(sessionDir, { recursive: true, mode: 448 });
1064
+ return sessionDir;
1065
+ }
1066
+ async function listSessionIDs(stateRoot) {
1067
+ let entries;
1068
+ try {
1069
+ const { readdir } = await import("fs/promises");
1070
+ entries = await readdir(join(stateRoot, SESSIONS_DIRNAME), {
1071
+ withFileTypes: true
1072
+ });
1073
+ } catch {
1074
+ return [];
1075
+ }
1076
+ return entries.filter((entry) => entry.isDirectory() && SESSION_ID_PATTERN.test(entry.name)).map((entry) => entry.name).sort();
1077
+ }
1078
+
1079
+ // src/tui-disk-state.ts
1080
+ function resolveStateRoot(directory, stateRoot) {
1081
+ const configured = stateRoot ?? process.env.FIXATE_ON_STATE_ROOT;
1082
+ return resolve2(directory ? resolve2(directory) : process.cwd(), configured ?? DEFAULT_STATE_ROOT);
1083
+ }
1084
+ function sessionIDFromStatePath(path) {
1085
+ const parts = path.split(/[\\/]/);
1086
+ const idx = parts.lastIndexOf(SESSIONS_DIRNAME);
1087
+ if (idx < 0 || idx + 1 >= parts.length - 1)
1088
+ return;
1089
+ return parts[idx + 1];
1090
+ }
1091
+ async function discoverStateFiles(directory, explicitPath, stateRoot) {
1092
+ const { readdir, stat } = await import("fs/promises");
1093
+ const { join } = await import("path");
1094
+ if (explicitPath) {
1095
+ const direct = resolve2(explicitPath);
1096
+ try {
1097
+ return (await stat(direct)).isFile() ? [direct] : [];
1098
+ } catch {
1099
+ return [];
1100
+ }
1101
+ }
1102
+ const sessionsRoot = join(resolveStateRoot(directory, stateRoot), SESSIONS_DIRNAME);
1103
+ try {
1104
+ const entries = await readdir(sessionsRoot, { withFileTypes: true });
1105
+ return entries.filter((entry) => entry.isDirectory() && SESSION_ID_PATTERN.test(entry.name)).map((entry) => join(sessionsRoot, entry.name, STATE_FILENAME)).sort();
1106
+ } catch {
1107
+ return [];
1108
+ }
1109
+ }
1110
+ async function hydrateStoreFromDisk(store, directory, explicitPath, stateRoot) {
1111
+ const foundPaths = await discoverStateFiles(directory, explicitPath, stateRoot);
1112
+ let hydratedCount = 0;
1113
+ for (const foundPath of foundPaths) {
1114
+ const count = await hydrateFromStateFile(store, foundPath);
1115
+ hydratedCount += count;
1116
+ }
1117
+ return { hydratedCount };
1118
+ }
1119
+ async function hydrateFromStateFile(store, filePath) {
1120
+ try {
1121
+ const { text, truncated } = await portableReadBounded(filePath);
1122
+ if (truncated)
1123
+ return 0;
1124
+ if (!text.trim())
1125
+ return 0;
1126
+ const parsed = parseStateJson(text);
1127
+ if (!parsed)
1128
+ return 0;
1129
+ const snapshots = snapshotsFromParsed(parsed, sessionIDFromStatePath(filePath));
1130
+ for (const snapshot of snapshots) {
1131
+ store.applyEvent({
1132
+ kind: "create",
1133
+ sessionID: snapshot.sessionID,
1134
+ goalId: snapshot.goalId,
1135
+ snapshot: { ...snapshot, origin: "disk" },
1136
+ timestamp: Date.now()
1137
+ });
1138
+ }
1139
+ return snapshots.length;
1140
+ } catch {
1141
+ return 0;
1142
+ }
1143
+ }
1144
+ function parseStateJson(content) {
1145
+ try {
1146
+ return JSON.parse(content);
1147
+ } catch {
1148
+ return null;
1149
+ }
1150
+ }
1151
+ function snapshotsFromParsed(parsed, originSessionID) {
1152
+ const rawGoals = Array.isArray(parsed?.goals) ? parsed.goals : [];
1153
+ const out = [];
1154
+ for (const g of rawGoals) {
1155
+ if (!g || typeof g !== "object" || !g.goalId || !g.sessionID)
1156
+ continue;
1157
+ const r = g;
1158
+ if (originSessionID !== undefined && String(r.sessionID) !== originSessionID)
1159
+ continue;
1160
+ out.push({
1161
+ goalId: String(r.goalId),
1162
+ sessionID: String(r.sessionID),
1163
+ condition: String(r.condition ?? ""),
1164
+ artifactPointers: Array.isArray(r.artifactPointers) ? [...r.artifactPointers] : [],
1165
+ pendingProposal: r.pendingProposal ? {
1166
+ ...r.pendingProposal
1167
+ } : null,
1168
+ claims: Array.isArray(r.claims) ? r.claims.map((c) => ({
1169
+ ...c
1170
+ })) : [],
1171
+ lastClaim: r.lastClaim ? { ...r.lastClaim } : null,
1172
+ status: VALID_GOAL_STATUSES.has(String(r.status)) ? r.status : "active",
1173
+ revision: typeof r.revision === "number" ? r.revision : 0,
1174
+ turnCount: typeof r.turnCount === "number" ? r.turnCount : 0,
1175
+ totalTokens: typeof r.totalTokens === "number" ? r.totalTokens : 0,
1176
+ maxTokens: typeof r.maxTokens === "number" ? r.maxTokens : 1e6,
1177
+ maxTurns: typeof r.maxTurns === "number" ? r.maxTurns : 0,
1178
+ tokenBudget: typeof r.tokenBudget === "number" ? r.tokenBudget : null,
1179
+ usage: r.usage ?? {
1180
+ input: 0,
1181
+ output: 0,
1182
+ reasoning: 0,
1183
+ cacheRead: 0,
1184
+ cacheWrite: 0,
1185
+ cost: 0,
1186
+ costKnown: false
1187
+ },
1188
+ stopReason: String(r.stopReason ?? ""),
1189
+ blockedReason: String(r.blockedReason ?? ""),
1190
+ pausedAt: typeof r.pausedAt === "number" && Number.isFinite(r.pausedAt) && r.pausedAt > 0 ? r.pausedAt : 0,
1191
+ stoppedAt: typeof r.stoppedAt === "number" && Number.isFinite(r.stoppedAt) && r.stoppedAt > 0 ? r.stoppedAt : 0,
1192
+ createdAt: typeof r.createdAt === "number" ? r.createdAt : Date.now(),
1193
+ updatedAt: typeof r.updatedAt === "number" ? r.updatedAt : Date.now(),
1194
+ finishedAt: typeof r.finishedAt === "number" ? r.finishedAt : null,
1195
+ lastCheckpoint: r.lastCheckpoint ? {
1196
+ summary: String(r.lastCheckpoint.summary),
1197
+ timestamp: Number(r.lastCheckpoint.timestamp)
1198
+ } : null,
1199
+ history: Array.isArray(r.history) ? r.history.map((h) => ({
1200
+ type: String(h.type ?? ""),
1201
+ detail: String(h.detail ?? ""),
1202
+ timestamp: Number(h.timestamp ?? 0)
1203
+ })) : []
1204
+ });
1205
+ }
1206
+ return out;
1207
+ }
1208
+ async function readDiskGoalSnapshots(directory, explicitPath, stateRoot) {
1209
+ const { join } = await import("path");
1210
+ const foundPaths = await discoverStateFiles(directory, explicitPath, stateRoot);
1211
+ const out = [];
1212
+ const readableSessions = new Set;
1213
+ let filesRead = 0;
1214
+ for (const p of foundPaths) {
1215
+ try {
1216
+ const { text, truncated } = await portableReadBounded(p);
1217
+ if (truncated)
1218
+ continue;
1219
+ if (!text.trim())
1220
+ continue;
1221
+ const parsed = parseStateJson(text);
1222
+ if (!parsed)
1223
+ continue;
1224
+ filesRead += 1;
1225
+ const pathSession = sessionIDFromStatePath(p);
1226
+ if (pathSession)
1227
+ readableSessions.add(pathSession);
1228
+ const snaps = snapshotsFromParsed(parsed, pathSession);
1229
+ for (const s of snaps)
1230
+ readableSessions.add(s.sessionID);
1231
+ out.push(...snaps);
1232
+ } catch {}
1233
+ }
1234
+ let stateDirMissing = false;
1235
+ try {
1236
+ const { stat } = await import("fs/promises");
1237
+ if (explicitPath) {
1238
+ stateDirMissing = false;
1239
+ } else {
1240
+ await stat(join(resolveStateRoot(directory, stateRoot), SESSIONS_DIRNAME));
1241
+ }
1242
+ } catch {
1243
+ stateDirMissing = true;
1244
+ }
1245
+ return { snapshots: out, filesRead, stateDirMissing, readableSessions };
1246
+ }
1247
+
1248
+ // src/tui-companion-refresh.ts
1249
+ function keyOf(sessionID, goalId) {
1250
+ return `${sessionID}\x00${goalId}`;
1251
+ }
1252
+ function createDiskRefreshLoop(options) {
1253
+ const { store, onEvent } = options;
1254
+ const intervalMs = options.intervalMs ?? 1000;
1255
+ let timer = null;
1256
+ let ticking = false;
1257
+ let baselined = false;
1258
+ let previous = new Map;
1259
+ function synthesize(current, readableSessions) {
1260
+ const events = [];
1261
+ const seen = new Set;
1262
+ for (const snap of current) {
1263
+ const key = keyOf(snap.sessionID, snap.goalId);
1264
+ seen.add(key);
1265
+ const prev = previous.get(key);
1266
+ if (!prev) {
1267
+ events.push({
1268
+ kind: "create",
1269
+ sessionID: snap.sessionID,
1270
+ timestamp: Date.now(),
1271
+ snapshot: { ...snap, origin: "disk" }
1272
+ });
1273
+ } else if (prev.revision !== snap.revision || prev.status !== snap.status || prev.totalTokens !== snap.totalTokens || prev.turnCount !== snap.turnCount) {
1274
+ events.push({
1275
+ kind: "transition",
1276
+ sessionID: snap.sessionID,
1277
+ timestamp: Date.now(),
1278
+ snapshot: { ...snap, origin: "disk" },
1279
+ previousStatus: prev.status
1280
+ });
1281
+ }
1282
+ }
1283
+ for (const [key, prev] of previous) {
1284
+ if (seen.has(key))
1285
+ continue;
1286
+ if (!readableSessions.has(prev.sessionID))
1287
+ continue;
1288
+ events.push({
1289
+ kind: "remove",
1290
+ sessionID: prev.sessionID,
1291
+ goalId: prev.goalId,
1292
+ timestamp: Date.now()
1293
+ });
1294
+ }
1295
+ return events;
1296
+ }
1297
+ async function tick() {
1298
+ if (ticking)
1299
+ return;
1300
+ ticking = true;
1301
+ try {
1302
+ const read = await readDiskGoalSnapshots(options.directory, options.explicitPath, options.stateRoot);
1303
+ if (!baselined) {
1304
+ if (read.filesRead === 0 && !read.stateDirMissing)
1305
+ return;
1306
+ baselined = true;
1307
+ previous = new Map(read.snapshots.map((s) => [keyOf(s.sessionID, s.goalId), s]));
1308
+ return;
1309
+ }
1310
+ if (read.filesRead === 0 && previous.size > 0)
1311
+ return;
1312
+ for (const event of synthesize(read.snapshots, read.readableSessions)) {
1313
+ if (event.snapshot || event.goalId)
1314
+ store.applyEvent(event);
1315
+ onEvent(event);
1316
+ }
1317
+ const oldPrevious = previous;
1318
+ previous = new Map(read.snapshots.map((s) => [keyOf(s.sessionID, s.goalId), s]));
1319
+ for (const [key, snap] of oldPrevious) {
1320
+ if (!read.readableSessions.has(snap.sessionID) && !previous.has(key)) {
1321
+ previous.set(key, snap);
1322
+ }
1323
+ }
1324
+ } catch {} finally {
1325
+ ticking = false;
1326
+ }
1327
+ }
1328
+ return {
1329
+ tick,
1330
+ seedBaseline(snapshots) {
1331
+ baselined = true;
1332
+ previous = new Map(snapshots.map((s) => [keyOf(s.sessionID, s.goalId), s]));
1333
+ },
1334
+ start() {
1335
+ if (timer)
1336
+ return;
1337
+ if (!baselined)
1338
+ tick();
1339
+ timer = setInterval(() => void tick(), intervalMs);
1340
+ if (typeof timer === "object" && timer !== null && "unref" in timer) {
1341
+ timer.unref();
1342
+ }
1343
+ },
1344
+ stop() {
1345
+ if (timer) {
1346
+ clearInterval(timer);
1347
+ timer = null;
1348
+ }
1349
+ }
1350
+ };
1351
+ }
1352
+
1353
+ // src/tui-action-labels.ts
1354
+ var MUTATING_ROOTS = new Set([
1355
+ "pause",
1356
+ "resume",
1357
+ "clear",
1358
+ "edit",
1359
+ "checkpoint",
1360
+ "focus",
1361
+ "add",
1362
+ "sequence",
1363
+ "accept",
1364
+ "reject",
1365
+ "handback",
1366
+ "review-payload"
1367
+ ]);
1368
+ function isMutatingGoalCommand(command) {
1369
+ const root = command.trim().split(/\s+/)[0];
1370
+ return MUTATING_ROOTS.has(root);
1371
+ }
1372
+ function outcomeNeutralLabel(command) {
1373
+ const root = command.trim().split(/\s+/)[0];
1374
+ return `Goal requested: ${root}`;
1375
+ }
1376
+ function watchdogTimeoutMessage(host, command, timeoutMs) {
1377
+ const seconds = Math.round(timeoutMs / 1000);
1378
+ const shown = seconds < 1 ? "<1s" : `${seconds}s`;
1379
+ const root = command.trim().split(/\s+/)[0];
1380
+ const retry = host === "v1" ? `Retry from the Goal palette or /goal ${root}.` : "Retry from the Goal palette.";
1381
+ return `Goal action "${root}" did not land within ${shown}. ${retry}`;
1382
+ }
1383
+ var DEGRADED_MODE_MESSAGE = `${PRODUCT_DISPLAY_NAME} is not loaded: actions from this palette cannot take effect. ` + "Check the server plugin loaded, then reopen this palette.";
1384
+ function createDegradedModeDetector() {
1385
+ let surfaceAlive = false;
1386
+ let announcedThisEpisode = false;
1387
+ return {
1388
+ noteSurfaceAlive() {
1389
+ surfaceAlive = true;
1390
+ announcedThisEpisode = false;
1391
+ },
1392
+ checkDispatch() {
1393
+ if (surfaceAlive || announcedThisEpisode)
1394
+ return null;
1395
+ announcedThisEpisode = true;
1396
+ return DEGRADED_MODE_MESSAGE;
1397
+ },
1398
+ get isDegraded() {
1399
+ return !surfaceAlive;
1400
+ }
1401
+ };
1402
+ }
1403
+ function createGoalWatchdogs(host, notifyTimeout, defaultTimeoutMs = 15000) {
1404
+ const active = new Map;
1405
+ const keyOf = (sessionID, command) => `${sessionID}:${command.trim().split(/\s+/)[0]}`;
1406
+ return {
1407
+ arm(sessionID, command, timeoutMs = defaultTimeoutMs) {
1408
+ const key = keyOf(sessionID, command);
1409
+ const existing = active.get(key);
1410
+ if (existing)
1411
+ clearTimeout(existing.timer);
1412
+ const timer = setTimeout(() => {
1413
+ active.delete(key);
1414
+ notifyTimeout(watchdogTimeoutMessage(host, command, timeoutMs));
1415
+ }, timeoutMs);
1416
+ active.set(key, { timer, command, sessionID });
1417
+ },
1418
+ disarmSession(sessionID) {
1419
+ for (const [key, w] of active.entries()) {
1420
+ if (w.sessionID === sessionID) {
1421
+ clearTimeout(w.timer);
1422
+ active.delete(key);
1423
+ }
1424
+ }
1425
+ },
1426
+ cancel(sessionID, command) {
1427
+ const key = keyOf(sessionID, command);
1428
+ const w = active.get(key);
1429
+ if (w) {
1430
+ clearTimeout(w.timer);
1431
+ active.delete(key);
1432
+ }
1433
+ },
1434
+ get armedCount() {
1435
+ return active.size;
1436
+ }
1437
+ };
1438
+ }
1439
+
1440
+ // src/tui-toast-policy.ts
1441
+ init_status_label();
1442
+ var TOAST_MESSAGE_MAX = 120;
1443
+ var REMEMBERED_LIMIT = 4096;
1444
+ var TOAST_MIN_INTERVAL_MS = 2000;
1445
+ var TOAST_COALESCE_WINDOW_MS = 500;
1446
+ var TOAST_QUEUE_MAX = 3;
1447
+ var BRIEFING_SESSION_KEY = "\x00briefing";
1448
+ function truncateCondition(text, max = 60) {
1449
+ const clean = text.replace(/\s+/g, " ").trim();
1450
+ if (clean.length <= max)
1451
+ return clean;
1452
+ const cut = clean.slice(0, max);
1453
+ const lastSpace = cut.lastIndexOf(" ");
1454
+ return `${(lastSpace > max * 0.5 ? cut.slice(0, lastSpace) : cut).trimEnd()}\u2026`;
1455
+ }
1456
+ function shouldToast(event) {
1457
+ switch (event.kind) {
1458
+ case "create":
1459
+ return true;
1460
+ case "remove":
1461
+ return true;
1462
+ case "usage":
1463
+ return false;
1464
+ case "transition":
1465
+ return lifecycleSide(event) !== null;
1466
+ default:
1467
+ return false;
1468
+ }
1469
+ }
1470
+ function lifecycleSide(event) {
1471
+ const status = event.snapshot?.status;
1472
+ if (!status)
1473
+ return null;
1474
+ const from = previousStatusOf(event);
1475
+ if (from !== undefined && from === status)
1476
+ return null;
1477
+ if (from === undefined) {
1478
+ return status === "active" || status === "finalizing" ? null : "stop";
1479
+ }
1480
+ if (status === "complete" || status === "blocked")
1481
+ return "stop";
1482
+ if (status === "active")
1483
+ return "start";
1484
+ if (STOPPED_STATUSES.has(status)) {
1485
+ return SELF_RESOLVING_STOP_REASONS.has(event.snapshot?.stopReason ?? "") ? null : "stop";
1486
+ }
1487
+ return null;
1488
+ }
1489
+ function previousStatusOf(event) {
1490
+ return event.previousStatus ?? event.transition?.from;
1491
+ }
1492
+ var STOPPED_STATUSES = new Set([
1493
+ "paused",
1494
+ "blocked",
1495
+ "budgetLimited",
1496
+ "complete"
1497
+ ]);
1498
+ function isLimitOrEscalationPause(stopReason) {
1499
+ return /recovery exhausted|escalated|max turns|max stall|max context tokens|budget/i.test(stopReason);
1500
+ }
1501
+ var LIMIT_PAUSE_PHRASES = [
1502
+ [/max turns/i, "Goal stopped \u2014 it reached its turn limit"],
1503
+ [/max stall/i, "Goal stopped \u2014 it ran for its time limit without finishing"],
1504
+ [/max context tokens/i, "Goal stopped \u2014 it reached its context limit"],
1505
+ [/budget/i, "Goal stopped \u2014 its token budget ran out"],
1506
+ [
1507
+ /recovery exhausted/i,
1508
+ "Goal paused after repeated failures \u2014 review needed"
1509
+ ],
1510
+ [/escalated/i, "Goal escalated \u2014 it needs you to decide how to continue"]
1511
+ ];
1512
+ function limitPausePhrase(stopReason) {
1513
+ for (const [pattern, phrase] of LIMIT_PAUSE_PHRASES) {
1514
+ if (pattern.test(stopReason))
1515
+ return phrase;
1516
+ }
1517
+ return isLimitOrEscalationPause(stopReason) ? "Goal stopped by a limit it reached" : null;
1518
+ }
1519
+ var YIELDING_STOP_REASONS = new Set([
1520
+ USER_INTERVENTION_STOP_REASON
1521
+ ]);
1522
+ var NEEDS_YOU_PHRASES = [
1523
+ [/tool surface unavailable/i, "the goal tools are gone"],
1524
+ [
1525
+ /verifier:\s*(COMPLETE|NEEDS_INPUT|CANCELLED|BLOCKED|WORKING)/i,
1526
+ "a verifier stopped it"
1527
+ ],
1528
+ [
1529
+ /unattested completion asserted repeatedly|no attestation/i,
1530
+ "the claim could not be attested"
1531
+ ],
1532
+ [/judge rejected/i, "the judge rejected the claim"],
1533
+ [/permission rejected/i, "a permission was rejected"],
1534
+ [/session error/i, "a session error"],
1535
+ [/execution (failure|interrupted)|message aborted/i, "an execution error"],
1536
+ [/no tool calls/i, "no tool calls"],
1537
+ [/no progress/i, "no progress"],
1538
+ [/deferred too many times/i, "deferred too many times"],
1539
+ [/compaction loop/i, "the session is stuck compacting"],
1540
+ [/^(paused|explicit pause)$/i, "paused"],
1541
+ [/blocked/i, "blocked"]
1542
+ ];
1543
+ var MACHINE_STRING = /[()]|\w+:|[a-z][A-Z]|_/;
1544
+ function needsYouReason(stopReason) {
1545
+ for (const [pattern, phrase] of NEEDS_YOU_PHRASES) {
1546
+ if (pattern.test(stopReason))
1547
+ return phrase;
1548
+ }
1549
+ const clean = stopReason.trim();
1550
+ if (clean === "" || MACHINE_STRING.test(clean))
1551
+ return "stopped for a reason the plugin did not name";
1552
+ return truncateCondition(clean);
1553
+ }
1554
+ function goalNeedsTheUser(snapshot, now) {
1555
+ const status = snapshot.status;
1556
+ if (status === "active" || status === "finalizing" || status === "complete")
1557
+ return false;
1558
+ if (isSelfResolvingStop(status, snapshot.stopReason, snapshot.stoppedAt, now ?? Date.now(), snapshot.updatedAt))
1559
+ return false;
1560
+ return true;
1561
+ }
1562
+ function reasonForGoal(snapshot, now) {
1563
+ if (snapshot.status === "blocked") {
1564
+ return snapshot.blockedReason ? truncateCondition(snapshot.blockedReason, 40) : "blocked";
1565
+ }
1566
+ if (isYieldingPause(snapshot.status, snapshot.stopReason) && !isLiveYield(snapshot.status, snapshot.stopReason, snapshot.stoppedAt, now ?? Date.now(), snapshot.updatedAt)) {
1567
+ return "it did not pick your message back up";
1568
+ }
1569
+ if (snapshot.status === "budgetLimited" && !snapshot.stopReason)
1570
+ return "the token budget ran out";
1571
+ return needsYouReason(snapshot.stopReason);
1572
+ }
1573
+ function summarizeGoalsNeedingYou(snapshots) {
1574
+ const counts = new Map;
1575
+ let total = 0;
1576
+ for (const snapshot of snapshots) {
1577
+ if (!goalNeedsTheUser(snapshot))
1578
+ continue;
1579
+ const reason = reasonForGoal(snapshot);
1580
+ counts.set(reason, (counts.get(reason) ?? 0) + 1);
1581
+ total += 1;
1582
+ }
1583
+ if (total === 0)
1584
+ return null;
1585
+ const ordered = [...counts.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
1586
+ const goalWord = total === 1 ? "1 goal needs you" : `${total} goals need you`;
1587
+ const budget = TOAST_MESSAGE_MAX - 1;
1588
+ const compose = (parts, dropped) => {
1589
+ const list = parts.map(([reason, count]) => count > 1 ? `${count} ${reason}` : reason).join(", ");
1590
+ const tail = dropped > 0 ? `, +${dropped} more` : "";
1591
+ const text = `${goalWord}: ${list}${tail}`;
1592
+ return text.length <= TOAST_MESSAGE_MAX ? text : `${text.slice(0, TOAST_MESSAGE_MAX - 1)}\u2026`;
1593
+ };
1594
+ let kept = ordered;
1595
+ let dropped = 0;
1596
+ while (kept.length > 1 && compose(kept, 0).length > budget) {
1597
+ const removed = kept[kept.length - 1];
1598
+ dropped += removed[1];
1599
+ kept = kept.slice(0, -1);
1600
+ }
1601
+ return {
1602
+ title: PRODUCT_DISPLAY_NAME,
1603
+ variant: "warning",
1604
+ message: compose(kept, dropped)
1605
+ };
1606
+ }
1607
+ var CLAIM_PLAIN = {
1608
+ "verified-complete": "attested",
1609
+ "unverifiable-claim": "completed, but no attestation could be obtained",
1610
+ "claim-refuted": "claimed done, but the evidence said otherwise",
1611
+ "blocked-acknowledged": "stopped with a known blocker"
1612
+ };
1613
+ function formatCuratedToast(event, startAnnouncement = true) {
1614
+ const condition = truncateCondition(event.snapshot?.condition ?? "goal");
1615
+ switch (event.kind) {
1616
+ case "create":
1617
+ return {
1618
+ title: PRODUCT_DISPLAY_NAME,
1619
+ variant: "info",
1620
+ message: `Goal started: ${condition}`
1621
+ };
1622
+ case "remove":
1623
+ return {
1624
+ title: PRODUCT_DISPLAY_NAME,
1625
+ variant: "info",
1626
+ message: `Goal cleared: ${truncateCondition(event.snapshot?.condition ?? event.goalId ?? "goal")}`
1627
+ };
1628
+ case "transition": {
1629
+ const status = event.snapshot?.status;
1630
+ if (status === "complete") {
1631
+ const outcomeStatus = event.snapshot?.lastClaim?.outcome.status;
1632
+ const suffix = outcomeStatus && outcomeStatus !== "verified-complete" ? ` (${CLAIM_PLAIN[outcomeStatus] ?? outcomeStatus})` : "";
1633
+ return {
1634
+ title: PRODUCT_DISPLAY_NAME,
1635
+ variant: "info",
1636
+ message: `Goal complete: ${condition}${suffix}`
1637
+ };
1638
+ }
1639
+ if (status === "blocked") {
1640
+ const reason = truncateCondition(event.snapshot?.blockedReason ?? "needs your input");
1641
+ return {
1642
+ title: PRODUCT_DISPLAY_NAME,
1643
+ variant: "warning",
1644
+ message: `Paused \u2014 ${reason}`
1645
+ };
1646
+ }
1647
+ const limitPause = limitPausePhrase(event.snapshot?.stopReason ?? "");
1648
+ if (limitPause) {
1649
+ return {
1650
+ title: PRODUCT_DISPLAY_NAME,
1651
+ variant: "error",
1652
+ message: `${limitPause} (${condition})`
1653
+ };
1654
+ }
1655
+ if (status === "active" && startAnnouncement) {
1656
+ return {
1657
+ title: PRODUCT_DISPLAY_NAME,
1658
+ variant: "info",
1659
+ message: `Goal started: ${condition}`
1660
+ };
1661
+ }
1662
+ if (status === "active") {
1663
+ return {
1664
+ title: PRODUCT_DISPLAY_NAME,
1665
+ variant: "info",
1666
+ message: `Goal running again: ${condition}`
1667
+ };
1668
+ }
1669
+ if (status !== undefined && STOPPED_STATUSES.has(status)) {
1670
+ return {
1671
+ title: PRODUCT_DISPLAY_NAME,
1672
+ variant: "warning",
1673
+ message: `Goal stopped \u2014 ${needsYouReason(event.snapshot?.stopReason ?? "")} (${condition})`
1674
+ };
1675
+ }
1676
+ return {
1677
+ title: PRODUCT_DISPLAY_NAME,
1678
+ variant: "info",
1679
+ message: `Goal update: ${condition}`
1680
+ };
1681
+ }
1682
+ default:
1683
+ return {
1684
+ title: PRODUCT_DISPLAY_NAME,
1685
+ variant: "info",
1686
+ message: `Goal update: ${condition}`
1687
+ };
1688
+ }
1689
+ }
1690
+
1691
+ class ToastCoalescer {
1692
+ emit;
1693
+ now;
1694
+ autoFlushMs;
1695
+ queues = new Map;
1696
+ lastEmittedAt = new Map;
1697
+ lastMessageBySession = new Map;
1698
+ announced = new Set;
1699
+ yielding = new Set;
1700
+ pumpTimer = null;
1701
+ constructor(emit, now = Date.now, autoFlushMs = null) {
1702
+ this.emit = emit;
1703
+ this.now = now;
1704
+ this.autoFlushMs = autoFlushMs;
1705
+ }
1706
+ get queuedCount() {
1707
+ let total = 0;
1708
+ for (const queue of this.queues.values())
1709
+ total += queue.length;
1710
+ return total;
1711
+ }
1712
+ accept(event, sessionKey) {
1713
+ this.flush();
1714
+ const goalId = event.snapshot?.goalId;
1715
+ const memoryKey = goalId ? `${sessionKey}|${goalId}` : null;
1716
+ const side = lifecycleSide(event);
1717
+ if (memoryKey) {
1718
+ if (event.kind === "remove" && event.goalId) {
1719
+ this.announced.delete(memoryKey);
1720
+ this.yielding.delete(memoryKey);
1721
+ } else if (event.kind === "create") {
1722
+ this.claimStartAnnouncement(sessionKey, goalId);
1723
+ } else if (event.snapshot?.status === "paused" && YIELDING_STOP_REASONS.has(event.snapshot.stopReason)) {
1724
+ this.yielding.add(memoryKey);
1725
+ this.pruneRemembered();
1726
+ }
1727
+ }
1728
+ let firstTime = false;
1729
+ if (!shouldToast(event))
1730
+ return;
1731
+ if (side === "start" && memoryKey) {
1732
+ if (this.yielding.has(memoryKey)) {
1733
+ this.yielding.delete(memoryKey);
1734
+ return;
1735
+ }
1736
+ }
1737
+ if (side === "start" && goalId)
1738
+ firstTime = this.claimStartAnnouncement(sessionKey, goalId);
1739
+ this.enqueue(sessionKey, formatCuratedToast(event, firstTime), goalId);
1740
+ }
1741
+ brief(sessionKey, toast) {
1742
+ this.flush();
1743
+ this.enqueue(sessionKey, toast, undefined);
1744
+ }
1745
+ flush() {
1746
+ for (const [sessionKey, queue] of [...this.queues]) {
1747
+ while (queue.length > 0) {
1748
+ const nowTs = this.now();
1749
+ if (nowTs - this.emittedAtFor(sessionKey) < TOAST_MIN_INTERVAL_MS)
1750
+ break;
1751
+ const next = queue.shift();
1752
+ if (!next)
1753
+ break;
1754
+ this.emitNow(sessionKey, next, nowTs);
1755
+ }
1756
+ if (queue.length === 0)
1757
+ this.queues.delete(sessionKey);
1758
+ }
1759
+ }
1760
+ startAutoFlush() {
1761
+ if (this.pumpTimer || this.autoFlushMs === null)
1762
+ return;
1763
+ this.pumpTimer = setInterval(() => this.flush(), this.autoFlushMs);
1764
+ if (typeof this.pumpTimer === "object" && this.pumpTimer !== null && "unref" in this.pumpTimer) {
1765
+ this.pumpTimer.unref();
1766
+ }
1767
+ }
1768
+ stopAutoFlush() {
1769
+ if (this.pumpTimer) {
1770
+ clearInterval(this.pumpTimer);
1771
+ this.pumpTimer = null;
1772
+ }
1773
+ }
1774
+ claimStartAnnouncement(sessionKey, goalId) {
1775
+ if (!goalId)
1776
+ return true;
1777
+ const key = `${sessionKey}|${goalId}`;
1778
+ if (this.announced.has(key))
1779
+ return false;
1780
+ this.announced.add(key);
1781
+ this.pruneRemembered();
1782
+ return true;
1783
+ }
1784
+ pruneRemembered() {
1785
+ while (this.announced.size + this.yielding.size > REMEMBERED_LIMIT) {
1786
+ const oldest = this.announced.values().next();
1787
+ if (!oldest.done) {
1788
+ this.announced.delete(oldest.value);
1789
+ continue;
1790
+ }
1791
+ const oldestYield = this.yielding.values().next();
1792
+ if (oldestYield.done)
1793
+ return;
1794
+ this.yielding.delete(oldestYield.value);
1795
+ }
1796
+ }
1797
+ enqueue(sessionKey, toast, goalId) {
1798
+ const last = this.lastMessageBySession.get(sessionKey);
1799
+ if (last && toast.message === last.message && this.now() - last.at < TOAST_COALESCE_WINDOW_MS) {
1800
+ return;
1801
+ }
1802
+ this.lastMessageBySession.set(sessionKey, {
1803
+ message: toast.message,
1804
+ at: this.now()
1805
+ });
1806
+ const nowTs = this.now();
1807
+ if (nowTs - this.emittedAtFor(sessionKey) >= TOAST_MIN_INTERVAL_MS) {
1808
+ this.emitNow(sessionKey, toast, nowTs);
1809
+ return;
1810
+ }
1811
+ let queue = this.queues.get(sessionKey);
1812
+ if (!queue) {
1813
+ queue = [];
1814
+ this.queues.set(sessionKey, queue);
1815
+ }
1816
+ if (goalId) {
1817
+ const staleAt = queue.findIndex((queued) => queued.goalId === goalId);
1818
+ if (staleAt >= 0)
1819
+ queue.splice(staleAt, 1);
1820
+ }
1821
+ queue.push({ ...toast, goalId });
1822
+ if (queue.length > TOAST_QUEUE_MAX) {
1823
+ queue.shift();
1824
+ }
1825
+ }
1826
+ emittedAtFor(sessionKey) {
1827
+ return this.lastEmittedAt.get(sessionKey) ?? Number.NEGATIVE_INFINITY;
1828
+ }
1829
+ emitNow(sessionKey, toast, nowTs) {
1830
+ let final = toast;
1831
+ if (final.message.length > TOAST_MESSAGE_MAX) {
1832
+ final = {
1833
+ ...final,
1834
+ message: `${final.message.slice(0, TOAST_MESSAGE_MAX - 1)}\u2026`
1835
+ };
1836
+ }
1837
+ this.lastEmittedAt.set(sessionKey, nowTs);
1838
+ const { goalId: _goalId, ...visible } = final;
1839
+ this.emit(visible);
1840
+ }
1841
+ }
1842
+
1843
+ // src/tui.ts
1844
+ init_tui_views();
1845
+
1846
+ // src/tui-sound.ts
1847
+ function soundForEvent(kind, status) {
1848
+ switch (kind) {
1849
+ case "create":
1850
+ return "default";
1851
+ case "transition":
1852
+ switch (status) {
1853
+ case "complete":
1854
+ return "done";
1855
+ case "paused":
1856
+ return "question";
1857
+ case "blocked":
1858
+ return "question";
1859
+ case "budgetLimited":
1860
+ return "error";
1861
+ case "active":
1862
+ return "default";
1863
+ case "finalizing":
1864
+ return;
1865
+ default:
1866
+ return;
1867
+ }
1868
+ case "usage":
1869
+ return;
1870
+ case "remove":
1871
+ return;
1872
+ default:
1873
+ return;
1874
+ }
1875
+ }
1876
+
1877
+ // src/tui.ts
1878
+ var GOAL_PREFIX = "ctrl+shift+g";
1879
+ function chord(actionKey) {
1880
+ return `${GOAL_PREFIX} ${actionKey}`;
1881
+ }
1882
+ var GoalTuiPlugin = async (api, options, _meta) => {
1883
+ const opts = {
1884
+ logLevel: options?.logLevel ?? "info",
1885
+ directory: options?.directory,
1886
+ stateRoot: options?.stateRoot
1887
+ };
1888
+ const store = createTuiStateStore();
1889
+ const activeSessionID = () => {
1890
+ const route = api.route.current;
1891
+ if (route.name !== "session" || !route.params || typeof route.params.sessionID !== "string") {
1892
+ return null;
1893
+ }
1894
+ return route.params.sessionID;
1895
+ };
1896
+ const log = (level, message) => {
1897
+ if (opts.logLevel === "error" && level !== "error")
1898
+ return;
1899
+ if (opts.logLevel === "info" && level === "debug")
1900
+ return;
1901
+ try {
1902
+ if (level === "error") {
1903
+ api.ui.toast({
1904
+ variant: "error",
1905
+ title: PRODUCT_DISPLAY_NAME,
1906
+ message,
1907
+ duration: 6000
1908
+ });
1909
+ }
1910
+ console[level === "error" ? "error" : "log"](`[${GOAL_TUI_EVENT_TITLE}/tui] ${message}`);
1911
+ } catch {}
1912
+ };
1913
+ const degraded = createDegradedModeDetector();
1914
+ const watchdogs = createGoalWatchdogs("v1", (message) => {
1915
+ api.ui.toast({
1916
+ variant: "warning",
1917
+ title: PRODUCT_DISPLAY_NAME,
1918
+ message: degraded.checkDispatch() ?? message,
1919
+ duration: 8000
1920
+ });
1921
+ });
1922
+ store.subscribe((event) => {
1923
+ degraded.noteSurfaceAlive();
1924
+ watchdogs.disarmSession(event.sessionID);
1925
+ });
1926
+ const sendGoalCommand = async (command) => {
1927
+ let sessionID = activeSessionID();
1928
+ if (!sessionID) {
1929
+ try {
1930
+ const created = await api.client.session.create({});
1931
+ const data = created ?? {};
1932
+ const newID = typeof data.data?.id === "string" ? data.data.id : typeof data.id === "string" ? data.id : "";
1933
+ if (newID) {
1934
+ sessionID = newID;
1935
+ api.ui.toast({
1936
+ variant: "info",
1937
+ title: PRODUCT_DISPLAY_NAME,
1938
+ message: "Started a new session for the goal."
1939
+ });
1940
+ }
1941
+ } catch {}
1942
+ }
1943
+ if (!sessionID) {
1944
+ api.ui.toast({
1945
+ variant: "warning",
1946
+ title: PRODUCT_DISPLAY_NAME,
1947
+ message: "Open a session before controlling a goal."
1948
+ });
1949
+ return;
1950
+ }
1951
+ try {
1952
+ await api.client.session.command({
1953
+ sessionID,
1954
+ command: "goal",
1955
+ arguments: command
1956
+ });
1957
+ if (isMutatingGoalCommand(command)) {
1958
+ watchdogs.arm(sessionID, command);
1959
+ }
1960
+ } catch (error) {
1961
+ api.ui.toast({
1962
+ variant: "error",
1963
+ title: PRODUCT_DISPLAY_NAME,
1964
+ message: `Command failed: ${error instanceof Error ? error.message : String(error)}`
1965
+ });
1966
+ }
1967
+ };
1968
+ const getCockpitSnapshots = () => {
1969
+ const sessionID = activeSessionID();
1970
+ let snaps = sessionID ? store.getSnapshots(sessionID) : [];
1971
+ if (snaps.length === 0) {
1972
+ snaps = store.getAllSnapshots().filter((s) => s.origin === "disk");
1973
+ }
1974
+ return snaps;
1975
+ };
1976
+ const dashboardSections = () => {
1977
+ return formatGoalStatusDashboard(getCockpitSnapshots(), activeSessionID());
1978
+ };
1979
+ const dashboardMessage = () => {
1980
+ return dashboardSections().map((section) => `${section.title}
1981
+ ${section.text}`).join(`
1982
+
1983
+ `);
1984
+ };
1985
+ const formatGoalDetail = (snap) => {
1986
+ const sections = formatGoalStatusDashboard([snap], activeSessionID());
1987
+ return sections.map((s) => `${s.title}
1988
+ ${s.text}`).join(`
1989
+
1990
+ `);
1991
+ };
1992
+ let dashboardUnsubscribe = null;
1993
+ let cockpitGeneration = 0;
1994
+ const cleanupCockpit = () => {
1995
+ if (dashboardUnsubscribe) {
1996
+ try {
1997
+ dashboardUnsubscribe();
1998
+ } catch {}
1999
+ dashboardUnsubscribe = null;
2000
+ }
2001
+ };
2002
+ const CHAIN_REOPEN_MS = 30;
2003
+ const chainReplace = (render, onClose) => {
2004
+ api.ui.dialog.clear();
2005
+ setTimeout(() => {
2006
+ api.ui.dialog.replace(render, onClose);
2007
+ }, CHAIN_REOPEN_MS);
2008
+ };
2009
+ const showGoalActions = (goalId, gen) => {
2010
+ if (gen !== cockpitGeneration)
2011
+ return;
2012
+ const actions = [
2013
+ { title: "Pause", value: "pause", description: "Pause this goal" },
2014
+ { title: "Resume", value: "resume", description: "Resume this goal" },
2015
+ { title: "Focus", value: "focus", description: "Focus this goal" },
2016
+ {
2017
+ title: "Edit Objective",
2018
+ value: "edit",
2019
+ description: "Change the objective"
2020
+ },
2021
+ {
2022
+ title: "Checkpoint",
2023
+ value: "checkpoint",
2024
+ description: "Save a checkpoint"
2025
+ },
2026
+ { title: "Clear", value: "clear", description: "Clear this goal" },
2027
+ {
2028
+ title: "\u2190 Back to Goals",
2029
+ value: "back",
2030
+ description: "Return to goal list"
2031
+ }
2032
+ ];
2033
+ chainReplace(() => api.ui.DialogSelect({
2034
+ title: `Actions: ${goalId.substring(0, 8)}`,
2035
+ options: actions,
2036
+ onSelect: (option) => {
2037
+ if (gen !== cockpitGeneration)
2038
+ return;
2039
+ switch (option.value) {
2040
+ case "pause":
2041
+ sendGoalCommand(`pause ${goalId}`);
2042
+ api.ui.toast({
2043
+ variant: "info",
2044
+ title: PRODUCT_DISPLAY_NAME,
2045
+ message: outcomeNeutralLabel("pause")
2046
+ });
2047
+ showGoalDetail(goalId, gen);
2048
+ break;
2049
+ case "resume":
2050
+ sendGoalCommand(`resume ${goalId}`);
2051
+ api.ui.toast({
2052
+ variant: "info",
2053
+ title: PRODUCT_DISPLAY_NAME,
2054
+ message: outcomeNeutralLabel("resume")
2055
+ });
2056
+ showGoalDetail(goalId, gen);
2057
+ break;
2058
+ case "focus":
2059
+ sendGoalCommand(`focus ${goalId}`);
2060
+ api.ui.toast({
2061
+ variant: "info",
2062
+ title: PRODUCT_DISPLAY_NAME,
2063
+ message: outcomeNeutralLabel(`focus ${goalId}`)
2064
+ });
2065
+ showGoalDetail(goalId, gen);
2066
+ break;
2067
+ case "edit":
2068
+ chainReplace(() => api.ui.DialogPrompt({
2069
+ title: "Edit Goal",
2070
+ placeholder: "Updated objective",
2071
+ onConfirm: (objective) => {
2072
+ api.ui.dialog.clear();
2073
+ if (!objective) {
2074
+ showGoalActions(goalId, gen);
2075
+ return;
2076
+ }
2077
+ sendGoalCommand(`edit ${goalId} ${objective}`);
2078
+ api.ui.toast({
2079
+ variant: "info",
2080
+ title: PRODUCT_DISPLAY_NAME,
2081
+ message: outcomeNeutralLabel("edit")
2082
+ });
2083
+ showGoalDetail(goalId, gen);
2084
+ }
2085
+ }));
2086
+ break;
2087
+ case "checkpoint":
2088
+ chainReplace(() => api.ui.DialogPrompt({
2089
+ title: "Save Checkpoint",
2090
+ placeholder: "Checkpoint summary",
2091
+ onConfirm: (summary) => {
2092
+ api.ui.dialog.clear();
2093
+ if (!summary) {
2094
+ showGoalActions(goalId, gen);
2095
+ return;
2096
+ }
2097
+ sendGoalCommand(`checkpoint ${goalId} ${summary}`);
2098
+ api.ui.toast({
2099
+ variant: "info",
2100
+ title: PRODUCT_DISPLAY_NAME,
2101
+ message: outcomeNeutralLabel("checkpoint")
2102
+ });
2103
+ showGoalDetail(goalId, gen);
2104
+ }
2105
+ }));
2106
+ break;
2107
+ case "clear":
2108
+ sendGoalCommand(`clear ${goalId}`);
2109
+ api.ui.toast({
2110
+ variant: "info",
2111
+ title: PRODUCT_DISPLAY_NAME,
2112
+ message: outcomeNeutralLabel("clear")
2113
+ });
2114
+ cleanupCockpit();
2115
+ api.ui.dialog.clear();
2116
+ break;
2117
+ case "back":
2118
+ showDashboard();
2119
+ break;
2120
+ }
2121
+ }
2122
+ }), () => {
2123
+ if (gen === cockpitGeneration)
2124
+ cleanupCockpit();
2125
+ });
2126
+ };
2127
+ const showGoalDetail = (goalId, gen) => {
2128
+ if (gen !== cockpitGeneration)
2129
+ return;
2130
+ const snaps = getCockpitSnapshots();
2131
+ const snap = snaps.find((s) => s.goalId === goalId);
2132
+ if (!snap) {
2133
+ showDashboard();
2134
+ return;
2135
+ }
2136
+ chainReplace(() => api.ui.DialogAlert({
2137
+ title: `Goal: ${goalId.substring(0, 8)}`,
2138
+ message: formatGoalDetail(snap),
2139
+ onConfirm: () => {
2140
+ if (gen === cockpitGeneration) {
2141
+ showGoalActions(goalId, gen);
2142
+ }
2143
+ }
2144
+ }), () => {
2145
+ if (gen === cockpitGeneration)
2146
+ cleanupCockpit();
2147
+ });
2148
+ };
2149
+ const renderGoalList = (snaps, gen) => {
2150
+ api.ui.dialog.replace(() => api.ui.DialogSelect({
2151
+ title: PRODUCT_DISPLAY_NAME,
2152
+ options: snaps.map((s, idx) => ({
2153
+ ...goalListRow(s, idx, activeSessionID()),
2154
+ value: s.goalId
2155
+ })),
2156
+ onSelect: (option) => {
2157
+ if (gen !== cockpitGeneration)
2158
+ return;
2159
+ cleanupCockpit();
2160
+ showGoalDetail(option.value, gen);
2161
+ }
2162
+ }), () => {
2163
+ if (gen === cockpitGeneration)
2164
+ cleanupCockpit();
2165
+ });
2166
+ };
2167
+ const showDashboard = () => {
2168
+ cockpitGeneration++;
2169
+ const gen = cockpitGeneration;
2170
+ cleanupCockpit();
2171
+ const snaps = getCockpitSnapshots();
2172
+ if (snaps.length === 0) {
2173
+ api.ui.dialog.replace(() => api.ui.DialogAlert({
2174
+ title: PRODUCT_DISPLAY_NAME,
2175
+ message: dashboardMessage(),
2176
+ onConfirm: () => {
2177
+ cleanupCockpit();
2178
+ api.ui.dialog.clear();
2179
+ }
2180
+ }), () => cleanupCockpit());
2181
+ return;
2182
+ }
2183
+ renderGoalList(snaps, gen);
2184
+ dashboardUnsubscribe = store.subscribe(() => {
2185
+ if (gen !== cockpitGeneration)
2186
+ return;
2187
+ const currentSnaps = getCockpitSnapshots();
2188
+ if (currentSnaps.length === 0) {
2189
+ api.ui.dialog.replace(() => api.ui.DialogAlert({
2190
+ title: PRODUCT_DISPLAY_NAME,
2191
+ message: "No active goals.",
2192
+ onConfirm: () => {
2193
+ cleanupCockpit();
2194
+ api.ui.dialog.clear();
2195
+ }
2196
+ }), () => cleanupCockpit());
2197
+ return;
2198
+ }
2199
+ renderGoalList(currentSnaps, gen);
2200
+ });
2201
+ };
2202
+ const paletteTarget = () => {
2203
+ const sessionID = activeSessionID();
2204
+ if (sessionID === null)
2205
+ return { refusal: "Open a session before controlling a goal." };
2206
+ const snaps = store.getSnapshots(sessionID);
2207
+ if (snaps.length === 0)
2208
+ return { refusal: "This session has no goals." };
2209
+ const goalId = resolveFocusedGoalId(store, sessionID);
2210
+ if (goalId === null)
2211
+ return { refusal: "This session has no goals." };
2212
+ return { goalId };
2213
+ };
2214
+ const refuseWithReason = (refusal) => {
2215
+ api.ui.toast({
2216
+ variant: "warning",
2217
+ title: PRODUCT_DISPLAY_NAME,
2218
+ message: refusal
2219
+ });
2220
+ };
2221
+ const handlePause = () => {
2222
+ const target = paletteTarget();
2223
+ if ("refusal" in target) {
2224
+ refuseWithReason(target.refusal);
2225
+ return;
2226
+ }
2227
+ sendGoalCommand(`pause ${target.goalId}`);
2228
+ api.ui.toast({
2229
+ variant: "info",
2230
+ title: PRODUCT_DISPLAY_NAME,
2231
+ message: outcomeNeutralLabel("pause")
2232
+ });
2233
+ };
2234
+ const handleResume = () => {
2235
+ const target = paletteTarget();
2236
+ if ("refusal" in target) {
2237
+ refuseWithReason(target.refusal);
2238
+ return;
2239
+ }
2240
+ sendGoalCommand(`resume ${target.goalId}`);
2241
+ api.ui.toast({
2242
+ variant: "info",
2243
+ title: PRODUCT_DISPLAY_NAME,
2244
+ message: outcomeNeutralLabel("resume")
2245
+ });
2246
+ };
2247
+ const handleClear = () => {
2248
+ const target = paletteTarget();
2249
+ if ("refusal" in target) {
2250
+ refuseWithReason(target.refusal);
2251
+ return;
2252
+ }
2253
+ sendGoalCommand(`clear ${target.goalId}`);
2254
+ api.ui.toast({
2255
+ variant: "info",
2256
+ title: PRODUCT_DISPLAY_NAME,
2257
+ message: outcomeNeutralLabel("clear")
2258
+ });
2259
+ };
2260
+ const handleEdit = () => {
2261
+ const target = paletteTarget();
2262
+ if ("refusal" in target) {
2263
+ refuseWithReason(target.refusal);
2264
+ return;
2265
+ }
2266
+ const goalId = target.goalId;
2267
+ api.ui.dialog.replace(() => api.ui.DialogPrompt({
2268
+ title: "Edit Goal",
2269
+ placeholder: "Updated objective",
2270
+ onConfirm: (objective) => {
2271
+ api.ui.dialog.clear();
2272
+ if (!objective)
2273
+ return;
2274
+ sendGoalCommand(`edit ${goalId} ${objective}`);
2275
+ api.ui.toast({
2276
+ variant: "info",
2277
+ title: PRODUCT_DISPLAY_NAME,
2278
+ message: outcomeNeutralLabel("edit")
2279
+ });
2280
+ }
2281
+ }));
2282
+ };
2283
+ const handleCheckpoint = () => {
2284
+ const target = paletteTarget();
2285
+ if ("refusal" in target) {
2286
+ refuseWithReason(target.refusal);
2287
+ return;
2288
+ }
2289
+ const goalId = target.goalId;
2290
+ api.ui.dialog.replace(() => api.ui.DialogPrompt({
2291
+ title: "Save Checkpoint",
2292
+ placeholder: "Checkpoint summary",
2293
+ onConfirm: (summary) => {
2294
+ api.ui.dialog.clear();
2295
+ if (!summary)
2296
+ return;
2297
+ sendGoalCommand(`checkpoint ${goalId} ${summary}`);
2298
+ api.ui.toast({
2299
+ variant: "info",
2300
+ title: PRODUCT_DISPLAY_NAME,
2301
+ message: outcomeNeutralLabel("checkpoint")
2302
+ });
2303
+ }
2304
+ }));
2305
+ };
2306
+ const unregisterCommands = api.keymap.registerLayer({
2307
+ commands: [
2308
+ {
2309
+ name: "fixate-on.dashboard",
2310
+ namespace: "palette",
2311
+ slashName: "goal-dashboard",
2312
+ title: `${PRODUCT_DISPLAY_NAME}: Dashboard`,
2313
+ description: "Open the live goal dashboard (goal status, tokens, turns)",
2314
+ category: PRODUCT_DISPLAY_NAME,
2315
+ run: showDashboard
2316
+ },
2317
+ {
2318
+ name: "fixate-on.pause",
2319
+ namespace: "palette",
2320
+ slashName: "goal-pause",
2321
+ title: `${PRODUCT_DISPLAY_NAME}: Pause Goal`,
2322
+ description: "Pause the active goal",
2323
+ category: PRODUCT_DISPLAY_NAME,
2324
+ run: handlePause
2325
+ },
2326
+ {
2327
+ name: "fixate-on.resume",
2328
+ namespace: "palette",
2329
+ slashName: "goal-resume",
2330
+ title: `${PRODUCT_DISPLAY_NAME}: Resume Goal`,
2331
+ description: "Resume a paused goal",
2332
+ category: PRODUCT_DISPLAY_NAME,
2333
+ run: handleResume
2334
+ },
2335
+ {
2336
+ name: "fixate-on.clear",
2337
+ namespace: "palette",
2338
+ slashName: "goal-clear",
2339
+ title: `${PRODUCT_DISPLAY_NAME}: Clear Goals`,
2340
+ description: "Clear active goal(s)",
2341
+ category: PRODUCT_DISPLAY_NAME,
2342
+ run: handleClear
2343
+ },
2344
+ {
2345
+ name: "fixate-on.edit",
2346
+ namespace: "palette",
2347
+ slashName: "goal-edit",
2348
+ title: `${PRODUCT_DISPLAY_NAME}: Edit Objective`,
2349
+ description: "Edit objective of the active goal",
2350
+ category: PRODUCT_DISPLAY_NAME,
2351
+ run: handleEdit
2352
+ },
2353
+ {
2354
+ name: "fixate-on.checkpoint",
2355
+ namespace: "palette",
2356
+ slashName: "goal-checkpoint",
2357
+ title: `${PRODUCT_DISPLAY_NAME}: Save Checkpoint`,
2358
+ description: "Save a checkpoint for the active goal",
2359
+ category: PRODUCT_DISPLAY_NAME,
2360
+ run: handleCheckpoint
2361
+ },
2362
+ {
2363
+ name: "fixate-on.list",
2364
+ namespace: "palette",
2365
+ slashName: "goal-list",
2366
+ title: `${PRODUCT_DISPLAY_NAME}: List Goals`,
2367
+ description: "List all active and archived goals",
2368
+ category: PRODUCT_DISPLAY_NAME,
2369
+ run: () => {
2370
+ sendGoalCommand("list");
2371
+ }
2372
+ },
2373
+ {
2374
+ name: "fixate-on.history",
2375
+ namespace: "palette",
2376
+ slashName: "goal-history",
2377
+ title: `${PRODUCT_DISPLAY_NAME}: Show History`,
2378
+ description: "Show goal history and transition log",
2379
+ category: PRODUCT_DISPLAY_NAME,
2380
+ run: () => {
2381
+ sendGoalCommand("history");
2382
+ }
2383
+ },
2384
+ {
2385
+ name: "fixate-on.focus",
2386
+ namespace: "palette",
2387
+ slashName: "goal-focus",
2388
+ title: `${PRODUCT_DISPLAY_NAME}: Focus Goal`,
2389
+ description: "Focus a specific goal in the session",
2390
+ category: PRODUCT_DISPLAY_NAME,
2391
+ run: () => {
2392
+ const sessionID = activeSessionID();
2393
+ const goals = sessionID ? store.getSnapshots(sessionID) : [];
2394
+ if (goals.length === 0) {
2395
+ api.ui.toast({
2396
+ variant: "warning",
2397
+ title: PRODUCT_DISPLAY_NAME,
2398
+ message: "No active goals to focus."
2399
+ });
2400
+ return;
2401
+ }
2402
+ api.ui.dialog.replace(() => api.ui.DialogSelect({
2403
+ title: "Focus Goal",
2404
+ options: goals.map((g, idx) => ({
2405
+ title: `${idx + 1}. ${g.condition}`,
2406
+ value: g.goalId,
2407
+ description: `Status: ${g.status}`
2408
+ })),
2409
+ onSelect: (option) => {
2410
+ api.ui.dialog.clear();
2411
+ sendGoalCommand(`focus ${option.value}`);
2412
+ api.ui.toast({
2413
+ variant: "info",
2414
+ title: PRODUCT_DISPLAY_NAME,
2415
+ message: outcomeNeutralLabel(`focus ${option.value}`)
2416
+ });
2417
+ }
2418
+ }));
2419
+ }
2420
+ },
2421
+ {
2422
+ name: "fixate-on.add",
2423
+ namespace: "palette",
2424
+ slashName: "goal-add",
2425
+ title: `${PRODUCT_DISPLAY_NAME}: Add Goal`,
2426
+ description: "Add a new goal to the session",
2427
+ category: PRODUCT_DISPLAY_NAME,
2428
+ run: () => {
2429
+ api.ui.dialog.replace(() => api.ui.DialogPrompt({
2430
+ title: "Add New Goal",
2431
+ placeholder: "New goal objective",
2432
+ onConfirm: (objective) => {
2433
+ api.ui.dialog.clear();
2434
+ if (!objective)
2435
+ return;
2436
+ sendGoalCommand(`add ${objective}`);
2437
+ api.ui.toast({
2438
+ variant: "info",
2439
+ title: PRODUCT_DISPLAY_NAME,
2440
+ message: outcomeNeutralLabel("add")
2441
+ });
2442
+ }
2443
+ }));
2444
+ }
2445
+ },
2446
+ {
2447
+ name: "fixate-on.sequence",
2448
+ namespace: "palette",
2449
+ slashName: "goal-sequence",
2450
+ title: `${PRODUCT_DISPLAY_NAME}: Start Sequence`,
2451
+ description: "Start an ordered sequence of goals",
2452
+ category: PRODUCT_DISPLAY_NAME,
2453
+ run: () => {
2454
+ api.ui.dialog.replace(() => api.ui.DialogPrompt({
2455
+ title: "Start Goal Sequence",
2456
+ placeholder: "Objective 1; Objective 2; Objective 3",
2457
+ onConfirm: (text) => {
2458
+ api.ui.dialog.clear();
2459
+ if (!text)
2460
+ return;
2461
+ sendGoalCommand(`sequence ${text}`);
2462
+ api.ui.toast({
2463
+ variant: "info",
2464
+ title: PRODUCT_DISPLAY_NAME,
2465
+ message: outcomeNeutralLabel("sequence")
2466
+ });
2467
+ }
2468
+ }));
2469
+ }
2470
+ }
2471
+ ],
2472
+ bindings: [
2473
+ { key: chord("d"), cmd: "fixate-on.dashboard" },
2474
+ { key: chord("p"), cmd: "fixate-on.pause" },
2475
+ { key: chord("r"), cmd: "fixate-on.resume" },
2476
+ { key: chord("c"), cmd: "fixate-on.clear" },
2477
+ { key: chord("e"), cmd: "fixate-on.edit" },
2478
+ { key: chord("k"), cmd: "fixate-on.checkpoint" }
2479
+ ]
2480
+ });
2481
+ log("info", "TUI companion initialized \u2014 subscribing to goal events.");
2482
+ const playSound = (kind, status) => {
2483
+ const soundName = soundForEvent(kind, status);
2484
+ if (!soundName)
2485
+ return;
2486
+ try {
2487
+ Promise.resolve(api.attention.notify({
2488
+ message: `Goal ${kind}${status ? ` \u2192 ${status}` : ""}`,
2489
+ sound: { name: soundName, when: "always" },
2490
+ notification: false
2491
+ })).catch(() => {});
2492
+ } catch {}
2493
+ };
2494
+ const coalescer = new ToastCoalescer((toast) => {
2495
+ try {
2496
+ api.ui.toast({
2497
+ variant: toast.variant,
2498
+ title: PRODUCT_DISPLAY_NAME,
2499
+ message: toast.message,
2500
+ duration: 5000
2501
+ });
2502
+ } catch {}
2503
+ }, Date.now, 500);
2504
+ coalescer.startAutoFlush();
2505
+ const refreshLoop = createDiskRefreshLoop({
2506
+ directory: opts.directory,
2507
+ stateRoot: opts.stateRoot,
2508
+ store,
2509
+ intervalMs: 1000,
2510
+ onEvent: (event) => {
2511
+ playSound(event.kind, event.snapshot?.status);
2512
+ coalescer.accept(event, event.sessionID);
2513
+ }
2514
+ });
2515
+ let disposed = false;
2516
+ api.lifecycle.onDispose(() => {
2517
+ disposed = true;
2518
+ unregisterCommands();
2519
+ coalescer.stopAutoFlush();
2520
+ refreshLoop.stop();
2521
+ if (dashboardUnsubscribe) {
2522
+ try {
2523
+ dashboardUnsubscribe();
2524
+ } catch {}
2525
+ dashboardUnsubscribe = null;
2526
+ }
2527
+ log("info", "TUI companion disposed.");
2528
+ });
2529
+ try {
2530
+ const read = await readDiskGoalSnapshots(opts.directory, undefined, opts.stateRoot);
2531
+ if (!disposed) {
2532
+ for (const snap of read.snapshots) {
2533
+ store.applyEvent({
2534
+ kind: "create",
2535
+ sessionID: snap.sessionID,
2536
+ goalId: snap.goalId,
2537
+ snapshot: { ...snap, origin: "disk" },
2538
+ timestamp: Date.now()
2539
+ });
2540
+ }
2541
+ log("info", `Hydrated ${read.snapshots.length} goal(s) from persisted state.`);
2542
+ if (read.filesRead > 0 || read.stateDirMissing) {
2543
+ refreshLoop.seedBaseline(read.snapshots);
2544
+ } else {
2545
+ log("info", "state file was unreadable at boot; deferring the baseline rather than assuming an empty workspace");
2546
+ }
2547
+ refreshLoop.start();
2548
+ if (read.filesRead > 0) {
2549
+ const briefing = summarizeGoalsNeedingYou(read.snapshots);
2550
+ if (briefing) {
2551
+ log("info", `Briefing: ${briefing.message}`);
2552
+ coalescer.brief(BRIEFING_SESSION_KEY, briefing);
2553
+ }
2554
+ }
2555
+ }
2556
+ } catch {
2557
+ if (!disposed)
2558
+ refreshLoop.start();
2559
+ }
2560
+ };
2561
+ var goalTuiPluginModule = {
2562
+ id: "fixate-on-tui",
2563
+ tui: GoalTuiPlugin
2564
+ };
2565
+ var tui_default = goalTuiPluginModule;
2566
+ export {
2567
+ GOAL_TUI_EVENT_TITLE,
2568
+ GoalTuiPlugin,
2569
+ createGoalBroadcaster,
2570
+ createTuiStateStore,
2571
+ tui_default as default,
2572
+ parseTuiSyncEvent,
2573
+ serializeGoalForTui
2574
+ };