@causyne/agent 1.20.116 → 1.20.118
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +7 -2
- package/src/agentLoop.js +81 -31
- package/src/agentLoop.ts +82 -33
- package/src/browser/causyneBrowser.js +30 -7
- package/src/browser/causyneBrowser.ts +29 -7
- package/src/cliMode.js +24 -4
- package/src/commands.js +7 -1
- package/src/memory/scopedFacts.js +171 -0
- package/src/memory/scopedFacts.ts +214 -0
- package/src/memory.d.ts +13 -1
- package/src/memory.js +9 -12
- package/src/perception.js +124 -3
- package/src/perception.ts +128 -4
- package/src/planCache.js +17 -3
- package/src/planCache.ts +17 -3
- package/src/plugins/pluginManager.js +74 -0
- package/src/reporting.js +12 -4
- package/src/skillsManager.js +3 -2
- package/src/skillsManager.ts +3 -2
- package/src/smartToolsUse.js +4 -5
- package/src/smartToolsUse.ts +4 -6
- package/src/taskShape.js +49 -7
- package/src/taskShape.ts +55 -7
- package/src/toolPacks.js +27 -5
- package/src/toolPacks.ts +32 -5
- package/src/tools/memoryWrite.js +8 -10
- package/src/tools/memoryWrite.ts +13 -11
- package/src/tools/pluginManager.js +17 -2
- package/src/tui/chatRenderer.js +4 -1
- package/src/tui/codeProgress.js +3 -2
- package/src/tui/codeProgress.ts +3 -2
- package/src/tui/codeStreamRenderer.js +41 -15
- package/src/tui/codeStreamRenderer.ts +40 -15
- package/src/tui/composerControls.js +16 -3
- package/src/tui/composerControls.ts +14 -3
- package/src/tui/keys.js +3 -1
- package/src/tui/prompt.js +146 -16
- package/src/tui/scrollInteraction.js +2 -2
- package/src/tui/scrollInteraction.ts +2 -2
- package/src/tui/stageSurface.js +114 -4
- package/src/tui/turnRail.js +21 -14
- package/src/tui/turnRail.ts +19 -14
- package/src/tui/usageCard.js +164 -71
- package/src/tui/usageCard.ts +187 -96
- package/src/tui/workspaceSwitch.js +2 -0
- package/src/tui/workspaceSwitch.ts +1 -0
- package/src/types/contracts.ts +3 -0
- package/src/verification/boundedExplorer.js +119 -0
- package/src/verification/cliProbe.js +116 -0
- package/src/verification/featureMap.js +78 -0
- package/src/verification/interactivePty.js +188 -0
- package/src/verification/propertyProbe.js +121 -0
- package/src/verification/ptyProbe.js +125 -0
- package/src/verification/skillCatalog.d.ts +1 -0
- package/src/verification/skillCatalog.js +60 -0
- package/src/verification/statechart.js +143 -0
- package/src/verification/uiRuntime.js +57 -0
- package/src/verificationPlan.js +1 -1
- package/src/verificationPlan.ts +1 -1
package/src/tui/usageCard.ts
CHANGED
|
@@ -13,6 +13,7 @@ import { loadConfig } from '../config.js';
|
|
|
13
13
|
import { buildContextReport } from '../reporting.js';
|
|
14
14
|
import { isAntigravityProvider } from '../providers/antigravity.js';
|
|
15
15
|
import { isAcpProvider } from '../providers/acp.js';
|
|
16
|
+
import { resolveModelContextTokens } from '../contextManager.js';
|
|
16
17
|
|
|
17
18
|
export interface UsageCardData {
|
|
18
19
|
sessionId: string;
|
|
@@ -34,6 +35,12 @@ export interface UsageCardData {
|
|
|
34
35
|
budgetLimitTokens?: number | undefined;
|
|
35
36
|
budgetCostCeilingUsd?: number | undefined;
|
|
36
37
|
budgetPercentUsed?: number | undefined;
|
|
38
|
+
/** All accounting is local; session counters require an active loop. */
|
|
39
|
+
sessionMetricsAvailable?: boolean;
|
|
40
|
+
/** A context ratio derived from text length and configured/assumed model window. */
|
|
41
|
+
contextLimitSource?: 'configured' | 'inferred';
|
|
42
|
+
/** Local history mixes provider token telemetry, ACP text estimates and media equivalents. */
|
|
43
|
+
usageProvenance?: string;
|
|
37
44
|
}
|
|
38
45
|
|
|
39
46
|
function oneLineText(value: unknown): string {
|
|
@@ -90,8 +97,10 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
|
|
|
90
97
|
const daily = await tracker.getDailyUsage();
|
|
91
98
|
const config = loadConfig() as Record<string, any>;
|
|
92
99
|
|
|
93
|
-
|
|
94
|
-
const
|
|
100
|
+
// The running agent can differ from saved settings after a model switch.
|
|
101
|
+
const liveConfig = loop?.config || {};
|
|
102
|
+
const provider = oneLineText(liveConfig.provider || config.provider || 'default') || 'default';
|
|
103
|
+
const model = oneLineText(liveConfig.model || config.model || 'default') || 'default';
|
|
95
104
|
const isAgy = isAntigravityProvider(provider);
|
|
96
105
|
const isAcp = isAcpProvider(provider);
|
|
97
106
|
const billingNote = (isAgy || isAcp)
|
|
@@ -105,8 +114,21 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
|
|
|
105
114
|
|
|
106
115
|
// Context accounting
|
|
107
116
|
const contextReport = buildContextReport();
|
|
108
|
-
const
|
|
109
|
-
|
|
117
|
+
const override = liveConfig.contextTokens || liveConfig.maxContextTokens
|
|
118
|
+
|| config.contextTokens || config.maxContextTokens;
|
|
119
|
+
const explicitLimit = Number.isFinite(Number(override)) && Number(override) > 0;
|
|
120
|
+
// report() uses persisted settings and can describe a *different* model.
|
|
121
|
+
// Resolve against the actual running provider/model; otherwise say inferred.
|
|
122
|
+
const modelLimit = resolveModelContextTokens({
|
|
123
|
+
provider, model, overrideTokens: explicitLimit ? Number(override) : 0
|
|
124
|
+
});
|
|
125
|
+
const liveLimitChars = finiteNonNeg(loop?._contextLimitChars, 0);
|
|
126
|
+
const liveLimitTokens = liveLimitChars > 0 ? Math.round(liveLimitChars / 4) : 0;
|
|
127
|
+
const poolTokens = Math.floor(
|
|
128
|
+
modelLimit > 0
|
|
129
|
+
? finiteNonNeg(modelLimit, 0)
|
|
130
|
+
: (liveLimitTokens > 0 ? liveLimitTokens : finiteNonNeg(contextReport?.approxTokenPool, 0))
|
|
131
|
+
);
|
|
110
132
|
|
|
111
133
|
// Measure active messages tokens
|
|
112
134
|
let messageChars = 0;
|
|
@@ -138,8 +160,13 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
|
|
|
138
160
|
|
|
139
161
|
const messageTokens = Math.round(messageChars / 4);
|
|
140
162
|
const coreToolTokens = Math.floor(finiteNonNeg(contextReport?.core?.tokens, 5000));
|
|
141
|
-
const
|
|
142
|
-
const
|
|
163
|
+
const liveContextChars = finiteNonNeg(loop?._contextChars, 0);
|
|
164
|
+
const liveContextTokens = liveContextChars > 0 ? Math.round(liveContextChars / 4) : 0;
|
|
165
|
+
const contextUsed = liveContextTokens > 0
|
|
166
|
+
? Math.max(liveContextTokens, messageTokens)
|
|
167
|
+
: (messageTokens + coreToolTokens);
|
|
168
|
+
const contextPctLeft = poolTokens > 0
|
|
169
|
+
? Math.max(0, Math.min(100, Math.round(((poolTokens - contextUsed) / poolTokens) * 100))) : 0;
|
|
143
170
|
|
|
144
171
|
// Budget
|
|
145
172
|
const budget = config.tokenBudget || {};
|
|
@@ -152,8 +179,10 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
|
|
|
152
179
|
const rawCostCeiling = finiteNonNeg(budget.maxCostUsd, 0);
|
|
153
180
|
|
|
154
181
|
const sessionId = oneLineText(loop?.memoryManager?.sessionId || 'default') || 'default';
|
|
155
|
-
const
|
|
156
|
-
|
|
182
|
+
const sessionMetricsAvailable = Boolean(loop?.tokenTracker);
|
|
183
|
+
// These counters are per tracker instance, not persisted across restarts.
|
|
184
|
+
const sessionTokens = finiteNonNeg(tracker.sessionTokens, finiteNonNeg(reported?.sessionTokens, 0));
|
|
185
|
+
const sessionCostUsd = finiteNonNeg(tracker.sessionCostUsd, finiteNonNeg(reported?.sessionCostUsd, 0));
|
|
157
186
|
|
|
158
187
|
return {
|
|
159
188
|
sessionId,
|
|
@@ -174,102 +203,164 @@ export async function collectUsageCardData(loop?: any): Promise<UsageCardData> {
|
|
|
174
203
|
budgetEnabled,
|
|
175
204
|
budgetLimitTokens,
|
|
176
205
|
budgetCostCeilingUsd: rawCostCeiling > 0 ? rawCostCeiling : undefined,
|
|
177
|
-
budgetPercentUsed
|
|
206
|
+
budgetPercentUsed,
|
|
207
|
+
sessionMetricsAvailable,
|
|
208
|
+
contextLimitSource: explicitLimit ? 'configured' : 'inferred',
|
|
209
|
+
usageProvenance: 'Local tracker: provider reports, ACP text estimates and media equivalents can be mixed'
|
|
178
210
|
};
|
|
179
211
|
}
|
|
180
212
|
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
const frameWidth = Math.max(40, safeWidth);
|
|
187
|
-
const innerWidth = Math.max(20, frameWidth - 4); // border (1) + pad (1) on each side
|
|
188
|
-
const borderRole = 'accent';
|
|
189
|
-
const surfaceRole = 'surface';
|
|
190
|
-
|
|
191
|
-
// Header row
|
|
192
|
-
const title = ` ${bold(paint('accent', 'Usage & Context'))} `;
|
|
193
|
-
const closeHint = ` ${dim('esc close')} `;
|
|
194
|
-
const hLineLength = Math.max(0, frameWidth - 3 - visibleWidth(title) - visibleWidth(closeHint));
|
|
195
|
-
const topBorder = paint(borderRole, FRAME.tl + FRAME.h)
|
|
196
|
-
+ title
|
|
197
|
-
+ paint(borderRole, FRAME.h.repeat(hLineLength))
|
|
198
|
-
+ closeHint
|
|
199
|
-
+ paint(borderRole, FRAME.tr);
|
|
200
|
-
|
|
201
|
-
// Content lines inside card
|
|
202
|
-
const lines: string[] = [];
|
|
203
|
-
|
|
204
|
-
// 1. Session ID & Message count
|
|
205
|
-
const cleanSession = oneLineText(data.sessionId || 'default') || 'default';
|
|
206
|
-
const sessionChars = Array.from(cleanSession);
|
|
207
|
-
const shortSession = sessionChars.length > 24
|
|
208
|
-
? `${sessionChars.slice(0, 10).join('')}…${sessionChars.slice(-10).join('')}`
|
|
209
|
-
: cleanSession;
|
|
210
|
-
lines.push(
|
|
211
|
-
`${dim('Session/Chat :')} ${paint('ink', shortSession)} ${dim(`(${formatNumber(data.sessionTurns)} messages)`)}`
|
|
212
|
-
);
|
|
213
|
-
|
|
214
|
-
// 2. Context Window & Progress bar
|
|
215
|
-
const safePercentLeft = Number.isFinite(data.contextPercentLeft)
|
|
216
|
-
? Math.max(0, Math.min(100, Math.round(data.contextPercentLeft)))
|
|
217
|
-
: 0;
|
|
218
|
-
const pBar = renderProgressBar(safePercentLeft, 22, false);
|
|
219
|
-
lines.push(
|
|
220
|
-
`${dim('Context :')} ${bold(`${safePercentLeft}% left`)} ${dim(`(${formatNumber(data.contextUsedTokens)} used / ${formatNumber(data.contextPoolTokens)})`)} ${pBar}`
|
|
221
|
-
);
|
|
222
|
-
|
|
223
|
-
// 3. This Session Usage
|
|
224
|
-
lines.push(
|
|
225
|
-
`${dim('This Session :')} ${bold(formatNumber(data.sessionTokens))} tokens${formatCostEstimate(data.sessionCostUsd)}`
|
|
226
|
-
);
|
|
227
|
-
|
|
228
|
-
// 4. Daily Usage (Today)
|
|
229
|
-
lines.push(
|
|
230
|
-
`${dim('Today (24h) :')} ${bold(formatNumber(data.dailyTokens))} tokens${formatCostEstimate(data.dailyCostUsd)}`
|
|
231
|
-
);
|
|
232
|
-
|
|
233
|
-
// 5. All-Time / Lifetime Usage
|
|
234
|
-
lines.push(
|
|
235
|
-
`${dim('All-Time :')} ${bold(formatNumber(data.lifetimeTokens))} tokens${formatCostEstimate(data.lifetimeCostUsd)} ${dim(`(${formatNumber(data.lifetimeCalls)} calls)`)}`
|
|
236
|
-
);
|
|
213
|
+
interface FramedCardOptions {
|
|
214
|
+
title: string;
|
|
215
|
+
footer?: string;
|
|
216
|
+
labelWidth?: number;
|
|
217
|
+
}
|
|
237
218
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
219
|
+
function buildFramedCardRows(
|
|
220
|
+
width: number,
|
|
221
|
+
options: FramedCardOptions,
|
|
222
|
+
populate: (addRow: (label: string, value: string) => void, addLine: (line: string) => void, ctx: { innerWidth: number; labelWidth: number }) => void
|
|
223
|
+
): string[] {
|
|
224
|
+
const safeWidth = Number.isFinite(width) ? Math.max(4, Math.floor(width)) : 80;
|
|
225
|
+
const frameWidth = safeWidth; // Never paint outside the terminal's actual columns.
|
|
226
|
+
const innerWidth = Math.max(0, frameWidth - 4);
|
|
227
|
+
const edge = paint('accent', FRAME.v);
|
|
228
|
+
const cleanTitle = oneLineText(options.title);
|
|
229
|
+
const title = frameWidth >= 32 ? ` ${bold(paint('accent', cleanTitle))} `
|
|
230
|
+
: frameWidth >= 13 ? ` ${cleanTitle.split(/\s+/)[0] || cleanTitle} ` : '';
|
|
231
|
+
const footerText = oneLineText(options.footer || 'esc close');
|
|
232
|
+
const hint = frameWidth >= 43 && footerText ? ` ${dim(footerText)} ` : '';
|
|
233
|
+
const lineRoom = Math.max(0, frameWidth - 3 - visibleWidth(title) - visibleWidth(hint));
|
|
234
|
+
const top = paint('accent', FRAME.tl + FRAME.h)
|
|
235
|
+
+ title + paint('accent', FRAME.h.repeat(lineRoom)) + hint + paint('accent', FRAME.tr);
|
|
236
|
+
const rows = [fill('surface', top)];
|
|
237
|
+
|
|
238
|
+
const labelWidth = options.labelWidth ?? (innerWidth >= 60 ? 16 : 13);
|
|
239
|
+
const pushInnerRow = (text: string): void => {
|
|
240
|
+
const clipped = visibleWidth(text) > innerWidth
|
|
241
|
+
? truncate(text, innerWidth, GLYPHS.ellipsis) : text;
|
|
242
|
+
const padding = ' '.repeat(Math.max(0, innerWidth - visibleWidth(clipped)));
|
|
243
|
+
rows.push(fill('surface', `${edge} ${clipped}${padding} ${edge}`));
|
|
244
|
+
};
|
|
245
|
+
const addRow = (label: string, value: string): void => {
|
|
246
|
+
const name = dim(String(label).padEnd(labelWidth));
|
|
247
|
+
pushInnerRow(name + value);
|
|
248
|
+
};
|
|
245
249
|
|
|
246
|
-
|
|
247
|
-
if (data.budgetEnabled && typeof data.budgetLimitTokens === 'number' && Number.isFinite(data.budgetLimitTokens) && data.budgetLimitTokens > 0) {
|
|
248
|
-
const safeBudgetPercent = typeof data.budgetPercentUsed === 'number' && Number.isFinite(data.budgetPercentUsed)
|
|
249
|
-
? Math.max(0, Math.round(data.budgetPercentUsed))
|
|
250
|
-
: 0;
|
|
251
|
-
const bBar = renderProgressBar(safeBudgetPercent, 16, true);
|
|
252
|
-
lines.push(
|
|
253
|
-
`${dim('Daily Budget :')} ${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tokens (${safeBudgetPercent}% used) ${bBar}`
|
|
254
|
-
);
|
|
255
|
-
}
|
|
250
|
+
populate(addRow, pushInnerRow, { innerWidth, labelWidth });
|
|
256
251
|
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
252
|
+
const bottom = paint('accent', FRAME.bl + FRAME.h.repeat(Math.max(0, frameWidth - 2)) + FRAME.br);
|
|
253
|
+
rows.push(fill('surface', bottom));
|
|
254
|
+
rows.push(''); // Keep the composer visually separate from the pinned panel.
|
|
255
|
+
return rows;
|
|
256
|
+
}
|
|
260
257
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
}
|
|
258
|
+
/**
|
|
259
|
+
* Render the usage card as an array of styled terminal rows, exactly matching `width`.
|
|
260
|
+
*/
|
|
261
|
+
export function renderUsageCardRows(data: UsageCardData, width: number): string[] {
|
|
262
|
+
return buildFramedCardRows(width, { title: 'Usage & Context', footer: 'esc close' }, (addRow, _addLine, { innerWidth, labelWidth }) => {
|
|
263
|
+
const session = oneLineText(data.sessionId || 'unknown') || 'unknown';
|
|
264
|
+
const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
|
|
265
|
+
addRow('Session/Chat', `${paint('ink', sessionName)} ${dim(`(${formatNumber(data.sessionTurns)} messages)`)}`);
|
|
266
|
+
// Model and provider occupy separate rows, rather than squeezing two long
|
|
267
|
+
// identifiers into a single line where neither is readable.
|
|
268
|
+
addRow('Active Model', paint('accent', oneLineText(data.model || 'unknown')));
|
|
269
|
+
addRow('Provider', `${paint('ink', oneLineText(data.provider || 'unknown'))} ${dim(oneLineText(data.billingNote || ''))}`);
|
|
270
|
+
|
|
271
|
+
const pool = Number.isFinite(data.contextPoolTokens) && data.contextPoolTokens > 0
|
|
272
|
+
? data.contextPoolTokens : 0;
|
|
273
|
+
const estimatedUsed = formatNumber(data.contextUsedTokens);
|
|
274
|
+
if (pool > 0) {
|
|
275
|
+
const percent = Number.isFinite(data.contextPercentLeft)
|
|
276
|
+
? Math.max(0, Math.min(100, Math.round(data.contextPercentLeft))) : 0;
|
|
277
|
+
const poolSource = data.contextLimitSource === 'configured' ? 'configured cap' : 'inferred cap';
|
|
278
|
+
addRow('Context (est.)', `~${estimatedUsed} / ~${formatNumber(pool)} tokens (~${percent}% left; ${poolSource})`);
|
|
279
|
+
const barRoom = Math.max(0, innerWidth - labelWidth - 13);
|
|
280
|
+
if (barRoom >= 8) {
|
|
281
|
+
const barWidth = Math.min(28, barRoom);
|
|
282
|
+
const bar = renderProgressBar(percent, barWidth, false);
|
|
283
|
+
addRow('Window left', `[${bar}] ${String(percent).padStart(3)}% left`);
|
|
284
|
+
}
|
|
285
|
+
} else {
|
|
286
|
+
addRow('Context (est.)', `~${estimatedUsed} tokens; model limit unknown`);
|
|
287
|
+
}
|
|
266
288
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
289
|
+
addRow('This Session', data.sessionMetricsAvailable === false
|
|
290
|
+
? dim('unavailable (no live tracker)')
|
|
291
|
+
: `${bold(formatNumber(data.sessionTokens))} tracked tokens ${dim('(current process only)')}`);
|
|
292
|
+
addRow('Today (local)', `${bold(formatNumber(data.dailyTokens))} tracked tokens ${dim('(calendar day)')}`);
|
|
293
|
+
addRow('All-Time', `${bold(formatNumber(data.lifetimeTokens))} tracked tokens ${dim(`(${formatNumber(data.lifetimeCalls)} recorded events)`)}`);
|
|
294
|
+
|
|
295
|
+
const totalEstimate = formatCostEstimate(data.lifetimeCostUsd).trim();
|
|
296
|
+
const dailyEstimate = formatCostEstimate(data.dailyCostUsd).trim();
|
|
297
|
+
addRow('Cost (estimate)', totalEstimate
|
|
298
|
+
? `${totalEstimate} all-time${dailyEstimate ? ` · ${dailyEstimate} today` : ''}`
|
|
299
|
+
: dim('no positive local estimate recorded'));
|
|
300
|
+
|
|
301
|
+
addRow('Data source', dim('Local tracker; not provider billing or exact token telemetry'));
|
|
302
|
+
if (data.budgetEnabled && typeof data.budgetLimitTokens === 'number' && Number.isFinite(data.budgetLimitTokens) && data.budgetLimitTokens > 0) {
|
|
303
|
+
const pct = typeof data.budgetPercentUsed === 'number' && Number.isFinite(data.budgetPercentUsed)
|
|
304
|
+
? Math.max(0, Math.round(data.budgetPercentUsed)) : 0;
|
|
305
|
+
addRow('Daily budget', `${formatNumber(data.dailyTokens)} / ${formatNumber(data.budgetLimitTokens)} tracked (${pct}% used)`);
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
}
|
|
270
309
|
|
|
271
|
-
|
|
272
|
-
|
|
310
|
+
/**
|
|
311
|
+
* Render the pinned `/status` card matching the Usage card styling, plus live session/context meters when available.
|
|
312
|
+
*/
|
|
313
|
+
export function renderStatusCardRows(
|
|
314
|
+
statusText: string,
|
|
315
|
+
usageData: UsageCardData | null | undefined,
|
|
316
|
+
width: number
|
|
317
|
+
): string[] {
|
|
318
|
+
return buildFramedCardRows(width, { title: 'Status', footer: 'esc close' }, (addRow, addLine, { innerWidth, labelWidth }) => {
|
|
319
|
+
const rawLines = String(statusText || '').split(/\r?\n/);
|
|
320
|
+
if (rawLines[0]?.trim() === 'Status') rawLines.shift();
|
|
321
|
+
let hasSessionLine = false;
|
|
322
|
+
for (const rawLine of rawLines) {
|
|
323
|
+
const trimmed = oneLineText(rawLine);
|
|
324
|
+
if (!trimmed) continue;
|
|
325
|
+
const sepIdx = trimmed.indexOf(':');
|
|
326
|
+
if (sepIdx > 0 && sepIdx <= 20) {
|
|
327
|
+
const key = trimmed.slice(0, sepIdx).trim();
|
|
328
|
+
const val = trimmed.slice(sepIdx + 1).trim();
|
|
329
|
+
if (key.toLowerCase() === 'session') hasSessionLine = true;
|
|
330
|
+
const coloredVal = key.toLowerCase().includes('provider')
|
|
331
|
+
? paint('accent', val)
|
|
332
|
+
: paint('ink', val);
|
|
333
|
+
addRow(key, coloredVal);
|
|
334
|
+
} else {
|
|
335
|
+
addLine(dim(trimmed));
|
|
336
|
+
}
|
|
337
|
+
}
|
|
273
338
|
|
|
274
|
-
|
|
339
|
+
if (usageData) {
|
|
340
|
+
if (!hasSessionLine) {
|
|
341
|
+
const session = oneLineText(usageData.sessionId || 'unknown') || 'unknown';
|
|
342
|
+
const sessionName = truncate(session, Math.max(8, Math.floor(innerWidth / 2)), '…');
|
|
343
|
+
addRow('Session', `${paint('ink', sessionName)} ${dim(`(${formatNumber(usageData.sessionTurns)} messages)`)}`);
|
|
344
|
+
}
|
|
345
|
+
const pool = Number.isFinite(usageData.contextPoolTokens) && usageData.contextPoolTokens > 0
|
|
346
|
+
? usageData.contextPoolTokens : 0;
|
|
347
|
+
const used = formatNumber(usageData.contextUsedTokens);
|
|
348
|
+
if (pool > 0) {
|
|
349
|
+
const percent = Number.isFinite(usageData.contextPercentLeft)
|
|
350
|
+
? Math.max(0, Math.min(100, Math.round(usageData.contextPercentLeft))) : 0;
|
|
351
|
+
const barRoom = Math.max(0, innerWidth - labelWidth - 13);
|
|
352
|
+
if (barRoom >= 8) {
|
|
353
|
+
const barWidth = Math.min(26, barRoom);
|
|
354
|
+
const bar = renderProgressBar(percent, barWidth, false);
|
|
355
|
+
addRow('Context left', `[${bar}] ${String(percent).padStart(3)}% left`);
|
|
356
|
+
}
|
|
357
|
+
addRow('Context tokens', `~${used} / ~${formatNumber(pool)} tokens`);
|
|
358
|
+
} else {
|
|
359
|
+
addRow('Context tokens', `~${used} tokens; model limit unknown`);
|
|
360
|
+
}
|
|
361
|
+
if (usageData.sessionMetricsAvailable !== false) {
|
|
362
|
+
addRow('Tracked tokens', `${bold(formatNumber(usageData.sessionTokens))} session · ${bold(formatNumber(usageData.dailyTokens))} today`);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
});
|
|
275
366
|
}
|
|
@@ -33,6 +33,8 @@ export function switchChatWorkspace({ workspaceRoot, createLoop, prompt = null,
|
|
|
33
33
|
// queued attachments or active skills from the previous workspace.
|
|
34
34
|
prompt.pendingAttachments = [];
|
|
35
35
|
prompt.completion = null;
|
|
36
|
+
if (typeof prompt.refreshPinnedPanels === 'function')
|
|
37
|
+
prompt.refreshPinnedPanels(replacement);
|
|
36
38
|
if (typeof prompt.scheduleDraw === 'function')
|
|
37
39
|
prompt.scheduleDraw();
|
|
38
40
|
}
|
|
@@ -60,6 +60,7 @@ export function switchChatWorkspace<TLoop extends {
|
|
|
60
60
|
// queued attachments or active skills from the previous workspace.
|
|
61
61
|
prompt.pendingAttachments = [];
|
|
62
62
|
prompt.completion = null;
|
|
63
|
+
if (typeof prompt.refreshPinnedPanels === 'function') prompt.refreshPinnedPanels(replacement);
|
|
63
64
|
if (typeof prompt.scheduleDraw === 'function') prompt.scheduleDraw();
|
|
64
65
|
}
|
|
65
66
|
|
package/src/types/contracts.ts
CHANGED
|
@@ -298,6 +298,9 @@ export interface WorkspaceContext {
|
|
|
298
298
|
projectType?: string;
|
|
299
299
|
designSystem?: string;
|
|
300
300
|
keyFiles?: string[];
|
|
301
|
+
subprojectStacks?: string[];
|
|
302
|
+
docFiles?: string[];
|
|
303
|
+
buildFiles?: string[];
|
|
301
304
|
applicationRoot?: string;
|
|
302
305
|
workspaceRoot?: string;
|
|
303
306
|
allowedReadRoots?: string[];
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
const DEFAULT_DEPTH = 6;
|
|
2
|
+
const DEFAULT_STATES = 10_000;
|
|
3
|
+
|
|
4
|
+
function boundedInteger(value, fallback, maximum) {
|
|
5
|
+
if (value === undefined) return fallback;
|
|
6
|
+
if (!Number.isSafeInteger(value) || value < 0 || value > maximum) {
|
|
7
|
+
throw new RangeError('Invalid exploration bound');
|
|
8
|
+
}
|
|
9
|
+
return value;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export function exploreStateMachine(options) {
|
|
13
|
+
const { initial, actions, transition, invariant } = options || {};
|
|
14
|
+
if (!Array.isArray(actions) || actions.length === 0) throw new TypeError('actions must be nonempty');
|
|
15
|
+
if (actions.length > 10000) throw new RangeError('Too many actions to explore safely');
|
|
16
|
+
if (typeof transition !== 'function') throw new TypeError('transition must be a function');
|
|
17
|
+
if (typeof invariant !== 'function') throw new TypeError('invariant must be a function');
|
|
18
|
+
|
|
19
|
+
if (initial && typeof initial.then === 'function') {
|
|
20
|
+
throw new TypeError('Async initial state is not supported by synchronous model exploration');
|
|
21
|
+
}
|
|
22
|
+
const maxDepth = boundedInteger(options.maxDepth, DEFAULT_DEPTH, 32);
|
|
23
|
+
const maxStates = boundedInteger(options.maxStates, DEFAULT_STATES, 100_000);
|
|
24
|
+
if (maxStates === 0) throw new RangeError('maxStates must be positive');
|
|
25
|
+
const key = options.stateKey || JSON.stringify;
|
|
26
|
+
if (typeof key !== 'function') throw new TypeError('stateKey must be a function');
|
|
27
|
+
|
|
28
|
+
const checkedState = value => {
|
|
29
|
+
try { return structuredClone(value); }
|
|
30
|
+
catch { throw new TypeError('State must be structured-cloneable for sound bounded exploration'); }
|
|
31
|
+
};
|
|
32
|
+
const checkedAction = value => {
|
|
33
|
+
try { return structuredClone(value); }
|
|
34
|
+
catch { throw new TypeError('Actions must be structured-cloneable for sound bounded exploration'); }
|
|
35
|
+
};
|
|
36
|
+
const stableActions = actions.map(checkedAction);
|
|
37
|
+
const startState = checkedState(initial);
|
|
38
|
+
const startKey = key(checkedState(startState));
|
|
39
|
+
if (startKey && typeof startKey.then === 'function') {
|
|
40
|
+
throw new TypeError('Async stateKey is not supported');
|
|
41
|
+
}
|
|
42
|
+
if (typeof startKey !== 'string') throw new TypeError('stateKey must produce a string');
|
|
43
|
+
let nodesVisited = 1;
|
|
44
|
+
let transitions = 0;
|
|
45
|
+
let deepest = 0;
|
|
46
|
+
const root = { state: startState, trace: [] };
|
|
47
|
+
const queue = [root];
|
|
48
|
+
const seen = new Set([startKey]);
|
|
49
|
+
|
|
50
|
+
function failed(node) {
|
|
51
|
+
const result = invariant(checkedState(node.state));
|
|
52
|
+
if (result && typeof result.then === 'function') {
|
|
53
|
+
throw new TypeError('Async invariants are not supported');
|
|
54
|
+
}
|
|
55
|
+
if (result === true) return null;
|
|
56
|
+
return {
|
|
57
|
+
status: 'counterexample',
|
|
58
|
+
depthLimit: maxDepth,
|
|
59
|
+
statesExplored: nodesVisited,
|
|
60
|
+
transitionsExplored: transitions,
|
|
61
|
+
exploredDepth: node.trace.length,
|
|
62
|
+
trace: node.trace,
|
|
63
|
+
state: node.state,
|
|
64
|
+
reason: typeof result === 'string' ? result : 'Invariant returned false'
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const initialFailure = failed(root);
|
|
69
|
+
if (initialFailure) return initialFailure;
|
|
70
|
+
for (let head = 0; head < queue.length; head++) {
|
|
71
|
+
const current = queue[head];
|
|
72
|
+
deepest = Math.max(deepest, current.trace.length);
|
|
73
|
+
if (current.trace.length >= maxDepth) continue;
|
|
74
|
+
for (const action of stableActions) {
|
|
75
|
+
// Each branch must start from the same immutable snapshot. A mutating
|
|
76
|
+
// transition otherwise poisons later siblings and can produce false proofs.
|
|
77
|
+
const isolated = checkedState(current.state);
|
|
78
|
+
const next = transition(isolated, checkedAction(action));
|
|
79
|
+
if (next && typeof next.then === 'function') {
|
|
80
|
+
throw new TypeError('Async transitions are not supported');
|
|
81
|
+
}
|
|
82
|
+
transitions++;
|
|
83
|
+
if (next === null || next === undefined) continue;
|
|
84
|
+
const trace = current.trace.concat(action);
|
|
85
|
+
const nextNode = { state: next, trace };
|
|
86
|
+
const failure = failed(nextNode);
|
|
87
|
+
if (failure) return failure;
|
|
88
|
+
const identity = key(checkedState(next));
|
|
89
|
+
if (identity && typeof identity.then === 'function') {
|
|
90
|
+
throw new TypeError('Async stateKey is not supported');
|
|
91
|
+
}
|
|
92
|
+
if (typeof identity !== 'string') throw new TypeError('stateKey must produce a string');
|
|
93
|
+
if (seen.has(identity)) continue;
|
|
94
|
+
if (nodesVisited >= maxStates) {
|
|
95
|
+
return {
|
|
96
|
+
status: 'incomplete',
|
|
97
|
+
depthLimit: maxDepth,
|
|
98
|
+
statesExplored: nodesVisited,
|
|
99
|
+
transitionsExplored: transitions,
|
|
100
|
+
exploredDepth: trace.length,
|
|
101
|
+
trace: [],
|
|
102
|
+
reason: 'Exploration reached maxStates before completing the bound'
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
seen.add(identity);
|
|
106
|
+
nodesVisited++;
|
|
107
|
+
queue.push(nextNode);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return {
|
|
111
|
+
status: 'bounded-pass',
|
|
112
|
+
depthLimit: maxDepth,
|
|
113
|
+
statesExplored: nodesVisited,
|
|
114
|
+
transitionsExplored: transitions,
|
|
115
|
+
exploredDepth: deepest,
|
|
116
|
+
trace: [],
|
|
117
|
+
reason: 'Invariant holds for reachable states within the stated bound; not an unbounded proof'
|
|
118
|
+
};
|
|
119
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { realpathSync } from 'node:fs';
|
|
4
|
+
|
|
5
|
+
function inside(root, candidate) {
|
|
6
|
+
const lexicalRoot = path.resolve(root);
|
|
7
|
+
const base = realpathSync(root);
|
|
8
|
+
const lexical = path.relative(lexicalRoot, path.resolve(candidate));
|
|
9
|
+
if (lexical === '..' || lexical.startsWith('..' + path.sep) || path.isAbsolute(lexical)) return false;
|
|
10
|
+
let target;
|
|
11
|
+
try {
|
|
12
|
+
target = realpathSync(candidate);
|
|
13
|
+
} catch (error) {
|
|
14
|
+
if (error?.code === 'ENOENT') return true;
|
|
15
|
+
throw error;
|
|
16
|
+
}
|
|
17
|
+
const relative = path.relative(base, target);
|
|
18
|
+
return relative === '' || (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative));
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function runCliProbe(options) {
|
|
22
|
+
const { workspace, program, args = [], timeoutMs = 8_000, outputLimit = 32_768,
|
|
23
|
+
expectedExitCode = 0, contains = null } = options || {};
|
|
24
|
+
if (typeof workspace !== 'string' || typeof program !== 'string'
|
|
25
|
+
|| !Array.isArray(args) || !args.every(a => typeof a === 'string')) {
|
|
26
|
+
throw new TypeError('workspace, program, and string argv are required');
|
|
27
|
+
}
|
|
28
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 10 || timeoutMs > 60_000) {
|
|
29
|
+
throw new RangeError('timeoutMs must be between 10 and 60000');
|
|
30
|
+
}
|
|
31
|
+
if (!Number.isSafeInteger(outputLimit) || outputLimit < 64 || outputLimit > 1_048_576) {
|
|
32
|
+
throw new RangeError('outputLimit must be between 64 and 1048576');
|
|
33
|
+
}
|
|
34
|
+
if (!Number.isInteger(expectedExitCode) || expectedExitCode < 0 || expectedExitCode > 255) {
|
|
35
|
+
throw new RangeError('invalid expectedExitCode');
|
|
36
|
+
}
|
|
37
|
+
if (contains !== null && (typeof contains !== 'string' || contains.length > 1000)) {
|
|
38
|
+
throw new TypeError('contains must be a bounded string');
|
|
39
|
+
}
|
|
40
|
+
const cwd = path.resolve(workspace);
|
|
41
|
+
if (program !== 'node' && !path.isAbsolute(program)
|
|
42
|
+
&& !program.includes('/') && !program.includes('\\')) {
|
|
43
|
+
throw new Error('Executable must be an explicit workspace path or node');
|
|
44
|
+
}
|
|
45
|
+
const executable = program === 'node' ? process.execPath : program;
|
|
46
|
+
const resolvedProgram = path.isAbsolute(executable) ? executable
|
|
47
|
+
: executable.includes('/') || executable.includes('\\') ? path.resolve(cwd, executable) : executable;
|
|
48
|
+
if (!inside(cwd, cwd)) throw new Error('Invalid workspace');
|
|
49
|
+
if ((executable.includes('/') || executable.includes('\\')) && !inside(cwd, resolvedProgram)
|
|
50
|
+
&& resolvedProgram !== process.execPath) {
|
|
51
|
+
throw new Error('Executable must remain inside workspace');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const started = Date.now();
|
|
55
|
+
return new Promise(resolve => {
|
|
56
|
+
let stdout = '';
|
|
57
|
+
let stderr = '';
|
|
58
|
+
let usedBytes = 0;
|
|
59
|
+
let truncated = false;
|
|
60
|
+
let timedOut = false;
|
|
61
|
+
let exitCode = null;
|
|
62
|
+
let signal = null;
|
|
63
|
+
let spawnError = null;
|
|
64
|
+
let settled = false;
|
|
65
|
+
let child;
|
|
66
|
+
let timer;
|
|
67
|
+
const finish = () => {
|
|
68
|
+
if (settled) return;
|
|
69
|
+
settled = true;
|
|
70
|
+
if (timer) clearTimeout(timer);
|
|
71
|
+
const success = !timedOut && !spawnError && exitCode === expectedExitCode
|
|
72
|
+
&& !truncated && (contains === null || (stdout + stderr).includes(contains));
|
|
73
|
+
resolve({
|
|
74
|
+
status: success ? 'observed-pass' : 'observed-fail',
|
|
75
|
+
success, command: { program, args, workspace: cwd },
|
|
76
|
+
exitCode, signal, timedOut, truncated, stdout, stderr,
|
|
77
|
+
error: spawnError, durationMs: Math.max(0, Date.now() - started),
|
|
78
|
+
surface: 'cli-pipe',
|
|
79
|
+
limitation: 'A pipe subprocess does not verify terminal rendering, mouse events, or desktop UI behavior'
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
const collect = (field, chunk) => {
|
|
83
|
+
const data = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
|
|
84
|
+
const available = Math.max(0, outputLimit - usedBytes);
|
|
85
|
+
if (data.length > available) truncated = true;
|
|
86
|
+
if (available) {
|
|
87
|
+
const safe = data.subarray(0, available).toString('utf8');
|
|
88
|
+
if (field === 'stdout') stdout += safe;
|
|
89
|
+
else stderr += safe;
|
|
90
|
+
usedBytes += Math.min(available, data.length);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
try {
|
|
94
|
+
child = spawn(resolvedProgram, args, {
|
|
95
|
+
cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true,
|
|
96
|
+
env: { ...process.env, CAUSYNE_VERIFY_PROBE: '1' }
|
|
97
|
+
});
|
|
98
|
+
child.stdout?.on('data', chunk => collect('stdout', chunk));
|
|
99
|
+
child.stderr?.on('data', chunk => collect('stderr', chunk));
|
|
100
|
+
child.on('error', error => { spawnError = String(error.message || error); finish(); });
|
|
101
|
+
child.on('close', (code, sig) => {
|
|
102
|
+
exitCode = code;
|
|
103
|
+
signal = sig;
|
|
104
|
+
finish();
|
|
105
|
+
});
|
|
106
|
+
timer = setTimeout(() => {
|
|
107
|
+
timedOut = true;
|
|
108
|
+
child.kill('SIGKILL');
|
|
109
|
+
}, timeoutMs);
|
|
110
|
+
timer.unref?.();
|
|
111
|
+
} catch (error) {
|
|
112
|
+
spawnError = String(error?.message || error);
|
|
113
|
+
finish();
|
|
114
|
+
}
|
|
115
|
+
});
|
|
116
|
+
}
|