@tokensize/cli 0.3.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 TokenSize
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,32 @@
1
+ # TokenSize CLI
2
+
3
+ TokenSize discovers local coding harnesses and sends only capability/task metadata to the hosted router by default. Credentials and execution remain local.
4
+
5
+ The easiest setup is the browser callback flow:
6
+
7
+ ```sh
8
+ npx @tokensize/cli auth login
9
+ ```
10
+
11
+ It opens `tokensize.dev`, asks the signed-in user to approve the terminal, and stores the credential in `~/.tokensize/credentials.json` with owner-only permissions. For headless systems, create a key at [tokensize.dev/account](https://tokensize.dev/account), then set it manually:
12
+
13
+ ```sh
14
+ export TOKENSIZE_API_URL=https://api.tokensize.dev
15
+ read -rsp "TokenSize API key: " TOKENSIZE_API_KEY; echo
16
+ npx @tokensize/cli doctor --json
17
+ npx @tokensize/cli allowance --refresh --json
18
+ npx @tokensize/cli route --task "Review the auth boundary" --role review --permission inspect --json
19
+ npx @tokensize/cli delegate --task "Implement issue 42" --role implement --permission edit --json
20
+ ```
21
+
22
+ The hosted service defaults to `https://api.tokensize.dev`; set `TOKENSIZE_API_URL` only for an authorized alternative deployment. If the CLI says `TOKENSIZE_API_KEY` is missing, repeat the `export` and `read -rsp` commands in the same terminal. Never print, commit, or put the key in command arguments.
23
+
24
+ `route` never executes a harness. `delegate` is also a preview unless `--execute` is present. Codex and Claude Code execution adapters are available for inspect/edit tasks; Cursor Agent and OpenCode execution are inspect-only; Copilot is currently discovery-only. Subscription-backed harnesses must explicitly set `TOKENSIZE_ALLOW_SUBSCRIPTION_HARNESSES=claude,codex,cursor,opencode` when their product and provider terms permit automated use.
25
+
26
+ Discovery is cached owner-only for six hours at `~/.tokensize/discovery.json`. Use `--refresh` after installing, upgrading, authenticating, or changing a harness. Selected-target and execution availability failures trigger a bounded refresh automatically.
27
+
28
+ Feedback uses a private `~/.tokensize/last-route.json` receipt containing only the route ID, short-lived feedback token, expiry, and selected target. Never include code, prompts, model output, secrets, personal information, or repository details in comments.
29
+
30
+ Allowance checks do not invoke a model. Normalized remaining fractions are cached owner-only for five minutes at `~/.tokensize/allowance.json`; raw account output and identity are discarded. The router never trades down in quality: among the top quality-equivalent candidates it prefers unmetered, known-available, unknown, then known-low allowance, with the selected cost/latency objective as the final tie-breaker. Codex and macOS Claude Code expose live data in the tested clients; unsupported harness interfaces remain `unknown` rather than being guessed.
31
+
32
+ The CLI is the canonical TokenSize local-client implementation. The public `$delegate` skill is a pinned launcher for this package; it does not contain a second copy of discovery, routing, or execution logic.
package/dist/cli.d.ts ADDED
@@ -0,0 +1 @@
1
+ import '@tokensize/agent-client';
package/dist/cli.js ADDED
@@ -0,0 +1,436 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { execFile } from "child_process";
5
+ import { randomUUID } from "crypto";
6
+ import { access, mkdir } from "fs/promises";
7
+ import { createServer } from "http";
8
+ import path from "path";
9
+ import {
10
+ AGENT_ROUTER_SCHEMA_VERSION,
11
+ agentRouteResponseSchema,
12
+ featurizeAgentTask
13
+ } from "@tokensize/agent-router";
14
+ import {
15
+ allowanceReport,
16
+ allowanceScopesForHarness,
17
+ allowances,
18
+ applyAllowances,
19
+ discoverHarnessesCached,
20
+ executionArgs,
21
+ flattenModels,
22
+ home,
23
+ installationId,
24
+ readApiKey,
25
+ readLastRoute,
26
+ readLocalPolicy,
27
+ rootAllowance,
28
+ run,
29
+ saveApiKey,
30
+ saveLastRoute,
31
+ saveLocalPolicy
32
+ } from "@tokensize/agent-client";
33
+ var roles = ["inspect", "plan", "implement", "review", "test"];
34
+ var permissions = ["inspect", "edit", "test", "network"];
35
+ function value(flag) {
36
+ const index = process.argv.indexOf(flag);
37
+ return index < 0 ? void 0 : process.argv[index + 1];
38
+ }
39
+ function has(flag) {
40
+ return process.argv.includes(flag);
41
+ }
42
+ function output(data) {
43
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
44
+ `);
45
+ }
46
+ function fail(message) {
47
+ process.stderr.write(`tokensize: ${message}
48
+ `);
49
+ process.exit(1);
50
+ }
51
+ function apiUrl() {
52
+ return (process.env.TOKENSIZE_API_URL ?? "https://api.tokensize.dev").replace(/\/$/, "");
53
+ }
54
+ function presented(route) {
55
+ return has("--include-feedback-token") ? route : { ...route, feedbackToken: "[redacted]" };
56
+ }
57
+ async function apiKey(required = true) {
58
+ const key = process.env.TOKENSIZE_API_KEY ?? await readApiKey();
59
+ if (!key && required) fail("TokenSize API key is missing. Run: npx @tokensize/cli auth login");
60
+ return key;
61
+ }
62
+ async function api(pathname, options = {}) {
63
+ const key = await apiKey();
64
+ const response = await fetch(`${apiUrl()}${pathname}`, {
65
+ ...options,
66
+ headers: {
67
+ authorization: `Bearer ${key}`,
68
+ ...options.body ? { "content-type": "application/json" } : {},
69
+ ...options.headers
70
+ }
71
+ });
72
+ const text = await response.text();
73
+ let body;
74
+ try {
75
+ body = JSON.parse(text);
76
+ } catch {
77
+ body = { message: text.slice(0, 500) };
78
+ }
79
+ if (!response.ok) {
80
+ const record = body;
81
+ throw new Error(`service returned ${response.status}: ${record.error?.message ?? record.message ?? "request failed"}`);
82
+ }
83
+ return body;
84
+ }
85
+ function publicDiscovery(harnesses) {
86
+ if (has("--verbose")) return harnesses;
87
+ return harnesses.map((item) => ({
88
+ harness: item.harness,
89
+ installed: item.installed,
90
+ authenticated: item.authenticated,
91
+ version: item.version,
92
+ modelCount: item.models.length,
93
+ allowanceScopes: allowanceScopesForHarness(item),
94
+ warnings: item.warnings
95
+ }));
96
+ }
97
+ async function prepare(task) {
98
+ const role = value("--role") ?? "inspect";
99
+ const permission = value("--permission") ?? "inspect";
100
+ if (!roles.includes(role)) fail("invalid --role");
101
+ if (!permissions.includes(permission)) fail("invalid --permission");
102
+ const discovered = await discoverHarnessesCached({ forceRefresh: has("--refresh"), reason: has("--refresh") ? "manual" : void 0 });
103
+ const allowanceSnapshot = await allowances(discovered.harnesses, has("--refresh"));
104
+ const discovery = applyAllowances(discovered.harnesses, allowanceSnapshot);
105
+ const rootHarness = process.env.TOKENSIZE_ROOT_HARNESS ?? "codex";
106
+ const rootActive = process.env.TOKENSIZE_ROOT_ACTIVE === "1";
107
+ const body = {
108
+ schemaVersion: AGENT_ROUTER_SCHEMA_VERSION,
109
+ client: {
110
+ surface: process.env.TOKENSIZE_CLIENT_SURFACE ?? "cli",
111
+ version: process.env.TOKENSIZE_CLIENT_VERSION ?? "0.2.0-beta.0"
112
+ },
113
+ requestId: randomUUID(),
114
+ installationId: await installationId(),
115
+ routerMode: has("--share-prompt") ? "prompt-assisted" : "metadata-only",
116
+ task: featurizeAgentTask({ task, role, permissionProfile: permission }),
117
+ ...has("--share-prompt") ? { prompt: task } : {},
118
+ candidates: flattenModels(discovery),
119
+ root: {
120
+ harness: rootHarness,
121
+ active: rootActive,
122
+ qualityPrior: Number(process.env.TOKENSIZE_ROOT_QUALITY_PRIOR ?? 0.82),
123
+ allowance: rootAllowance(rootHarness, allowanceSnapshot)
124
+ },
125
+ policy: {
126
+ objective: value("--objective") ?? "balanced",
127
+ maxDelegationDepth: 1,
128
+ delegationDepth: Number(process.env.TOKENSIZE_DELEGATION_DEPTH ?? 0),
129
+ permissionCeiling: permission,
130
+ wallTimeBudgetMs: Number(value("--timeout-ms") ?? 9e5)
131
+ }
132
+ };
133
+ return { body, discovery, cache: { discovery: discovered.cache, allowance: allowanceSnapshot.cache } };
134
+ }
135
+ async function requestRoute(body) {
136
+ const response = await api("/v1/agent-routes", { method: "POST", body: JSON.stringify(body) });
137
+ const parsed = agentRouteResponseSchema.safeParse(response);
138
+ if (!parsed.success) fail("router returned an incompatible response");
139
+ const runId = typeof response.runId === "string" ? response.runId : void 0;
140
+ return { route: parsed.data, ...runId ? { runId } : {} };
141
+ }
142
+ function dashboardUrl(runId) {
143
+ return `https://tokensize.dev/runs/${runId}`;
144
+ }
145
+ async function appendRunEvent(runId, receiptToken, actor, type, data) {
146
+ if (!runId) return;
147
+ try {
148
+ await api(`/v1/runs/${runId}/events`, {
149
+ method: "POST",
150
+ body: JSON.stringify({ receiptToken, autoSeq: true, event: { seq: 0, at: (/* @__PURE__ */ new Date()).toISOString(), actor, type, data } })
151
+ });
152
+ } catch {
153
+ }
154
+ }
155
+ async function refreshDiscovery(reason) {
156
+ return (await discoverHarnessesCached({ forceRefresh: true, reason })).cache;
157
+ }
158
+ async function execute(task, route, discovery, cache, runId) {
159
+ if (!route.plan.targetId) fail(`no local target selected (${route.reasonCodes.join(", ")})`);
160
+ if (route.plan.permissionProfile === "network") fail("network delegation is not supported");
161
+ const target = discovery.flatMap((item) => item.models.map((model) => ({ item, model }))).find(({ model }) => model.id === route.plan.targetId);
162
+ if (!target?.item.executable || !target.item.authenticated) {
163
+ await refreshDiscovery("selected-target-unavailable");
164
+ fail("selected target is no longer available; local discovery cache refreshed");
165
+ }
166
+ try {
167
+ await access(target.item.executable);
168
+ } catch {
169
+ await refreshDiscovery("selected-executable-missing");
170
+ fail("selected harness executable no longer exists; local discovery cache refreshed");
171
+ }
172
+ if (!["codex", "claude", "cursor", "opencode"].includes(target.model.harness)) fail(`${target.model.harness} is discovery-only in this client`);
173
+ if (["cursor", "opencode"].includes(target.model.harness) && route.plan.permissionProfile !== "inspect") fail(`${target.model.harness === "cursor" ? "Cursor" : "OpenCode"} execution is inspect-only`);
174
+ let cwd = process.cwd();
175
+ let worktree = null;
176
+ if (route.plan.requiresWorktree) {
177
+ const gitCheck = await run("git", ["rev-parse", "--show-toplevel"], { cwd, timeoutMs: 15e3 });
178
+ if (gitCheck.code !== 0) fail("edit/test delegation requires a Git repository");
179
+ worktree = path.join(home(), "worktrees", route.routeId);
180
+ await mkdir(path.dirname(worktree), { recursive: true, mode: 448 });
181
+ const branch = `tokensize/${route.routeId.slice(0, 8)}`;
182
+ const created = await run("git", ["worktree", "add", "-b", branch, worktree, "HEAD"], { cwd, timeoutMs: 3e4 });
183
+ if (created.code !== 0) fail(`could not create isolated worktree: ${created.stderr.trim()}`);
184
+ cwd = worktree;
185
+ }
186
+ await appendRunEvent(runId, route.feedbackToken, "delegate", "execution-started", {
187
+ targetId: target.model.id,
188
+ permissionProfile: route.plan.permissionProfile,
189
+ worktree: worktree !== null
190
+ });
191
+ const started = Date.now();
192
+ const result = await run(target.item.executable, executionArgs(target.model.harness, target.model.nativeModelId, route.plan.permissionProfile, cwd), {
193
+ cwd,
194
+ input: task,
195
+ timeoutMs: route.plan.maxWallMs,
196
+ env: {
197
+ ...process.env,
198
+ TOKENSIZE_ROOT_HARNESS: target.model.harness,
199
+ TOKENSIZE_ROOT_ACTIVE: "1",
200
+ TOKENSIZE_DELEGATION_DEPTH: String(Number(process.env.TOKENSIZE_DELEGATION_DEPTH ?? 0) + 1),
201
+ TOKENSIZE_CLIENT_SURFACE: "cli"
202
+ }
203
+ });
204
+ const elapsed = Date.now() - started;
205
+ await appendRunEvent(runId, route.feedbackToken, "delegate", "execution-finished", {
206
+ outcome: result.timedOut ? "timeout" : result.code === 0 ? "success" : "failure",
207
+ ...result.code === 0 && !result.timedOut ? {} : { failureCode: result.timedOut ? "EXECUTION_TIMEOUT" : "EXECUTION_FAILED" },
208
+ elapsedMs: elapsed,
209
+ usage: { contextTokensEstimated: route.expected.contextTokens, source: "estimated" }
210
+ });
211
+ const combined = `${result.stderr}
212
+ ${result.stdout}`;
213
+ const availabilityFailure = result.timedOut || result.code !== 0 && /unknown model|model.{0,24}(not found|not available|unavailable|invalid)|invalid value.{0,80}--model|not logged in|unauthenticated|authentication|command not found|enoent/i.test(combined);
214
+ const allowanceFailure = result.code !== 0 && /rate.?limit|usage.?limit|quota|allowance|credit(?:s)? exhausted|insufficient credit/i.test(combined);
215
+ const discoveryRefresh = availabilityFailure ? await refreshDiscovery(result.timedOut ? "execution-timeout" : "execution-availability-failure") : void 0;
216
+ const allowanceRefresh = allowanceFailure ? (await allowances(discovery, true)).cache : void 0;
217
+ let feedbackWarning;
218
+ try {
219
+ await api("/v1/agent-feedback", {
220
+ method: "POST",
221
+ body: JSON.stringify({
222
+ schemaVersion: AGENT_ROUTER_SCHEMA_VERSION,
223
+ routeId: route.routeId,
224
+ feedbackToken: route.feedbackToken,
225
+ idempotencyKey: randomUUID(),
226
+ status: result.code === 0 ? "completed" : "failed",
227
+ confirmedTargetId: target.model.id,
228
+ identityConfirmed: true,
229
+ checksPassed: 0,
230
+ checksFailed: 0,
231
+ retries: 0,
232
+ usage: { contextTokensEstimated: route.expected.contextTokens, source: "estimated" },
233
+ timings: { totalMs: elapsed, routingMs: 0, executionMs: elapsed, verificationMs: 0 },
234
+ ...result.code === 0 ? {} : { failureCode: result.timedOut ? "EXECUTION_TIMEOUT" : "EXECUTION_FAILED" }
235
+ })
236
+ });
237
+ } catch (error) {
238
+ feedbackWarning = error instanceof Error ? error.message : String(error);
239
+ }
240
+ return { target: target.model.id, code: result.code, timedOut: result.timedOut, worktree, stdout: result.stdout, stderr: result.stderr, feedbackWarning, cacheUsed: cache, discoveryRefresh, allowanceRefresh };
241
+ }
242
+ async function login() {
243
+ const state = randomUUID();
244
+ let completed = false;
245
+ const server = createServer((request, response) => {
246
+ if (request.method === "OPTIONS" && request.url === `/callback/${state}`) {
247
+ response.writeHead(204, { "access-control-allow-origin": "https://tokensize.dev", "access-control-allow-methods": "POST", "access-control-allow-headers": "content-type" }).end();
248
+ return;
249
+ }
250
+ if (request.method !== "POST" || request.url !== `/callback/${state}`) {
251
+ response.writeHead(404).end();
252
+ return;
253
+ }
254
+ let body = "";
255
+ request.on("data", (chunk) => {
256
+ body += chunk;
257
+ });
258
+ request.on("end", async () => {
259
+ try {
260
+ const payload = JSON.parse(body);
261
+ if (payload.state !== state || typeof payload.apiKey !== "string" || payload.apiKey.length < 20 || /\s/.test(payload.apiKey)) throw new Error("invalid callback");
262
+ await saveApiKey(payload.apiKey);
263
+ completed = true;
264
+ response.writeHead(200, { "content-type": "text/plain", "access-control-allow-origin": "https://tokensize.dev" }).end("TokenSize connected. You can close this window.\n");
265
+ setTimeout(() => server.close(), 100);
266
+ } catch {
267
+ response.writeHead(400, { "access-control-allow-origin": "https://tokensize.dev" }).end("Invalid TokenSize callback.\n");
268
+ }
269
+ });
270
+ });
271
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
272
+ const address = server.address();
273
+ if (!address || typeof address === "string") fail("could not start local callback");
274
+ const callback = `http://127.0.0.1:${address.port}/callback/${state}`;
275
+ const url = `https://tokensize.dev/authorize?callback=${encodeURIComponent(callback)}&state=${encodeURIComponent(state)}`;
276
+ process.stdout.write(`Opening TokenSize authorization\u2026
277
+ ${url}
278
+ `);
279
+ execFile(process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open", process.platform === "win32" ? ["/c", "start", url] : [url]);
280
+ const timeout = setTimeout(() => server.close(), 10 * 60 * 1e3);
281
+ await new Promise((resolve) => server.on("close", resolve));
282
+ clearTimeout(timeout);
283
+ if (!completed) fail("browser authorization timed out or was cancelled");
284
+ process.stdout.write(`Saved credentials to ${path.join(home(), "credentials.json")}
285
+ `);
286
+ }
287
+ async function main() {
288
+ const command = process.argv[2] ?? "help";
289
+ if (command === "auth") {
290
+ if (process.argv[3] !== "login") fail("use: tokensize auth login");
291
+ await login();
292
+ return;
293
+ }
294
+ if (command === "doctor" || command === "allowance") {
295
+ const [key, discovered] = await Promise.all([apiKey(false), discoverHarnessesCached({ forceRefresh: has("--refresh"), reason: has("--refresh") ? "manual" : void 0 })]);
296
+ const [catalog, allowanceSnapshot] = await Promise.all([
297
+ key ? api("/v1/agent-catalog").catch((error) => ({ warning: error instanceof Error ? error.message : String(error) })) : null,
298
+ allowances(discovered.harnesses, has("--refresh"))
299
+ ]);
300
+ const available = applyAllowances(discovered.harnesses, allowanceSnapshot);
301
+ if (command === "allowance") {
302
+ output({ format: "json", privacy: "only normalized allowance metadata is cached locally; raw account output is discarded", cache: allowanceSnapshot.cache, harnesses: allowanceReport(available, allowanceSnapshot) });
303
+ return;
304
+ }
305
+ output({
306
+ service: { url: apiUrl(), authenticated: Boolean(key), catalog },
307
+ installationId: await installationId(),
308
+ privacy: "credentials, raw account output, and prompts remain local unless prompt sharing is explicit",
309
+ cache: { discovery: discovered.cache, allowance: allowanceSnapshot.cache },
310
+ harnesses: publicDiscovery(available)
311
+ });
312
+ return;
313
+ }
314
+ if (command === "feedback") {
315
+ const rating = Number(value("--rating"));
316
+ const modelChoice = value("--model-choice");
317
+ const wouldUseAgain = value("--would-use-again");
318
+ if (!Number.isInteger(rating) || rating < 1 || rating > 5) fail("--rating must be an integer from 1 to 5");
319
+ if (!modelChoice || !["right", "acceptable", "wrong"].includes(modelChoice)) fail("--model-choice must be right, acceptable, or wrong");
320
+ if (!wouldUseAgain || !["yes", "no"].includes(wouldUseAgain)) fail("--would-use-again must be yes or no");
321
+ let receipt;
322
+ try {
323
+ receipt = await readLastRoute();
324
+ } catch {
325
+ fail("no valid local route receipt found; delegate a task first");
326
+ }
327
+ if (Date.parse(receipt.expiresAt) < Date.now()) fail("the last route has expired; delegate another task first");
328
+ const response = await api("/v1/agent-feedback", {
329
+ method: "POST",
330
+ body: JSON.stringify({
331
+ schemaVersion: AGENT_ROUTER_SCHEMA_VERSION,
332
+ routeId: receipt.routeId,
333
+ feedbackToken: receipt.feedbackToken,
334
+ idempotencyKey: randomUUID(),
335
+ status: modelChoice === "wrong" ? "failed" : "verified",
336
+ confirmedTargetId: receipt.targetId,
337
+ identityConfirmed: true,
338
+ checksPassed: modelChoice === "right" ? 1 : 0,
339
+ checksFailed: modelChoice === "wrong" ? 1 : 0,
340
+ retries: 0,
341
+ usage: { contextTokensEstimated: 0, source: "unknown" },
342
+ timings: { totalMs: 0, routingMs: 0, executionMs: 0, verificationMs: 0 }
343
+ })
344
+ });
345
+ output({ ...response, routeId: receipt.routeId, privacy: "feedback excludes prompts, repository contents, model output, and credentials" });
346
+ return;
347
+ }
348
+ if (command === "route" || command === "delegate") {
349
+ const task = value("--task");
350
+ if (!task) fail("--task is required");
351
+ const prepared = await prepare(task);
352
+ const { route: selected, runId } = await requestRoute(prepared.body);
353
+ await saveLastRoute({ routeId: selected.routeId, ...runId ? { runId } : {}, feedbackToken: selected.feedbackToken, expiresAt: selected.expiresAt, targetId: selected.plan.targetId });
354
+ if (command === "route" || !has("--execute")) {
355
+ output({ dryRun: true, ...runId ? { runId, run: dashboardUrl(runId) } : {}, route: presented(selected), cache: prepared.cache, harnesses: publicDiscovery(prepared.discovery) });
356
+ return;
357
+ }
358
+ const execution = await execute(task, selected, prepared.discovery, prepared.cache, runId);
359
+ output({ dryRun: false, ...runId ? { runId, run: dashboardUrl(runId) } : {}, route: presented(selected), execution });
360
+ if (execution.code !== 0) process.exitCode = 1;
361
+ return;
362
+ }
363
+ if (command === "runs") {
364
+ const sub = process.argv[3];
365
+ if (sub === "watch") {
366
+ const runId = process.argv[4] ?? (await readLastRoute().catch(() => null))?.runId;
367
+ if (!runId) fail("use: tokensize runs watch <runId>");
368
+ const deadline = Date.now() + Number(value("--timeout-ms") ?? 9e5);
369
+ let printed = 0;
370
+ for (; ; ) {
371
+ const doc = await api(`/v1/runs/${runId}`);
372
+ for (const event of doc.events.slice(printed)) output(event);
373
+ printed = doc.events.length;
374
+ if (["completed", "failed", "cancelled", "expired"].includes(doc.status)) {
375
+ output({ runId, status: doc.status, run: dashboardUrl(runId) });
376
+ if (doc.status !== "completed") process.exitCode = 1;
377
+ return;
378
+ }
379
+ if (Date.now() > deadline) fail("watch timed out; the run is still live on the dashboard");
380
+ await new Promise((resolve) => setTimeout(resolve, 2e3));
381
+ }
382
+ }
383
+ const limit = Number(value("--limit") ?? 25);
384
+ output(await api(`/v1/runs?limit=${Number.isInteger(limit) && limit > 0 ? Math.min(limit, 100) : 25}`));
385
+ return;
386
+ }
387
+ if (command === "approve" || command === "cancel") {
388
+ const runId = process.argv[3] ?? (await readLastRoute().catch(() => null))?.runId;
389
+ if (!runId) fail(`use: tokensize ${command} <runId>`);
390
+ const event = command === "approve" ? { seq: 0, at: (/* @__PURE__ */ new Date()).toISOString(), actor: "human", type: "approval-granted", data: { kind: value("--kind") ?? "subscription-use", grantedBy: "local-cli" } } : { seq: 0, at: (/* @__PURE__ */ new Date()).toISOString(), actor: "human", type: "cancelled", data: { by: "human" } };
391
+ const result = await api(`/v1/runs/${runId}/events`, { method: "POST", body: JSON.stringify({ autoSeq: true, event }) });
392
+ output({ ...result, run: dashboardUrl(runId) });
393
+ return;
394
+ }
395
+ if (command === "open") {
396
+ const runId = process.argv[3] ?? (await readLastRoute().catch(() => null))?.runId;
397
+ if (!runId) fail("use: tokensize open <runId>");
398
+ const url = dashboardUrl(runId);
399
+ process.stdout.write(`${url}
400
+ `);
401
+ execFile(process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open", process.platform === "win32" ? ["/c", "start", url] : [url]);
402
+ return;
403
+ }
404
+ if (command === "policy") {
405
+ if (process.argv[3] === "set") {
406
+ const patch = {};
407
+ const objective = value("--objective");
408
+ const ceiling = value("--permission-ceiling");
409
+ const rootHarness = value("--root-harness");
410
+ const depth = value("--max-delegation-depth");
411
+ const share = value("--share-prompt");
412
+ const approve = value("--approve-subscription");
413
+ const revoke = value("--revoke-subscription");
414
+ if (objective) patch.objective = objective;
415
+ if (ceiling) patch.permissionCeiling = ceiling;
416
+ if (rootHarness) patch.rootHarness = rootHarness;
417
+ if (depth) patch.maxDelegationDepth = Number(depth);
418
+ if (share) patch.sharePromptDefault = share === "true";
419
+ if (approve || revoke) {
420
+ const current = (await readLocalPolicy()).subscriptionHarnesses ?? [];
421
+ const next = new Set(current);
422
+ if (approve) next.add(approve);
423
+ if (revoke) next.delete(revoke);
424
+ patch.subscriptionHarnesses = [...next];
425
+ }
426
+ if (Object.keys(patch).length === 0) fail("nothing to set; see tokensize help");
427
+ output({ policy: await saveLocalPolicy(patch), file: path.join(home(), "policy.json") });
428
+ return;
429
+ }
430
+ output({ policy: await readLocalPolicy(), file: path.join(home(), "policy.json"), note: "local ceilings always win; the hosted service can only narrow them" });
431
+ return;
432
+ }
433
+ process.stdout.write("TokenSize CLI\n\n auth login\n doctor [--refresh] [--verbose] [--json]\n allowance [--refresh] [--json]\n route --task TEXT [--role inspect|plan|implement|review|test] [--permission inspect|edit|test] [--refresh] [--verbose]\n delegate --task TEXT [same options] [--execute]\n runs [--limit N] | runs watch [runId] [--timeout-ms N]\n approve [runId] [--kind subscription-use|execute|share-prompt]\n cancel [runId]\n open [runId]\n policy [get] | policy set [--objective X] [--permission-ceiling X] [--root-harness X] [--max-delegation-depth N] [--share-prompt true|false] [--approve-subscription HARNESS] [--revoke-subscription HARNESS]\n feedback --rating 1..5 --model-choice right|acceptable|wrong --would-use-again yes|no\n");
434
+ }
435
+ main().catch((error) => fail(error instanceof Error ? error.message : String(error)));
436
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/cli.ts"],"sourcesContent":["import { execFile } from \"node:child_process\";\nimport { randomUUID } from \"node:crypto\";\nimport { access, mkdir } from \"node:fs/promises\";\nimport { createServer } from \"node:http\";\nimport path from \"node:path\";\nimport {\n\tAGENT_ROUTER_SCHEMA_VERSION,\n\tagentRouteResponseSchema,\n\tfeaturizeAgentTask,\n\ttype AgentRouteRequest,\n\ttype AgentRouteResponse,\n} from \"@tokensize/agent-router\";\nimport {\n\tallowanceReport,\n\tallowanceScopesForHarness,\n\tallowances,\n\tapplyAllowances,\n\tdiscoverHarnessesCached,\n\texecutionArgs,\n\tflattenModels,\n\thome,\n\tinstallationId,\n\treadApiKey,\n\treadLastRoute,\n\treadLocalPolicy,\n\trootAllowance,\n\trun,\n\tsaveApiKey,\n\tsaveLastRoute,\n\tsaveLocalPolicy,\n\ttype DiscoveryCacheMetadata,\n\ttype HarnessDiscovery,\n\ttype LocalPolicy,\n} from \"@tokensize/agent-client\";\n\nconst roles = [\"inspect\", \"plan\", \"implement\", \"review\", \"test\"] as const;\nconst permissions = [\"inspect\", \"edit\", \"test\", \"network\"] as const;\n\nfunction value(flag: string): string | undefined {\n\tconst index = process.argv.indexOf(flag);\n\treturn index < 0 ? undefined : process.argv[index + 1];\n}\n\nfunction has(flag: string): boolean { return process.argv.includes(flag); }\nfunction output(data: unknown): void { process.stdout.write(`${JSON.stringify(data, null, 2)}\\n`); }\nfunction fail(message: string): never {\n\tprocess.stderr.write(`tokensize: ${message}\\n`);\n\tprocess.exit(1);\n}\nfunction apiUrl(): string { return (process.env.TOKENSIZE_API_URL ?? \"https://api.tokensize.dev\").replace(/\\/$/, \"\"); }\nfunction presented(route: AgentRouteResponse): AgentRouteResponse {\n\treturn has(\"--include-feedback-token\") ? route : { ...route, feedbackToken: \"[redacted]\" };\n}\n\nasync function apiKey(required = true): Promise<string | null> {\n\tconst key = process.env.TOKENSIZE_API_KEY ?? await readApiKey();\n\tif (!key && required) fail(\"TokenSize API key is missing. Run: npx @tokensize/cli auth login\");\n\treturn key;\n}\n\nasync function api<T>(pathname: string, options: RequestInit = {}): Promise<T> {\n\tconst key = await apiKey();\n\tconst response = await fetch(`${apiUrl()}${pathname}`, {\n\t\t...options,\n\t\theaders: {\n\t\t\tauthorization: `Bearer ${key}`,\n\t\t\t...(options.body ? { \"content-type\": \"application/json\" } : {}),\n\t\t\t...options.headers,\n\t\t},\n\t});\n\tconst text = await response.text();\n\tlet body: unknown;\n\ttry { body = JSON.parse(text); } catch { body = { message: text.slice(0, 500) }; }\n\tif (!response.ok) {\n\t\tconst record = body as { error?: { message?: string }; message?: string };\n\t\tthrow new Error(`service returned ${response.status}: ${record.error?.message ?? record.message ?? \"request failed\"}`);\n\t}\n\treturn body as T;\n}\n\nfunction publicDiscovery(harnesses: HarnessDiscovery[]): unknown[] {\n\tif (has(\"--verbose\")) return harnesses;\n\treturn harnesses.map((item) => ({\n\t\tharness: item.harness,\n\t\tinstalled: item.installed,\n\t\tauthenticated: item.authenticated,\n\t\tversion: item.version,\n\t\tmodelCount: item.models.length,\n\t\tallowanceScopes: allowanceScopesForHarness(item),\n\t\twarnings: item.warnings,\n\t}));\n}\n\nasync function prepare(task: string): Promise<{\n\tbody: AgentRouteRequest;\n\tdiscovery: HarnessDiscovery[];\n\tcache: { discovery: DiscoveryCacheMetadata; allowance: Awaited<ReturnType<typeof allowances>>[\"cache\"] };\n}> {\n\tconst role = (value(\"--role\") ?? \"inspect\") as AgentRouteRequest[\"task\"][\"role\"];\n\tconst permission = (value(\"--permission\") ?? \"inspect\") as AgentRouteRequest[\"policy\"][\"permissionCeiling\"];\n\tif (!roles.includes(role)) fail(\"invalid --role\");\n\tif (!permissions.includes(permission)) fail(\"invalid --permission\");\n\tconst discovered = await discoverHarnessesCached({ forceRefresh: has(\"--refresh\"), reason: has(\"--refresh\") ? \"manual\" : undefined });\n\tconst allowanceSnapshot = await allowances(discovered.harnesses, has(\"--refresh\"));\n\tconst discovery = applyAllowances(discovered.harnesses, allowanceSnapshot);\n\tconst rootHarness = (process.env.TOKENSIZE_ROOT_HARNESS ?? \"codex\") as AgentRouteRequest[\"root\"][\"harness\"];\n\tconst rootActive = process.env.TOKENSIZE_ROOT_ACTIVE === \"1\";\n\tconst body: AgentRouteRequest = {\n\t\tschemaVersion: AGENT_ROUTER_SCHEMA_VERSION,\n\t\tclient: {\n\t\t\tsurface: (process.env.TOKENSIZE_CLIENT_SURFACE ?? \"cli\") as AgentRouteRequest[\"client\"][\"surface\"],\n\t\t\tversion: process.env.TOKENSIZE_CLIENT_VERSION ?? \"0.2.0-beta.0\",\n\t\t},\n\t\trequestId: randomUUID(),\n\t\tinstallationId: await installationId(),\n\t\trouterMode: has(\"--share-prompt\") ? \"prompt-assisted\" : \"metadata-only\",\n\t\ttask: featurizeAgentTask({ task, role, permissionProfile: permission }),\n\t\t...(has(\"--share-prompt\") ? { prompt: task } : {}),\n\t\tcandidates: flattenModels(discovery),\n\t\troot: {\n\t\t\tharness: rootHarness,\n\t\t\tactive: rootActive,\n\t\t\tqualityPrior: Number(process.env.TOKENSIZE_ROOT_QUALITY_PRIOR ?? 0.82),\n\t\t\tallowance: rootAllowance(rootHarness, allowanceSnapshot),\n\t\t},\n\t\tpolicy: {\n\t\t\tobjective: (value(\"--objective\") ?? \"balanced\") as AgentRouteRequest[\"policy\"][\"objective\"],\n\t\t\tmaxDelegationDepth: 1,\n\t\t\tdelegationDepth: Number(process.env.TOKENSIZE_DELEGATION_DEPTH ?? 0),\n\t\t\tpermissionCeiling: permission,\n\t\t\twallTimeBudgetMs: Number(value(\"--timeout-ms\") ?? 900_000),\n\t\t},\n\t};\n\treturn { body, discovery, cache: { discovery: discovered.cache, allowance: allowanceSnapshot.cache } };\n}\n\nasync function requestRoute(body: AgentRouteRequest): Promise<{ route: AgentRouteResponse; runId?: string }> {\n\tconst response = await api<unknown>(\"/v1/agent-routes\", { method: \"POST\", body: JSON.stringify(body) });\n\tconst parsed = agentRouteResponseSchema.safeParse(response);\n\tif (!parsed.success) fail(\"router returned an incompatible response\");\n\tconst runId = typeof (response as { runId?: unknown }).runId === \"string\" ? (response as { runId: string }).runId : undefined;\n\treturn { route: parsed.data, ...(runId ? { runId } : {}) };\n}\n\nfunction dashboardUrl(runId: string): string {\n\treturn `https://tokensize.dev/runs/${runId}`;\n}\n\n/** Best-effort append to the Run document; local execution never blocks on it. */\nasync function appendRunEvent(runId: string | undefined, receiptToken: string, actor: string, type: string, data: Record<string, unknown>): Promise<void> {\n\tif (!runId) return;\n\ttry {\n\t\tawait api(`/v1/runs/${runId}/events`, {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({ receiptToken, autoSeq: true, event: { seq: 0, at: new Date().toISOString(), actor, type, data } }),\n\t\t});\n\t} catch { /* offline or expired: the local receipt remains the fallback record */ }\n}\n\nasync function refreshDiscovery(reason: string): Promise<DiscoveryCacheMetadata> {\n\treturn (await discoverHarnessesCached({ forceRefresh: true, reason })).cache;\n}\n\nasync function execute(\n\ttask: string,\n\troute: AgentRouteResponse,\n\tdiscovery: HarnessDiscovery[],\n\tcache: { discovery: DiscoveryCacheMetadata; allowance: Awaited<ReturnType<typeof allowances>>[\"cache\"] },\n\trunId?: string,\n) {\n\tif (!route.plan.targetId) fail(`no local target selected (${route.reasonCodes.join(\", \")})`);\n\tif (route.plan.permissionProfile === \"network\") fail(\"network delegation is not supported\");\n\tconst target = discovery.flatMap((item) => item.models.map((model) => ({ item, model }))).find(({ model }) => model.id === route.plan.targetId);\n\tif (!target?.item.executable || !target.item.authenticated) {\n\t\tawait refreshDiscovery(\"selected-target-unavailable\");\n\t\tfail(\"selected target is no longer available; local discovery cache refreshed\");\n\t}\n\ttry { await access(target.item.executable); } catch {\n\t\tawait refreshDiscovery(\"selected-executable-missing\");\n\t\tfail(\"selected harness executable no longer exists; local discovery cache refreshed\");\n\t}\n\tif (![\"codex\", \"claude\", \"cursor\", \"opencode\"].includes(target.model.harness)) fail(`${target.model.harness} is discovery-only in this client`);\n\tif ([\"cursor\", \"opencode\"].includes(target.model.harness) && route.plan.permissionProfile !== \"inspect\") fail(`${target.model.harness === \"cursor\" ? \"Cursor\" : \"OpenCode\"} execution is inspect-only`);\n\n\tlet cwd = process.cwd();\n\tlet worktree: string | null = null;\n\tif (route.plan.requiresWorktree) {\n\t\tconst gitCheck = await run(\"git\", [\"rev-parse\", \"--show-toplevel\"], { cwd, timeoutMs: 15_000 });\n\t\tif (gitCheck.code !== 0) fail(\"edit/test delegation requires a Git repository\");\n\t\tworktree = path.join(home(), \"worktrees\", route.routeId);\n\t\tawait mkdir(path.dirname(worktree), { recursive: true, mode: 0o700 });\n\t\tconst branch = `tokensize/${route.routeId.slice(0, 8)}`;\n\t\tconst created = await run(\"git\", [\"worktree\", \"add\", \"-b\", branch, worktree, \"HEAD\"], { cwd, timeoutMs: 30_000 });\n\t\tif (created.code !== 0) fail(`could not create isolated worktree: ${created.stderr.trim()}`);\n\t\tcwd = worktree;\n\t}\n\n\tawait appendRunEvent(runId, route.feedbackToken, \"delegate\", \"execution-started\", {\n\t\ttargetId: target.model.id,\n\t\tpermissionProfile: route.plan.permissionProfile,\n\t\tworktree: worktree !== null,\n\t});\n\tconst started = Date.now();\n\tconst result = await run(target.item.executable, executionArgs(target.model.harness, target.model.nativeModelId, route.plan.permissionProfile, cwd), {\n\t\tcwd,\n\t\tinput: task,\n\t\ttimeoutMs: route.plan.maxWallMs,\n\t\tenv: {\n\t\t\t...process.env,\n\t\t\tTOKENSIZE_ROOT_HARNESS: target.model.harness,\n\t\t\tTOKENSIZE_ROOT_ACTIVE: \"1\",\n\t\t\tTOKENSIZE_DELEGATION_DEPTH: String(Number(process.env.TOKENSIZE_DELEGATION_DEPTH ?? 0) + 1),\n\t\t\tTOKENSIZE_CLIENT_SURFACE: \"cli\",\n\t\t},\n\t});\n\tconst elapsed = Date.now() - started;\n\tawait appendRunEvent(runId, route.feedbackToken, \"delegate\", \"execution-finished\", {\n\t\toutcome: result.timedOut ? \"timeout\" : result.code === 0 ? \"success\" : \"failure\",\n\t\t...(result.code === 0 && !result.timedOut ? {} : { failureCode: result.timedOut ? \"EXECUTION_TIMEOUT\" : \"EXECUTION_FAILED\" }),\n\t\telapsedMs: elapsed,\n\t\tusage: { contextTokensEstimated: route.expected.contextTokens, source: \"estimated\" },\n\t});\n\tconst combined = `${result.stderr}\\n${result.stdout}`;\n\tconst availabilityFailure = result.timedOut || (result.code !== 0 && /unknown model|model.{0,24}(not found|not available|unavailable|invalid)|invalid value.{0,80}--model|not logged in|unauthenticated|authentication|command not found|enoent/i.test(combined));\n\tconst allowanceFailure = result.code !== 0 && /rate.?limit|usage.?limit|quota|allowance|credit(?:s)? exhausted|insufficient credit/i.test(combined);\n\tconst discoveryRefresh = availabilityFailure ? await refreshDiscovery(result.timedOut ? \"execution-timeout\" : \"execution-availability-failure\") : undefined;\n\tconst allowanceRefresh = allowanceFailure ? (await allowances(discovery, true)).cache : undefined;\n\tlet feedbackWarning: string | undefined;\n\ttry {\n\t\tawait api(\"/v1/agent-feedback\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tschemaVersion: AGENT_ROUTER_SCHEMA_VERSION,\n\t\t\t\trouteId: route.routeId,\n\t\t\t\tfeedbackToken: route.feedbackToken,\n\t\t\t\tidempotencyKey: randomUUID(),\n\t\t\t\tstatus: result.code === 0 ? \"completed\" : \"failed\",\n\t\t\t\tconfirmedTargetId: target.model.id,\n\t\t\t\tidentityConfirmed: true,\n\t\t\t\tchecksPassed: 0,\n\t\t\t\tchecksFailed: 0,\n\t\t\t\tretries: 0,\n\t\t\t\tusage: { contextTokensEstimated: route.expected.contextTokens, source: \"estimated\" },\n\t\t\t\ttimings: { totalMs: elapsed, routingMs: 0, executionMs: elapsed, verificationMs: 0 },\n\t\t\t\t...(result.code === 0 ? {} : { failureCode: result.timedOut ? \"EXECUTION_TIMEOUT\" : \"EXECUTION_FAILED\" }),\n\t\t\t}),\n\t\t});\n\t} catch (error) { feedbackWarning = error instanceof Error ? error.message : String(error); }\n\treturn { target: target.model.id, code: result.code, timedOut: result.timedOut, worktree, stdout: result.stdout, stderr: result.stderr, feedbackWarning, cacheUsed: cache, discoveryRefresh, allowanceRefresh };\n}\n\nasync function login(): Promise<void> {\n\tconst state = randomUUID();\n\tlet completed = false;\n\tconst server = createServer((request, response) => {\n\t\tif (request.method === \"OPTIONS\" && request.url === `/callback/${state}`) {\n\t\t\tresponse.writeHead(204, { \"access-control-allow-origin\": \"https://tokensize.dev\", \"access-control-allow-methods\": \"POST\", \"access-control-allow-headers\": \"content-type\" }).end();\n\t\t\treturn;\n\t\t}\n\t\tif (request.method !== \"POST\" || request.url !== `/callback/${state}`) { response.writeHead(404).end(); return; }\n\t\tlet body = \"\";\n\t\trequest.on(\"data\", (chunk) => { body += chunk; });\n\t\trequest.on(\"end\", async () => {\n\t\t\ttry {\n\t\t\t\tconst payload = JSON.parse(body) as { state?: string; apiKey?: string };\n\t\t\t\tif (payload.state !== state || typeof payload.apiKey !== \"string\" || payload.apiKey.length < 20 || /\\s/.test(payload.apiKey)) throw new Error(\"invalid callback\");\n\t\t\t\tawait saveApiKey(payload.apiKey);\n\t\t\t\tcompleted = true;\n\t\t\t\tresponse.writeHead(200, { \"content-type\": \"text/plain\", \"access-control-allow-origin\": \"https://tokensize.dev\" }).end(\"TokenSize connected. You can close this window.\\n\");\n\t\t\t\tsetTimeout(() => server.close(), 100);\n\t\t\t} catch { response.writeHead(400, { \"access-control-allow-origin\": \"https://tokensize.dev\" }).end(\"Invalid TokenSize callback.\\n\"); }\n\t\t});\n\t});\n\tawait new Promise<void>((resolve) => server.listen(0, \"127.0.0.1\", resolve));\n\tconst address = server.address();\n\tif (!address || typeof address === \"string\") fail(\"could not start local callback\");\n\tconst callback = `http://127.0.0.1:${address.port}/callback/${state}`;\n\tconst url = `https://tokensize.dev/authorize?callback=${encodeURIComponent(callback)}&state=${encodeURIComponent(state)}`;\n\tprocess.stdout.write(`Opening TokenSize authorization…\\n${url}\\n`);\n\texecFile(process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"cmd\" : \"xdg-open\", process.platform === \"win32\" ? [\"/c\", \"start\", url] : [url]);\n\tconst timeout = setTimeout(() => server.close(), 10 * 60 * 1_000);\n\tawait new Promise<void>((resolve) => server.on(\"close\", resolve));\n\tclearTimeout(timeout);\n\tif (!completed) fail(\"browser authorization timed out or was cancelled\");\n\tprocess.stdout.write(`Saved credentials to ${path.join(home(), \"credentials.json\")}\\n`);\n}\n\nasync function main(): Promise<void> {\n\tconst command = process.argv[2] ?? \"help\";\n\tif (command === \"auth\") {\n\t\tif (process.argv[3] !== \"login\") fail(\"use: tokensize auth login\");\n\t\tawait login();\n\t\treturn;\n\t}\n\tif (command === \"doctor\" || command === \"allowance\") {\n\t\tconst [key, discovered] = await Promise.all([apiKey(false), discoverHarnessesCached({ forceRefresh: has(\"--refresh\"), reason: has(\"--refresh\") ? \"manual\" : undefined })]);\n\t\tconst [catalog, allowanceSnapshot] = await Promise.all([\n\t\t\tkey ? api(\"/v1/agent-catalog\").catch((error) => ({ warning: error instanceof Error ? error.message : String(error) })) : null,\n\t\t\tallowances(discovered.harnesses, has(\"--refresh\")),\n\t\t]);\n\t\tconst available = applyAllowances(discovered.harnesses, allowanceSnapshot);\n\t\tif (command === \"allowance\") {\n\t\t\toutput({ format: \"json\", privacy: \"only normalized allowance metadata is cached locally; raw account output is discarded\", cache: allowanceSnapshot.cache, harnesses: allowanceReport(available, allowanceSnapshot) });\n\t\t\treturn;\n\t\t}\n\t\toutput({\n\t\t\tservice: { url: apiUrl(), authenticated: Boolean(key), catalog },\n\t\t\tinstallationId: await installationId(),\n\t\t\tprivacy: \"credentials, raw account output, and prompts remain local unless prompt sharing is explicit\",\n\t\t\tcache: { discovery: discovered.cache, allowance: allowanceSnapshot.cache },\n\t\t\tharnesses: publicDiscovery(available),\n\t\t});\n\t\treturn;\n\t}\n\tif (command === \"feedback\") {\n\t\tconst rating = Number(value(\"--rating\"));\n\t\tconst modelChoice = value(\"--model-choice\");\n\t\tconst wouldUseAgain = value(\"--would-use-again\");\n\t\tif (!Number.isInteger(rating) || rating < 1 || rating > 5) fail(\"--rating must be an integer from 1 to 5\");\n\t\tif (!modelChoice || ![\"right\", \"acceptable\", \"wrong\"].includes(modelChoice)) fail(\"--model-choice must be right, acceptable, or wrong\");\n\t\tif (!wouldUseAgain || ![\"yes\", \"no\"].includes(wouldUseAgain)) fail(\"--would-use-again must be yes or no\");\n\t\tlet receipt: Awaited<ReturnType<typeof readLastRoute>>;\n\t\ttry { receipt = await readLastRoute(); } catch { fail(\"no valid local route receipt found; delegate a task first\"); }\n\t\tif (Date.parse(receipt.expiresAt) < Date.now()) fail(\"the last route has expired; delegate another task first\");\n\t\tconst response = await api<Record<string, unknown>>(\"/v1/agent-feedback\", {\n\t\t\tmethod: \"POST\",\n\t\t\tbody: JSON.stringify({\n\t\t\t\tschemaVersion: AGENT_ROUTER_SCHEMA_VERSION,\n\t\t\t\trouteId: receipt.routeId,\n\t\t\t\tfeedbackToken: receipt.feedbackToken,\n\t\t\t\tidempotencyKey: randomUUID(),\n\t\t\t\tstatus: modelChoice === \"wrong\" ? \"failed\" : \"verified\",\n\t\t\t\tconfirmedTargetId: receipt.targetId,\n\t\t\t\tidentityConfirmed: true,\n\t\t\t\tchecksPassed: modelChoice === \"right\" ? 1 : 0,\n\t\t\t\tchecksFailed: modelChoice === \"wrong\" ? 1 : 0,\n\t\t\t\tretries: 0,\n\t\t\t\tusage: { contextTokensEstimated: 0, source: \"unknown\" },\n\t\t\t\ttimings: { totalMs: 0, routingMs: 0, executionMs: 0, verificationMs: 0 },\n\t\t\t}),\n\t\t});\n\t\toutput({ ...response, routeId: receipt.routeId, privacy: \"feedback excludes prompts, repository contents, model output, and credentials\" });\n\t\treturn;\n\t}\n\tif (command === \"route\" || command === \"delegate\") {\n\t\tconst task = value(\"--task\");\n\t\tif (!task) fail(\"--task is required\");\n\t\tconst prepared = await prepare(task);\n\t\tconst { route: selected, runId } = await requestRoute(prepared.body);\n\t\tawait saveLastRoute({ routeId: selected.routeId, ...(runId ? { runId } : {}), feedbackToken: selected.feedbackToken, expiresAt: selected.expiresAt, targetId: selected.plan.targetId });\n\t\tif (command === \"route\" || !has(\"--execute\")) {\n\t\t\toutput({ dryRun: true, ...(runId ? { runId, run: dashboardUrl(runId) } : {}), route: presented(selected), cache: prepared.cache, harnesses: publicDiscovery(prepared.discovery) });\n\t\t\treturn;\n\t\t}\n\t\tconst execution = await execute(task, selected, prepared.discovery, prepared.cache, runId);\n\t\toutput({ dryRun: false, ...(runId ? { runId, run: dashboardUrl(runId) } : {}), route: presented(selected), execution });\n\t\tif (execution.code !== 0) process.exitCode = 1;\n\t\treturn;\n\t}\n\tif (command === \"runs\") {\n\t\tconst sub = process.argv[3];\n\t\tif (sub === \"watch\") {\n\t\t\tconst runId = process.argv[4] ?? (await readLastRoute().catch(() => null))?.runId;\n\t\t\tif (!runId) fail(\"use: tokensize runs watch <runId>\");\n\t\t\tconst deadline = Date.now() + Number(value(\"--timeout-ms\") ?? 900_000);\n\t\t\tlet printed = 0;\n\t\t\tfor (;;) {\n\t\t\t\tconst doc = await api<{ status: string; events: Array<Record<string, unknown>> }>(`/v1/runs/${runId}`);\n\t\t\t\tfor (const event of doc.events.slice(printed)) output(event);\n\t\t\t\tprinted = doc.events.length;\n\t\t\t\tif ([\"completed\", \"failed\", \"cancelled\", \"expired\"].includes(doc.status)) {\n\t\t\t\t\toutput({ runId, status: doc.status, run: dashboardUrl(runId) });\n\t\t\t\t\tif (doc.status !== \"completed\") process.exitCode = 1;\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (Date.now() > deadline) fail(\"watch timed out; the run is still live on the dashboard\");\n\t\t\t\tawait new Promise((resolve) => setTimeout(resolve, 2_000));\n\t\t\t}\n\t\t}\n\t\tconst limit = Number(value(\"--limit\") ?? 25);\n\t\toutput(await api(`/v1/runs?limit=${Number.isInteger(limit) && limit > 0 ? Math.min(limit, 100) : 25}`));\n\t\treturn;\n\t}\n\tif (command === \"approve\" || command === \"cancel\") {\n\t\tconst runId = process.argv[3] ?? (await readLastRoute().catch(() => null))?.runId;\n\t\tif (!runId) fail(`use: tokensize ${command} <runId>`);\n\t\tconst event = command === \"approve\"\n\t\t\t? { seq: 0, at: new Date().toISOString(), actor: \"human\", type: \"approval-granted\", data: { kind: value(\"--kind\") ?? \"subscription-use\", grantedBy: \"local-cli\" } }\n\t\t\t: { seq: 0, at: new Date().toISOString(), actor: \"human\", type: \"cancelled\", data: { by: \"human\" } };\n\t\tconst result = await api(`/v1/runs/${runId}/events`, { method: \"POST\", body: JSON.stringify({ autoSeq: true, event }) });\n\t\toutput({ ...(result as Record<string, unknown>), run: dashboardUrl(runId) });\n\t\treturn;\n\t}\n\tif (command === \"open\") {\n\t\tconst runId = process.argv[3] ?? (await readLastRoute().catch(() => null))?.runId;\n\t\tif (!runId) fail(\"use: tokensize open <runId>\");\n\t\tconst url = dashboardUrl(runId);\n\t\tprocess.stdout.write(`${url}\\n`);\n\t\texecFile(process.platform === \"darwin\" ? \"open\" : process.platform === \"win32\" ? \"cmd\" : \"xdg-open\", process.platform === \"win32\" ? [\"/c\", \"start\", url] : [url]);\n\t\treturn;\n\t}\n\tif (command === \"policy\") {\n\t\tif (process.argv[3] === \"set\") {\n\t\t\tconst patch: Partial<LocalPolicy> = {};\n\t\t\tconst objective = value(\"--objective\");\n\t\t\tconst ceiling = value(\"--permission-ceiling\");\n\t\t\tconst rootHarness = value(\"--root-harness\");\n\t\t\tconst depth = value(\"--max-delegation-depth\");\n\t\t\tconst share = value(\"--share-prompt\");\n\t\t\tconst approve = value(\"--approve-subscription\");\n\t\t\tconst revoke = value(\"--revoke-subscription\");\n\t\t\tif (objective) patch.objective = objective as LocalPolicy[\"objective\"];\n\t\t\tif (ceiling) patch.permissionCeiling = ceiling as LocalPolicy[\"permissionCeiling\"];\n\t\t\tif (rootHarness) patch.rootHarness = rootHarness;\n\t\t\tif (depth) patch.maxDelegationDepth = Number(depth);\n\t\t\tif (share) patch.sharePromptDefault = share === \"true\";\n\t\t\tif (approve || revoke) {\n\t\t\t\tconst current = (await readLocalPolicy()).subscriptionHarnesses ?? [];\n\t\t\t\tconst next = new Set(current);\n\t\t\t\tif (approve) next.add(approve);\n\t\t\t\tif (revoke) next.delete(revoke);\n\t\t\t\tpatch.subscriptionHarnesses = [...next];\n\t\t\t}\n\t\t\tif (Object.keys(patch).length === 0) fail(\"nothing to set; see tokensize help\");\n\t\t\toutput({ policy: await saveLocalPolicy(patch), file: path.join(home(), \"policy.json\") });\n\t\t\treturn;\n\t\t}\n\t\toutput({ policy: await readLocalPolicy(), file: path.join(home(), \"policy.json\"), note: \"local ceilings always win; the hosted service can only narrow them\" });\n\t\treturn;\n\t}\n\tprocess.stdout.write(\"TokenSize CLI\\n\\n auth login\\n doctor [--refresh] [--verbose] [--json]\\n allowance [--refresh] [--json]\\n route --task TEXT [--role inspect|plan|implement|review|test] [--permission inspect|edit|test] [--refresh] [--verbose]\\n delegate --task TEXT [same options] [--execute]\\n runs [--limit N] | runs watch [runId] [--timeout-ms N]\\n approve [runId] [--kind subscription-use|execute|share-prompt]\\n cancel [runId]\\n open [runId]\\n policy [get] | policy set [--objective X] [--permission-ceiling X] [--root-harness X] [--max-delegation-depth N] [--share-prompt true|false] [--approve-subscription HARNESS] [--revoke-subscription HARNESS]\\n feedback --rating 1..5 --model-choice right|acceptable|wrong --would-use-again yes|no\\n\");\n}\n\nmain().catch((error) => fail(error instanceof Error ? error.message : String(error)));\n"],"mappings":";;;AAAA,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,QAAQ,aAAa;AAC9B,SAAS,oBAAoB;AAC7B,OAAO,UAAU;AACjB;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,OAGM;AACP;AAAA,EACC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIM;AAE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r/bin/env node
2
+
3
+ // src/index.ts
4
+ export * from "@tokensize/agent-client";
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["// Compatibility surface: the implementation lives in @tokensize/agent-client.\n// The CLI package re-exports it so existing `@tokensize/cli` imports keep\n// working while the dependency direction stays adapters → agent-client.\nexport * from \"@tokensize/agent-client\";\n"],"mappings":";;;AAGA,cAAc;","names":[]}
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@tokensize/cli",
3
+ "version": "0.3.0-beta.0",
4
+ "description": "Discover and safely delegate work to local coding harnesses using TokenSize routing",
5
+ "type": "module",
6
+ "bin": { "tokensize": "dist/cli.js" },
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": { ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" } },
10
+ "files": ["dist", "README.md", "LICENSE"],
11
+ "repository": { "type": "git", "url": "git+https://github.com/tokensize/tokensize.git", "directory": "packages/cli" },
12
+ "homepage": "https://tokensize.dev",
13
+ "bugs": { "url": "https://github.com/tokensize/tokensize/issues" },
14
+ "keywords": ["ai", "agents", "cli", "delegation", "routing"],
15
+ "publishConfig": { "access": "public", "provenance": true, "tag": "beta" },
16
+ "engines": { "node": ">=20" },
17
+ "scripts": { "prebuild": "npm --prefix ../.. run build --workspace @tokensize/agent-client", "build": "tsup", "pretypecheck": "npm --prefix ../.. run build --workspace @tokensize/agent-client", "typecheck": "tsc --noEmit", "test": "vitest run", "prepack": "npm run build", "prepublishOnly": "npm run typecheck && npm test" },
18
+ "dependencies": { "@tokensize/agent-client": "0.3.0-beta.0", "@tokensize/agent-router": "0.3.0-beta.0" },
19
+ "devDependencies": { "@types/node": "^26.1.1", "tsup": "^8.5.0", "typescript": "^5.5.2", "vitest": "^4.1.10" },
20
+ "license": "MIT"
21
+ }