@botiverse/bottega 0.0.0-stage → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,1355 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ ConfigError,
4
+ DEFAULT_CONTEXT_BUDGET,
5
+ ESTIMATED,
6
+ FAUX_PROVIDER,
7
+ KIND_LABEL,
8
+ ModelError,
9
+ THINKING_LEVELS,
10
+ TRACE_META,
11
+ TRACE_SCRIPT,
12
+ TRACE_STEPS,
13
+ Workspace,
14
+ WorkspaceError,
15
+ addApp,
16
+ allModels,
17
+ applyAction,
18
+ appsDir,
19
+ authApp,
20
+ bootstrapWorkspace,
21
+ bottegaStore,
22
+ bottegaVersion,
23
+ captureFrame,
24
+ check,
25
+ commonPrefix,
26
+ composited,
27
+ conversationApp,
28
+ costs,
29
+ createWorkspace,
30
+ ctxOf,
31
+ envStore,
32
+ estimateTokens,
33
+ fitScreen,
34
+ installApps,
35
+ installed,
36
+ isSpeaking,
37
+ keepList,
38
+ kindOf,
39
+ listAvailable,
40
+ newWorkspaceConfig,
41
+ notify,
42
+ openWindow,
43
+ openingLine,
44
+ overheadTokens,
45
+ paintOrder,
46
+ personSays,
47
+ readSettings,
48
+ refreshCatalog,
49
+ remove,
50
+ renderWorkspace,
51
+ runSession,
52
+ scaleOf,
53
+ screenFromContext,
54
+ serve,
55
+ signOutApp,
56
+ slice,
57
+ stage,
58
+ step,
59
+ summarize,
60
+ systemPrompt,
61
+ toolsFor,
62
+ traceMeta,
63
+ transcript,
64
+ update,
65
+ writeResult
66
+ } from "./chunk-CTW72PQK.js";
67
+
68
+ // ../bottega/src/cli.ts
69
+ import { spawnSync } from "node:child_process";
70
+ import { readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
71
+ import { join as join2, resolve } from "node:path";
72
+ import { createInterface } from "node:readline/promises";
73
+ import { parseArgs } from "node:util";
74
+
75
+ // ../bottega/src/doorbell.ts
76
+ import { timingSafeEqual } from "node:crypto";
77
+ import { createServer } from "node:http";
78
+ var URGENCIES = ["ambient", "notice", "wake"];
79
+ var RAFT_WAKE = "raft-channel-wake.v1";
80
+ var RAFT_DRAIN = "raft-activity-drain.v1";
81
+ var RAFT_LINE = "something new waits in your Raft inbox \u2014 `raft inbox check` lists it";
82
+ var BODY_LIMIT = 64 * 1024;
83
+ var Refusal = class extends Error {
84
+ status;
85
+ failureClass;
86
+ constructor(status, message, failureClass) {
87
+ super(message);
88
+ this.status = status;
89
+ this.failureClass = failureClass;
90
+ }
91
+ };
92
+ function same(given, token) {
93
+ const a = Buffer.from(given);
94
+ const b = Buffer.from(token);
95
+ return a.length === b.length && timingSafeEqual(a, b);
96
+ }
97
+ function allowed(request, token) {
98
+ if (!token) return true;
99
+ const bridge = request.headers["x-raft-bridge-token"];
100
+ const bearer = /^Bearer (.+)$/.exec(request.headers.authorization ?? "")?.[1];
101
+ return [bridge, bearer].some((given) => typeof given === "string" && same(given, token));
102
+ }
103
+ async function bodyOf(request) {
104
+ const chunks = [];
105
+ let size = 0;
106
+ for await (const chunk of request) {
107
+ size += chunk.length;
108
+ if (size > BODY_LIMIT) throw new Refusal(413, "a ring is a few short fields");
109
+ chunks.push(chunk);
110
+ }
111
+ try {
112
+ const value = JSON.parse(Buffer.concat(chunks).toString("utf8"));
113
+ if (value && typeof value === "object" && !Array.isArray(value)) return value;
114
+ } catch {
115
+ }
116
+ throw new Refusal(400, "the body is not a JSON object");
117
+ }
118
+ var text = (value) => typeof value === "string" && value.trim() ? value : void 0;
119
+ function eventOf(body) {
120
+ const line = text(body.line);
121
+ if (!line) throw new Refusal(400, "say what happened: `line`");
122
+ const urgency = body.urgency ?? "notice";
123
+ if (!URGENCIES.includes(urgency)) throw new Refusal(400, `urgency is one of ${URGENCIES.join(", ")}`);
124
+ const app = text(body.app) ?? "notify";
125
+ const refresh = Array.isArray(body.refresh) ? body.refresh.filter((id) => typeof id === "string") : [];
126
+ return {
127
+ app,
128
+ event: {
129
+ subject: text(body.subject) ?? app,
130
+ line,
131
+ urgency,
132
+ ...refresh.length ? { refresh } : {},
133
+ ...text(body.from) ? { from: text(body.from) } : {},
134
+ ...text(body.id) ? { id: text(body.id) } : {}
135
+ }
136
+ };
137
+ }
138
+ function doorbell(options) {
139
+ const answer = (response, status, body) => {
140
+ response.writeHead(status, { "content-type": "application/json" });
141
+ response.end(JSON.stringify(body));
142
+ };
143
+ const handle = async (request) => {
144
+ const path = new URL(request.url ?? "/", "http://127.0.0.1").pathname;
145
+ if (!["/notify", "/raft/wake", "/activity/drain"].includes(path))
146
+ throw new Refusal(404, "no such door", "no_session");
147
+ if (!allowed(request, options.token)) throw new Refusal(401, "the token is missing or wrong", "auth_revoked");
148
+ if (path === "/activity/drain") {
149
+ if (request.method !== "GET") throw new Refusal(405, "GET the drain");
150
+ return { status: 200, body: { schema: RAFT_DRAIN, events: [] } };
151
+ }
152
+ if (request.method !== "POST") throw new Refusal(405, "POST a ring");
153
+ const body = await bodyOf(request);
154
+ if (path === "/notify") {
155
+ const { app, event } = eventOf(body);
156
+ notify(options.root, app, event);
157
+ return { status: 200, body: { ok: true } };
158
+ }
159
+ if (body.schema !== RAFT_WAKE) throw new Refusal(426, `this door takes ${RAFT_WAKE}`, "protocol_mismatch");
160
+ const message = text(body.messageId) ?? text(body.eventId);
161
+ if (!message) throw new Refusal(400, "a wake names its message", "protocol_mismatch");
162
+ await options.beforeRaftWake?.().catch(() => void 0);
163
+ notify(options.root, "raft", { subject: "inbox", line: RAFT_LINE, urgency: "wake", id: `raft:${message}` });
164
+ return { status: 200, body: { ok: true, runtimeSession: options.session } };
165
+ };
166
+ const server = createServer((request, response) => {
167
+ handle(request).then(
168
+ ({ status, body }) => answer(response, status, body),
169
+ (error) => {
170
+ const refusal = error instanceof Refusal ? error : new Refusal(500, String(error), "injection_failed");
171
+ answer(response, refusal.status, {
172
+ ok: false,
173
+ ...refusal.failureClass ? { failureClass: refusal.failureClass } : {},
174
+ reason: refusal.message
175
+ });
176
+ }
177
+ );
178
+ });
179
+ return new Promise((resolve2, reject) => {
180
+ server.once("error", reject);
181
+ server.listen(options.port ?? 0, "127.0.0.1", () => {
182
+ const { port } = server.address();
183
+ resolve2({
184
+ url: `http://127.0.0.1:${port}`,
185
+ port,
186
+ close: () => new Promise((closed) => server.close(() => closed()))
187
+ });
188
+ });
189
+ });
190
+ }
191
+
192
+ // ../bottega/src/proxy.ts
193
+ import { EnvHttpProxyAgent, setGlobalDispatcher } from "undici";
194
+ function envProxy(env = process.env) {
195
+ return env.HTTPS_PROXY || env.https_proxy || env.HTTP_PROXY || env.http_proxy || void 0;
196
+ }
197
+ function routeThroughEnvProxy(env = process.env) {
198
+ const proxy = envProxy(env);
199
+ if (!proxy) return void 0;
200
+ setGlobalDispatcher(new EnvHttpProxyAgent());
201
+ return proxy;
202
+ }
203
+
204
+ // ../bottega/src/replay.ts
205
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
206
+ import { tmpdir } from "node:os";
207
+ import { basename, join } from "node:path";
208
+ var WORKDIR_TOKEN = "\u241Fworkdir\u241F";
209
+ function pathForms(dir) {
210
+ const forms = /* @__PURE__ */ new Set([dir]);
211
+ try {
212
+ forms.add(realpathSync(dir));
213
+ } catch {
214
+ }
215
+ if (dir.startsWith("/var/")) forms.add(`/private${dir}`);
216
+ if (dir.startsWith("/private/")) forms.add(dir.slice("/private".length));
217
+ return [...forms].sort((a, b) => b.length - a.length);
218
+ }
219
+ function canonical(text2, forms) {
220
+ return forms.reduce((out, form) => out.split(form).join(WORKDIR_TOKEN), text2);
221
+ }
222
+ function firstDifferentLine(a, b) {
223
+ const left = a.split("\n");
224
+ const right = b.split("\n");
225
+ for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
226
+ if (left[i] !== right[i]) return i + 1;
227
+ }
228
+ return null;
229
+ }
230
+ function readMeta(dir) {
231
+ const path = join(dir, TRACE_META);
232
+ if (!existsSync(path)) {
233
+ throw new WorkspaceError(
234
+ `${path} not found \u2014 this recording predates \`meta.json\`, so there is nothing describing the run to rebuild it from. Re-record it to replay it.`
235
+ );
236
+ }
237
+ return JSON.parse(readFileSync(path, "utf8"));
238
+ }
239
+ function readScript(dir) {
240
+ const path = join(dir, TRACE_SCRIPT);
241
+ if (!existsSync(path)) throw new WorkspaceError(`${path} not found \u2014 nothing to replay`);
242
+ return readFileSync(path, "utf8").split("\n").filter((line) => line.trim());
243
+ }
244
+ function recordedPrompt(dir, stepNumber) {
245
+ const path = join(dir, TRACE_STEPS, `${String(stepNumber).padStart(4, "0")}.prompt.txt`);
246
+ return existsSync(path) ? readFileSync(path, "utf8") : void 0;
247
+ }
248
+ async function replayWorkspace(meta, script, workdir, home) {
249
+ const config = {
250
+ provider: FAUX_PROVIDER,
251
+ model: FAUX_PROVIDER,
252
+ // Not the recording's: the recorded turns already *are* the model's output,
253
+ // and asking the offline provider to think, or to retry, would only add
254
+ // what the recording does not have.
255
+ runtime: { baseUrl: null, thinking: null, retries: 0 },
256
+ workdir,
257
+ apps: meta.apps,
258
+ order: meta.order,
259
+ instructions: meta.instructions
260
+ };
261
+ const ws = await bootstrapWorkspace("replay", config, {
262
+ store: envStore(home),
263
+ budget: meta.screenBudget,
264
+ cwd: home
265
+ });
266
+ personSays(ws, meta.task, 0);
267
+ ws.save();
268
+ const rewrite = (text2) => workdir === meta.workdir ? text2 : text2.split(meta.workdir).join(workdir);
269
+ for (const turn of script) ws.pushScript(rewrite(turn));
270
+ return ws;
271
+ }
272
+ function compareStep(report, sides) {
273
+ const replayed = canonical(report.prompt, sides.replayed.forms);
274
+ const recordedRaw = recordedPrompt(sides.recorded.dir, report.step);
275
+ const recorded = recordedRaw === void 0 ? void 0 : canonical(recordedRaw, sides.recorded.forms);
276
+ if (replayed !== report.prompt) {
277
+ const readable = replayed.split(WORKDIR_TOKEN).join(sides.replayed.workdir);
278
+ writeFileSync(
279
+ join(sides.replayed.out, TRACE_STEPS, `${String(report.step).padStart(4, "0")}.prompt.txt`),
280
+ readable
281
+ );
282
+ }
283
+ const shared = recorded ? commonPrefix(recorded, replayed) : 0;
284
+ return {
285
+ step: report.step,
286
+ identical: recorded !== void 0 && recorded === replayed,
287
+ unchecked: recorded === void 0,
288
+ sharedShare: recorded?.length ? shared / recorded.length : 0,
289
+ line: recorded === void 0 || recorded === replayed ? null : firstDifferentLine(recorded, replayed),
290
+ actions: report.actions.map((action) => action.name)
291
+ };
292
+ }
293
+ async function replayTrace(options) {
294
+ const { dir } = options;
295
+ const meta = readMeta(dir);
296
+ const script = readScript(dir);
297
+ if (!options.workdir && !options.from) {
298
+ throw new WorkspaceError(
299
+ "replay needs a working directory: --from <dir> to copy a pristine tree into a scratch copy, or --workdir <dir> to run against one in place"
300
+ );
301
+ }
302
+ const home = mkdtempSync(join(tmpdir(), "bottega-replay-"));
303
+ let workdir = options.workdir ?? "";
304
+ if (options.from) {
305
+ if (!existsSync(options.from)) throw new WorkspaceError(`--from ${options.from} does not exist`);
306
+ workdir = join(home, basename(meta.workdir) || "workdir");
307
+ cpSync(options.from, workdir, { recursive: true });
308
+ }
309
+ const out = options.out ?? join(home, "trajectory");
310
+ mkdirSync(out, { recursive: true });
311
+ const ws = await replayWorkspace(meta, script, workdir, home);
312
+ const sides = {
313
+ recorded: { dir, forms: pathForms(meta.workdir) },
314
+ replayed: { out, forms: pathForms(workdir), workdir: meta.workdir }
315
+ };
316
+ const limit = Math.min(options.steps ?? script.length, script.length);
317
+ const steps = [];
318
+ let firstDivergence = null;
319
+ let outcome = limit < script.length ? "steps" : "script_exhausted";
320
+ let spoke = false;
321
+ const outer = { BOTTEGA_TRACE_DIR: process.env.BOTTEGA_TRACE_DIR, BOTTEGA_TRACE_GIT: process.env.BOTTEGA_TRACE_GIT };
322
+ process.env.BOTTEGA_TRACE_DIR = out;
323
+ delete process.env.BOTTEGA_TRACE_GIT;
324
+ try {
325
+ for (let i = 0; i < limit; i += 1) {
326
+ const report = await step(ws);
327
+ const result = compareStep(report, sides);
328
+ steps.push(result);
329
+ spoke ||= report.actions.some((action) => isSpeaking(ws.data.config.apps, action));
330
+ if (!result.identical && !result.unchecked && firstDivergence === null) firstDivergence = result.step;
331
+ options.onStep?.(result);
332
+ if (report.idle) {
333
+ outcome = spoke ? "done" : "idle";
334
+ break;
335
+ }
336
+ }
337
+ } finally {
338
+ for (const [name, value] of Object.entries(outer)) {
339
+ if (value === void 0) delete process.env[name];
340
+ else process.env[name] = value;
341
+ }
342
+ }
343
+ return { dir, out, workdir, meta, steps, firstDivergence, outcome };
344
+ }
345
+
346
+ // ../bottega/src/trace.ts
347
+ function embed(value) {
348
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
349
+ }
350
+ var STYLE = `
351
+ :root {
352
+ --bg: #0e1116; --panel: #151a22; --edge: #232b38; --ink: #d7dde8; --dim: #7d8798;
353
+ --accent: #6ea8ff; --warm: #ffb454; --good: #7ee0a8;
354
+ }
355
+ * { box-sizing: border-box; }
356
+ body {
357
+ margin: 0; background: var(--bg); color: var(--ink);
358
+ font: 13px/1.5 ui-sans-serif, -apple-system, "Segoe UI", sans-serif;
359
+ }
360
+ header {
361
+ display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap;
362
+ padding: 14px 22px; border-bottom: 1px solid var(--edge);
363
+ }
364
+ header h1 { font-size: 15px; margin: 0; font-weight: 600; }
365
+ header .meta { color: var(--dim); font-size: 12px; }
366
+ header code { color: var(--accent); font-family: ui-monospace, Menlo, monospace; }
367
+
368
+ /* -- the stage: the context as one vertical column ------------------------- */
369
+ #stage {
370
+ position: relative; height: 66vh; min-height: 380px; overflow: hidden;
371
+ background: radial-gradient(120% 80% at 50% 0%, #131924 0%, var(--bg) 70%);
372
+ }
373
+ #camera { position: absolute; inset: 0; transform-origin: 50% 0; transition: transform .55s cubic-bezier(.4,.1,.2,1); }
374
+ #column { position: absolute; top: 0; left: 50%; transition: transform .55s cubic-bezier(.4,.1,.2,1); }
375
+
376
+ .win {
377
+ position: absolute; left: 0; border-radius: 5px; overflow: hidden;
378
+ background: var(--panel); border: 1px solid var(--edge);
379
+ transition: top .55s cubic-bezier(.4,.1,.2,1), height .55s cubic-bezier(.4,.1,.2,1),
380
+ opacity .35s ease, filter .45s ease, box-shadow .35s ease, border-color .35s ease;
381
+ }
382
+ .win .bar {
383
+ display: flex; gap: 6px; align-items: center; white-space: nowrap;
384
+ padding: 0 6px; height: 15px; font: 600 9px/15px ui-monospace, Menlo, monospace;
385
+ background: #1b2230; border-bottom: 1px solid var(--edge);
386
+ }
387
+ .win .bar .dot { width: 5px; height: 5px; border-radius: 50%; flex: none; }
388
+ .win .bar .ttl { overflow: hidden; text-overflow: ellipsis; }
389
+ .win .bar .cost { margin-left: auto; color: var(--dim); font-weight: 400; }
390
+ .win pre {
391
+ margin: 0; padding: 1px 6px; font-family: ui-monospace, Menlo, monospace;
392
+ color: #b9c2d0; white-space: pre; overflow: hidden;
393
+ }
394
+ .win.focused { box-shadow: 0 0 0 1.5px var(--accent); border-color: var(--accent); }
395
+ .win.repainted { border-color: #6b4a20; }
396
+ .win.repainted .bar { background: #3a2a17; }
397
+ .win.repainted .bar .paint { color: var(--warm); }
398
+ .win .paint { color: #46506a; }
399
+ .win.locked { border-color: #3a4a63; }
400
+ .win.locked .bar { background: #182233; }
401
+ /* Off screen: still in the workspace, contributing nothing to the context. */
402
+ .win.offscreen { opacity: .32; filter: grayscale(1); }
403
+ .win.offscreen pre { display: none; }
404
+ .win.entering { opacity: 0; transform: translateY(10px); }
405
+ .win.leaving { opacity: 0; }
406
+
407
+ /* The context boundary: everything drawn inside it is this turn's prompt. */
408
+ #bounds {
409
+ position: absolute; left: 50%; pointer-events: none;
410
+ border: 1px solid rgba(110,168,255,.45); border-radius: 8px;
411
+ transition: top .55s cubic-bezier(.4,.1,.2,1), height .55s cubic-bezier(.4,.1,.2,1),
412
+ width .55s cubic-bezier(.4,.1,.2,1), transform .55s cubic-bezier(.4,.1,.2,1);
413
+ }
414
+ #bounds::before {
415
+ content: "IN CONTEXT"; position: absolute; top: -7px; left: 10px; padding: 0 6px;
416
+ background: #10141b; color: var(--accent); font: 600 8px/14px ui-monospace, Menlo, monospace;
417
+ letter-spacing: .12em;
418
+ }
419
+
420
+ /* -- transport ------------------------------------------------------------- */
421
+ #transport {
422
+ display: flex; align-items: center; gap: 12px; padding: 10px 22px;
423
+ border-top: 1px solid var(--edge); border-bottom: 1px solid var(--edge); background: #11151c;
424
+ }
425
+ button {
426
+ background: #1c2331; color: var(--ink); border: 1px solid var(--edge); border-radius: 5px;
427
+ padding: 5px 11px; font: 12px ui-sans-serif, sans-serif; cursor: pointer;
428
+ }
429
+ button:hover { border-color: var(--accent); color: #fff; }
430
+ #pos { font: 12px ui-monospace, Menlo, monospace; color: var(--dim); min-width: 96px; }
431
+ input[type=range] { flex: 1; accent-color: var(--accent); }
432
+
433
+ /* -- token timeline -------------------------------------------------------- */
434
+ #tokens { display: flex; align-items: flex-end; gap: 2px; height: 54px; padding: 8px 22px; }
435
+ #tokens .col { flex: 1; min-width: 3px; cursor: pointer; display: flex; flex-direction: column; justify-content: flex-end; }
436
+ #tokens .col .fresh { background: var(--warm); border-radius: 1px 1px 0 0; }
437
+ #tokens .col .reused { background: #2f5aa0; }
438
+ #tokens .col .sys { background: #2a3446; }
439
+ #tokens .col.on .fresh { background: #fff; }
440
+ #tokens .col:hover .fresh { background: var(--good); }
441
+
442
+ /* -- caption --------------------------------------------------------------- */
443
+ #caption { padding: 12px 22px 24px; border-top: 1px solid var(--edge); }
444
+ #caption .step { color: var(--accent); font: 600 12px ui-monospace, Menlo, monospace; }
445
+ #caption .say { margin: 6px 0 0; }
446
+ #caption ul { margin: 8px 0 0; padding: 0; list-style: none; }
447
+ #caption li { padding: 2px 0; font: 12px ui-monospace, Menlo, monospace; color: var(--dim); }
448
+ #caption li b { color: var(--warm); font-weight: 600; }
449
+ #caption li span { color: #93a0b4; }
450
+ .legend { color: var(--dim); font-size: 11px; padding: 0 22px 18px; }
451
+ .legend i { font-style: normal; color: var(--accent); }
452
+ `;
453
+ var SCRIPT = String.raw`
454
+ const APP_COLOR = {
455
+ chat: "#6ea8ff", files: "#7ee0a8", editor: "#ffb454", terminal: "#74d8e6",
456
+ journal: "#d99bff", notes: "#e6d074", tasks: "#f0a0c0", board: "#b8c0ff", slack: "#8ad0a0",
457
+ };
458
+ const WIDTH = 620, LINE_H = 9.6, BAR = 15, GAP = 10, PAD = 26;
459
+
460
+ const stage = document.getElementById("stage");
461
+ const camera = document.getElementById("camera");
462
+ const column = document.getElementById("column");
463
+ const bounds = document.getElementById("bounds");
464
+ const slider = document.getElementById("slider");
465
+ const pos = document.getElementById("pos");
466
+ const caption = document.getElementById("caption");
467
+ const tokensEl = document.getElementById("tokens");
468
+ const playBtn = document.getElementById("play");
469
+
470
+ const els = new Map();
471
+ let index = 0, timer = null;
472
+
473
+ /**
474
+ * The context is one-dimensional, so the picture is one column: each window a
475
+ * block, stacked in the order the model reads them, with height proportional to
476
+ * the lines it actually spends. Watching it across steps is watching the
477
+ * context breathe.
478
+ */
479
+ function layout(frame) {
480
+ const inContext = frame.windows.filter(w => w.onScreen);
481
+ const outside = frame.windows.filter(w => !w.onScreen);
482
+ // Paint order for what is in context; the rest listed after, collapsed.
483
+ const order = [...inContext].sort((a, b) => a.paint - b.paint);
484
+ const boxes = new Map();
485
+ let y = 0;
486
+ for (const w of order.concat(outside)) {
487
+ const h = w.onScreen ? BAR + Math.max(1, w.lines.length) * LINE_H + 3 : BAR;
488
+ boxes.set(w.id, { y, h, w });
489
+ y += h + GAP;
490
+ }
491
+ const contextHeight = order.reduce((sum, w) => sum + boxes.get(w.id).h + GAP, 0) - GAP;
492
+ return { boxes, total: Math.max(y - GAP, 1), contextHeight: Math.max(contextHeight, 1) };
493
+ }
494
+
495
+ function draw(i) {
496
+ index = Math.max(0, Math.min(FRAMES.length - 1, i));
497
+ const frame = FRAMES[index];
498
+ const { boxes, total, contextHeight } = layout(frame);
499
+
500
+ // Fit the whole column, so every step shows the entire context at once.
501
+ const scale = Math.max(0.2, Math.min(1.35, Math.min(
502
+ (stage.clientHeight - PAD * 2) / total,
503
+ (stage.clientWidth - PAD * 2) / WIDTH,
504
+ )));
505
+ camera.style.transform = "scale(" + scale + ")";
506
+ column.style.transform = "translate(" + (-WIDTH / 2) + "px," + (PAD / scale) + "px)";
507
+ bounds.style.width = (WIDTH + 16) + "px";
508
+ bounds.style.height = (contextHeight + 16) + "px";
509
+ bounds.style.top = (PAD - 8 * scale) + "px";
510
+ bounds.style.transform = "translateX(" + (-(WIDTH + 16) / 2 * scale) + "px) scale(" + scale + ")";
511
+ bounds.style.transformOrigin = "50% 0";
512
+
513
+ const seen = new Set();
514
+ for (const w of frame.windows) {
515
+ seen.add(w.id);
516
+ const box = boxes.get(w.id);
517
+ let el = els.get(w.id);
518
+ if (!el) {
519
+ el = document.createElement("div");
520
+ el.className = "win entering";
521
+ el.innerHTML = '<div class="bar"><span class="dot"></span><span class="ttl"></span>'
522
+ + '<span class="cost"></span><span class="paint"></span></div><pre></pre>';
523
+ column.appendChild(el);
524
+ els.set(w.id, el);
525
+ requestAnimationFrame(() => requestAnimationFrame(() => el.classList.remove("entering")));
526
+ }
527
+ const repainted = (frame.damaged || []).indexOf(w.id) >= 0;
528
+ el.classList.remove("leaving");
529
+ el.classList.toggle("offscreen", !w.onScreen);
530
+ el.classList.toggle("focused", !!w.focused);
531
+ el.classList.toggle("locked", !!w.locked);
532
+ el.classList.toggle("repainted", repainted && w.onScreen);
533
+ el.style.width = WIDTH + "px";
534
+ el.style.top = box.y + "px";
535
+ el.style.height = box.h + "px";
536
+ const color = APP_COLOR[w.app] || "#9aa6bb";
537
+ el.querySelector(".dot").style.background = color;
538
+ const place = "#" + (w.column + 1);
539
+ el.querySelector(".ttl").textContent = w.id + " " + w.app + " " + place + ((w.title || w.holding) ? " · " + (w.title || w.holding) : "");
540
+ el.querySelector(".ttl").style.color = color;
541
+ el.querySelector(".cost").textContent = w.onScreen
542
+ ? "~" + w.cost + "/" + w.budget + " tok"
543
+ : "not in context";
544
+ el.querySelector(".paint").textContent = w.onScreen ? (repainted ? " REPAINT" : " CACHED") : "";
545
+ const pre = el.querySelector("pre");
546
+ pre.style.fontSize = (LINE_H * 0.8).toFixed(2) + "px";
547
+ pre.style.lineHeight = LINE_H + "px";
548
+ pre.textContent = w.lines.join("\n");
549
+ }
550
+ for (const [id, el] of els) {
551
+ if (seen.has(id)) continue;
552
+ el.classList.add("leaving");
553
+ setTimeout(() => { el.remove(); els.delete(id); }, 400);
554
+ }
555
+
556
+ slider.value = String(index);
557
+ pos.textContent = "step " + frame.step + " / " + FRAMES[FRAMES.length - 1].step;
558
+ renderCaption(frame);
559
+ for (const col of tokensEl.children) col.classList.toggle("on", Number(col.dataset.i) === index);
560
+ }
561
+
562
+ function renderCaption(frame) {
563
+ const bits = ['<span class="step">step ' + frame.step + '</span> '
564
+ + '<span style="color:var(--dim)">context ~' + frame.promptTokens + ' tok'
565
+ + ' + system ~' + frame.systemTokens + ' tok'
566
+ + ' · prefix reused ~' + (frame.reusablePrefixTokens || 0) + ' tok ('
567
+ + Math.round((frame.reusablePrefixShare || 0) * 100) + '%)'
568
+ + (frame.usage ? ' · billed in=' + frame.usage.input + ' out=' + frame.usage.output : '')
569
+ + '</span>'];
570
+ if (frame.text && frame.text.trim()) bits.push('<p class="say">' + esc(frame.text.trim()) + '</p>');
571
+ if (frame.actions && frame.actions.length) {
572
+ bits.push('<ul>' + frame.actions.map(a =>
573
+ '<li><b>' + esc(a.name) + '</b> ' + esc(compact(a.arguments)) + '<br><span>→ ' + esc(a.note) + '</span></li>'
574
+ ).join("") + '</ul>');
575
+ } else {
576
+ bits.push('<ul><li><span>(final state)</span></li></ul>');
577
+ }
578
+ caption.innerHTML = bits.join("");
579
+ }
580
+
581
+ function compact(args) {
582
+ const s = JSON.stringify(args || {});
583
+ return s.length > 220 ? s.slice(0, 219) + "…" : s;
584
+ }
585
+ function esc(s) {
586
+ return String(s).replace(/[&<>]/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;" }[c]));
587
+ }
588
+
589
+ function buildTokenTimeline() {
590
+ const max = Math.max(...FRAMES.map(f => f.promptTokens + f.systemTokens), 1);
591
+ FRAMES.forEach((f, i) => {
592
+ const col = document.createElement("div");
593
+ col.className = "col";
594
+ col.dataset.i = String(i);
595
+ const reused = Math.min(f.promptTokens, f.reusablePrefixTokens || 0);
596
+ col.title = "step " + f.step + " · context ~" + f.promptTokens + " tok (" + reused + " reused)";
597
+ for (const [cls, val] of [["fresh", f.promptTokens - reused], ["reused", reused], ["sys", f.systemTokens]]) {
598
+ const d = document.createElement("div");
599
+ d.className = cls;
600
+ d.style.height = (val / max * 38) + "px";
601
+ col.appendChild(d);
602
+ }
603
+ col.onclick = () => { stop(); draw(i); };
604
+ tokensEl.appendChild(col);
605
+ });
606
+ }
607
+
608
+ function stop() { if (timer) { clearInterval(timer); timer = null; playBtn.textContent = "▶ play"; } }
609
+ function play() {
610
+ if (timer) return stop();
611
+ playBtn.textContent = "❚❚ pause";
612
+ timer = setInterval(() => { if (index >= FRAMES.length - 1) return stop(); draw(index + 1); }, 1700);
613
+ }
614
+
615
+ slider.max = String(FRAMES.length - 1);
616
+ slider.oninput = () => { stop(); draw(Number(slider.value)); };
617
+ playBtn.onclick = play;
618
+ document.getElementById("prev").onclick = () => { stop(); draw(index - 1); };
619
+ document.getElementById("next").onclick = () => { stop(); draw(index + 1); };
620
+ document.getElementById("first").onclick = () => { stop(); draw(0); };
621
+ document.getElementById("last").onclick = () => { stop(); draw(FRAMES.length - 1); };
622
+ addEventListener("keydown", e => {
623
+ if (e.key === "ArrowLeft") { stop(); draw(index - 1); }
624
+ else if (e.key === "ArrowRight") { stop(); draw(index + 1); }
625
+ else if (e.key === " ") { e.preventDefault(); play(); }
626
+ });
627
+ addEventListener("resize", () => draw(index));
628
+
629
+ buildTokenTimeline();
630
+ draw(0);
631
+ `;
632
+ function renderTraceHtml(meta, frames) {
633
+ const last = frames.at(-1);
634
+ const peak = Math.max(0, ...frames.map((f) => f.promptTokens));
635
+ const cost = frames.reduce((sum, f) => sum + (f.usage?.cost ?? 0), 0);
636
+ return `<!doctype html>
637
+ <html lang="en"><head><meta charset="utf-8">
638
+ <meta name="viewport" content="width=device-width, initial-scale=1">
639
+ <title>bottega \xB7 ${meta.name} \xB7 trajectory</title>
640
+ <style>${STYLE}</style>
641
+ </head><body>
642
+ <header>
643
+ <h1>bottega \xB7 ${meta.name}</h1>
644
+ <span class="meta"><code>${meta.config.provider}/${meta.config.model ?? "-"}</code></span>
645
+ <span class="meta">${frames.length} frame(s) \xB7 ${last?.step ?? 0} step(s)</span>
646
+ <span class="meta">peak screen ~${peak} tok${cost ? ` \xB7 $${cost.toFixed(4)}` : ""}</span>
647
+ <span class="meta">paint ${meta.config.order ?? "stable"}</span>
648
+ </header>
649
+
650
+ <div id="stage">
651
+ <div id="camera"><div id="column"></div></div>
652
+ <div id="bounds"></div>
653
+ </div>
654
+
655
+ <div id="transport">
656
+ <button id="first">\u23EE</button>
657
+ <button id="prev">\u25C0</button>
658
+ <button id="play">\u25B6 play</button>
659
+ <button id="next">\u25B6</button>
660
+ <button id="last">\u23ED</button>
661
+ <span id="pos"></span>
662
+ <input id="slider" type="range" min="0" value="0" step="1">
663
+ </div>
664
+
665
+ <div id="tokens"></div>
666
+
667
+ <div id="caption"></div>
668
+ <p class="legend">
669
+ The column <i>is</i> the context, top to bottom in the order the model reads it, each block as
670
+ tall as the tokens it spends. Inside the lit boundary is this turn's prompt; collapsed grey
671
+ windows still exist, with all their state, and cost nothing.
672
+ <i>CACHED</i> / <i>REPAINT</i> is damage tracking: unchanged windows are written first so they
673
+ stay a byte-identical prefix, and only the repainted tail has to be re-read. Bars above, bottom
674
+ to top: static system prefix, reused prefix, fresh tokens. \u2190 / \u2192 to step, space to play.
675
+ </p>
676
+
677
+ <script>const FRAMES = ${embed(frames)};</script>
678
+ <script>${SCRIPT}</script>
679
+ </body></html>
680
+ `;
681
+ }
682
+
683
+ // ../bottega/src/cli.ts
684
+ await installApps();
685
+ var store = bottegaStore();
686
+ var ORDERS = ["stable", "spatial"];
687
+ var URGENCIES2 = ["ambient", "notice", "wake"];
688
+ var UsageError = class extends Error {
689
+ };
690
+ function describePlan(plan) {
691
+ const { manifest, origin } = plan;
692
+ return [
693
+ `${manifest.label ?? manifest.name} (${manifest.name}) ${manifest.version ?? ""} \u2014 ${KIND_LABEL[plan.kind]}${manifest.author ? `, by ${manifest.author}` : ""}`,
694
+ ` ${manifest.about ?? manifest.summary}`,
695
+ ` from ${origin.source}${origin.commit ? ` @ ${origin.commit.slice(0, 12)}` : ""}${plan.replaces ? ` \u2014 replaces ${plan.replaces}` : ""}`,
696
+ ...plan.reach.map((line) => ` \xB7 ${line}`)
697
+ ];
698
+ }
699
+ function str(values, name) {
700
+ const value = values[name];
701
+ return typeof value === "string" ? value : void 0;
702
+ }
703
+ function flag(values, name) {
704
+ return values[name] === true;
705
+ }
706
+ function num(values, name, fallback) {
707
+ const raw = str(values, name);
708
+ if (raw === void 0) return fallback;
709
+ const match = /^\s*([0-9]*\.?[0-9]+)\s*([kKmM])?\s*$/.exec(raw);
710
+ if (!match) throw new UsageError(`--${name} must be a number, e.g. 256000, 256k or 1M (got '${raw}')`);
711
+ const scale = { k: 1e3, m: 1e6 }[(match[2] ?? "").toLowerCase()] ?? 1;
712
+ return Number(match[1]) * scale;
713
+ }
714
+ function choice(values, name, allowed2, fallback) {
715
+ const raw = str(values, name);
716
+ if (raw === void 0) return fallback;
717
+ if (!allowed2.includes(raw)) {
718
+ throw new UsageError(`--${name} must be one of: ${allowed2.join(", ")} (got '${raw}')`);
719
+ }
720
+ return raw;
721
+ }
722
+ function requireWorkspace(positionals) {
723
+ const name = positionals[0];
724
+ if (!name) throw new UsageError("missing <workspace> argument");
725
+ return Workspace.open(store, name);
726
+ }
727
+ function readText(values, positional) {
728
+ const text2 = str(values, "text") ?? positional;
729
+ if (text2 !== void 0) return text2;
730
+ const file = str(values, "file");
731
+ if (file) return readFileSync2(file, "utf8");
732
+ if (!process.stdin.isTTY) return readFileSync2(0, "utf8");
733
+ throw new UsageError("provide text via a positional arg, --text, --file, or stdin");
734
+ }
735
+ function human(tokens) {
736
+ if (tokens >= 1e6) return `${(tokens / 1e6).toFixed(tokens % 1e6 ? 2 : 0)}M`;
737
+ if (tokens >= 1e3) return `${Math.round(tokens / 1e3)}k`;
738
+ return String(tokens);
739
+ }
740
+ function budgetLine(ws) {
741
+ const asked = ws.data.config.contextBudget;
742
+ const screen = ws.data.viewport.budget;
743
+ const overhead = overheadTokens(ws.data.config.apps, ws.data.config.instructions, ws.data.config.features);
744
+ const scale = ws.data.tokens ? scaleOf(ws.data.tokens) : ESTIMATED;
745
+ const policy = screenFromContext(asked ?? 0, overhead, scale) - (scale.chrome ?? 0);
746
+ const capped = asked && policy > screen ? ", capped by the model" : "";
747
+ return `context=${asked ? human(asked) : "?"} \u2192 screen=~${screen.toLocaleString()} tok (after ~${overhead.toLocaleString()} tok of prompt + schemas${capped})`;
748
+ }
749
+ async function workspaceFromFlags(name, values) {
750
+ const instructionsFile = str(values, "instructions-file");
751
+ const thinking = str(values, "thinking") === void 0 ? void 0 : choice(values, "thinking", THINKING_LEVELS, "off");
752
+ const config = newWorkspaceConfig(
753
+ {
754
+ provider: str(values, "provider"),
755
+ model: str(values, "model"),
756
+ baseUrl: str(values, "base-url"),
757
+ thinking,
758
+ workdir: str(values, "workdir") ?? process.cwd(),
759
+ apps: str(values, "apps")?.split(",").map((a) => a.trim()).filter(Boolean),
760
+ order: str(values, "order") === void 0 ? void 0 : choice(values, "order", ORDERS, "stable"),
761
+ retries: str(values, "retries") === void 0 ? void 0 : num(values, "retries", 3),
762
+ features: values.feature === void 0 ? void 0 : values.feature,
763
+ contextBudget: str(values, "context") === void 0 ? void 0 : num(values, "context", DEFAULT_CONTEXT_BUDGET),
764
+ instructions: instructionsFile ? readFileSync2(instructionsFile, "utf8") : str(values, "instructions")
765
+ },
766
+ readSettings(),
767
+ { contextBudget: DEFAULT_CONTEXT_BUDGET, thinking: "off" }
768
+ );
769
+ return createWorkspace(name, config, { bare: flag(values, "bare") });
770
+ }
771
+ var COMMANDS = {
772
+ solve: {
773
+ summary: "one-shot: create a workspace, give it a task, run until it yields",
774
+ usage: 'bottega solve --provider <id> --model <id> [--workdir dir] [--steps N] [--feature name] "<task>"',
775
+ options: {
776
+ provider: { type: "string" },
777
+ model: { type: "string" },
778
+ "base-url": { type: "string" },
779
+ thinking: { type: "string" },
780
+ workdir: { type: "string" },
781
+ apps: { type: "string" },
782
+ context: { type: "string" },
783
+ retries: { type: "string" },
784
+ feature: { type: "string", multiple: true },
785
+ steps: { type: "string" },
786
+ deadline: { type: "string" },
787
+ quiet: { type: "boolean" }
788
+ },
789
+ async run(values, positionals) {
790
+ const task = positionals.join(" ").trim();
791
+ if (!task) throw new UsageError("give the task as a positional argument");
792
+ const ws = await workspaceFromFlags(Workspace.newSessionId(), values);
793
+ if (conversationApp(ws.data.config.apps)) personSays(ws, task, 0);
794
+ else if (ws.data.config.apps.includes("problem")) await openWindow(ws, "problem", task);
795
+ else
796
+ throw new UsageError(
797
+ "solve needs somewhere to put the task: an app with a conversation, or `problem`, in --apps"
798
+ );
799
+ const deadline = Number(str(values, "deadline") ?? 0);
800
+ if (deadline > 0) ws.data.deadline = { at: Date.now() + deadline * 1e3, seconds: deadline };
801
+ ws.save();
802
+ traceMeta(ws, task);
803
+ const quiet = flag(values, "quiet");
804
+ let lastTurn = transcript(ws).at(-1)?.id ?? "";
805
+ const drain = () => {
806
+ const turns = transcript(ws);
807
+ const from = lastTurn ? turns.findIndex((turn) => turn.id === lastTurn) + 1 : 0;
808
+ for (const turn of turns.slice(from)) {
809
+ if (turn.who === "agent") console.log(`
810
+ ${turn.text}
811
+ `);
812
+ }
813
+ lastTurn = turns.at(-1)?.id ?? lastTurn;
814
+ };
815
+ const limit = num(values, "steps", 40);
816
+ const { steps, outcome } = await runSession(ws, {
817
+ limit,
818
+ onStep(report) {
819
+ drain();
820
+ if (quiet) return;
821
+ for (const action of report.actions) console.log(`\xB7 ${action.name} \u2192 ${action.note}`);
822
+ }
823
+ });
824
+ writeResult(summarize(ws, outcome, steps));
825
+ if (outcome.startsWith("inference_error")) {
826
+ console.error(outcome);
827
+ process.exitCode = 1;
828
+ }
829
+ }
830
+ },
831
+ list: {
832
+ summary: "sessions here, newest first",
833
+ usage: "bottega list [--all]",
834
+ options: { all: { type: "boolean" } },
835
+ run(values) {
836
+ const everywhere = flag(values, "all");
837
+ const roots = everywhere ? Workspace.projectRoots(store) : [process.cwd()];
838
+ let found = 0;
839
+ for (const root of roots) {
840
+ const sessions = Workspace.sessions(store, root);
841
+ if (!sessions.length) continue;
842
+ if (everywhere) console.log(`
843
+ ${root}`);
844
+ for (const session of sessions) {
845
+ const ws = Workspace.open(store, session.id, root);
846
+ const said = openingLine(ws, 46);
847
+ const when = new Date(session.at).toLocaleString();
848
+ console.log(
849
+ ` ${session.id.padEnd(14)} ${String(ws.data.step).padStart(3)} steps ${when}${said ? ` ${said}` : ""}`
850
+ );
851
+ found += 1;
852
+ }
853
+ }
854
+ if (!found)
855
+ console.log(everywhere ? "no sessions yet" : `no sessions in ${process.cwd()} \u2014 run \`bottega\` to start one`);
856
+ }
857
+ },
858
+ delete: {
859
+ summary: "delete sessions here",
860
+ usage: "bottega delete <id>\u2026 | bottega delete --all | bottega delete --empty",
861
+ options: { all: { type: "boolean" }, empty: { type: "boolean" } },
862
+ run(values, positionals) {
863
+ const here = Workspace.sessions(store);
864
+ if (!here.length) {
865
+ console.log(`no sessions in ${process.cwd()}`);
866
+ return;
867
+ }
868
+ const doomed = flag(values, "all") ? here : flag(values, "empty") ? here.filter((session) => Workspace.open(store, session.id).data.step === 0) : positionals.map((wanted) => {
869
+ const matches = here.filter((session) => session.id === wanted || session.id.startsWith(wanted));
870
+ const exact = matches.find((session) => session.id === wanted);
871
+ if (!matches.length) throw new UsageError(`no session here starting with '${wanted}'`);
872
+ if (!exact && matches.length > 1) {
873
+ throw new UsageError(`'${wanted}' matches ${matches.map((s) => s.id).join(", ")} \u2014 say which`);
874
+ }
875
+ return exact ?? matches[0];
876
+ });
877
+ if (!doomed.length) throw new UsageError("say which \u2014 an id, or --all, or --empty");
878
+ for (const session of doomed) {
879
+ Workspace.remove(store, session.id);
880
+ console.log(`deleted ${session.id}`);
881
+ }
882
+ }
883
+ },
884
+ render: {
885
+ summary: "print the exact prompt the model would see this turn",
886
+ usage: "bottega render <workspace> [--system]",
887
+ options: { system: { type: "boolean" } },
888
+ run(values, positionals) {
889
+ const ws = requireWorkspace(positionals);
890
+ if (flag(values, "system")) {
891
+ const prompt = systemPrompt(
892
+ ws.data.config.apps,
893
+ ws.data.config.instructions ?? void 0,
894
+ ws.data.config.features
895
+ );
896
+ console.log(prompt);
897
+ console.error(
898
+ `
899
+ [system prompt ~${estimateTokens(prompt)} tok, ${toolsFor(ws.data.config.apps).length} tools]`
900
+ );
901
+ return;
902
+ }
903
+ const text2 = renderWorkspace(ws);
904
+ console.log(text2);
905
+ console.error(`[~${estimateTokens(text2)} tok]`);
906
+ }
907
+ },
908
+ set: {
909
+ summary: "change a workspace's rendering knobs",
910
+ usage: "bottega set <workspace> [--order stable|spatial] [--context N]",
911
+ options: { order: { type: "string" }, context: { type: "string" } },
912
+ run(values, positionals) {
913
+ const ws = requireWorkspace(positionals);
914
+ const config = ws.data.config;
915
+ if (values.order) config.order = choice(values, "order", ORDERS, "stable");
916
+ if (values.context) {
917
+ config.contextBudget = num(values, "context", DEFAULT_CONTEXT_BUDGET);
918
+ fitScreen(ws, { asked: true });
919
+ }
920
+ ws.save();
921
+ console.log(`order=${config.order} ${budgetLine(ws)}`);
922
+ }
923
+ },
924
+ trace: {
925
+ summary: "render the trajectory as an animated window manager (HTML)",
926
+ usage: "bottega trace <workspace> [--out trace.html] [--open]",
927
+ options: { out: { type: "string" }, open: { type: "boolean" } },
928
+ run(values, positionals) {
929
+ const ws = requireWorkspace(positionals);
930
+ const frames = ws.frames();
931
+ if (!frames.length) throw new WorkspaceError(`workspace '${ws.name}' has no recorded steps yet`);
932
+ const final = {
933
+ ...captureFrame(ws, ws.data.step + 1),
934
+ thinking: "",
935
+ text: "",
936
+ actions: [],
937
+ damaged: [],
938
+ reusablePrefixTokens: 0,
939
+ reusablePrefixShare: 0,
940
+ promptTokens: estimateTokens(renderWorkspace(ws)),
941
+ systemTokens: estimateTokens(
942
+ systemPrompt(ws.data.config.apps, ws.data.config.instructions ?? void 0, ws.data.config.features)
943
+ )
944
+ };
945
+ const out = resolve(str(values, "out") ?? `${ws.name}-trace.html`);
946
+ writeFileSync2(out, renderTraceHtml({ name: ws.name, config: ws.data.config }, [...frames, final]));
947
+ console.log(`wrote ${out} (${frames.length + 1} frames)`);
948
+ if (flag(values, "open")) spawnSync("open", [out]);
949
+ }
950
+ },
951
+ replay: {
952
+ summary: "re-run a recorded trajectory offline and diff it against the recording",
953
+ // --workdir at the *recorded* path is what makes a replay byte-exact: the
954
+ // screen and the agent's own commands both name the directory, and no
955
+ // amount of translating a different path recovers an elided one.
956
+ usage: "bottega replay <trace-dir> (--from <pristine-dir> | --workdir <dir>) [--out dir] [--steps N]",
957
+ options: {
958
+ from: { type: "string" },
959
+ workdir: { type: "string" },
960
+ out: { type: "string" },
961
+ steps: { type: "string" }
962
+ },
963
+ async run(values, positionals) {
964
+ const dir = positionals[0];
965
+ if (!dir) throw new UsageError("missing <trace-dir> argument (the directory holding meta.json)");
966
+ const report = await replayTrace({
967
+ dir: resolve(dir),
968
+ ...str(values, "from") ? { from: resolve(str(values, "from")) } : {},
969
+ ...str(values, "workdir") ? { workdir: resolve(str(values, "workdir")) } : {},
970
+ ...str(values, "out") ? { out: resolve(str(values, "out")) } : {},
971
+ ...str(values, "steps") ? { steps: num(values, "steps", 0) } : {},
972
+ onStep(result) {
973
+ const label = result.unchecked ? "\xB7 not in the recording" : result.identical ? "\u2713 identical" : `\u2717 diverged at line ${result.line} (${(result.sharedShare * 100).toFixed(1)}% shared)`;
974
+ console.log(` step ${String(result.step).padStart(3)} ${label} ${result.actions.join(" ")}`);
975
+ }
976
+ });
977
+ const diverged = report.steps.filter((s) => !s.identical && !s.unchecked).length;
978
+ console.log(`
979
+ recording ${report.dir}`);
980
+ console.log(` recorded by ${report.meta.commit ?? "(unknown commit)"} on ${report.meta.started}`);
981
+ console.log(` workdir ${report.workdir}`);
982
+ console.log(` replay ${report.out}`);
983
+ console.log(
984
+ diverged === 0 ? `
985
+ ${report.steps.length} step(s) reproduced exactly (${report.outcome})` : `
986
+ ${diverged} of ${report.steps.length} step(s) diverged, first at step ${report.firstDivergence} (${report.outcome})
987
+ diff -ru ${join2(report.dir, "steps")} ${join2(report.out, "steps")}`
988
+ );
989
+ if (diverged > 0) process.exitCode = 1;
990
+ }
991
+ },
992
+ budget: {
993
+ summary: "what each window costs this turn, and what a message list would have cost",
994
+ usage: "bottega budget <workspace>",
995
+ run(_values, positionals) {
996
+ const ws = requireWorkspace(positionals);
997
+ const report = costs(ws);
998
+ console.log("window app state budget buffered on-screen whole buffer");
999
+ for (const row of report.rows) {
1000
+ console.log(
1001
+ `${row.id.padEnd(8)} ${row.app.padEnd(9)} ${(row.visible ? "visible" : "off-screen").padEnd(11)} ${String(row.budget).padStart(6)} ${String(row.buffered).padStart(8)} ${String(row.tokens).padStart(9)} ${String(row.bufferTokens).padStart(12)}`
1002
+ );
1003
+ }
1004
+ const sys = estimateTokens(
1005
+ systemPrompt(ws.data.config.apps, ws.data.config.instructions ?? void 0, ws.data.config.features)
1006
+ );
1007
+ const tools = toolsFor(ws.data.config.apps);
1008
+ const schemas = estimateTokens(JSON.stringify(tools));
1009
+ console.log(
1010
+ `
1011
+ prompt this turn: ~${report.rendered} tok workspace + ~${sys} tok system + ~${schemas} tok schemas (${tools.length} tools) = ~${report.rendered + sys + schemas}`
1012
+ );
1013
+ console.log(`fixed overhead, paid every request: ~${sys + schemas} tok`);
1014
+ console.log(`all buffers in full (lower bound for a message list): ~${report.ifUnbounded} tok`);
1015
+ const total = ws.totalUsage();
1016
+ if (total) {
1017
+ console.log(
1018
+ `billed so far: in=${total.input + total.cacheRead + total.cacheWrite} out=${total.output} $${total.cost.total.toFixed(5)} over ${ws.data.step} step(s)`
1019
+ );
1020
+ }
1021
+ }
1022
+ },
1023
+ windows: {
1024
+ summary: "list the windows, in the order they are painted",
1025
+ usage: "bottega windows <workspace>",
1026
+ run(_values, positionals) {
1027
+ const ws = requireWorkspace(positionals);
1028
+ ws.allocateBudgets();
1029
+ const painted = paintOrder(ws, composited(ws), ws.data.config.order ?? "stable");
1030
+ painted.forEach((win, index) => {
1031
+ const view = slice(win, ctxOf(ws));
1032
+ const marks = [
1033
+ win.locked ? "locked" : "",
1034
+ win.collapsed ? "stood down" : "",
1035
+ ws.data.focus === win.id ? "focus" : ""
1036
+ ].filter(Boolean);
1037
+ console.log(
1038
+ `#${String(index + 1).padStart(2)} ${win.id.padEnd(5)} ${win.app.padEnd(8)} ${(win.title || "-").padEnd(24)} ~${String(view.cost).padStart(4)}/${String(win.budget).padEnd(5)} tok ln ${view.from}-${view.to}/${view.total}${marks.length ? ` [${marks.join(", ")}]` : ""}`
1039
+ );
1040
+ });
1041
+ const { budget: screen } = ws.data.viewport;
1042
+ console.log(
1043
+ `
1044
+ screen: ${painted.length} window(s) in ~${screen} tok${ws.locked.length ? `; locked: ${ws.locked.map((w) => w.id).join(", ")}` : ""}`
1045
+ );
1046
+ }
1047
+ },
1048
+ wm: {
1049
+ summary: "run any window-manager action by hand (focus, close, resize, ...)",
1050
+ usage: `bottega wm <workspace> <action> '{"window": "w3", "tokens": 3000}'`,
1051
+ async run(_values, positionals) {
1052
+ const ws = requireWorkspace(positionals);
1053
+ const action = positionals[1];
1054
+ if (!action)
1055
+ throw new UsageError(
1056
+ `missing <action> (one of: ${toolsFor(ws.data.config.apps).map((tool) => tool.name).join(", ")})`
1057
+ );
1058
+ const raw = positionals.slice(2).join(" ") || "{}";
1059
+ let args;
1060
+ try {
1061
+ args = JSON.parse(raw);
1062
+ } catch (error) {
1063
+ throw new UsageError(`arguments must be JSON: ${raw} (${String(error)})`);
1064
+ }
1065
+ const result = await applyAction(ws, { type: "toolCall", id: "manual", name: action, arguments: args });
1066
+ ws.save();
1067
+ console.log(result.note);
1068
+ }
1069
+ },
1070
+ notify: {
1071
+ summary: "tell a session something happened: a line on its screen, windows drawn again, a turn",
1072
+ usage: 'bottega notify <session> "<line>" [--app name] [--subject s] [--urgency ambient|notice|wake] [--refresh w3,w7] [--from who] [--id id]',
1073
+ options: {
1074
+ app: { type: "string" },
1075
+ subject: { type: "string" },
1076
+ urgency: { type: "string" },
1077
+ refresh: { type: "string" },
1078
+ from: { type: "string" },
1079
+ id: { type: "string" },
1080
+ text: { type: "string" },
1081
+ file: { type: "string" }
1082
+ },
1083
+ run(values, positionals) {
1084
+ const ws = requireWorkspace(positionals);
1085
+ const line = readText(values, positionals.slice(1).join(" ") || void 0).trim();
1086
+ if (!line) throw new UsageError('say what happened: bottega notify <session> "<line>"');
1087
+ const app = str(values, "app") ?? "notify";
1088
+ const urgency = choice(values, "urgency", URGENCIES2, "notice");
1089
+ const refresh = str(values, "refresh")?.split(",").map((id) => id.trim()).filter(Boolean);
1090
+ notify(ws.root, app, {
1091
+ subject: str(values, "subject") ?? app,
1092
+ line,
1093
+ urgency,
1094
+ ...refresh?.length ? { refresh } : {},
1095
+ ...str(values, "from") ? { from: str(values, "from") } : {},
1096
+ ...str(values, "id") ? { id: str(values, "id") } : {}
1097
+ });
1098
+ console.log(`${ws.name} \u2190 ${app}: ${line} (${urgency})`);
1099
+ }
1100
+ },
1101
+ doorbell: {
1102
+ summary: "open a session's doorbell on a local port, so a push from outside rings its inbox",
1103
+ usage: "bottega doorbell <session> [--port n] [--raft <raft command>] (BOTTEGA_DOORBELL_TOKEN: a secret every ring must carry)",
1104
+ options: { port: { type: "string" }, raft: { type: "string" } },
1105
+ async run(values, positionals) {
1106
+ const ws = requireWorkspace(positionals);
1107
+ const port = str(values, "port");
1108
+ if (port !== void 0 && !/^\d+$/.test(port)) throw new UsageError("--port is a number");
1109
+ const raftCommand = str(values, "raft");
1110
+ const bell = await doorbell({
1111
+ root: ws.root,
1112
+ session: ws.name,
1113
+ ...port ? { port: Number(port) } : {},
1114
+ ...process.env.BOTTEGA_DOORBELL_TOKEN ? { token: process.env.BOTTEGA_DOORBELL_TOKEN } : {},
1115
+ // With the session's raft app: Raft's list is asked for as its wake arrives, and kept where the app reads it.
1116
+ ...raftCommand ? { beforeRaftWake: () => keepList(join2(ws.root, "apps", "raft"), raftCommand) } : {}
1117
+ });
1118
+ console.log(`${ws.name} \xB7 doorbell at ${bell.url}`);
1119
+ console.log(` anything: POST ${bell.url}/notify {"line": "\u2026"}`);
1120
+ console.log(
1121
+ ` Raft: raft agent bridge --wake-adapter wake-channel --wake-channel-endpoint ${bell.url}/raft/wake`
1122
+ );
1123
+ await new Promise(() => {
1124
+ });
1125
+ }
1126
+ },
1127
+ serve: {
1128
+ summary: "be driven by a host: one session, JSON lines on stdin and stdout",
1129
+ usage: "bottega serve (the lines are described at the top of bottega/src/serve.ts)",
1130
+ async run() {
1131
+ console.log = (...args) => console.error(...args);
1132
+ await serve(process.stdin, process.stdout);
1133
+ }
1134
+ },
1135
+ script: {
1136
+ summary: "queue one scripted turn for the offline `faux` provider",
1137
+ usage: "bottega script <workspace> '<think:/text:/action: lines>'",
1138
+ options: { text: { type: "string" }, file: { type: "string" } },
1139
+ run(values, positionals) {
1140
+ const ws = requireWorkspace(positionals);
1141
+ ws.pushScript(readText(values, positionals.slice(1).join(" ") || void 0));
1142
+ console.log("queued 1 scripted turn");
1143
+ }
1144
+ },
1145
+ app: {
1146
+ summary: "the apps on this machine: packages under ~/.bottega/apps, from a path, a repository or a URL",
1147
+ usage: "bottega app list | add <source> [--as name] [--yes] | update [name] | remove <name> | info <source> | check [dir] | auth <name> | signout <name>",
1148
+ options: { as: { type: "string" }, yes: { type: "boolean" } },
1149
+ async run(values, positionals) {
1150
+ const [verb, target] = positionals;
1151
+ const confirm = async (plan) => {
1152
+ console.log(describePlan(plan).join("\n"));
1153
+ if (values.yes === true || !plan.runsCode) return true;
1154
+ if (!process.stdin.isTTY) throw new UsageError("this app runs code here; say --yes to install it unasked");
1155
+ const asking = createInterface({ input: process.stdin, output: process.stdout });
1156
+ const answer = await asking.question("install it? [y/N] ");
1157
+ asking.close();
1158
+ return /^y(es)?$/i.test(answer.trim());
1159
+ };
1160
+ if (verb === "add") {
1161
+ if (!target) throw new UsageError("give a source: a path, owner/repo[/dir][@ref], or a git or manifest URL");
1162
+ const entry = await addApp(target, { confirm, ...str(values, "as") ? { as: str(values, "as") } : {} });
1163
+ console.log(entry ? `installed ${entry.name} ${entry.receipt.version} \u2014 ${entry.dir}` : "not installed");
1164
+ return;
1165
+ }
1166
+ if (verb === "info") {
1167
+ if (!target) throw new UsageError("give the source to look at");
1168
+ const staged = await stage(target);
1169
+ console.log(describePlan(staged).join("\n"));
1170
+ staged.discard();
1171
+ return;
1172
+ }
1173
+ if (verb === "update") {
1174
+ for (const result of await update(target, { confirm }))
1175
+ console.log(
1176
+ result.changed ? `${result.name}: ${result.from} \u2192 ${result.to}` : `${result.name}: ${result.from}, current`
1177
+ );
1178
+ return;
1179
+ }
1180
+ if (verb === "check") {
1181
+ const { lines, warnings } = await check(target ?? ".");
1182
+ console.log(lines.join("\n"));
1183
+ for (const warning of warnings) console.log(`! ${warning}`);
1184
+ return;
1185
+ }
1186
+ if (verb === "auth") {
1187
+ if (!target) throw new UsageError("give the app to authorize");
1188
+ console.log(`opening the browser for ${target} \u2014 consent there, then come back here`);
1189
+ console.log(await authApp(target, store, (url) => spawnSync("open", [url], { stdio: "ignore" })));
1190
+ return;
1191
+ }
1192
+ if (verb === "signout") {
1193
+ if (!target) throw new UsageError("give the app to sign out of");
1194
+ console.log(await signOutApp(target, store));
1195
+ return;
1196
+ }
1197
+ if (verb === "remove") {
1198
+ if (!target) throw new UsageError("give the app to remove");
1199
+ console.log(`removed ${remove(target)}`);
1200
+ return;
1201
+ }
1202
+ if (verb === "list" || verb === void 0) {
1203
+ const problems = [];
1204
+ const entries = installed(void 0, problems);
1205
+ for (const entry of entries)
1206
+ console.log(
1207
+ `${entry.name.padEnd(14)} ${entry.receipt.version.padEnd(9)} ${kindOf(entry.manifest).padEnd(8)} ${entry.receipt.source}`
1208
+ );
1209
+ for (const problem of problems) console.log(`! ${problem}`);
1210
+ if (!entries.length) console.log(`no installed apps \u2014 bottega app add <source> puts one under ${appsDir()}`);
1211
+ return;
1212
+ }
1213
+ throw new UsageError(`bottega app has no '${verb}': ${this.usage}`);
1214
+ }
1215
+ },
1216
+ models: {
1217
+ summary: "list the providers and models pi offers",
1218
+ usage: "bottega models [provider] [--check] [--stale] [--json]",
1219
+ options: { check: { type: "boolean" }, stale: { type: "boolean" }, json: { type: "boolean" } },
1220
+ async run(values, positionals) {
1221
+ const models = allModels();
1222
+ if (!flag(values, "stale")) {
1223
+ for (const [id, error] of await refreshCatalog(models)) {
1224
+ console.error(`${id}: could not refresh \u2014 ${error.message}`);
1225
+ }
1226
+ }
1227
+ const providerId = positionals[0];
1228
+ if (flag(values, "json")) {
1229
+ const listed = await listAvailable(models, readSettings().defaults, providerId);
1230
+ console.log(JSON.stringify({ models: listed }));
1231
+ return;
1232
+ }
1233
+ if (providerId === FAUX_PROVIDER) {
1234
+ console.log(
1235
+ `${FAUX_PROVIDER} (offline) \u2014 one model, '${FAUX_PROVIDER}'. Apps run for real; the model's turns are
1236
+ queued with \`bottega script\`, using \`think:\` / \`text:\` / \`action: <tool> <json>\` lines.`
1237
+ );
1238
+ return;
1239
+ }
1240
+ if (providerId) {
1241
+ const provider = models.getProvider(providerId);
1242
+ if (!provider) throw new ModelError(`unknown provider '${providerId}'`);
1243
+ const list = [...models.getModels(providerId)].sort((a, b) => a.id.localeCompare(b.id));
1244
+ console.log(`${provider.name} (${provider.id}) \u2014 ${list.length} models`);
1245
+ for (const model of list) {
1246
+ const tags = [`ctx=${model.contextWindow}`];
1247
+ if (model.reasoning) tags.push("reasoning");
1248
+ console.log(` ${model.id.padEnd(40)} ${tags.join(" ")}`);
1249
+ }
1250
+ return;
1251
+ }
1252
+ const providers = [...models.getProviders()].sort((a, b) => a.id.localeCompare(b.id));
1253
+ const configured = /* @__PURE__ */ new Map();
1254
+ if (flag(values, "check")) {
1255
+ await Promise.all(
1256
+ providers.map(async (provider) => {
1257
+ try {
1258
+ const auth = await models.checkAuth(provider.id);
1259
+ if (auth) configured.set(provider.id, auth.source ?? auth.type);
1260
+ } catch {
1261
+ }
1262
+ })
1263
+ );
1264
+ }
1265
+ for (const provider of providers) {
1266
+ const source = configured.get(provider.id);
1267
+ console.log(
1268
+ `${provider.id.padEnd(16)} ${String([...models.getModels(provider.id)].length).padStart(4)} models` + (source ? ` [configured: ${source}]` : "")
1269
+ );
1270
+ }
1271
+ console.log(`${FAUX_PROVIDER.padEnd(16)} 1 models [offline, always available]`);
1272
+ }
1273
+ }
1274
+ };
1275
+ var GROUPS = [
1276
+ // Sessions here do not die of a full context, so a project tends to have one
1277
+ // and keeping it is the whole of session management. These exist for the
1278
+ // times that is not true, which is why they are not the first thing listed.
1279
+ ["sessions and models", ["list", "delete", "models"]],
1280
+ ["running it in batch", ["solve"]],
1281
+ ["looking inside", ["render", "windows", "budget", "wm", "set", "script"]],
1282
+ ["what a run left behind", ["trace", "replay"]],
1283
+ ["from outside", ["notify", "doorbell", "serve"]],
1284
+ ["apps on this machine", ["app"]]
1285
+ ];
1286
+ function help() {
1287
+ console.log("bottega \u2014 an AI agent whose state lives in apps, not in its context\n");
1288
+ console.log(" bottega <command> the command line: one task at a time, and a look inside any session");
1289
+ console.log(
1290
+ " the desktop from a checkout of https://github.com/botiverse/bottega: pnpm --filter bottega start"
1291
+ );
1292
+ const width = Math.max(...Object.keys(COMMANDS).map((name) => name.length));
1293
+ for (const [group, names] of GROUPS) {
1294
+ console.log(`
1295
+ ${group}`);
1296
+ for (const name of names) {
1297
+ const command = COMMANDS[name];
1298
+ if (command) console.log(` ${name.padEnd(width)} ${command.summary}`);
1299
+ }
1300
+ }
1301
+ console.log("\nrun `bottega <command> --help` for usage");
1302
+ }
1303
+ async function main() {
1304
+ routeThroughEnvProxy();
1305
+ const argv = process.argv.slice(2);
1306
+ const name = argv[0];
1307
+ if (name === "--help" || name === "-h" || name === "help") {
1308
+ help();
1309
+ return;
1310
+ }
1311
+ if (name === "--version") {
1312
+ console.log(bottegaVersion());
1313
+ return;
1314
+ }
1315
+ if (!name) {
1316
+ help();
1317
+ return;
1318
+ }
1319
+ const command = COMMANDS[name];
1320
+ if (!command) {
1321
+ console.error(`unknown command '${name}'
1322
+ `);
1323
+ help();
1324
+ process.exitCode = 2;
1325
+ return;
1326
+ }
1327
+ if (argv.includes("--help") || argv.includes("-h")) {
1328
+ console.log(command.usage);
1329
+ return;
1330
+ }
1331
+ const { values, positionals } = parseArgs({
1332
+ args: argv.slice(1),
1333
+ options: command.options ?? {},
1334
+ allowPositionals: true
1335
+ });
1336
+ const literal = positionals.indexOf("--");
1337
+ if (literal >= 0) positionals.splice(literal, 1);
1338
+ await command.run(values, positionals);
1339
+ }
1340
+ try {
1341
+ await main();
1342
+ } catch (error) {
1343
+ if (error instanceof UsageError) {
1344
+ console.error(`usage: ${error.message}`);
1345
+ process.exitCode = 2;
1346
+ } else if (error instanceof WorkspaceError || error instanceof ModelError || error instanceof ConfigError) {
1347
+ console.error(`error: ${error.message}`);
1348
+ process.exitCode = 1;
1349
+ } else {
1350
+ console.error(`error: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
1351
+ process.exitCode = 1;
1352
+ }
1353
+ } finally {
1354
+ process.stdout.write("", () => process.exit(process.exitCode ?? 0));
1355
+ }