Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
executable file
·755 lines (691 loc) · 29.4 KB
/
Copy pathindex.ts
File metadata and controls
executable file
·755 lines (691 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
#!/usr/bin/env bun
/**
* index.ts — Tabstack CLI entry point.
*
* A single subcommand router over the Tabstack AI API:
* extract markdown | extract json | generate json | research | automate | input | status
*
* Conventions (the "gold standard", matching the official Go CLI):
* - data → stdout, progress/errors → stderr
* - output is pretty on a TTY and JSON when piped; force with -o pretty|json
* (streaming commands emit one NDJSON line per event in JSON mode)
* - exit codes: 0 ok, 1 runtime/API error, 2 usage error, 3 task reported failure
* - --help / --version are handled before any network or key lookup
* - one clean "Error: <message>" line on failure
*/
import { getApiKey, resolveKey, getBaseUrl, setBaseUrl, ENDPOINTS, CONFIG_FILE } from "./config";
import { postJson, postStream, setRequestTimeout, TabstackError } from "./client";
import {
json,
ndjson,
progress,
green,
dimOut,
disableColor,
resolveMode,
resolveJsonArg,
resolveTextArg,
UsageError,
type OutputMode,
} from "./format";
import { login, logout } from "./auth";
import { RECIPES, HEAT_BADGE } from "./recipes";
import { SKILL_MD, AGENTS_SNIPPET } from "./skill";
import {
readState,
writeState,
readLedger,
addCalibration,
estimateRemaining,
syncFromConsole,
} from "./usage";
import { homedir } from "os";
import { join } from "path";
import { mkdirSync, writeFileSync, existsSync } from "fs";
// =============================================================================
// Arg parsing helpers
// =============================================================================
function getArg(args: string[], flag: string): string | undefined {
const idx = args.indexOf(flag);
if (idx >= 0 && idx + 1 < args.length) return args[idx + 1];
return undefined;
}
function hasFlag(args: string[], flag: string): boolean {
return args.includes(flag);
}
/** Nth positional arg, skipping flags and their values. */
function getPositional(args: string[], index: number): string | undefined {
let pos = 0;
for (let i = 0; i < args.length; i++) {
// A bare "-" is a value (stdin), not a flag.
if (args[i].length > 1 && args[i].startsWith("-")) {
// Boolean flags take no value; valued flags consume the next token.
if (!BOOLEAN_FLAGS.has(args[i])) i++;
continue;
}
if (pos === index) return args[i];
pos++;
}
return undefined;
}
/** Flags that do NOT consume a following value. */
const BOOLEAN_FLAGS = new Set([
"--json",
"--nocache",
"--metadata",
"--interactive",
"--allow-actions",
"--project",
"--no-browser",
"--no-verify",
"--no-color",
"-h",
"--help",
"-v",
"--version",
]);
/** Fail with a usage message (printed to stderr, exit 2). */
function usage(message: string): never {
throw new UsageError(message);
}
/** Expand "--flag=value" (and "-o=json") into ["--flag", "value"]. */
function expandEquals(args: string[]): string[] {
return args.flatMap((a) => {
if (a.length > 1 && a.startsWith("-") && a.includes("=")) {
const eq = a.indexOf("=");
return [a.slice(0, eq), a.slice(eq + 1)];
}
return [a];
});
}
/**
* Apply global flags (--base-url, --timeout, --no-color) and resolve the
* output mode. Called once before any command runs.
*/
function setupGlobals(args: string[]): OutputMode {
if (hasFlag(args, "--no-color")) disableColor();
const baseUrl = getArg(args, "--base-url");
if (baseUrl) setBaseUrl(baseUrl);
const timeout = getArg(args, "--timeout");
if (timeout) {
const secs = Number(timeout);
if (!Number.isFinite(secs) || secs <= 0) usage(`--timeout must be a positive number of seconds (got "${timeout}")`);
setRequestTimeout(secs);
}
return resolveMode(getArg(args, "-o") ?? getArg(args, "--output"), hasFlag(args, "--json"));
}
/** Shared option builders. */
function commonExtractOpts(args: string[]) {
const opts: Record<string, unknown> = {};
const effort = getArg(args, "--effort");
if (effort) {
if (!["min", "standard", "max"].includes(effort)) {
usage(`--effort must be min, standard, or max (got "${effort}")`);
}
opts.effort = effort;
}
if (hasFlag(args, "--nocache")) opts.nocache = true;
const geo = getArg(args, "--geo");
if (geo) opts.geo_target = { country: geo };
return opts;
}
// =============================================================================
// Help
// =============================================================================
const HELP = `
tabstack - CLI for the Tabstack AI web extraction, generation & automation API
Usage:
tabstack <command> [options]
Commands:
login Open the Tabstack console and store an API key
logout Remove the stored API key
status Show how your API key is being resolved (never prints it)
extract markdown <url> Fetch a page as clean markdown
extract json <url> --schema S Extract structured JSON matching a schema
generate json <url> --schema S --instructions T
AI-transform a page into JSON (summarize, classify, ...)
research <query> Multi-source autonomous research (streams progress)
automate <task> [--url U] Natural-language browser automation (streams progress)
input <request-id> --data D Respond to a paused automation that asked for input
recipes [n|name] Browse the cookbook (10 recipes, light to hard)
skill install [--project] Install the Claude Code skill (~/.claude/skills)
skill agents Print an AGENTS.md section (skill agents >> AGENTS.md)
usage Credit budget: balance, learned per-call costs, rate limit
usage set <credits> Calibrate from the console dashboard's credit balance
usage cookie <value> Store a console session cookie for automatic sync
usage sync Pull the balance from the console and recalibrate
help Show this help
version Show version
Global options:
-o, --output <pretty|json> Output mode (default: pretty on a TTY, json when piped)
--json Shorthand for -o json (streams emit NDJSON, one event/line)
--api-key <key> Override the TABSTACK_API_KEY env var
--base-url <url> Override the API base URL (or TABSTACK_BASE_URL)
--timeout <seconds> Request timeout for non-streaming calls
--no-color Disable colored output (NO_COLOR is also honored)
-h, --help Show this help
-v, --version Show version
Extract / generate options:
--schema <@file|-|inline> JSON schema: a file (@schema.json), stdin (-), or inline JSON
--instructions <@file|-|text> (generate) how to transform the page
--metadata (extract markdown) include page metadata in the response
--effort <min|standard|max> Speed vs. capability (default: standard)
--nocache Bypass cache, force a fresh fetch
--geo <CC> Fetch from a country (ISO 3166-1 alpha-2, e.g. US, GB)
Research options:
--mode <fast|balanced> Depth vs. speed (default: fast; balanced needs a paid plan)
--nocache Force fresh results
--fetch-timeout <seconds> Per-page fetch timeout
Automate options:
--url <url> Starting URL for the task
--data <@file|-|inline> Context data (e.g. form fields) as JSON
--guardrails <text> Safety constraints (default: browse & extract only)
--allow-actions Drop the default read-only guardrail (use with care)
--interactive Let the agent pause and ask for input (answer with 'tabstack input')
--max-iterations <n> Max agent iterations (1-100, default: 50)
--max-validation-attempts <n> Max validation attempts (1-10)
--geo <CC> Browse from a country (ISO 3166-1 alpha-2)
Input options (responding to a paused automation):
--data <@file|-|inline> {"fields":[{"ref":"...","value":"..."}]} or {"cancelled":true}
Login options:
--with-key <key> Store this key directly (skip the browser/prompt)
--no-browser Don't open the browser; just print the URL
--no-verify Skip the test API call that validates the key
Auth (resolved in order):
--api-key <key> → TABSTACK_API_KEY env → stored key from 'tabstack login'
Run 'tabstack login' once, or create a key at https://console.tabstack.ai
Exit codes:
0 success · 1 runtime/API error · 2 usage error · 3 task reported failure
Agents:
Piped output is always JSON; research/automate stream NDJSON (one event/line).
'tabstack recipes --json' lists ten ready patterns with runnable commands.
Full agent contract: AGENTS.md in the repo.
Examples:
tabstack login
tabstack login --with-key ts_xxx --no-verify
tabstack extract markdown https://example.com --metadata
tabstack extract markdown https://example.com | jq .
echo '{"type":"object","properties":{"title":{"type":"string"}}}' | \\
tabstack extract json https://news.ycombinator.com --schema -
tabstack extract json https://shop.example.com --schema @schema.json --effort max
tabstack generate json https://blog.example.com/post --schema @s.json \\
--instructions "Write a 2-sentence summary into 'summary'"
tabstack research "approaches to browser automation for AI agents" --mode fast
tabstack automate "find the top 3 trending repos and their stars" \\
--url https://github.com/trending
`;
function version(): string {
const pkg = require("../package.json");
return `tabstack ${pkg.version}`;
}
// =============================================================================
// Commands
// =============================================================================
async function cmdExtract(args: string[], mode: OutputMode): Promise<void> {
const sub = args[1];
if (sub === "markdown") {
const url = getPositional(args.slice(2), 0);
if (!url) usage("Usage: tabstack extract markdown <url> [--metadata] [--effort] [--nocache] [--geo CC]");
const body: Record<string, unknown> = { url, ...commonExtractOpts(args) };
if (hasFlag(args, "--metadata")) body.metadata = true;
const apiKey = getApiKey(getArg(args, "--api-key"));
const result = await postJson<{ url: string; content: string; metadata?: unknown }>(
ENDPOINTS.extractMarkdown,
body,
apiKey,
);
if (mode === "json") {
console.log(json(result));
} else {
console.log(result.content);
if (result.metadata !== undefined) console.log("\n" + json(result.metadata));
}
return;
}
if (sub === "json") {
const url = getPositional(args.slice(2), 0);
const schemaArg = getArg(args, "--schema");
if (!url || !schemaArg) {
usage("Usage: tabstack extract json <url> --schema <@file|-|inline> [--effort] [--nocache] [--geo CC]");
}
const json_schema = await resolveJsonArg(schemaArg, "--schema");
const apiKey = getApiKey(getArg(args, "--api-key"));
const result = await postJson(
ENDPOINTS.extractJson,
{ url, json_schema, ...commonExtractOpts(args) },
apiKey,
);
console.log(json(result));
return;
}
usage("Usage: tabstack extract <markdown|json> <url> [options]");
}
async function cmdGenerate(args: string[]): Promise<void> {
const sub = args[1];
if (sub !== "json") usage("Usage: tabstack generate json <url> --schema <...> --instructions <...>");
const url = getPositional(args.slice(2), 0);
const schemaArg = getArg(args, "--schema");
const instructionsArg = getArg(args, "--instructions");
if (!url || !schemaArg || !instructionsArg) {
usage("Usage: tabstack generate json <url> --schema <@file|-|inline> --instructions <@file|-|text> [--effort] [--nocache] [--geo CC]");
}
const json_schema = await resolveJsonArg(schemaArg, "--schema");
const instructions = await resolveTextArg(instructionsArg);
const apiKey = getApiKey(getArg(args, "--api-key"));
const result = await postJson(
ENDPOINTS.generateJson,
{ url, json_schema, instructions, ...commonExtractOpts(args) },
apiKey,
);
console.log(json(result));
}
async function cmdResearch(args: string[], outMode: OutputMode): Promise<void> {
const query = getPositional(args.slice(1), 0);
if (!query) {
usage('Usage: tabstack research "<query>" [--mode fast|balanced] [--nocache] [--fetch-timeout <s>]');
}
const apiKey = getApiKey(getArg(args, "--api-key"));
const body: Record<string, unknown> = { query };
const mode = getArg(args, "--mode");
if (mode) body.mode = mode;
if (hasFlag(args, "--nocache")) body.nocache = true;
const fetchTimeout = getArg(args, "--fetch-timeout");
if (fetchTimeout) {
const secs = Number(fetchTimeout);
if (!Number.isFinite(secs) || secs <= 0) {
usage(`--fetch-timeout must be a positive number of seconds (got "${fetchTimeout}")`);
}
body.fetch_timeout = secs;
}
for await (const evt of postStream(ENDPOINTS.research, body, apiKey)) {
if (outMode === "json") console.log(ndjson(evt.event, evt.data));
switch (evt.event) {
case "start":
if (outMode === "pretty") progress("· starting research");
break;
case "planning:start":
if (outMode === "pretty") progress("· planning searches");
break;
case "iteration:start":
if (outMode === "pretty") progress(`· iteration ${evt.data?.iteration ?? "?"}/${evt.data?.maxIterations ?? "?"}`);
break;
case "writing:start":
if (outMode === "pretty") progress("· writing report");
break;
case "complete": {
if (outMode === "pretty") {
console.log(evt.data?.report ?? "");
const cited = evt.data?.metadata?.citedPages ?? evt.data?.metadata?.cited_pages ?? [];
if (cited.length) {
progress(`\nCited ${cited.length} source${cited.length === 1 ? "" : "s"}:`);
for (const p of cited) progress(` - ${p.title ?? "(untitled)"}: ${p.url}`);
}
}
return;
}
case "error":
// In-band failure from the stream → exit 3 (matches the official CLI).
console.error(`Error: ${evt.data?.error?.message ?? evt.data?.message ?? "research failed"}`);
process.exit(3);
}
}
}
async function cmdAutomate(args: string[], outMode: OutputMode): Promise<void> {
const task = getPositional(args.slice(1), 0);
if (!task) {
usage('Usage: tabstack automate "<task>" [--url <url>] [--guardrails <text>] [--interactive] [--max-iterations <n>] [--max-validation-attempts <n>] [--data <@file>] [--geo CC]');
}
const apiKey = getApiKey(getArg(args, "--api-key"));
const body: Record<string, unknown> = { task };
const url = getArg(args, "--url");
if (url) body.url = url;
// Safe by default: read-only unless the user opts into actions.
const guardrails = getArg(args, "--guardrails");
if (guardrails) body.guardrails = guardrails;
else if (!hasFlag(args, "--allow-actions"))
body.guardrails = "browse and extract only; do not submit forms, make purchases, or modify data";
const maxIter = getArg(args, "--max-iterations");
if (maxIter) {
const n = Number(maxIter);
if (!Number.isInteger(n) || n < 1 || n > 100) usage(`--max-iterations must be between 1 and 100 (got ${maxIter})`);
body.maxIterations = n;
}
const maxValidation = getArg(args, "--max-validation-attempts");
if (maxValidation) {
const n = Number(maxValidation);
if (!Number.isInteger(n) || n < 1 || n > 10) usage(`--max-validation-attempts must be between 1 and 10 (got ${maxValidation})`);
body.maxValidationAttempts = n;
}
const dataArg = getArg(args, "--data");
if (dataArg) body.data = await resolveJsonArg(dataArg, "--data");
const geo = getArg(args, "--geo");
// Snake_case per the API spec — unlike maxIterations, which really is camel.
if (geo) body.geo_target = { country: geo };
// The API only emits interactive:form_data:request events when opted in.
if (hasFlag(args, "--interactive")) body.interactive = true;
for await (const evt of postStream(ENDPOINTS.automate, body, apiKey)) {
if (outMode === "json") console.log(ndjson(evt.event, evt.data));
switch (evt.event) {
case "agent:status":
if (outMode === "pretty") progress(`· ${evt.data?.message ?? ""}`);
break;
case "agent:action":
if (outMode === "pretty") progress(`· action: ${evt.data?.action ?? ""}${evt.data?.value ? ` (${evt.data.value})` : ""}`);
break;
case "browser:navigated":
if (outMode === "pretty") progress(`· navigated: ${evt.data?.url ?? ""}`);
break;
case "interactive:form_data:request": {
// The agent paused for human input. Surface the request id and how to answer.
const id = evt.data?.requestId ?? evt.data?.request_id ?? "<request-id>";
progress(`· input requested (expires in ~2 minutes)`);
progress(` respond with: tabstack input ${id} --data '{"fields":[{"ref":"...","value":"..."}]}'`);
progress(` or decline: tabstack input ${id} --data '{"cancelled":true}'`);
break;
}
case "task:completed": {
if (evt.data?.success === false) {
console.error(`Error: automation reported failure${evt.data?.finalAnswer ? `: ${evt.data.finalAnswer}` : ""}`);
process.exit(3);
}
if (outMode === "pretty") {
const answer = evt.data?.finalAnswer;
console.log(typeof answer === "string" ? answer : json(answer));
}
return;
}
case "task:aborted":
console.error(`Error: aborted: ${evt.data?.reason ?? "unknown reason"}`);
process.exit(3);
// eslint-disable-next-line no-fallthrough
case "error":
console.error(
`Error: ${(typeof evt.data?.error === "string" ? evt.data.error : evt.data?.error?.message) ?? "automation failed"}`,
);
process.exit(3);
}
}
}
/** `tabstack input <request-id> --data <...>` → POST /v1/automate/{id}/input. */
async function cmdInput(args: string[], outMode: OutputMode): Promise<void> {
const requestId = getPositional(args.slice(1), 0);
const dataArg = getArg(args, "--data");
if (!requestId || !dataArg) {
usage('Usage: tabstack input <request-id> --data <@file|-|inline>\n' +
' --data must be {"fields":[{"ref":"...","value":"..."}]} to answer, or {"cancelled":true} to decline');
}
const payload = (await resolveJsonArg(dataArg, "--data")) as {
fields?: unknown[];
cancelled?: boolean;
};
if (!payload || typeof payload !== "object" || (!Array.isArray(payload.fields) && payload.cancelled !== true)) {
usage('--data must set "fields" (to submit values) or "cancelled":true (to decline)');
}
const apiKey = getApiKey(getArg(args, "--api-key"));
await postJson(ENDPOINTS.automateInput(requestId), payload, apiKey);
if (outMode === "json") console.log(json({ submitted: true }));
else console.log(green("input submitted"));
}
/** `tabstack recipes [n]` — the cookbook, in the terminal. No network, no key. */
function cmdRecipes(args: string[], outMode: OutputMode): void {
const which = getPositional(args.slice(1), 0);
if (!which) {
if (outMode === "json") {
console.log(json(RECIPES));
return;
}
console.log("The cookbook — run 'tabstack recipes <n>' for the full command.\n");
for (const r of RECIPES) {
console.log(` ${HEAT_BADGE[r.heat]} ${String(r.n).padStart(2)}. ${r.name}`);
console.log(dimOut(` ${r.verbs.join(" + ")} — ${r.blurb.split(". ")[0].replace(/\.$/, "")}.`));
}
console.log("\nFull writeup with sample outputs: RECIPES.md in the repo.");
return;
}
const n = Number(which);
const recipe = RECIPES.find((r) => r.n === n || r.name.toLowerCase().includes(which.toLowerCase()));
if (!recipe) usage(`No recipe "${which}". Run 'tabstack recipes' to list all ${RECIPES.length}.`);
if (outMode === "json") {
console.log(json(recipe));
return;
}
console.log(`${HEAT_BADGE[recipe.heat]} ${recipe.n}. ${recipe.name} ${dimOut(`(${recipe.verbs.join(" + ")})`)}`);
console.log(dimOut(recipe.blurb));
console.log();
console.log(recipe.command);
}
/**
* `tabstack skill [install|agents]` — distribute the agent integration.
* No network, no key; the skill ships inside the binary.
*/
function cmdSkill(args: string[], outMode: OutputMode): void {
const sub = getPositional(args.slice(1), 0);
// Print the Claude Code skill to stdout (pipe or redirect anywhere).
if (!sub) {
console.log(SKILL_MD);
return;
}
// Condensed contract for AGENTS.md-reading agents (Codex, Cursor, Copilot…):
// tabstack skill agents >> AGENTS.md
if (sub === "agents") {
console.log(AGENTS_SNIPPET);
return;
}
if (sub === "install") {
const root = hasFlag(args, "--project")
? join(process.cwd(), ".claude", "skills", "tabstack")
: join(homedir(), ".claude", "skills", "tabstack");
const path = join(root, "SKILL.md");
const existed = existsSync(path);
mkdirSync(root, { recursive: true });
writeFileSync(path, SKILL_MD);
if (outMode === "json") {
console.log(json({ installed: true, updated: existed, path }));
} else {
console.log(`${green("✓")} skill ${existed ? "updated" : "installed"}: ${path}`);
console.log(dimOut("Claude Code picks it up on the next session."));
console.log(dimOut("For AGENTS.md-based agents: tabstack skill agents >> AGENTS.md"));
}
return;
}
usage("Usage: tabstack skill [install [--project] | agents]");
}
/**
* `tabstack usage [set <n> | sync | cookie [value]]` — token budget tracking.
* The API has no balance endpoint, so balances come from the console
* dashboard (pasted or cookie-scraped) and per-verb costs are learned from
* the deltas between readings.
*/
async function cmdUsage(args: string[], outMode: OutputMode): Promise<void> {
const sub = getPositional(args.slice(1), 0);
if (sub === "set") {
const raw = getPositional(args.slice(1), 1);
const tokens = Number(raw?.replace(/,/g, ""));
if (!raw || !Number.isFinite(tokens) || tokens < 0) {
usage("Usage: tabstack usage set <credits-remaining> (the number from the console dashboard)");
}
const { consumed, callsInWindow } = addCalibration(Math.round(tokens), "manual");
if (outMode === "json") {
console.log(json({ calibrated: Math.round(tokens), consumed: consumed ?? null, callsInWindow }));
} else {
console.log(`${green("✓")} calibrated: ${Math.round(tokens).toLocaleString()} credits remaining`);
if (consumed !== undefined)
console.log(dimOut(`${consumed.toLocaleString()} credits consumed across ${callsInWindow} logged calls since last reading — per-verb costs updated.`));
}
return;
}
if (sub === "cookie") {
let value = getPositional(args.slice(1), 1);
if (!value || value === "-") value = (await resolveTextArg("-")).trim();
if (!value) usage("Usage: tabstack usage cookie <console-session-cookie> (or pipe it on stdin)");
if (!value.includes("=")) {
usage('That does not look like a cookie — paste the full "name=value" string from DevTools → Application → Cookies → console.tabstack.ai');
}
const state = readState();
state.consoleCookie = value;
writeState(state);
console.log(`${green("✓")} console cookie stored (0600). Run 'tabstack usage sync'.`);
return;
}
if (sub === "sync") {
const state = readState();
const cookie = process.env.TABSTACK_CONSOLE_COOKIE || state.consoleCookie;
if (!cookie) {
throw new Error(
"No console cookie. Copy it from your browser (DevTools → Application → Cookies → console.tabstack.ai) and run 'tabstack usage cookie <value>'.",
);
}
const { tokens, page } = await syncFromConsole(cookie);
const { consumed, callsInWindow } = addCalibration(tokens, "sync");
if (outMode === "json") {
console.log(json({ tokens, page, consumed: consumed ?? null, callsInWindow }));
} else {
console.log(`${green("✓")} synced from console${page}: ${tokens.toLocaleString()} credits remaining`);
if (consumed !== undefined)
console.log(dimOut(`${consumed.toLocaleString()} consumed across ${callsInWindow} calls since last reading — per-verb costs updated.`));
}
return;
}
if (sub) usage("Usage: tabstack usage [set <tokens> | sync | cookie [value]]");
// Report.
const state = readState();
const ledger = readLedger();
const last = state.calibrations.at(-1);
const remaining = estimateRemaining(state);
const since = last ? ledger.filter((e) => e.ts > last.ts) : ledger;
const byVerb: Record<string, number> = {};
for (const e of since) byVerb[e.verb] = (byVerb[e.verb] ?? 0) + 1;
const lastRl = [...ledger].reverse().find((e) => e.rlRemaining !== undefined);
if (outMode === "json") {
console.log(json({
lastCalibration: last ?? null,
estimatedRemaining: remaining ?? null,
callsSinceCalibration: byVerb,
learnedCostPerCall: state.learned,
lastRateLimit: lastRl ? { remaining: lastRl.rlRemaining, limit: lastRl.rlLimit } : null,
totalCallsLogged: ledger.length,
}));
return;
}
if (!last) {
console.log("No balance readings yet. Get the credit balance from the console dashboard, then:");
console.log(" tabstack usage set <credits> # paste the number");
console.log(" tabstack usage cookie <cookie> # or store a session cookie and");
console.log(" tabstack usage sync # pull it automatically");
console.log(dimOut(`\n${ledger.length} calls logged locally so far — they'll price themselves after two readings.`));
return;
}
console.log(`balance: ${last.tokens.toLocaleString()} credits (${last.source}, ${new Date(last.ts).toLocaleString()})`);
if (remaining !== undefined && remaining !== last.tokens)
console.log(`est. now: ~${remaining.toLocaleString()} credits`);
if (Object.keys(byVerb).length)
console.log(`since: ${Object.entries(byVerb).map(([v, n]) => `${n}× ${v}`).join(", ")}`);
if (Object.keys(state.learned).length) {
console.log("per call: " + Object.entries(state.learned)
.map(([v, l]) => `${v} ~${l.avg.toLocaleString()} (${l.samples} samples)`)
.join(" · "));
} else {
console.log(dimOut("per call: uncalibrated — take a second reading after a few calls to learn costs"));
}
if (lastRl) console.log(dimOut(`ratelimit: ${lastRl.rlRemaining}/${lastRl.rlLimit} at last call`));
}
/** `tabstack status` — how the key resolves, without ever printing it. */
function cmdStatus(args: string[], outMode: OutputMode): void {
const resolved = resolveKey(getArg(args, "--api-key"));
if (outMode === "json") {
console.log(json({
authenticated: Boolean(resolved),
source: resolved?.source ?? null,
configFile: CONFIG_FILE,
baseUrl: getBaseUrl(),
}));
return;
}
if (!resolved) {
console.log("No API key configured. Set one with 'tabstack login'.");
} else {
console.log(`${green("✓")} API key configured`);
console.log(`source: ${resolved.source}`);
}
console.log(`base url: ${getBaseUrl()}`);
console.log(`config: ${CONFIG_FILE}`);
}
// =============================================================================
// Main
// =============================================================================
async function main(): Promise<void> {
const args = expandEquals(process.argv.slice(2));
const command = args[0];
// -h/--help works anywhere, not just as the first token.
if (!command || command === "help" || args.includes("--help") || args.includes("-h")) {
console.log(HELP);
return;
}
if (command === "version" || command === "--version" || command === "-v") {
console.log(version());
return;
}
// Global flags apply to every command — including login's verify call,
// which must honor --base-url/--timeout/--no-color.
const outMode = setupGlobals(args);
// Auth commands don't need an existing key.
if (command === "login") {
await login({
withKey: getArg(args, "--with-key"),
openBrowser: !hasFlag(args, "--no-browser"),
verify: !hasFlag(args, "--no-verify"),
});
return;
}
if (command === "logout") {
logout();
return;
}
// Each command validates its own args BEFORE resolving the API key, so a
// usage mistake prints a Usage: line rather than an auth error.
switch (command) {
case "recipes":
cmdRecipes(args, outMode);
break;
case "skill":
cmdSkill(args, outMode);
break;
case "usage":
await cmdUsage(args, outMode);
break;
case "status":
cmdStatus(args, outMode);
break;
case "extract":
await cmdExtract(args, outMode);
break;
case "generate":
await cmdGenerate(args);
break;
case "research":
await cmdResearch(args, outMode);
break;
case "automate":
await cmdAutomate(args, outMode);
break;
case "input":
await cmdInput(args, outMode);
break;
default:
console.error(`Unknown command: ${command}`);
console.error("Run 'tabstack help' for usage.");
process.exit(1);
}
}
main().catch((err) => {
if (err instanceof UsageError) {
console.error(err.message);
process.exit(2);
}
if (err instanceof TabstackError) {
console.error(`Error (${err.status}): ${err.message}`);
} else {
console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
}
process.exit(1);
});