@great-arrow/cli 0.1.35 → 0.1.36

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.
Files changed (2) hide show
  1. package/dist/index.js +1413 -1236
  2. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -9399,7 +9399,7 @@ function isNodeError(value) {
9399
9399
 
9400
9400
  // src/lib/version.ts
9401
9401
  var CLI_PACKAGE_NAME = "@great-arrow/cli";
9402
- var CLI_VERSION = "0.1.35";
9402
+ var CLI_VERSION = "0.1.36";
9403
9403
  var GAD_INSTALL_VERSION = "2026.08.08";
9404
9404
  var GAD_INSTALL_MIN_VERSION = "2026.06.22";
9405
9405
  var GAD_INSTALL_HEADER = "X-GAD-Install-Version";
@@ -16261,1384 +16261,1561 @@ function askCommand() {
16261
16261
  return cmd;
16262
16262
  }
16263
16263
 
16264
- // ../../src/lib/account/local-model-prefs-shared.ts
16265
- var LOCAL_PROVIDERS = ["ollama", "lmstudio"];
16266
- var LOCAL_PROVIDER_PRESETS = {
16267
- ollama: { baseUrl: "http://localhost:11434", label: "Ollama" },
16268
- lmstudio: { baseUrl: "http://localhost:1234", label: "LM Studio" }
16269
- };
16270
- var LOCAL_DEFAULT_BASE_URL = LOCAL_PROVIDER_PRESETS.ollama.baseUrl;
16271
- var MAX_LOCAL_MODELS = 50;
16272
- var MAX_LOCAL_MODEL_ID_LEN = 128;
16273
- var LOCAL_MODEL_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,127}$/;
16274
- function isValidLocalModelId(id) {
16275
- return typeof id === "string" && id.length > 0 && id.length <= MAX_LOCAL_MODEL_ID_LEN && LOCAL_MODEL_ID_RE.test(id);
16276
- }
16277
- function isValidLocalBaseUrl(value) {
16278
- if (typeof value !== "string" || value.length > 200) return false;
16279
- let url;
16280
- try {
16281
- url = new URL(value);
16282
- } catch {
16283
- return false;
16284
- }
16285
- if (url.protocol !== "http:" && url.protocol !== "https:") return false;
16286
- if (url.username || url.password) return false;
16287
- const host = url.hostname.toLowerCase();
16288
- return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
16289
- }
16290
-
16291
- // ../../src/lib/ai/local/delegate.ts
16292
- var LOCAL_CAPABLE_HEADER = "x-gad-local-capable";
16293
- var LOCAL_CAPABLE_VALUE = "1";
16294
- var LOCAL_TURN_HEADER = "x-gad-local-turn";
16295
- var UNFINISHED_TURN_AFTER_MS = 6 * 6e4;
16296
-
16297
- // ../../src/lib/chat/agentic-steps.ts
16298
- var MAX_AGENTIC_STEPS = 6;
16299
-
16300
- // ../../src/lib/ai/local/endpoint.ts
16301
- function localApiUrl(baseUrl, path10) {
16302
- return `${baseUrl.replace(/\/+$/, "")}${path10}`;
16303
- }
16264
+ // src/lib/glance-footer.ts
16265
+ import { readFile as readFile4, writeFile as writeFile4, mkdir as mkdir4 } from "node:fs/promises";
16266
+ import { homedir as homedir4 } from "node:os";
16267
+ import { join as join6, dirname as dirname5 } from "node:path";
16304
16268
 
16305
- // ../../src/lib/ai/local/tool-loop.ts
16306
- var MAX_TOOL_CALLS_PER_STEP = 4;
16307
- var MAX_TOOL_ARGUMENT_CHARS = 8e3;
16308
- var MAX_TOOL_RESULT_CHARS = 6e3;
16309
- function accumulateToolCalls(current, deltas) {
16310
- const next = current.map((call) => ({ ...call }));
16311
- for (const delta of deltas) {
16312
- const at = delta.position;
16313
- if (!Number.isInteger(at) || at < 0 || at >= MAX_TOOL_CALLS_PER_STEP) {
16314
- continue;
16315
- }
16316
- while (next.length <= at) next.push({ id: "", name: "", arguments: "" });
16317
- const slot = next[at];
16318
- if (delta.id) slot.id = delta.id;
16319
- if (delta.name) slot.name = delta.name;
16320
- if (delta.argumentsFragment) {
16321
- slot.arguments = (slot.arguments + delta.argumentsFragment).slice(
16322
- 0,
16323
- MAX_TOOL_ARGUMENT_CHARS
16324
- );
16325
- }
16326
- }
16327
- return next;
16328
- }
16329
- function finalizeToolCalls(calls) {
16330
- return calls.filter((call) => call.name.length > 0).slice(0, MAX_TOOL_CALLS_PER_STEP).map((call, index) => ({
16331
- ...call,
16332
- id: call.id || `call_${index}`,
16333
- arguments: call.arguments || "{}"
16334
- }));
16335
- }
16336
- function parseToolArguments(raw) {
16337
- if (raw.length > MAX_TOOL_ARGUMENT_CHARS) return null;
16338
- let parsed;
16269
+ // src/lib/seen.ts
16270
+ var SEEN_TIMEOUT_MS = 1e3;
16271
+ var MAX_KEYS = 50;
16272
+ async function reportSeen(opts) {
16273
+ const keys = [
16274
+ ...new Set(
16275
+ opts.keys.filter((k) => typeof k === "string" && k !== "")
16276
+ )
16277
+ ].slice(0, MAX_KEYS);
16278
+ if (keys.length === 0) return 0;
16279
+ const controller = new AbortController();
16280
+ const timer = setTimeout(() => controller.abort(), SEEN_TIMEOUT_MS);
16339
16281
  try {
16340
- parsed = JSON.parse(raw.trim() || "{}");
16282
+ const response = await fetch(
16283
+ `${opts.apiUrl.replace(/\/$/, "")}/api/attention/seen`,
16284
+ {
16285
+ method: "POST",
16286
+ headers: {
16287
+ "Content-Type": "application/json",
16288
+ Authorization: `Bearer ${opts.token}`
16289
+ },
16290
+ body: JSON.stringify({ keys }),
16291
+ signal: controller.signal
16292
+ }
16293
+ );
16294
+ if (!response.ok) return 0;
16295
+ const data = await response.json().catch(() => null);
16296
+ return typeof data?.seen === "number" ? data.seen : 0;
16341
16297
  } catch {
16342
- return null;
16343
- }
16344
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
16345
- return null;
16298
+ return 0;
16299
+ } finally {
16300
+ clearTimeout(timer);
16346
16301
  }
16347
- return parsed;
16348
16302
  }
16349
- function clampToolResult(value) {
16350
- let text2;
16303
+
16304
+ // src/lib/glance-footer.ts
16305
+ var FETCH_TIMEOUT_MS = 1500;
16306
+ var THROTTLE_INTERVAL_MS = 4 * 60 * 60 * 1e3;
16307
+ var URGENT_THRESHOLD = 15;
16308
+ var SKIP_COMMANDS = /* @__PURE__ */ new Set(["status", "needs", "login", "logout", "help"]);
16309
+ async function maybeShowGlanceFooter(argv) {
16351
16310
  try {
16352
- text2 = typeof value === "string" ? value : JSON.stringify(value);
16353
- } catch {
16354
- text2 = "";
16311
+ if (!shouldRunGlanceFooter(argv)) return;
16312
+ const auth = await resolveAuth();
16313
+ const payload = await fetchGlance(auth.apiUrl, auth.token);
16314
+ if (!payload) return;
16315
+ if (payload.urgency === null) return;
16316
+ const workspaceKey = auth.activeWorkspace ?? "default";
16317
+ const signature = topSignature(payload);
16318
+ const state = await loadGlanceState();
16319
+ const now = Date.now();
16320
+ if (!shouldShowGlance({
16321
+ urgency: payload.urgency,
16322
+ topItemId: signature,
16323
+ state: state[workspaceKey] ?? {},
16324
+ now
16325
+ })) {
16326
+ return;
16327
+ }
16328
+ const printed = renderFooter(payload, auth.apiUrl);
16329
+ state[workspaceKey] = { lastShownAt: now, lastTopItemId: signature };
16330
+ await saveGlanceState(state);
16331
+ await reportSeen({
16332
+ apiUrl: auth.apiUrl,
16333
+ token: auth.token,
16334
+ keys: printed
16335
+ });
16336
+ } catch (err) {
16337
+ debugSwallow("glance-footer", err);
16355
16338
  }
16356
- if (!text2) return "{}";
16357
- return text2.length > MAX_TOOL_RESULT_CHARS ? `${text2.slice(0, MAX_TOOL_RESULT_CHARS)}\u2026 (shortened)` : text2;
16358
- }
16359
- function assistantToolCallMessage(calls) {
16360
- return {
16361
- role: "assistant",
16362
- content: "",
16363
- toolCalls: calls.map((call) => ({
16364
- id: call.id,
16365
- type: "function",
16366
- function: { name: call.name, arguments: call.arguments }
16367
- }))
16368
- };
16369
16339
  }
16370
- function toolResultMessage(call, result) {
16371
- return {
16372
- role: "tool",
16373
- content: clampToolResult(result),
16374
- toolCallId: call.id,
16375
- name: call.name
16376
- };
16340
+ function shouldRunGlanceFooter(argv) {
16341
+ if (!process.stderr.isTTY) return false;
16342
+ if (process.env.CI) return false;
16343
+ if (process.env.GAD_NO_GLANCE) return false;
16344
+ if (argv.includes("--json")) return false;
16345
+ if (argv.includes("--quiet")) return false;
16346
+ if (argv.includes("--stdout")) return false;
16347
+ if (argv.includes("--no-glance")) return false;
16348
+ const command = firstCommand(argv);
16349
+ if (!command) return false;
16350
+ if (SKIP_COMMANDS.has(command)) return false;
16351
+ return true;
16377
16352
  }
16378
-
16379
- // ../../src/lib/ai/local/generate.ts
16380
- var LocalRunError = class extends Error {
16381
- constructor(message) {
16382
- super(message);
16383
- this.name = "LocalRunError";
16384
- }
16385
- };
16386
- var CHAT_PATH = {
16387
- ollama: "/api/chat",
16388
- lmstudio: "/v1/chat/completions"
16389
- };
16390
- async function* readLines(body) {
16391
- const reader = body.getReader();
16392
- const decoder = new TextDecoder();
16393
- let buffer = "";
16394
- while (true) {
16395
- const { done, value } = await reader.read();
16396
- if (done) break;
16397
- buffer += decoder.decode(value, { stream: true });
16398
- let index = buffer.indexOf("\n");
16399
- while (index >= 0) {
16400
- const line = buffer.slice(0, index).trim();
16401
- buffer = buffer.slice(index + 1);
16402
- if (line) yield line;
16403
- index = buffer.indexOf("\n");
16404
- }
16353
+ function firstCommand(argv) {
16354
+ for (const token of argv.slice(2)) {
16355
+ if (!token.startsWith("-")) return token;
16405
16356
  }
16406
- const tail = buffer.trim();
16407
- if (tail) yield tail;
16408
- }
16409
- function numberOrUndefined(value) {
16410
- return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : void 0;
16357
+ return null;
16411
16358
  }
16412
- function argumentsAsText(value) {
16413
- if (typeof value === "string") return value;
16359
+ async function fetchGlance(apiUrl, token) {
16360
+ const controller = new AbortController();
16361
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
16414
16362
  try {
16415
- return JSON.stringify(value ?? {});
16363
+ const response = await fetch(`${apiUrl}/api/mcp`, {
16364
+ method: "POST",
16365
+ headers: {
16366
+ "Content-Type": "application/json",
16367
+ Authorization: `Bearer ${token}`
16368
+ },
16369
+ body: JSON.stringify({
16370
+ jsonrpc: "2.0",
16371
+ id: `cli-glance-${Date.now()}`,
16372
+ method: "tools/call",
16373
+ params: { name: "glance", arguments: {} }
16374
+ }),
16375
+ signal: controller.signal
16376
+ });
16377
+ if (!response.ok) return null;
16378
+ const data = await response.json();
16379
+ if (data.error) return null;
16380
+ return normalizeGlance(
16381
+ parseMcpPayload(data.result?.content ?? data.result)
16382
+ );
16416
16383
  } catch {
16417
- return "{}";
16384
+ return null;
16385
+ } finally {
16386
+ clearTimeout(timer);
16418
16387
  }
16419
16388
  }
16420
- function readOllamaToolCalls(message) {
16421
- const raw = message?.tool_calls;
16422
- if (!Array.isArray(raw)) return [];
16423
- const out = [];
16424
- raw.forEach((entry, position) => {
16425
- if (!entry || typeof entry !== "object") return;
16426
- const fn = entry.function;
16427
- if (typeof fn?.name !== "string") return;
16428
- out.push({
16429
- position,
16430
- name: fn.name,
16431
- argumentsFragment: argumentsAsText(fn.arguments)
16432
- });
16389
+ function normalizeGlance(raw) {
16390
+ if (typeof raw !== "object" || raw === null) return null;
16391
+ const obj = raw;
16392
+ const needsYou = asArray2(obj.needsYou).flatMap((item) => {
16393
+ if (typeof item !== "object" || item === null) return [];
16394
+ const it = item;
16395
+ if (typeof it.title !== "string") return [];
16396
+ return [
16397
+ {
16398
+ kind: typeof it.kind === "string" ? it.kind : "nudge",
16399
+ title: it.title,
16400
+ action: typeof it.action === "string" ? it.action : null,
16401
+ href: typeof it.href === "string" && it.href !== "" ? it.href : null,
16402
+ ...typeof it.rank === "number" ? { rank: it.rank } : {},
16403
+ signalKey: typeof it.signalKey === "string" && it.signalKey !== "" ? it.signalKey : null,
16404
+ workspace: typeof it.workspace === "string" && it.workspace !== "" ? it.workspace : null,
16405
+ // Parsed like every other field: a non-string is dropped rather than
16406
+ // coerced, so a malformed payload cannot render as a currency claim.
16407
+ freshness: typeof it.freshness === "string" && it.freshness !== "" ? it.freshness : null,
16408
+ meta: typeof it.meta === "string" && it.meta !== "" ? it.meta : null
16409
+ }
16410
+ ];
16433
16411
  });
16434
- return out;
16435
- }
16436
- function readOllamaLine(line) {
16437
- let parsed;
16438
- try {
16439
- parsed = JSON.parse(line);
16440
- } catch {
16441
- return null;
16412
+ const atRisk = asArray2(obj.atRisk).flatMap((item) => {
16413
+ if (typeof item !== "object" || item === null) return [];
16414
+ const it = item;
16415
+ if (typeof it.title !== "string") return [];
16416
+ return [
16417
+ {
16418
+ classification: typeof it.classification === "string" ? it.classification : null,
16419
+ riskLevel: typeof it.riskLevel === "string" ? it.riskLevel : "high",
16420
+ title: it.title,
16421
+ branch: typeof it.branch === "string" ? it.branch : null,
16422
+ aheadMain: typeof it.aheadMain === "number" ? it.aheadMain : null,
16423
+ recommendedAction: typeof it.recommendedAction === "string" ? it.recommendedAction : null
16424
+ }
16425
+ ];
16426
+ });
16427
+ const integrations = asArray2(obj.integrations).flatMap((item) => {
16428
+ if (typeof item !== "object" || item === null) return [];
16429
+ const it = item;
16430
+ if (typeof it.kind !== "string") return [];
16431
+ return [
16432
+ {
16433
+ kind: it.kind,
16434
+ staleFor: typeof it.staleFor === "string" ? it.staleFor : null,
16435
+ refresh: typeof it.refresh === "string" ? it.refresh : null
16436
+ }
16437
+ ];
16438
+ });
16439
+ const agents = asArray2(obj.agents).flatMap((item) => {
16440
+ if (typeof item !== "object" || item === null) return [];
16441
+ const it = item;
16442
+ if (typeof it.name !== "string") return [];
16443
+ return [
16444
+ {
16445
+ name: it.name,
16446
+ tool: typeof it.tool === "string" ? it.tool : null,
16447
+ card: typeof it.card === "string" ? it.card : null
16448
+ }
16449
+ ];
16450
+ });
16451
+ let topGoal = null;
16452
+ if (typeof obj.topGoal === "object" && obj.topGoal !== null) {
16453
+ const g = obj.topGoal;
16454
+ if (typeof g.title === "string") {
16455
+ topGoal = {
16456
+ title: g.title,
16457
+ done: typeof g.done === "number" ? g.done : 0,
16458
+ total: typeof g.total === "number" ? g.total : 0,
16459
+ eta: typeof g.eta === "string" ? g.eta : null
16460
+ };
16461
+ }
16462
+ }
16463
+ let warRoom = null;
16464
+ if (typeof obj.warRoom === "object" && obj.warRoom !== null) {
16465
+ const w = obj.warRoom;
16466
+ warRoom = {
16467
+ priorityCount: typeof w.priorityCount === "number" ? w.priorityCount : 0,
16468
+ unreadTotal: typeof w.unreadTotal === "number" ? w.unreadTotal : 0,
16469
+ openRequestCount: typeof w.openRequestCount === "number" ? w.openRequestCount : 0,
16470
+ topSender: typeof w.topSender === "string" ? w.topSender : null,
16471
+ newestSender: typeof w.newestSender === "string" ? w.newestSender : null,
16472
+ newestPreview: typeof w.newestPreview === "string" ? w.newestPreview : null
16473
+ };
16442
16474
  }
16443
- if (!parsed || typeof parsed !== "object") return null;
16444
- const row = parsed;
16445
- if (typeof row.error === "string") throw new LocalRunError(row.error);
16446
- const message = row.message;
16447
- const delta = typeof message?.content === "string" ? message.content : "";
16448
16475
  return {
16449
- delta,
16450
- toolCalls: readOllamaToolCalls(message),
16451
- input: numberOrUndefined(row.prompt_eval_count),
16452
- output: numberOrUndefined(row.eval_count)
16476
+ workspace: typeof obj.workspace === "string" && obj.workspace !== "" ? obj.workspace : null,
16477
+ // An older server sends no `reads` at all, so this normalizes to an empty
16478
+ // list rather than inventing the pinned workspace as the read set — the
16479
+ // CLI then renders no breadth cue, which is honest, instead of a claim it
16480
+ // was never told.
16481
+ reads: Array.isArray(obj.reads) ? obj.reads.flatMap((r) => {
16482
+ if (typeof r !== "object" || r === null) return [];
16483
+ const row = r;
16484
+ return typeof row.id === "string" && typeof row.name === "string" ? [{ id: row.id, name: row.name }] : [];
16485
+ }) : [],
16486
+ needsYou,
16487
+ atRisk,
16488
+ topGoal,
16489
+ integrations,
16490
+ agents,
16491
+ warRoom,
16492
+ // Parsed like every other field: both halves must be the right type or the
16493
+ // whole line is dropped, so a malformed payload cannot render as a dollar.
16494
+ spend: (() => {
16495
+ const raw2 = obj.spend;
16496
+ if (typeof raw2 !== "object" || raw2 === null) return null;
16497
+ const sp = raw2;
16498
+ return typeof sp.line === "string" && sp.line !== "" && typeof sp.totalCostUsd === "number" && Number.isFinite(sp.totalCostUsd) ? { line: sp.line, totalCostUsd: sp.totalCostUsd } : null;
16499
+ })(),
16500
+ urgency: typeof obj.urgency === "number" ? obj.urgency : null,
16501
+ generatedAt: typeof obj.generatedAt === "string" ? obj.generatedAt : (/* @__PURE__ */ new Date()).toISOString()
16453
16502
  };
16454
16503
  }
16455
- function readOpenAiToolCalls(deltaObj) {
16456
- const raw = deltaObj?.tool_calls;
16457
- if (!Array.isArray(raw)) return [];
16458
- const out = [];
16459
- raw.forEach((entry, fallbackPosition) => {
16460
- if (!entry || typeof entry !== "object") return;
16461
- const row = entry;
16462
- const fn = row.function;
16463
- out.push({
16464
- position: typeof row.index === "number" ? row.index : fallbackPosition,
16465
- id: typeof row.id === "string" ? row.id : void 0,
16466
- name: typeof fn?.name === "string" ? fn.name : void 0,
16467
- argumentsFragment: typeof fn?.arguments === "string" ? fn.arguments : void 0
16468
- });
16469
- });
16470
- return out;
16504
+ function asArray2(value) {
16505
+ return Array.isArray(value) ? value : [];
16471
16506
  }
16472
- function readOpenAiLine(line) {
16473
- if (!line.startsWith("data:")) return null;
16474
- const payload = line.slice(5).trim();
16475
- if (!payload || payload === "[DONE]") return null;
16476
- let parsed;
16477
- try {
16478
- parsed = JSON.parse(payload);
16479
- } catch {
16480
- return null;
16507
+ function topSignature(payload) {
16508
+ if (payload.warRoom && payload.warRoom.priorityCount > 0) {
16509
+ return `warroom:${payload.warRoom.newestSender ?? "peer"}`;
16481
16510
  }
16482
- if (!parsed || typeof parsed !== "object") return null;
16483
- const row = parsed;
16484
- const choices = Array.isArray(row.choices) ? row.choices : [];
16485
- const first = choices[0];
16486
- const deltaObj = first?.delta;
16487
- const delta = typeof deltaObj?.content === "string" ? deltaObj.content : "";
16488
- const usage = row.usage;
16489
- return {
16490
- delta,
16491
- toolCalls: readOpenAiToolCalls(deltaObj),
16492
- input: numberOrUndefined(usage?.prompt_tokens),
16493
- output: numberOrUndefined(usage?.completion_tokens)
16494
- };
16511
+ const top = payload.needsYou[0];
16512
+ if (top) return `needs:${top.kind}:${top.title}`;
16513
+ const integration = payload.integrations[0];
16514
+ if (integration) return `stale:${integration.kind}`;
16515
+ const agent = payload.agents[0];
16516
+ if (agent) return `agent:${agent.name}`;
16517
+ if (payload.topGoal) return `goal:${payload.topGoal.title}`;
16518
+ return "empty";
16495
16519
  }
16496
- function wireMessage(message, provider) {
16497
- if (message.role === "tool") {
16498
- return provider === "ollama" ? {
16499
- role: "tool",
16500
- content: message.content,
16501
- tool_name: message.name ?? ""
16502
- } : {
16503
- role: "tool",
16504
- content: message.content,
16505
- tool_call_id: message.toolCallId ?? ""
16506
- };
16507
- }
16508
- if (message.role === "assistant" && message.toolCalls?.length) {
16509
- return {
16510
- role: "assistant",
16511
- content: message.content,
16512
- tool_calls: message.toolCalls.map(
16513
- (call) => provider === "ollama" ? {
16514
- function: {
16515
- name: call.function.name,
16516
- arguments: safeParseArguments(call.function.arguments)
16517
- }
16518
- } : call
16519
- )
16520
- };
16521
- }
16522
- return { role: message.role, content: message.content };
16520
+ function shouldShowGlance(input) {
16521
+ const { urgency, topItemId, state, now } = input;
16522
+ if (urgency > URGENT_THRESHOLD) return false;
16523
+ if (state.lastShownAt === void 0) return true;
16524
+ if (state.lastTopItemId !== topItemId) return true;
16525
+ return now - state.lastShownAt >= THROTTLE_INTERVAL_MS;
16523
16526
  }
16524
- function safeParseArguments(raw) {
16527
+ function getGlanceStatePath() {
16528
+ return join6(homedir4(), ".gad", "glance-state.json");
16529
+ }
16530
+ async function loadGlanceState() {
16525
16531
  try {
16526
- const parsed = JSON.parse(raw || "{}");
16527
- return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
16532
+ const content = await readFile4(getGlanceStatePath(), "utf-8");
16533
+ const parsed = JSON.parse(content);
16534
+ if (typeof parsed === "object" && parsed !== null) {
16535
+ return parsed;
16536
+ }
16537
+ return {};
16528
16538
  } catch {
16529
16539
  return {};
16530
16540
  }
16531
16541
  }
16532
- async function runLocalChat(opts) {
16533
- if (!isValidLocalBaseUrl(opts.baseUrl)) {
16534
- throw new LocalRunError("unusable address");
16542
+ async function saveGlanceState(state) {
16543
+ const path10 = getGlanceStatePath();
16544
+ await mkdir4(dirname5(path10), { recursive: true });
16545
+ await writeFile4(path10, JSON.stringify(state), "utf-8");
16546
+ }
16547
+ function glanceItemUrl(href, apiUrl) {
16548
+ if (!href) return null;
16549
+ if (/^https?:\/\//i.test(href)) return href;
16550
+ if (!href.startsWith("/") || href.startsWith("//")) return null;
16551
+ return `${apiUrl.replace(/\/$/, "")}${href}`;
16552
+ }
16553
+ function renderFooter(payload, apiUrl) {
16554
+ const c = createColor(false);
16555
+ const lines = [];
16556
+ const printed = [];
16557
+ const wr = payload.warRoom;
16558
+ if (wr && wr.priorityCount > 0) {
16559
+ lines.push(
16560
+ `${c.yellow("!")} ${wr.priorityCount} war-room message${wr.priorityCount === 1 ? "" : "s"} for you${wr.newestSender ? ` \u2014 ${wr.newestSender}` : ""}`
16561
+ );
16535
16562
  }
16536
- const doFetch = opts.fetchImpl ?? fetch;
16537
- const url = localApiUrl(opts.baseUrl, CHAT_PATH[opts.provider]);
16538
- const response = await doFetch(url, {
16539
- method: "POST",
16540
- headers: { "content-type": "application/json" },
16541
- body: JSON.stringify({
16542
- model: opts.modelId,
16543
- messages: opts.messages.map(
16544
- (message) => wireMessage(message, opts.provider)
16545
- ),
16546
- ...opts.tools?.length ? { tools: opts.tools } : {},
16547
- stream: true
16548
- }),
16549
- cache: "no-store",
16550
- signal: opts.signal
16551
- });
16552
- if (!response.ok || !response.body) {
16553
- throw new LocalRunError(`refused with ${response.status}`);
16554
- }
16555
- const readLine = opts.provider === "ollama" ? readOllamaLine : readOpenAiLine;
16556
- let text2 = "";
16557
- let toolCalls = [];
16558
- let inputTokens;
16559
- let outputTokens;
16560
- for await (const line of readLines(response.body)) {
16561
- const piece = readLine(line);
16562
- if (!piece) continue;
16563
- if (piece.input !== void 0) inputTokens = piece.input;
16564
- if (piece.output !== void 0) outputTokens = piece.output;
16565
- if (piece.toolCalls?.length) {
16566
- toolCalls = accumulateToolCalls(toolCalls, piece.toolCalls);
16567
- }
16568
- if (piece.delta) {
16569
- text2 += piece.delta;
16570
- opts.onDelta(piece.delta);
16563
+ const unpushed = (payload.atRisk ?? []).filter(
16564
+ (item) => item.classification === "unpushed"
16565
+ );
16566
+ if (unpushed.length > 0) {
16567
+ const commits = unpushed.reduce(
16568
+ (sum, item) => sum + (item.aheadMain ?? 0),
16569
+ 0
16570
+ );
16571
+ const scale = commits > 0 ? `${commits} commit${commits === 1 ? "" : "s"} on ${unpushed.length} branch${unpushed.length === 1 ? "" : "es"}` : `${unpushed.length} branch${unpushed.length === 1 ? "" : "es"}`;
16572
+ lines.push(`${c.yellow("!")} ${scale} exist on this machine only`);
16573
+ const first = unpushed[0];
16574
+ if (first?.branch) {
16575
+ lines.push(
16576
+ ` ${c.dim("\u2192")} ${c.cyan(`git push -u origin ${first.branch}`)}`
16577
+ );
16571
16578
  }
16572
16579
  }
16573
- const asked = finalizeToolCalls(toolCalls);
16574
- if (!text2 && asked.length === 0)
16575
- throw new LocalRunError("no answer produced");
16576
- return { text: text2, toolCalls: asked, inputTokens, outputTokens };
16577
- }
16578
-
16579
- // ../../src/lib/ai/local/run-turn.ts
16580
- var TOOL_EXEC_PATH = "/api/chat/tool-exec";
16581
- var MAX_REPORTED_PROMPT_CHARS = 4e6;
16582
- function charactersIn(messages) {
16583
- return messages.reduce((total, message) => total + message.content.length, 0);
16584
- }
16585
- async function callApp(call, handoff, signal, doFetch) {
16586
- const args = parseToolArguments(call.arguments);
16587
- if (!args) {
16588
- return {
16589
- result: { error: "unreadable_request", message: "Write that as JSON." },
16590
- exhausted: false
16591
- };
16592
- }
16593
- const response = await doFetch(TOOL_EXEC_PATH, {
16594
- method: "POST",
16595
- headers: { "content-type": "application/json" },
16596
- body: JSON.stringify({
16597
- grant: handoff.toolGrant,
16598
- tool: call.name,
16599
- args,
16600
- turnId: handoff.turnId
16601
- }),
16602
- cache: "no-store",
16603
- signal
16604
- });
16605
- const payload = await response.json().catch(() => null);
16606
- if (!response.ok || !payload) {
16607
- return {
16608
- result: {
16609
- error: payload?.error ?? "unavailable",
16610
- message: payload?.message ?? "That did not work."
16611
- },
16612
- exhausted: payload?.error === "step_budget_exhausted"
16613
- };
16580
+ for (const item of payload.needsYou.slice(0, 2)) {
16581
+ lines.push(`${c.yellow("!")} ${item.title}`);
16582
+ if (item.signalKey) printed.push(item.signalKey);
16583
+ if (item.action) {
16584
+ lines.push(` ${c.dim("\u2192")} ${c.cyan(item.action)}`);
16585
+ } else {
16586
+ const url = glanceItemUrl(item.href, apiUrl);
16587
+ if (url) lines.push(` ${c.dim("\u2192")} ${c.cyan(url)}`);
16588
+ }
16614
16589
  }
16615
- return { result: payload.result, exhausted: false };
16616
- }
16617
- async function runLocalTurn(opts) {
16618
- const doFetch = opts.fetchImpl ?? fetch;
16619
- const { handoff } = opts;
16620
- const messages = [...handoff.messages];
16621
- const offered = handoff.tools ?? [];
16622
- let text2 = "";
16623
- let inputTokens;
16624
- let outputTokens;
16625
- let promptCharacters = 0;
16626
- let toolCallCount = 0;
16627
- let toolsStillOffered = offered.length > 0 && !!handoff.toolGrant;
16628
- for (let pass = 0; pass <= MAX_AGENTIC_STEPS; pass++) {
16629
- promptCharacters += charactersIn(messages);
16630
- const result = await runLocalChat({
16631
- baseUrl: handoff.baseUrl,
16632
- provider: handoff.provider,
16633
- modelId: handoff.modelId,
16634
- messages,
16635
- ...toolsStillOffered ? { tools: offered } : {},
16636
- signal: opts.signal,
16637
- onDelta: opts.onDelta,
16638
- fetchImpl: doFetch
16639
- });
16640
- if (result.inputTokens !== void 0) inputTokens = result.inputTokens;
16641
- if (result.outputTokens !== void 0) outputTokens = result.outputTokens;
16642
- text2 += result.text;
16643
- if (!toolsStillOffered || result.toolCalls.length === 0) break;
16644
- messages.push(assistantToolCallMessage(result.toolCalls));
16645
- for (const call of result.toolCalls) {
16646
- toolCallCount += 1;
16647
- opts.onToolStep?.(call.name);
16648
- const answer = await callApp(call, handoff, opts.signal, doFetch);
16649
- messages.push(toolResultMessage(call, answer.result));
16650
- if (answer.exhausted) toolsStillOffered = false;
16590
+ if (lines.length === 0) {
16591
+ const integration = payload.integrations[0];
16592
+ if (integration) {
16593
+ const stale = integration.staleFor ? ` (stale ${integration.staleFor})` : "";
16594
+ lines.push(`${c.yellow("!")} ${integration.kind}${stale}`);
16595
+ if (integration.refresh) {
16596
+ lines.push(` ${c.dim("\u2192")} ${c.cyan(integration.refresh)}`);
16597
+ }
16651
16598
  }
16652
- if (pass === MAX_AGENTIC_STEPS - 1) toolsStillOffered = false;
16653
16599
  }
16654
- return {
16655
- text: text2,
16656
- inputTokens,
16657
- outputTokens,
16658
- // The settle route refuses a report with an implausible figure in it, and
16659
- // refusing the report would lose the whole turn. Keep it inside what that
16660
- // route accepts; a clipped ceiling only ever counts fewer words, never more.
16661
- promptCharacters: Math.min(promptCharacters, MAX_REPORTED_PROMPT_CHARS),
16662
- toolCallCount
16663
- };
16600
+ if (lines.length === 0) return [];
16601
+ lines.push(`${c.dim("\u2192")} ${c.cyan("gad status")} for the full picture.`);
16602
+ process.stderr.write("\n" + brandedBlock("needs you", lines) + "\n");
16603
+ return printed;
16604
+ }
16605
+ var GAD_MARK = "\u{1F3F9}";
16606
+ function brandedBlock(title, lines) {
16607
+ const header = `${GAD_MARK} Great Arrow \xB7 ${title}`;
16608
+ const rule = "\u2500".repeat(Math.min(60, [...header].length));
16609
+ return [header, rule, ...lines].join("\n");
16664
16610
  }
16665
16611
 
16666
- // ../../src/lib/ai/local/client.ts
16667
- var CHAT_PATH2 = "/api/chat";
16668
- var SETTLE_PATH = "/api/chat/local-turn";
16669
- var MAX_REPORTED_TEXT_CHARS = 2e5;
16670
- var MAX_REPORTED_LATENCY_MS = 36e5;
16671
- var HANDOFF_TIMEOUT_MS = 6e4;
16672
- var SETTLE_TIMEOUT_MS = 3e4;
16673
- var LocalTurnFailed = class extends Error {
16674
- stage;
16675
- /** Set once the turn was handed back, so a caller knows the conversation is
16676
- * not left with an unfinished reply in it. */
16677
- closed;
16678
- constructor(stage, message, closed) {
16679
- super(message);
16680
- this.name = "LocalTurnFailed";
16681
- this.stage = stage;
16682
- this.closed = closed;
16683
- }
16612
+ // ../../src/lib/account/local-model-prefs-shared.ts
16613
+ var LOCAL_PROVIDERS = ["ollama", "lmstudio"];
16614
+ var LOCAL_PROVIDER_PRESETS = {
16615
+ ollama: { baseUrl: "http://localhost:11434", label: "Ollama" },
16616
+ lmstudio: { baseUrl: "http://localhost:1234", label: "LM Studio" }
16684
16617
  };
16685
- function authHeaders(token) {
16686
- return {
16687
- "content-type": "application/json",
16688
- authorization: `Bearer ${token}`
16689
- };
16618
+ var LOCAL_DEFAULT_BASE_URL = LOCAL_PROVIDER_PRESETS.ollama.baseUrl;
16619
+ var BROWSER_REACHABLE_LOCAL_BASE_URLS = Object.values(LOCAL_PROVIDER_PRESETS).map((preset) => preset.baseUrl);
16620
+ var BROWSER_REACHABLE_ORIGINS = new Set(
16621
+ BROWSER_REACHABLE_LOCAL_BASE_URLS.map((url) => new URL(url).origin)
16622
+ );
16623
+ var MAX_LOCAL_MODELS = 50;
16624
+ var MAX_LOCAL_MODEL_ID_LEN = 128;
16625
+ var LOCAL_MODEL_ID_RE = /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,127}$/;
16626
+ function isValidLocalModelId(id) {
16627
+ return typeof id === "string" && id.length > 0 && id.length <= MAX_LOCAL_MODEL_ID_LEN && LOCAL_MODEL_ID_RE.test(id);
16690
16628
  }
16691
- function origin(apiUrl) {
16692
- return apiUrl.replace(/\/+$/, "");
16629
+ function isValidLocalBaseUrl(value) {
16630
+ if (typeof value !== "string" || value.length > 200) return false;
16631
+ let url;
16632
+ try {
16633
+ url = new URL(value);
16634
+ } catch {
16635
+ return false;
16636
+ }
16637
+ if (url.protocol !== "http:" && url.protocol !== "https:") return false;
16638
+ if (url.username || url.password) return false;
16639
+ const host = url.hostname.toLowerCase();
16640
+ return host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1";
16693
16641
  }
16694
- function appAwareFetch(apiUrl, token, base) {
16695
- return (input, init) => {
16696
- const target = typeof input === "string" ? input : String(input);
16697
- if (!target.startsWith("/")) return base(input, init);
16698
- return base(`${origin(apiUrl)}${target}`, {
16699
- ...init,
16700
- headers: {
16701
- ...init?.headers,
16702
- ...authHeaders(token)
16703
- }
16704
- });
16705
- };
16642
+
16643
+ // ../../src/lib/ai/local/delegate.ts
16644
+ var LOCAL_CAPABLE_HEADER = "x-gad-local-capable";
16645
+ var LOCAL_CAPABLE_VALUE = "1";
16646
+ var LOCAL_TURN_HEADER = "x-gad-local-turn";
16647
+ var UNFINISHED_TURN_AFTER_MS = 6 * 6e4;
16648
+
16649
+ // ../../src/lib/ai/local/endpoint.ts
16650
+ function localApiUrl(baseUrl, path10) {
16651
+ return `${baseUrl.replace(/\/+$/, "")}${path10}`;
16706
16652
  }
16707
- async function withTimeout(ms, run2) {
16653
+
16654
+ // ../../src/lib/ai/local/residency.ts
16655
+ var LOCAL_MODEL_LOAD_DEADLINE_MS = 9e4;
16656
+ var RESIDENCY_PROBE_TIMEOUT_MS = 1500;
16657
+ async function modelIsProvablyAbsent(baseUrl, provider, modelId, opts = {}) {
16658
+ if (provider !== "ollama") return false;
16659
+ if (!isValidLocalBaseUrl(baseUrl)) return false;
16660
+ if (!modelId) return false;
16661
+ const doFetch = opts.fetchImpl ?? (typeof fetch === "function" ? fetch : null);
16662
+ if (!doFetch || typeof AbortController !== "function") return false;
16708
16663
  const controller = new AbortController();
16709
- const timer = setTimeout(() => controller.abort(), ms);
16664
+ const timer = setTimeout(
16665
+ () => controller.abort(),
16666
+ opts.timeoutMs ?? RESIDENCY_PROBE_TIMEOUT_MS
16667
+ );
16710
16668
  try {
16711
- return await run2(controller.signal);
16669
+ const response = await doFetch(localApiUrl(baseUrl, "/api/ps"), {
16670
+ method: "GET",
16671
+ cache: "no-store",
16672
+ signal: controller.signal
16673
+ });
16674
+ if (!response.ok) return false;
16675
+ const json = await response.json();
16676
+ if (!Array.isArray(json.models)) return false;
16677
+ const running = /* @__PURE__ */ new Set();
16678
+ for (const entry of json.models) {
16679
+ if (typeof entry?.model === "string") running.add(entry.model);
16680
+ if (typeof entry?.name === "string") running.add(entry.name);
16681
+ }
16682
+ return !running.has(modelId);
16683
+ } catch {
16684
+ return false;
16712
16685
  } finally {
16713
16686
  clearTimeout(timer);
16714
16687
  }
16715
16688
  }
16716
- function readHandoff(payload) {
16717
- if (!payload || typeof payload !== "object") return null;
16718
- const row = payload;
16719
- const strings = ["turnId", "sessionId", "baseUrl", "modelId"];
16720
- for (const key of strings) {
16721
- if (typeof row[key] !== "string" || !row[key]) return null;
16722
- }
16723
- if (!LOCAL_PROVIDERS.includes(row.provider)) {
16724
- return null;
16725
- }
16726
- if (!Array.isArray(row.messages) || row.messages.length === 0) return null;
16727
- return {
16728
- turnId: row.turnId,
16729
- sessionId: row.sessionId,
16730
- provider: row.provider,
16731
- baseUrl: row.baseUrl,
16732
- modelId: row.modelId,
16733
- modelLabel: typeof row.modelLabel === "string" && row.modelLabel ? row.modelLabel : row.modelId,
16734
- deadlineMs: typeof row.deadlineMs === "number" ? row.deadlineMs : 12e4,
16735
- firstWordDeadlineMs: typeof row.firstWordDeadlineMs === "number" ? row.firstWordDeadlineMs : 25e3,
16736
- tools: Array.isArray(row.tools) ? row.tools : [],
16737
- toolGrant: typeof row.toolGrant === "string" ? row.toolGrant : null,
16738
- messages: row.messages,
16739
- citations: Array.isArray(row.citations) ? row.citations : []
16740
- };
16689
+ async function firstWordDeadlineMsFor(handoff, opts = {}) {
16690
+ const absent = await modelIsProvablyAbsent(
16691
+ handoff.baseUrl,
16692
+ handoff.provider,
16693
+ handoff.modelId,
16694
+ opts
16695
+ );
16696
+ return absent ? Math.max(handoff.firstWordDeadlineMs, LOCAL_MODEL_LOAD_DEADLINE_MS) : handoff.firstWordDeadlineMs;
16741
16697
  }
16742
- async function askForTheTurn(opts) {
16743
- let response;
16744
- try {
16745
- response = await withTimeout(
16746
- HANDOFF_TIMEOUT_MS,
16747
- (signal) => opts.doFetch(`${origin(opts.apiUrl)}${CHAT_PATH2}`, {
16748
- method: "POST",
16749
- headers: {
16750
- ...authHeaders(opts.token),
16751
- [LOCAL_CAPABLE_HEADER]: LOCAL_CAPABLE_VALUE
16752
- },
16753
- body: JSON.stringify({
16754
- messages: [
16755
- {
16756
- id: `local-${Date.now()}`,
16757
- role: "user",
16758
- parts: [{ type: "text", text: opts.question }]
16759
- }
16760
- ],
16761
- ...opts.sessionId ? { sessionId: opts.sessionId } : {},
16762
- ...opts.timezone ? { timezone: opts.timezone } : {}
16763
- }),
16764
- cache: "no-store",
16765
- signal
16766
- })
16767
- );
16768
- } catch (err) {
16769
- throw new LocalTurnFailed(
16770
- "handoff",
16771
- err instanceof Error && err.name === "AbortError" ? "Great Arrow did not answer in time." : "Could not reach Great Arrow.",
16772
- true
16773
- );
16698
+
16699
+ // ../../src/lib/chat/agentic-steps.ts
16700
+ var MAX_AGENTIC_STEPS = 6;
16701
+
16702
+ // ../../src/lib/ai/local/tool-loop.ts
16703
+ var MAX_TOOL_CALLS_PER_STEP = 4;
16704
+ var MAX_TOOL_ARGUMENT_CHARS = 8e3;
16705
+ var MAX_TOOL_RESULT_CHARS = 6e3;
16706
+ function accumulateToolCalls(current, deltas) {
16707
+ const next = current.map((call) => ({ ...call }));
16708
+ for (const delta of deltas) {
16709
+ const at = delta.position;
16710
+ if (!Number.isInteger(at) || at < 0 || at >= MAX_TOOL_CALLS_PER_STEP) {
16711
+ continue;
16712
+ }
16713
+ while (next.length <= at) next.push({ id: "", name: "", arguments: "" });
16714
+ const slot = next[at];
16715
+ if (delta.id) slot.id = delta.id;
16716
+ if (delta.name) slot.name = delta.name;
16717
+ if (delta.argumentsFragment) {
16718
+ slot.arguments = (slot.arguments + delta.argumentsFragment).slice(
16719
+ 0,
16720
+ MAX_TOOL_ARGUMENT_CHARS
16721
+ );
16722
+ }
16774
16723
  }
16775
- if (!response.ok) {
16776
- throw new LocalTurnFailed(
16777
- "handoff",
16778
- response.status === 401 || response.status === 403 ? "Sign in again \u2014 this computer is not allowed to ask for work." : `Great Arrow refused that (${response.status}).`,
16779
- true
16780
- );
16724
+ return next;
16725
+ }
16726
+ function finalizeToolCalls(calls) {
16727
+ return calls.filter((call) => call.name.length > 0).slice(0, MAX_TOOL_CALLS_PER_STEP).map((call, index) => ({
16728
+ ...call,
16729
+ id: call.id || `call_${index}`,
16730
+ arguments: call.arguments || "{}"
16731
+ }));
16732
+ }
16733
+ function parseToolArguments(raw) {
16734
+ if (raw.length > MAX_TOOL_ARGUMENT_CHARS) return null;
16735
+ let parsed;
16736
+ try {
16737
+ parsed = JSON.parse(raw.trim() || "{}");
16738
+ } catch {
16739
+ return null;
16781
16740
  }
16782
- if (response.headers.get(LOCAL_TURN_HEADER) !== "1") {
16783
- try {
16784
- await response.text();
16785
- } catch {
16786
- return null;
16787
- }
16741
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
16788
16742
  return null;
16789
16743
  }
16790
- let payload;
16744
+ return parsed;
16745
+ }
16746
+ function clampToolResult(value) {
16747
+ let text2;
16791
16748
  try {
16792
- payload = await response.json();
16749
+ text2 = typeof value === "string" ? value : JSON.stringify(value);
16793
16750
  } catch {
16794
- payload = null;
16751
+ text2 = "";
16795
16752
  }
16796
- const handoff = readHandoff(payload);
16797
- if (!handoff) {
16798
- throw new LocalTurnFailed(
16799
- "handoff",
16800
- "That work order made no sense.",
16801
- true
16802
- );
16753
+ if (!text2) return "{}";
16754
+ return text2.length > MAX_TOOL_RESULT_CHARS ? `${text2.slice(0, MAX_TOOL_RESULT_CHARS)}\u2026 (shortened)` : text2;
16755
+ }
16756
+ function assistantToolCallMessage(calls) {
16757
+ return {
16758
+ role: "assistant",
16759
+ content: "",
16760
+ toolCalls: calls.map((call) => ({
16761
+ id: call.id,
16762
+ type: "function",
16763
+ function: { name: call.name, arguments: call.arguments }
16764
+ }))
16765
+ };
16766
+ }
16767
+ function toolResultMessage(call, result) {
16768
+ return {
16769
+ role: "tool",
16770
+ content: clampToolResult(result),
16771
+ toolCallId: call.id,
16772
+ name: call.name
16773
+ };
16774
+ }
16775
+
16776
+ // ../../src/lib/ai/local/generate.ts
16777
+ var LocalRunError = class extends Error {
16778
+ constructor(message) {
16779
+ super(message);
16780
+ this.name = "LocalRunError";
16803
16781
  }
16804
- return handoff;
16782
+ };
16783
+ var CHAT_PATH = {
16784
+ ollama: "/api/chat",
16785
+ lmstudio: "/v1/chat/completions"
16786
+ };
16787
+ async function* readLines(body) {
16788
+ const reader = body.getReader();
16789
+ const decoder = new TextDecoder();
16790
+ let buffer = "";
16791
+ while (true) {
16792
+ const { done, value } = await reader.read();
16793
+ if (done) break;
16794
+ buffer += decoder.decode(value, { stream: true });
16795
+ let index = buffer.indexOf("\n");
16796
+ while (index >= 0) {
16797
+ const line = buffer.slice(0, index).trim();
16798
+ buffer = buffer.slice(index + 1);
16799
+ if (line) yield line;
16800
+ index = buffer.indexOf("\n");
16801
+ }
16802
+ }
16803
+ const tail = buffer.trim();
16804
+ if (tail) yield tail;
16805
16805
  }
16806
- async function handBack(opts) {
16806
+ function numberOrUndefined(value) {
16807
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.floor(value) : void 0;
16808
+ }
16809
+ function argumentsAsText(value) {
16810
+ if (typeof value === "string") return value;
16807
16811
  try {
16808
- const response = await withTimeout(
16809
- SETTLE_TIMEOUT_MS,
16810
- (signal) => opts.doFetch(`${origin(opts.apiUrl)}${SETTLE_PATH}`, {
16811
- method: "POST",
16812
- headers: authHeaders(opts.token),
16813
- body: JSON.stringify({
16814
- turnId: opts.handoff.turnId,
16815
- sessionId: opts.handoff.sessionId,
16816
- modelId: opts.handoff.modelId,
16817
- outcome: opts.outcome,
16818
- text: opts.text.slice(0, MAX_REPORTED_TEXT_CHARS),
16819
- ...opts.inputTokens !== void 0 ? { inputTokens: opts.inputTokens } : {},
16820
- ...opts.outputTokens !== void 0 ? { outputTokens: opts.outputTokens } : {},
16821
- latencyMs: Math.min(
16822
- Math.max(0, Math.round(opts.latencyMs)),
16823
- MAX_REPORTED_LATENCY_MS
16824
- ),
16825
- promptCharacters: opts.promptCharacters
16826
- }),
16827
- cache: "no-store",
16828
- signal
16829
- })
16830
- );
16831
- if (!response.ok) return false;
16832
- const body = await response.json();
16833
- return body?.recorded === true;
16812
+ return JSON.stringify(value ?? {});
16834
16813
  } catch {
16835
- return false;
16814
+ return "{}";
16836
16815
  }
16837
16816
  }
16838
- async function answerOnThisComputer(opts) {
16839
- const base = opts.fetchImpl ?? fetch;
16840
- const doFetch = appAwareFetch(opts.apiUrl, opts.token, base);
16841
- const handoff = await askForTheTurn({
16842
- apiUrl: opts.apiUrl,
16843
- token: opts.token,
16844
- question: opts.question,
16845
- sessionId: opts.sessionId ?? null,
16846
- timezone: opts.timezone,
16847
- doFetch: base
16817
+ function readOllamaToolCalls(message) {
16818
+ const raw = message?.tool_calls;
16819
+ if (!Array.isArray(raw)) return [];
16820
+ const out = [];
16821
+ raw.forEach((entry, position) => {
16822
+ if (!entry || typeof entry !== "object") return;
16823
+ const fn = entry.function;
16824
+ if (typeof fn?.name !== "string") return;
16825
+ out.push({
16826
+ position,
16827
+ name: fn.name,
16828
+ argumentsFragment: argumentsAsText(fn.arguments)
16829
+ });
16848
16830
  });
16849
- if (!handoff) {
16850
- return { answeredHere: false, reason: "answered_by_great_arrow" };
16851
- }
16852
- const ceiling = Math.min(
16853
- handoff.deadlineMs,
16854
- opts.deadlineMs ?? handoff.deadlineMs
16855
- );
16856
- const controller = new AbortController();
16857
- const startedAt = Date.now();
16858
- let words = "";
16859
- let sawFirstWord = false;
16860
- const firstWord = setTimeout(
16861
- () => {
16862
- if (!sawFirstWord) controller.abort();
16863
- },
16864
- Math.min(handoff.firstWordDeadlineMs, ceiling)
16865
- );
16866
- const whole = setTimeout(() => controller.abort(), ceiling);
16831
+ return out;
16832
+ }
16833
+ function readOllamaLine(line) {
16834
+ let parsed;
16867
16835
  try {
16868
- const result = await runLocalTurn({
16869
- handoff,
16870
- signal: controller.signal,
16871
- onDelta: (delta) => {
16872
- sawFirstWord = true;
16873
- words += delta;
16874
- opts.onWords?.(delta);
16875
- },
16876
- ...opts.onApp ? { onToolStep: opts.onApp } : {},
16877
- fetchImpl: doFetch
16878
- });
16879
- const recorded = await handBack({
16880
- apiUrl: opts.apiUrl,
16881
- token: opts.token,
16882
- handoff,
16883
- outcome: "finished",
16884
- text: result.text,
16885
- inputTokens: result.inputTokens,
16886
- outputTokens: result.outputTokens,
16887
- promptCharacters: result.promptCharacters,
16888
- latencyMs: Date.now() - startedAt,
16889
- doFetch: base
16890
- });
16891
- return {
16892
- answeredHere: true,
16893
- text: result.text,
16894
- modelLabel: handoff.modelLabel,
16895
- appsUsed: result.toolCallCount,
16896
- recorded
16897
- };
16836
+ parsed = JSON.parse(line);
16898
16837
  } catch {
16899
- const closed = await handBack({
16900
- apiUrl: opts.apiUrl,
16901
- token: opts.token,
16902
- handoff,
16903
- outcome: "stopped",
16904
- text: words,
16905
- inputTokens: void 0,
16906
- outputTokens: void 0,
16907
- promptCharacters: 0,
16908
- latencyMs: Date.now() - startedAt,
16909
- doFetch: base
16910
- });
16911
- throw new LocalTurnFailed(
16912
- "writing",
16913
- controller.signal.aborted ? `${handoff.modelLabel} took too long, so we stopped waiting. Ask again and Great Arrow will answer it.` : `${handoff.modelLabel} could not finish that. Check ${handoff.baseUrl} is still running.`,
16914
- closed
16915
- );
16916
- } finally {
16917
- clearTimeout(firstWord);
16918
- clearTimeout(whole);
16919
- }
16920
- }
16921
-
16922
- // ../../src/lib/ai/local/catalog.ts
16923
- var EMBEDDING_ONLY_PATTERNS = [
16924
- /nomic-embed/i,
16925
- /(?:^|[^a-z0-9])bge-/i,
16926
- /all-minilm/i,
16927
- /mxbai-embed/i,
16928
- /text-embedding/i
16929
- ];
16930
- function isEmbeddingOnlyModelId(id) {
16931
- return EMBEDDING_ONLY_PATTERNS.some((pattern) => pattern.test(id));
16932
- }
16933
- function positiveInt(value) {
16934
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(Math.floor(value), 1e7) : 0;
16935
- }
16936
- function firstString(...candidates) {
16937
- for (const candidate of candidates) {
16938
- if (typeof candidate === "string" && candidate.length > 0) return candidate;
16838
+ return null;
16939
16839
  }
16940
- return void 0;
16840
+ if (!parsed || typeof parsed !== "object") return null;
16841
+ const row = parsed;
16842
+ if (typeof row.error === "string") throw new LocalRunError(row.error);
16843
+ const message = row.message;
16844
+ const delta = typeof message?.content === "string" ? message.content : "";
16845
+ return {
16846
+ delta,
16847
+ toolCalls: readOllamaToolCalls(message),
16848
+ input: numberOrUndefined(row.prompt_eval_count),
16849
+ output: numberOrUndefined(row.eval_count)
16850
+ };
16941
16851
  }
16942
- function collect(entries, read) {
16943
- if (!Array.isArray(entries)) return [];
16852
+ function readOpenAiToolCalls(deltaObj) {
16853
+ const raw = deltaObj?.tool_calls;
16854
+ if (!Array.isArray(raw)) return [];
16944
16855
  const out = [];
16945
- const seen = /* @__PURE__ */ new Set();
16946
- for (const entry of entries) {
16947
- if (out.length >= MAX_LOCAL_MODELS) break;
16948
- if (!entry || typeof entry !== "object") continue;
16949
- const { id, label, contextLength } = read(entry);
16950
- if (!isValidLocalModelId(id)) continue;
16951
- if (seen.has(id)) continue;
16952
- if (isEmbeddingOnlyModelId(id)) continue;
16953
- seen.add(id);
16856
+ raw.forEach((entry, fallbackPosition) => {
16857
+ if (!entry || typeof entry !== "object") return;
16858
+ const row = entry;
16859
+ const fn = row.function;
16954
16860
  out.push({
16955
- id,
16956
- label: typeof label === "string" && label.length > 0 ? label : id,
16957
- // Never assumed. A model is only marked tool-capable once the provider
16958
- // says so (see normalizeShowResponse) — a model that silently ignores
16959
- // tool calls is worse than one that honestly offers chat only.
16960
- toolCapable: false,
16961
- contextLength: positiveInt(contextLength)
16861
+ position: typeof row.index === "number" ? row.index : fallbackPosition,
16862
+ id: typeof row.id === "string" ? row.id : void 0,
16863
+ name: typeof fn?.name === "string" ? fn.name : void 0,
16864
+ argumentsFragment: typeof fn?.arguments === "string" ? fn.arguments : void 0
16962
16865
  });
16963
- }
16866
+ });
16964
16867
  return out;
16965
16868
  }
16966
- function normalizeOllamaTags(json) {
16967
- if (!json || typeof json !== "object") return [];
16968
- const models = json.models;
16969
- return collect(models, (entry) => ({
16970
- id: firstString(entry.model, entry.name),
16971
- label: firstString(entry.name, entry.model)
16972
- }));
16973
- }
16974
- function normalizeLmStudioModels(json) {
16975
- if (!json || typeof json !== "object") return [];
16976
- const data = json.data;
16977
- return collect(data, (entry) => ({
16978
- id: entry.id,
16979
- label: firstString(entry.id),
16980
- contextLength: positiveInt(entry.max_context_length) || positiveInt(entry.loaded_context_length) || positiveInt(entry.context_length)
16981
- }));
16982
- }
16983
- function normalizeShowResponse(json) {
16984
- if (!json || typeof json !== "object") {
16985
- return { toolCapable: false, contextLength: 0 };
16986
- }
16987
- const o = json;
16988
- let toolCapable = false;
16989
- if (Array.isArray(o.capabilities)) {
16990
- toolCapable = o.capabilities.some(
16991
- (c) => typeof c === "string" && c.toLowerCase() === "tools"
16992
- );
16993
- }
16994
- if (!toolCapable) {
16995
- const template = typeof o.template === "string" ? o.template : "";
16996
- toolCapable = /\.tools\b/i.test(template);
16997
- }
16998
- return { toolCapable, contextLength: readContextLength(o.model_info) };
16999
- }
17000
- function readContextLength(modelInfo) {
17001
- if (!modelInfo || typeof modelInfo !== "object") return 0;
17002
- for (const [key, value] of Object.entries(
17003
- modelInfo
17004
- )) {
17005
- if (!key.endsWith(".context_length") && key !== "context_length") continue;
17006
- if (typeof value === "number" && Number.isFinite(value) && value > 0) {
17007
- return Math.floor(value);
17008
- }
16869
+ function readOpenAiLine(line) {
16870
+ if (!line.startsWith("data:")) return null;
16871
+ const payload = line.slice(5).trim();
16872
+ if (!payload || payload === "[DONE]") return null;
16873
+ let parsed;
16874
+ try {
16875
+ parsed = JSON.parse(payload);
16876
+ } catch {
16877
+ return null;
17009
16878
  }
17010
- return 0;
16879
+ if (!parsed || typeof parsed !== "object") return null;
16880
+ const row = parsed;
16881
+ const choices = Array.isArray(row.choices) ? row.choices : [];
16882
+ const first = choices[0];
16883
+ const deltaObj = first?.delta;
16884
+ const delta = typeof deltaObj?.content === "string" ? deltaObj.content : "";
16885
+ const usage = row.usage;
16886
+ return {
16887
+ delta,
16888
+ toolCalls: readOpenAiToolCalls(deltaObj),
16889
+ input: numberOrUndefined(usage?.prompt_tokens),
16890
+ output: numberOrUndefined(usage?.completion_tokens)
16891
+ };
17011
16892
  }
17012
-
17013
- // ../../src/lib/ai/local/discover.ts
17014
- var LIST_PATH = {
17015
- ollama: "/api/tags",
17016
- lmstudio: "/v1/models"
17017
- };
17018
- var DEFAULT_TIMEOUT_MS4 = 1e4;
17019
- var MAX_CAPABILITY_LOOKUPS = 12;
17020
- var LocalAppUnreachable = class extends Error {
17021
- baseUrl;
17022
- constructor(baseUrl, detail) {
17023
- super(detail);
17024
- this.name = "LocalAppUnreachable";
17025
- this.baseUrl = baseUrl;
16893
+ function wireMessage(message, provider) {
16894
+ if (message.role === "tool") {
16895
+ return provider === "ollama" ? {
16896
+ role: "tool",
16897
+ content: message.content,
16898
+ tool_name: message.name ?? ""
16899
+ } : {
16900
+ role: "tool",
16901
+ content: message.content,
16902
+ tool_call_id: message.toolCallId ?? ""
16903
+ };
17026
16904
  }
17027
- };
17028
- async function ask(doFetch, url, init, timeoutMs) {
17029
- const controller = new AbortController();
17030
- const timer = setTimeout(() => controller.abort(), timeoutMs);
17031
- try {
17032
- return await doFetch(url, {
17033
- ...init,
17034
- cache: "no-store",
17035
- signal: controller.signal
17036
- });
17037
- } finally {
17038
- clearTimeout(timer);
16905
+ if (message.role === "assistant" && message.toolCalls?.length) {
16906
+ return {
16907
+ role: "assistant",
16908
+ content: message.content,
16909
+ tool_calls: message.toolCalls.map(
16910
+ (call) => provider === "ollama" ? {
16911
+ function: {
16912
+ name: call.function.name,
16913
+ arguments: safeParseArguments(call.function.arguments)
16914
+ }
16915
+ } : call
16916
+ )
16917
+ };
17039
16918
  }
16919
+ return { role: message.role, content: message.content };
17040
16920
  }
17041
- async function capabilitiesOf(doFetch, baseUrl, modelId, timeoutMs) {
16921
+ function safeParseArguments(raw) {
17042
16922
  try {
17043
- const response = await ask(
17044
- doFetch,
17045
- localApiUrl(baseUrl, "/api/show"),
17046
- {
17047
- method: "POST",
17048
- headers: { "content-type": "application/json" },
17049
- body: JSON.stringify({ model: modelId })
17050
- },
17051
- timeoutMs
17052
- );
17053
- if (!response.ok) return { toolCapable: false, contextLength: 0 };
17054
- return normalizeShowResponse(await response.json());
16923
+ const parsed = JSON.parse(raw || "{}");
16924
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
17055
16925
  } catch {
17056
- return { toolCapable: false, contextLength: 0 };
16926
+ return {};
17057
16927
  }
17058
16928
  }
17059
- async function findInstalledModels(opts) {
16929
+ async function runLocalChat(opts) {
17060
16930
  if (!isValidLocalBaseUrl(opts.baseUrl)) {
17061
- throw new LocalAppUnreachable(opts.baseUrl, "That address is not usable.");
16931
+ throw new LocalRunError("unusable address");
17062
16932
  }
17063
16933
  const doFetch = opts.fetchImpl ?? fetch;
17064
- const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS4;
17065
- const url = localApiUrl(opts.baseUrl, LIST_PATH[opts.provider]);
17066
- let response;
17067
- try {
17068
- response = await ask(doFetch, url, { method: "GET" }, timeoutMs);
17069
- } catch (err) {
17070
- throw new LocalAppUnreachable(
17071
- opts.baseUrl,
17072
- err instanceof Error && err.name === "AbortError" ? "It did not answer in time." : "Nothing answered there."
17073
- );
16934
+ const url = localApiUrl(opts.baseUrl, CHAT_PATH[opts.provider]);
16935
+ const response = await doFetch(url, {
16936
+ method: "POST",
16937
+ headers: { "content-type": "application/json" },
16938
+ body: JSON.stringify({
16939
+ model: opts.modelId,
16940
+ messages: opts.messages.map(
16941
+ (message) => wireMessage(message, opts.provider)
16942
+ ),
16943
+ ...opts.tools?.length ? { tools: opts.tools } : {},
16944
+ stream: true
16945
+ }),
16946
+ cache: "no-store",
16947
+ signal: opts.signal
16948
+ });
16949
+ if (!response.ok || !response.body) {
16950
+ throw new LocalRunError(`refused with ${response.status}`);
17074
16951
  }
17075
- if (!response.ok) {
17076
- throw new LocalAppUnreachable(
17077
- opts.baseUrl,
17078
- `It answered with ${response.status}.`
17079
- );
16952
+ const readLine = opts.provider === "ollama" ? readOllamaLine : readOpenAiLine;
16953
+ let text2 = "";
16954
+ let toolCalls = [];
16955
+ let inputTokens;
16956
+ let outputTokens;
16957
+ for await (const line of readLines(response.body)) {
16958
+ const piece = readLine(line);
16959
+ if (!piece) continue;
16960
+ if (piece.input !== void 0) inputTokens = piece.input;
16961
+ if (piece.output !== void 0) outputTokens = piece.output;
16962
+ if (piece.toolCalls?.length) {
16963
+ toolCalls = accumulateToolCalls(toolCalls, piece.toolCalls);
16964
+ }
16965
+ if (piece.delta) {
16966
+ text2 += piece.delta;
16967
+ opts.onDelta(piece.delta);
16968
+ }
17080
16969
  }
17081
- const json = await response.json().catch(() => null);
17082
- const models = opts.provider === "ollama" ? normalizeOllamaTags(json) : normalizeLmStudioModels(json);
17083
- if (opts.provider !== "ollama") return models;
17084
- const looked = models.slice(0, MAX_CAPABILITY_LOOKUPS);
17085
- const details = await Promise.all(
17086
- looked.map(
17087
- (model) => capabilitiesOf(doFetch, opts.baseUrl, model.id, timeoutMs)
17088
- )
17089
- );
17090
- return models.map((model, index) => {
17091
- const detail = details[index];
17092
- if (!detail) return model;
16970
+ const asked = finalizeToolCalls(toolCalls);
16971
+ if (!text2 && asked.length === 0)
16972
+ throw new LocalRunError("no answer produced");
16973
+ return { text: text2, toolCalls: asked, inputTokens, outputTokens };
16974
+ }
16975
+
16976
+ // ../../src/lib/ai/local/run-turn.ts
16977
+ var TOOL_EXEC_PATH = "/api/chat/tool-exec";
16978
+ var MAX_REPORTED_PROMPT_CHARS = 4e6;
16979
+ function charactersIn(messages) {
16980
+ return messages.reduce((total, message) => total + message.content.length, 0);
16981
+ }
16982
+ async function callApp(call, handoff, signal, doFetch) {
16983
+ const args = parseToolArguments(call.arguments);
16984
+ if (!args) {
17093
16985
  return {
17094
- ...model,
17095
- toolCapable: detail.toolCapable,
17096
- // The list call never reports a window, so only ever widen from the
17097
- // lookup — a zero means "not reported", not "no room".
17098
- contextLength: detail.contextLength || model.contextLength
16986
+ result: { error: "unreadable_request", message: "Write that as JSON." },
16987
+ exhausted: false
17099
16988
  };
16989
+ }
16990
+ const response = await doFetch(TOOL_EXEC_PATH, {
16991
+ method: "POST",
16992
+ headers: { "content-type": "application/json" },
16993
+ body: JSON.stringify({
16994
+ grant: handoff.toolGrant,
16995
+ tool: call.name,
16996
+ args,
16997
+ turnId: handoff.turnId
16998
+ }),
16999
+ cache: "no-store",
17000
+ signal
17100
17001
  });
17101
- }
17102
-
17103
- // src/commands/local.ts
17104
- var CHECK_TIMEOUT_MS = 3e4;
17105
- function readProvider(raw) {
17106
- const value = typeof raw === "string" ? raw : "ollama";
17107
- if (!LOCAL_PROVIDERS.includes(value)) {
17108
- throw validationError(
17109
- `Unknown app "${value}".`,
17110
- `Use one of: ${LOCAL_PROVIDERS.join(", ")}.`
17111
- );
17002
+ const payload = await response.json().catch(() => null);
17003
+ if (!response.ok || !payload) {
17004
+ return {
17005
+ result: {
17006
+ error: payload?.error ?? "unavailable",
17007
+ message: payload?.message ?? "That did not work."
17008
+ },
17009
+ exhausted: payload?.error === "step_budget_exhausted"
17010
+ };
17112
17011
  }
17113
- return value;
17012
+ return { result: payload.result, exhausted: false };
17114
17013
  }
17115
- function checkCommand() {
17116
- return new Command("check").description("Find the models installed on this computer").option("--app <name>", "ollama or lmstudio", "ollama").option("--url <address>", "Where that app is listening").option("--use <model>", "Make this the model that answers you").action(async (options, command) => {
17117
- const g = globalOutputOpts(command);
17118
- const provider = readProvider(options.app);
17119
- const baseUrl = typeof options.url === "string" && options.url ? options.url : LOCAL_PROVIDER_PRESETS[provider].baseUrl;
17120
- const auth = await resolveAuth();
17121
- const client = new GadClient({ token: auth.token, apiUrl: auth.apiUrl });
17122
- const fmt = createFormatter({
17123
- json: g.json,
17124
- quiet: g.quiet,
17125
- isTTY: isTTY(),
17126
- noColor: g.noColor
17014
+ async function runLocalTurn(opts) {
17015
+ const doFetch = opts.fetchImpl ?? fetch;
17016
+ const { handoff } = opts;
17017
+ const messages = [...handoff.messages];
17018
+ const offered = handoff.tools ?? [];
17019
+ let text2 = "";
17020
+ let inputTokens;
17021
+ let outputTokens;
17022
+ let promptCharacters = 0;
17023
+ let toolCallCount = 0;
17024
+ let toolsStillOffered = offered.length > 0 && !!handoff.toolGrant;
17025
+ for (let pass = 0; pass <= MAX_AGENTIC_STEPS; pass++) {
17026
+ promptCharacters += charactersIn(messages);
17027
+ const result = await runLocalChat({
17028
+ baseUrl: handoff.baseUrl,
17029
+ provider: handoff.provider,
17030
+ modelId: handoff.modelId,
17031
+ messages,
17032
+ ...toolsStillOffered ? { tools: offered } : {},
17033
+ signal: opts.signal,
17034
+ onDelta: opts.onDelta,
17035
+ fetchImpl: doFetch
17127
17036
  });
17128
- let models;
17129
- try {
17130
- models = await findInstalledModels({ baseUrl, provider });
17131
- } catch (err) {
17132
- if (err instanceof LocalAppUnreachable) {
17133
- throw new CliError(
17134
- `Could not reach ${LOCAL_PROVIDER_PRESETS[provider].label} at ${err.baseUrl}. ${err.message}`,
17135
- 2 /* NETWORK_ERROR */,
17136
- `Start it on this computer and try again, or point somewhere else with --url.`
17137
- );
17138
- }
17139
- throw err;
17140
- }
17141
- const saved = await client.mcpCall(
17142
- "model_local_set",
17143
- {
17144
- enabled: true,
17145
- provider,
17146
- base_url: baseUrl,
17147
- models: models.map((model) => ({
17148
- id: model.id,
17149
- label: model.label,
17150
- tool_capable: model.toolCapable,
17151
- context_length: model.contextLength
17152
- })),
17153
- ...typeof options.use === "string" && options.use ? { default_model_id: options.use } : {}
17154
- },
17155
- CHECK_TIMEOUT_MS
17156
- );
17157
- if (g.json) {
17158
- process.stdout.write(JSON.stringify({ models, saved }) + "\n");
17159
- return;
17160
- }
17161
- if (models.length === 0) {
17162
- fmt.warn(
17163
- `${LOCAL_PROVIDER_PRESETS[provider].label} is running but has no models yet. Install one, then run this again.`
17164
- );
17165
- return;
17166
- }
17167
- const chosen = saved.preferences?.defaultModelId ?? null;
17168
- process.stdout.write(
17169
- `Found ${models.length} ${models.length === 1 ? "model" : "models"} on this computer:
17170
- `
17171
- );
17172
- for (const model of models) {
17173
- const mark = model.id === chosen ? "*" : " ";
17174
- const limits = model.toolCapable ? "can look things up" : "answers from your library only";
17175
- process.stdout.write(`${mark} ${model.label} \u2014 ${limits}
17176
- `);
17177
- }
17178
- if (chosen) {
17179
- process.stdout.write(`
17180
- Answering with ${chosen}.
17181
- `);
17182
- } else {
17183
- process.stdout.write(
17184
- `
17185
- Pick one with: gad local check --use <model>
17186
- `
17187
- );
17037
+ if (result.inputTokens !== void 0) inputTokens = result.inputTokens;
17038
+ if (result.outputTokens !== void 0) outputTokens = result.outputTokens;
17039
+ text2 += result.text;
17040
+ if (!toolsStillOffered || result.toolCalls.length === 0) break;
17041
+ messages.push(assistantToolCallMessage(result.toolCalls));
17042
+ for (const call of result.toolCalls) {
17043
+ toolCallCount += 1;
17044
+ opts.onToolStep?.(call.name);
17045
+ const answer = await callApp(call, handoff, opts.signal, doFetch);
17046
+ messages.push(toolResultMessage(call, answer.result));
17047
+ if (answer.exhausted) toolsStillOffered = false;
17188
17048
  }
17189
- });
17049
+ if (pass === MAX_AGENTIC_STEPS - 1) toolsStillOffered = false;
17050
+ }
17051
+ return {
17052
+ text: text2,
17053
+ inputTokens,
17054
+ outputTokens,
17055
+ // The settle route refuses a report with an implausible figure in it, and
17056
+ // refusing the report would lose the whole turn. Keep it inside what that
17057
+ // route accepts; a clipped ceiling only ever counts fewer words, never more.
17058
+ promptCharacters: Math.min(promptCharacters, MAX_REPORTED_PROMPT_CHARS),
17059
+ toolCallCount
17060
+ };
17190
17061
  }
17191
- function askHereCommand() {
17192
- return new Command("ask").description("Answer a question with a model on this computer").argument("<question>", "What you want to know").option("--session <id>", "Continue an existing conversation").action(async (question, options, command) => {
17193
- const g = globalOutputOpts(command);
17194
- const auth = await resolveAuth();
17195
- const fmt = createFormatter({
17196
- json: g.json,
17197
- quiet: g.quiet,
17198
- isTTY: isTTY(),
17199
- noColor: g.noColor
17200
- });
17201
- let report;
17202
- try {
17203
- report = await answerOnThisComputer({
17204
- apiUrl: auth.apiUrl,
17205
- token: auth.token,
17206
- question,
17207
- sessionId: typeof options.session === "string" ? options.session : null,
17208
- timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
17209
- ...g.json ? {} : { onWords: (delta) => process.stdout.write(delta) }
17210
- });
17211
- } catch (err) {
17212
- if (err instanceof LocalTurnFailed) {
17213
- throw new CliError(
17214
- err.message,
17215
- 2 /* NETWORK_ERROR */,
17216
- err.closed ? void 0 : "Your conversation may show this one as unfinished."
17217
- );
17062
+
17063
+ // ../../src/lib/ai/local/client.ts
17064
+ var CHAT_PATH2 = "/api/chat";
17065
+ var SETTLE_PATH = "/api/chat/local-turn";
17066
+ var MAX_REPORTED_TEXT_CHARS = 2e5;
17067
+ var MAX_REPORTED_LATENCY_MS = 36e5;
17068
+ var HANDOFF_TIMEOUT_MS = 6e4;
17069
+ var SETTLE_TIMEOUT_MS = 3e4;
17070
+ var LocalTurnFailed = class extends Error {
17071
+ stage;
17072
+ /** Set once the turn was handed back, so a caller knows the conversation is
17073
+ * not left with an unfinished reply in it. */
17074
+ closed;
17075
+ constructor(stage, message, closed) {
17076
+ super(message);
17077
+ this.name = "LocalTurnFailed";
17078
+ this.stage = stage;
17079
+ this.closed = closed;
17080
+ }
17081
+ };
17082
+ function authHeaders(token) {
17083
+ return {
17084
+ "content-type": "application/json",
17085
+ authorization: `Bearer ${token}`
17086
+ };
17087
+ }
17088
+ function origin(apiUrl) {
17089
+ return apiUrl.replace(/\/+$/, "");
17090
+ }
17091
+ function appAwareFetch(apiUrl, token, base) {
17092
+ return (input, init) => {
17093
+ const target = typeof input === "string" ? input : String(input);
17094
+ if (!target.startsWith("/")) return base(input, init);
17095
+ return base(`${origin(apiUrl)}${target}`, {
17096
+ ...init,
17097
+ headers: {
17098
+ ...init?.headers,
17099
+ ...authHeaders(token)
17218
17100
  }
17219
- throw err;
17220
- }
17221
- if (g.json) {
17222
- process.stdout.write(JSON.stringify(report) + "\n");
17223
- return;
17224
- }
17225
- if (!report.answeredHere) {
17226
- fmt.warn(
17227
- "Great Arrow answered this one itself \u2014 it does that for harder questions. The reply is in your conversation."
17228
- );
17229
- return;
17230
- }
17231
- process.stdout.write("\n");
17232
- if (!report.recorded) {
17233
- fmt.warn("Answered, but we could not save it to your conversation.");
17234
- }
17235
- });
17101
+ });
17102
+ };
17236
17103
  }
17237
- function localCommand() {
17238
- return new Command("local").description("Answer with a model running on this computer").addCommand(checkCommand()).addCommand(askHereCommand());
17104
+ async function withTimeout(ms, run2) {
17105
+ const controller = new AbortController();
17106
+ const timer = setTimeout(() => controller.abort(), ms);
17107
+ try {
17108
+ return await run2(controller.signal);
17109
+ } finally {
17110
+ clearTimeout(timer);
17111
+ }
17239
17112
  }
17240
-
17241
- // src/lib/hyperlink.ts
17242
- var SUPPORTED_TERM_PROGRAMS = /* @__PURE__ */ new Set([
17243
- "ghostty",
17244
- "iterm.app",
17245
- "wezterm",
17246
- "vscode",
17247
- "hyper",
17248
- "warpterminal",
17249
- "rio",
17250
- "contour",
17251
- "tabby"
17252
- ]);
17253
- var SUPPORTED_TERMS = /* @__PURE__ */ new Set([
17254
- "xterm-kitty",
17255
- "alacritty",
17256
- "foot",
17257
- "contour"
17258
- ]);
17259
- var UNSUPPORTED_TERM_PROGRAMS = /* @__PURE__ */ new Set(["apple_terminal"]);
17260
- var MIN_VTE_VERSION = 5e3;
17261
- function isTruthyFlag(value) {
17262
- if (value === void 0) return false;
17263
- const v = value.trim().toLowerCase();
17264
- return v !== "" && v !== "0" && v !== "false";
17113
+ function readHandoff(payload) {
17114
+ if (!payload || typeof payload !== "object") return null;
17115
+ const row = payload;
17116
+ const strings = ["turnId", "sessionId", "baseUrl", "modelId"];
17117
+ for (const key of strings) {
17118
+ if (typeof row[key] !== "string" || !row[key]) return null;
17119
+ }
17120
+ if (!LOCAL_PROVIDERS.includes(row.provider)) {
17121
+ return null;
17122
+ }
17123
+ if (!Array.isArray(row.messages) || row.messages.length === 0) return null;
17124
+ return {
17125
+ turnId: row.turnId,
17126
+ sessionId: row.sessionId,
17127
+ provider: row.provider,
17128
+ baseUrl: row.baseUrl,
17129
+ modelId: row.modelId,
17130
+ modelLabel: typeof row.modelLabel === "string" && row.modelLabel ? row.modelLabel : row.modelId,
17131
+ deadlineMs: typeof row.deadlineMs === "number" ? row.deadlineMs : 12e4,
17132
+ firstWordDeadlineMs: typeof row.firstWordDeadlineMs === "number" ? row.firstWordDeadlineMs : 25e3,
17133
+ tools: Array.isArray(row.tools) ? row.tools : [],
17134
+ toolGrant: typeof row.toolGrant === "string" ? row.toolGrant : null,
17135
+ messages: row.messages,
17136
+ citations: Array.isArray(row.citations) ? row.citations : []
17137
+ };
17265
17138
  }
17266
- function supportsHyperlinks(env4, isTTY2) {
17267
- if (isTruthyFlag(env4.FORCE_HYPERLINK)) return true;
17268
- if (env4.NO_COLOR !== void 0 && env4.NO_COLOR !== "") return false;
17269
- if (!isTTY2) return false;
17270
- if (isTruthyFlag(env4.CI)) return false;
17271
- const term = (env4.TERM ?? "").trim().toLowerCase();
17272
- if (term === "" || term === "dumb") return false;
17273
- if (term.startsWith("screen") || term.startsWith("tmux")) return false;
17274
- const program3 = (env4.TERM_PROGRAM ?? "").trim().toLowerCase();
17275
- if (UNSUPPORTED_TERM_PROGRAMS.has(program3)) return false;
17276
- if (SUPPORTED_TERM_PROGRAMS.has(program3)) return true;
17277
- if (SUPPORTED_TERMS.has(term)) return true;
17278
- if (isTruthyFlag(env4.WT_SESSION)) return true;
17279
- if (isTruthyFlag(env4.KONSOLE_VERSION)) return true;
17280
- if (env4.TERMINAL_EMULATOR === "JetBrains-JediTerm") return true;
17281
- const vte = Number.parseInt(env4.VTE_VERSION ?? "", 10);
17282
- if (Number.isFinite(vte) && vte >= MIN_VTE_VERSION) return true;
17283
- return false;
17139
+ async function askForTheTurn(opts) {
17140
+ let response;
17141
+ try {
17142
+ response = await withTimeout(
17143
+ HANDOFF_TIMEOUT_MS,
17144
+ (signal) => opts.doFetch(`${origin(opts.apiUrl)}${CHAT_PATH2}`, {
17145
+ method: "POST",
17146
+ headers: {
17147
+ ...authHeaders(opts.token),
17148
+ [LOCAL_CAPABLE_HEADER]: LOCAL_CAPABLE_VALUE
17149
+ },
17150
+ body: JSON.stringify({
17151
+ messages: [
17152
+ {
17153
+ id: `local-${Date.now()}`,
17154
+ role: "user",
17155
+ parts: [{ type: "text", text: opts.question }]
17156
+ }
17157
+ ],
17158
+ ...opts.sessionId ? { sessionId: opts.sessionId } : {},
17159
+ ...opts.timezone ? { timezone: opts.timezone } : {}
17160
+ }),
17161
+ cache: "no-store",
17162
+ signal
17163
+ })
17164
+ );
17165
+ } catch (err) {
17166
+ throw new LocalTurnFailed(
17167
+ "handoff",
17168
+ err instanceof Error && err.name === "AbortError" ? "Great Arrow did not answer in time." : "Could not reach Great Arrow.",
17169
+ true
17170
+ );
17171
+ }
17172
+ if (!response.ok) {
17173
+ throw new LocalTurnFailed(
17174
+ "handoff",
17175
+ response.status === 401 || response.status === 403 ? "Sign in again \u2014 this computer is not allowed to ask for work." : `Great Arrow refused that (${response.status}).`,
17176
+ true
17177
+ );
17178
+ }
17179
+ if (response.headers.get(LOCAL_TURN_HEADER) !== "1") {
17180
+ try {
17181
+ await response.text();
17182
+ } catch {
17183
+ return null;
17184
+ }
17185
+ return null;
17186
+ }
17187
+ let payload;
17188
+ try {
17189
+ payload = await response.json();
17190
+ } catch {
17191
+ payload = null;
17192
+ }
17193
+ const handoff = readHandoff(payload);
17194
+ if (!handoff) {
17195
+ throw new LocalTurnFailed(
17196
+ "handoff",
17197
+ "That work order made no sense.",
17198
+ true
17199
+ );
17200
+ }
17201
+ return handoff;
17284
17202
  }
17285
- var OSC = "\x1B]8;;";
17286
- var ST = "\x1B\\";
17287
- function hyperlink(text2, url, opts) {
17288
- if (!opts.enabled) return text2 === url ? url : `${text2} (${url})`;
17289
- return `${OSC}${url}${ST}${text2}${OSC}${ST}`;
17203
+ async function handBack(opts) {
17204
+ try {
17205
+ const response = await withTimeout(
17206
+ SETTLE_TIMEOUT_MS,
17207
+ (signal) => opts.doFetch(`${origin(opts.apiUrl)}${SETTLE_PATH}`, {
17208
+ method: "POST",
17209
+ headers: authHeaders(opts.token),
17210
+ body: JSON.stringify({
17211
+ turnId: opts.handoff.turnId,
17212
+ sessionId: opts.handoff.sessionId,
17213
+ modelId: opts.handoff.modelId,
17214
+ outcome: opts.outcome,
17215
+ text: opts.text.slice(0, MAX_REPORTED_TEXT_CHARS),
17216
+ ...opts.inputTokens !== void 0 ? { inputTokens: opts.inputTokens } : {},
17217
+ ...opts.outputTokens !== void 0 ? { outputTokens: opts.outputTokens } : {},
17218
+ latencyMs: Math.min(
17219
+ Math.max(0, Math.round(opts.latencyMs)),
17220
+ MAX_REPORTED_LATENCY_MS
17221
+ ),
17222
+ promptCharacters: opts.promptCharacters
17223
+ }),
17224
+ cache: "no-store",
17225
+ signal
17226
+ })
17227
+ );
17228
+ if (!response.ok) return false;
17229
+ const body = await response.json();
17230
+ return body?.recorded === true;
17231
+ } catch {
17232
+ return false;
17233
+ }
17290
17234
  }
17291
-
17292
- // src/lib/glance-footer.ts
17293
- import { readFile as readFile4, writeFile as writeFile4, mkdir as mkdir4 } from "node:fs/promises";
17294
- import { homedir as homedir4 } from "node:os";
17295
- import { join as join6, dirname as dirname5 } from "node:path";
17296
-
17297
- // src/lib/seen.ts
17298
- var SEEN_TIMEOUT_MS = 1e3;
17299
- var MAX_KEYS = 50;
17300
- async function reportSeen(opts) {
17301
- const keys = [
17302
- ...new Set(
17303
- opts.keys.filter((k) => typeof k === "string" && k !== "")
17304
- )
17305
- ].slice(0, MAX_KEYS);
17306
- if (keys.length === 0) return 0;
17235
+ async function answerOnThisComputer(opts) {
17236
+ const base = opts.fetchImpl ?? fetch;
17237
+ const doFetch = appAwareFetch(opts.apiUrl, opts.token, base);
17238
+ const handoff = await askForTheTurn({
17239
+ apiUrl: opts.apiUrl,
17240
+ token: opts.token,
17241
+ question: opts.question,
17242
+ sessionId: opts.sessionId ?? null,
17243
+ timezone: opts.timezone,
17244
+ doFetch: base
17245
+ });
17246
+ if (!handoff) {
17247
+ return { answeredHere: false, reason: "answered_by_great_arrow" };
17248
+ }
17249
+ const ceiling = Math.min(
17250
+ handoff.deadlineMs,
17251
+ opts.deadlineMs ?? handoff.deadlineMs
17252
+ );
17307
17253
  const controller = new AbortController();
17308
- const timer = setTimeout(() => controller.abort(), SEEN_TIMEOUT_MS);
17254
+ const startedAt = Date.now();
17255
+ let words = "";
17256
+ let sawFirstWord = false;
17257
+ const firstWord = setTimeout(
17258
+ () => {
17259
+ if (!sawFirstWord) controller.abort();
17260
+ },
17261
+ Math.min(await firstWordDeadlineMsFor(handoff), ceiling)
17262
+ );
17263
+ const whole = setTimeout(() => controller.abort(), ceiling);
17309
17264
  try {
17310
- const response = await fetch(
17311
- `${opts.apiUrl.replace(/\/$/, "")}/api/attention/seen`,
17312
- {
17313
- method: "POST",
17314
- headers: {
17315
- "Content-Type": "application/json",
17316
- Authorization: `Bearer ${opts.token}`
17317
- },
17318
- body: JSON.stringify({ keys }),
17319
- signal: controller.signal
17320
- }
17321
- );
17322
- if (!response.ok) return 0;
17323
- const data = await response.json().catch(() => null);
17324
- return typeof data?.seen === "number" ? data.seen : 0;
17265
+ const result = await runLocalTurn({
17266
+ handoff,
17267
+ signal: controller.signal,
17268
+ onDelta: (delta) => {
17269
+ sawFirstWord = true;
17270
+ words += delta;
17271
+ opts.onWords?.(delta);
17272
+ },
17273
+ ...opts.onApp ? { onToolStep: opts.onApp } : {},
17274
+ fetchImpl: doFetch
17275
+ });
17276
+ const recorded = await handBack({
17277
+ apiUrl: opts.apiUrl,
17278
+ token: opts.token,
17279
+ handoff,
17280
+ outcome: "finished",
17281
+ text: result.text,
17282
+ inputTokens: result.inputTokens,
17283
+ outputTokens: result.outputTokens,
17284
+ promptCharacters: result.promptCharacters,
17285
+ latencyMs: Date.now() - startedAt,
17286
+ doFetch: base
17287
+ });
17288
+ return {
17289
+ answeredHere: true,
17290
+ text: result.text,
17291
+ modelLabel: handoff.modelLabel,
17292
+ appsUsed: result.toolCallCount,
17293
+ recorded
17294
+ };
17325
17295
  } catch {
17326
- return 0;
17296
+ const closed = await handBack({
17297
+ apiUrl: opts.apiUrl,
17298
+ token: opts.token,
17299
+ handoff,
17300
+ outcome: "stopped",
17301
+ text: words,
17302
+ inputTokens: void 0,
17303
+ outputTokens: void 0,
17304
+ promptCharacters: 0,
17305
+ latencyMs: Date.now() - startedAt,
17306
+ doFetch: base
17307
+ });
17308
+ throw new LocalTurnFailed(
17309
+ "writing",
17310
+ controller.signal.aborted ? `${handoff.modelLabel} took too long, so we stopped waiting. Ask again and Great Arrow will answer it. If this was the first question since you started ${handoff.provider === "ollama" ? "Ollama" : "LM Studio"}, the model was probably still loading \u2014 it is quicker once it has.` : `${handoff.modelLabel} could not finish that. Check ${handoff.baseUrl} is still running.`,
17311
+ closed
17312
+ );
17327
17313
  } finally {
17328
- clearTimeout(timer);
17314
+ clearTimeout(firstWord);
17315
+ clearTimeout(whole);
17329
17316
  }
17330
17317
  }
17331
17318
 
17332
- // src/lib/glance-footer.ts
17333
- var FETCH_TIMEOUT_MS = 1500;
17334
- var THROTTLE_INTERVAL_MS = 4 * 60 * 60 * 1e3;
17335
- var URGENT_THRESHOLD = 15;
17336
- var SKIP_COMMANDS = /* @__PURE__ */ new Set(["status", "needs", "login", "logout", "help"]);
17337
- async function maybeShowGlanceFooter(argv) {
17338
- try {
17339
- if (!shouldRunGlanceFooter(argv)) return;
17340
- const auth = await resolveAuth();
17341
- const payload = await fetchGlance(auth.apiUrl, auth.token);
17342
- if (!payload) return;
17343
- if (payload.urgency === null) return;
17344
- const workspaceKey = auth.activeWorkspace ?? "default";
17345
- const signature = topSignature(payload);
17346
- const state = await loadGlanceState();
17347
- const now = Date.now();
17348
- if (!shouldShowGlance({
17349
- urgency: payload.urgency,
17350
- topItemId: signature,
17351
- state: state[workspaceKey] ?? {},
17352
- now
17353
- })) {
17354
- return;
17355
- }
17356
- const printed = renderFooter(payload, auth.apiUrl);
17357
- state[workspaceKey] = { lastShownAt: now, lastTopItemId: signature };
17358
- await saveGlanceState(state);
17359
- await reportSeen({
17360
- apiUrl: auth.apiUrl,
17361
- token: auth.token,
17362
- keys: printed
17319
+ // ../../src/lib/ai/local/catalog.ts
17320
+ var EMBEDDING_ONLY_PATTERNS = [
17321
+ /nomic-embed/i,
17322
+ /(?:^|[^a-z0-9])bge-/i,
17323
+ /all-minilm/i,
17324
+ /mxbai-embed/i,
17325
+ /text-embedding/i
17326
+ ];
17327
+ function isEmbeddingOnlyModelId(id) {
17328
+ return EMBEDDING_ONLY_PATTERNS.some((pattern) => pattern.test(id));
17329
+ }
17330
+ function positiveInt(value) {
17331
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.min(Math.floor(value), 1e7) : 0;
17332
+ }
17333
+ function firstString(...candidates) {
17334
+ for (const candidate of candidates) {
17335
+ if (typeof candidate === "string" && candidate.length > 0) return candidate;
17336
+ }
17337
+ return void 0;
17338
+ }
17339
+ function collect(entries, read) {
17340
+ if (!Array.isArray(entries)) return [];
17341
+ const out = [];
17342
+ const seen = /* @__PURE__ */ new Set();
17343
+ for (const entry of entries) {
17344
+ if (out.length >= MAX_LOCAL_MODELS) break;
17345
+ if (!entry || typeof entry !== "object") continue;
17346
+ const { id, label, contextLength } = read(entry);
17347
+ if (!isValidLocalModelId(id)) continue;
17348
+ if (seen.has(id)) continue;
17349
+ if (isEmbeddingOnlyModelId(id)) continue;
17350
+ seen.add(id);
17351
+ out.push({
17352
+ id,
17353
+ label: typeof label === "string" && label.length > 0 ? label : id,
17354
+ // Never assumed. A model is only marked tool-capable once the provider
17355
+ // says so (see normalizeShowResponse) — a model that silently ignores
17356
+ // tool calls is worse than one that honestly offers chat only.
17357
+ toolCapable: false,
17358
+ contextLength: positiveInt(contextLength)
17363
17359
  });
17364
- } catch (err) {
17365
- debugSwallow("glance-footer", err);
17366
17360
  }
17361
+ return out;
17367
17362
  }
17368
- function shouldRunGlanceFooter(argv) {
17369
- if (!process.stderr.isTTY) return false;
17370
- if (process.env.CI) return false;
17371
- if (process.env.GAD_NO_GLANCE) return false;
17372
- if (argv.includes("--json")) return false;
17373
- if (argv.includes("--quiet")) return false;
17374
- if (argv.includes("--stdout")) return false;
17375
- if (argv.includes("--no-glance")) return false;
17376
- const command = firstCommand(argv);
17377
- if (!command) return false;
17378
- if (SKIP_COMMANDS.has(command)) return false;
17379
- return true;
17363
+ function normalizeOllamaTags(json) {
17364
+ if (!json || typeof json !== "object") return [];
17365
+ const models = json.models;
17366
+ return collect(models, (entry) => ({
17367
+ id: firstString(entry.model, entry.name),
17368
+ label: firstString(entry.name, entry.model)
17369
+ }));
17380
17370
  }
17381
- function firstCommand(argv) {
17382
- for (const token of argv.slice(2)) {
17383
- if (!token.startsWith("-")) return token;
17371
+ function normalizeLmStudioModels(json) {
17372
+ if (!json || typeof json !== "object") return [];
17373
+ const data = json.data;
17374
+ return collect(data, (entry) => ({
17375
+ id: entry.id,
17376
+ label: firstString(entry.id),
17377
+ contextLength: positiveInt(entry.max_context_length) || positiveInt(entry.loaded_context_length) || positiveInt(entry.context_length)
17378
+ }));
17379
+ }
17380
+ function normalizeShowResponse(json) {
17381
+ if (!json || typeof json !== "object") {
17382
+ return { toolCapable: false, contextLength: 0 };
17383
+ }
17384
+ const o = json;
17385
+ let toolCapable = false;
17386
+ if (Array.isArray(o.capabilities)) {
17387
+ toolCapable = o.capabilities.some(
17388
+ (c) => typeof c === "string" && c.toLowerCase() === "tools"
17389
+ );
17390
+ }
17391
+ if (!toolCapable) {
17392
+ const template = typeof o.template === "string" ? o.template : "";
17393
+ toolCapable = /\.tools\b/i.test(template);
17394
+ }
17395
+ return { toolCapable, contextLength: readContextLength(o.model_info) };
17396
+ }
17397
+ function readContextLength(modelInfo) {
17398
+ if (!modelInfo || typeof modelInfo !== "object") return 0;
17399
+ for (const [key, value] of Object.entries(
17400
+ modelInfo
17401
+ )) {
17402
+ if (!key.endsWith(".context_length") && key !== "context_length") continue;
17403
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
17404
+ return Math.floor(value);
17405
+ }
17406
+ }
17407
+ return 0;
17408
+ }
17409
+
17410
+ // ../../src/lib/ai/local/discover.ts
17411
+ var LIST_PATH = {
17412
+ ollama: "/api/tags",
17413
+ lmstudio: "/v1/models"
17414
+ };
17415
+ var DEFAULT_TIMEOUT_MS4 = 1e4;
17416
+ var MAX_CAPABILITY_LOOKUPS = 12;
17417
+ var LocalAppUnreachable = class extends Error {
17418
+ baseUrl;
17419
+ constructor(baseUrl, detail) {
17420
+ super(detail);
17421
+ this.name = "LocalAppUnreachable";
17422
+ this.baseUrl = baseUrl;
17384
17423
  }
17385
- return null;
17386
- }
17387
- async function fetchGlance(apiUrl, token) {
17424
+ };
17425
+ async function ask(doFetch, url, init, timeoutMs) {
17388
17426
  const controller = new AbortController();
17389
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
17427
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
17390
17428
  try {
17391
- const response = await fetch(`${apiUrl}/api/mcp`, {
17392
- method: "POST",
17393
- headers: {
17394
- "Content-Type": "application/json",
17395
- Authorization: `Bearer ${token}`
17396
- },
17397
- body: JSON.stringify({
17398
- jsonrpc: "2.0",
17399
- id: `cli-glance-${Date.now()}`,
17400
- method: "tools/call",
17401
- params: { name: "glance", arguments: {} }
17402
- }),
17429
+ return await doFetch(url, {
17430
+ ...init,
17431
+ cache: "no-store",
17403
17432
  signal: controller.signal
17404
17433
  });
17405
- if (!response.ok) return null;
17406
- const data = await response.json();
17407
- if (data.error) return null;
17408
- return normalizeGlance(
17409
- parseMcpPayload(data.result?.content ?? data.result)
17410
- );
17411
- } catch {
17412
- return null;
17413
17434
  } finally {
17414
17435
  clearTimeout(timer);
17415
17436
  }
17416
17437
  }
17417
- function normalizeGlance(raw) {
17418
- if (typeof raw !== "object" || raw === null) return null;
17419
- const obj = raw;
17420
- const needsYou = asArray2(obj.needsYou).flatMap((item) => {
17421
- if (typeof item !== "object" || item === null) return [];
17422
- const it = item;
17423
- if (typeof it.title !== "string") return [];
17424
- return [
17425
- {
17426
- kind: typeof it.kind === "string" ? it.kind : "nudge",
17427
- title: it.title,
17428
- action: typeof it.action === "string" ? it.action : null,
17429
- href: typeof it.href === "string" && it.href !== "" ? it.href : null,
17430
- ...typeof it.rank === "number" ? { rank: it.rank } : {},
17431
- signalKey: typeof it.signalKey === "string" && it.signalKey !== "" ? it.signalKey : null,
17432
- workspace: typeof it.workspace === "string" && it.workspace !== "" ? it.workspace : null,
17433
- // Parsed like every other field: a non-string is dropped rather than
17434
- // coerced, so a malformed payload cannot render as a currency claim.
17435
- freshness: typeof it.freshness === "string" && it.freshness !== "" ? it.freshness : null,
17436
- meta: typeof it.meta === "string" && it.meta !== "" ? it.meta : null
17437
- }
17438
- ];
17439
- });
17440
- const atRisk = asArray2(obj.atRisk).flatMap((item) => {
17441
- if (typeof item !== "object" || item === null) return [];
17442
- const it = item;
17443
- if (typeof it.title !== "string") return [];
17444
- return [
17445
- {
17446
- classification: typeof it.classification === "string" ? it.classification : null,
17447
- riskLevel: typeof it.riskLevel === "string" ? it.riskLevel : "high",
17448
- title: it.title,
17449
- branch: typeof it.branch === "string" ? it.branch : null,
17450
- aheadMain: typeof it.aheadMain === "number" ? it.aheadMain : null,
17451
- recommendedAction: typeof it.recommendedAction === "string" ? it.recommendedAction : null
17452
- }
17453
- ];
17454
- });
17455
- const integrations = asArray2(obj.integrations).flatMap((item) => {
17456
- if (typeof item !== "object" || item === null) return [];
17457
- const it = item;
17458
- if (typeof it.kind !== "string") return [];
17459
- return [
17460
- {
17461
- kind: it.kind,
17462
- staleFor: typeof it.staleFor === "string" ? it.staleFor : null,
17463
- refresh: typeof it.refresh === "string" ? it.refresh : null
17464
- }
17465
- ];
17466
- });
17467
- const agents = asArray2(obj.agents).flatMap((item) => {
17468
- if (typeof item !== "object" || item === null) return [];
17469
- const it = item;
17470
- if (typeof it.name !== "string") return [];
17471
- return [
17438
+ async function capabilitiesOf(doFetch, baseUrl, modelId, timeoutMs) {
17439
+ try {
17440
+ const response = await ask(
17441
+ doFetch,
17442
+ localApiUrl(baseUrl, "/api/show"),
17472
17443
  {
17473
- name: it.name,
17474
- tool: typeof it.tool === "string" ? it.tool : null,
17475
- card: typeof it.card === "string" ? it.card : null
17476
- }
17477
- ];
17478
- });
17479
- let topGoal = null;
17480
- if (typeof obj.topGoal === "object" && obj.topGoal !== null) {
17481
- const g = obj.topGoal;
17482
- if (typeof g.title === "string") {
17483
- topGoal = {
17484
- title: g.title,
17485
- done: typeof g.done === "number" ? g.done : 0,
17486
- total: typeof g.total === "number" ? g.total : 0,
17487
- eta: typeof g.eta === "string" ? g.eta : null
17488
- };
17489
- }
17490
- }
17491
- let warRoom = null;
17492
- if (typeof obj.warRoom === "object" && obj.warRoom !== null) {
17493
- const w = obj.warRoom;
17494
- warRoom = {
17495
- priorityCount: typeof w.priorityCount === "number" ? w.priorityCount : 0,
17496
- unreadTotal: typeof w.unreadTotal === "number" ? w.unreadTotal : 0,
17497
- openRequestCount: typeof w.openRequestCount === "number" ? w.openRequestCount : 0,
17498
- topSender: typeof w.topSender === "string" ? w.topSender : null,
17499
- newestSender: typeof w.newestSender === "string" ? w.newestSender : null,
17500
- newestPreview: typeof w.newestPreview === "string" ? w.newestPreview : null
17501
- };
17444
+ method: "POST",
17445
+ headers: { "content-type": "application/json" },
17446
+ body: JSON.stringify({ model: modelId })
17447
+ },
17448
+ timeoutMs
17449
+ );
17450
+ if (!response.ok) return { toolCapable: false, contextLength: 0 };
17451
+ return normalizeShowResponse(await response.json());
17452
+ } catch {
17453
+ return { toolCapable: false, contextLength: 0 };
17502
17454
  }
17503
- return {
17504
- workspace: typeof obj.workspace === "string" && obj.workspace !== "" ? obj.workspace : null,
17505
- // An older server sends no `reads` at all, so this normalizes to an empty
17506
- // list rather than inventing the pinned workspace as the read set — the
17507
- // CLI then renders no breadth cue, which is honest, instead of a claim it
17508
- // was never told.
17509
- reads: Array.isArray(obj.reads) ? obj.reads.flatMap((r) => {
17510
- if (typeof r !== "object" || r === null) return [];
17511
- const row = r;
17512
- return typeof row.id === "string" && typeof row.name === "string" ? [{ id: row.id, name: row.name }] : [];
17513
- }) : [],
17514
- needsYou,
17515
- atRisk,
17516
- topGoal,
17517
- integrations,
17518
- agents,
17519
- warRoom,
17520
- // Parsed like every other field: both halves must be the right type or the
17521
- // whole line is dropped, so a malformed payload cannot render as a dollar.
17522
- spend: (() => {
17523
- const raw2 = obj.spend;
17524
- if (typeof raw2 !== "object" || raw2 === null) return null;
17525
- const sp = raw2;
17526
- return typeof sp.line === "string" && sp.line !== "" && typeof sp.totalCostUsd === "number" && Number.isFinite(sp.totalCostUsd) ? { line: sp.line, totalCostUsd: sp.totalCostUsd } : null;
17527
- })(),
17528
- urgency: typeof obj.urgency === "number" ? obj.urgency : null,
17529
- generatedAt: typeof obj.generatedAt === "string" ? obj.generatedAt : (/* @__PURE__ */ new Date()).toISOString()
17530
- };
17531
17455
  }
17532
- function asArray2(value) {
17533
- return Array.isArray(value) ? value : [];
17456
+ async function findInstalledModels(opts) {
17457
+ if (!isValidLocalBaseUrl(opts.baseUrl)) {
17458
+ throw new LocalAppUnreachable(opts.baseUrl, "That address is not usable.");
17459
+ }
17460
+ const doFetch = opts.fetchImpl ?? fetch;
17461
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS4;
17462
+ const url = localApiUrl(opts.baseUrl, LIST_PATH[opts.provider]);
17463
+ let response;
17464
+ try {
17465
+ response = await ask(doFetch, url, { method: "GET" }, timeoutMs);
17466
+ } catch (err) {
17467
+ throw new LocalAppUnreachable(
17468
+ opts.baseUrl,
17469
+ err instanceof Error && err.name === "AbortError" ? "It did not answer in time." : "Nothing answered there."
17470
+ );
17471
+ }
17472
+ if (!response.ok) {
17473
+ throw new LocalAppUnreachable(
17474
+ opts.baseUrl,
17475
+ `It answered with ${response.status}.`
17476
+ );
17477
+ }
17478
+ const json = await response.json().catch(() => null);
17479
+ const models = opts.provider === "ollama" ? normalizeOllamaTags(json) : normalizeLmStudioModels(json);
17480
+ if (opts.provider !== "ollama") return models;
17481
+ const looked = models.slice(0, MAX_CAPABILITY_LOOKUPS);
17482
+ const details = await Promise.all(
17483
+ looked.map(
17484
+ (model) => capabilitiesOf(doFetch, opts.baseUrl, model.id, timeoutMs)
17485
+ )
17486
+ );
17487
+ return models.map((model, index) => {
17488
+ const detail = details[index];
17489
+ if (!detail) return model;
17490
+ return {
17491
+ ...model,
17492
+ toolCapable: detail.toolCapable,
17493
+ // The list call never reports a window, so only ever widen from the
17494
+ // lookup — a zero means "not reported", not "no room".
17495
+ contextLength: detail.contextLength || model.contextLength
17496
+ };
17497
+ });
17534
17498
  }
17535
- function topSignature(payload) {
17536
- if (payload.warRoom && payload.warRoom.priorityCount > 0) {
17537
- return `warroom:${payload.warRoom.newestSender ?? "peer"}`;
17499
+
17500
+ // ../../src/lib/ai/local/usage-format.ts
17501
+ var LOCAL_USAGE_DEFAULT_DAYS = 30;
17502
+ function formatLocalUsageLine(summary) {
17503
+ if (summary.answers <= 0) {
17504
+ return "No answers have run on your computer yet.";
17538
17505
  }
17539
- const top = payload.needsYou[0];
17540
- if (top) return `needs:${top.kind}:${top.title}`;
17541
- const integration = payload.integrations[0];
17542
- if (integration) return `stale:${integration.kind}`;
17543
- const agent = payload.agents[0];
17544
- if (agent) return `agent:${agent.name}`;
17545
- if (payload.topGoal) return `goal:${payload.topGoal.title}`;
17546
- return "empty";
17506
+ const window = summary.days === 1 ? "day" : `${summary.days} days`;
17507
+ if (summary.answers === 1) {
17508
+ return `1 answer ran on your computer in the last ${window}. It cost nothing.`;
17509
+ }
17510
+ return `${summary.answers} answers ran on your computer in the last ${window}. They cost nothing.`;
17547
17511
  }
17548
- function shouldShowGlance(input) {
17549
- const { urgency, topItemId, state, now } = input;
17550
- if (urgency > URGENT_THRESHOLD) return false;
17551
- if (state.lastShownAt === void 0) return true;
17552
- if (state.lastTopItemId !== topItemId) return true;
17553
- return now - state.lastShownAt >= THROTTLE_INTERVAL_MS;
17512
+
17513
+ // src/commands/local.ts
17514
+ var CHECK_TIMEOUT_MS = 3e4;
17515
+ function throwIfRefused(payload, what) {
17516
+ if (typeof payload.error !== "string") return;
17517
+ throw new CliError(
17518
+ `Great Arrow could not ${what} (${payload.error}).`,
17519
+ 2 /* NETWORK_ERROR */,
17520
+ payload.hint
17521
+ );
17554
17522
  }
17555
- function getGlanceStatePath() {
17556
- return join6(homedir4(), ".gad", "glance-state.json");
17523
+ function readProvider(raw) {
17524
+ const value = typeof raw === "string" ? raw : "ollama";
17525
+ if (!LOCAL_PROVIDERS.includes(value)) {
17526
+ throw validationError(
17527
+ `Unknown app "${value}".`,
17528
+ `Use one of: ${LOCAL_PROVIDERS.join(", ")}.`
17529
+ );
17530
+ }
17531
+ return value;
17557
17532
  }
17558
- async function loadGlanceState() {
17559
- try {
17560
- const content = await readFile4(getGlanceStatePath(), "utf-8");
17561
- const parsed = JSON.parse(content);
17562
- if (typeof parsed === "object" && parsed !== null) {
17563
- return parsed;
17533
+ function checkCommand() {
17534
+ return new Command("check").description("Find the models installed on this computer").option("--app <name>", "ollama or lmstudio", "ollama").option("--url <address>", "Where that app is listening").option("--use <model>", "Make this the model that answers you").action(async (options, command) => {
17535
+ const g = globalOutputOpts(command);
17536
+ const provider = readProvider(options.app);
17537
+ const baseUrl = typeof options.url === "string" && options.url ? options.url : LOCAL_PROVIDER_PRESETS[provider].baseUrl;
17538
+ const auth = await resolveAuth();
17539
+ const client = new GadClient({ token: auth.token, apiUrl: auth.apiUrl });
17540
+ const fmt = createFormatter({
17541
+ json: g.json,
17542
+ quiet: g.quiet,
17543
+ isTTY: isTTY(),
17544
+ noColor: g.noColor
17545
+ });
17546
+ let models;
17547
+ try {
17548
+ models = await findInstalledModels({ baseUrl, provider });
17549
+ } catch (err) {
17550
+ if (err instanceof LocalAppUnreachable) {
17551
+ throw new CliError(
17552
+ `Could not reach ${LOCAL_PROVIDER_PRESETS[provider].label} at ${err.baseUrl}. ${err.message}`,
17553
+ 2 /* NETWORK_ERROR */,
17554
+ `Start it on this computer and try again, or point somewhere else with --url.`
17555
+ );
17556
+ }
17557
+ throw err;
17564
17558
  }
17565
- return {};
17566
- } catch {
17567
- return {};
17568
- }
17569
- }
17570
- async function saveGlanceState(state) {
17571
- const path10 = getGlanceStatePath();
17572
- await mkdir4(dirname5(path10), { recursive: true });
17573
- await writeFile4(path10, JSON.stringify(state), "utf-8");
17559
+ const saved = await client.mcpCall(
17560
+ "model_local_set",
17561
+ {
17562
+ enabled: true,
17563
+ provider,
17564
+ base_url: baseUrl,
17565
+ models: models.map((model) => ({
17566
+ id: model.id,
17567
+ label: model.label,
17568
+ tool_capable: model.toolCapable,
17569
+ context_length: model.contextLength
17570
+ })),
17571
+ ...typeof options.use === "string" && options.use ? { default_model_id: options.use } : {}
17572
+ },
17573
+ CHECK_TIMEOUT_MS
17574
+ );
17575
+ if (g.json) {
17576
+ process.stdout.write(JSON.stringify({ models, saved }) + "\n");
17577
+ return;
17578
+ }
17579
+ throwIfRefused(saved, "record what is on this computer");
17580
+ if (models.length === 0) {
17581
+ fmt.warn(
17582
+ `${LOCAL_PROVIDER_PRESETS[provider].label} is running but has no models yet. Install one, then run this again.`
17583
+ );
17584
+ return;
17585
+ }
17586
+ const chosen = saved.preferences?.defaultModelId ?? null;
17587
+ process.stdout.write(
17588
+ `Found ${models.length} ${models.length === 1 ? "model" : "models"} on this computer:
17589
+ `
17590
+ );
17591
+ for (const model of models) {
17592
+ const mark = model.id === chosen ? "*" : " ";
17593
+ const limits = model.toolCapable ? "can look things up" : "answers from your library only";
17594
+ process.stdout.write(`${mark} ${model.label} \u2014 ${limits}
17595
+ `);
17596
+ }
17597
+ if (chosen) {
17598
+ process.stdout.write(`
17599
+ Answering with ${chosen}.
17600
+ `);
17601
+ } else {
17602
+ process.stdout.write(
17603
+ `
17604
+ Pick one with: gad local check --use <model>
17605
+ `
17606
+ );
17607
+ }
17608
+ });
17574
17609
  }
17575
- function glanceItemUrl(href, apiUrl) {
17576
- if (!href) return null;
17577
- if (/^https?:\/\//i.test(href)) return href;
17578
- if (!href.startsWith("/") || href.startsWith("//")) return null;
17579
- return `${apiUrl.replace(/\/$/, "")}${href}`;
17610
+ function statusCommand2() {
17611
+ return new Command("status").description("Show what is set up for models on this computer").action(async (_options, command) => {
17612
+ const g = globalOutputOpts(command);
17613
+ const auth = await resolveAuth();
17614
+ const client = new GadClient({ token: auth.token, apiUrl: auth.apiUrl });
17615
+ const payload = await client.mcpCall(
17616
+ "model_local_get",
17617
+ {},
17618
+ CHECK_TIMEOUT_MS
17619
+ );
17620
+ if (g.json) {
17621
+ process.stdout.write(JSON.stringify(payload) + "\n");
17622
+ return;
17623
+ }
17624
+ throwIfRefused(payload, "read your on-device settings");
17625
+ process.stdout.write(renderStatus(payload, g.noColor || !isTTY()) + "\n");
17626
+ });
17580
17627
  }
17581
- function renderFooter(payload, apiUrl) {
17582
- const c = createColor(false);
17628
+ function renderStatus(payload, plain) {
17629
+ const c = createColor(plain);
17630
+ const prefs = payload.preferences ?? {};
17631
+ const models = Array.isArray(prefs.models) ? prefs.models : [];
17632
+ const provider = LOCAL_PROVIDERS.includes(
17633
+ prefs.provider ?? ""
17634
+ ) ? LOCAL_PROVIDER_PRESETS[prefs.provider] : null;
17635
+ const appLabel = provider?.label ?? prefs.provider ?? "Ollama";
17636
+ const baseUrl = prefs.baseUrl ?? provider?.baseUrl ?? "";
17637
+ const chosen = models.find((model) => model.id === prefs.defaultModelId);
17638
+ const chosenName = chosen?.label ?? chosen?.id ?? null;
17583
17639
  const lines = [];
17584
- const printed = [];
17585
- const wr = payload.warRoom;
17586
- if (wr && wr.priorityCount > 0) {
17640
+ lines.push(baseUrl ? `${appLabel} at ${baseUrl}` : appLabel);
17641
+ if (prefs.enabled !== true) {
17587
17642
  lines.push(
17588
- `${c.yellow("!")} ${wr.priorityCount} war-room message${wr.priorityCount === 1 ? "" : "s"} for you${wr.newestSender ? ` \u2014 ${wr.newestSender}` : ""}`
17643
+ `${c.dim("\xB7")} Off \u2014 Great Arrow writes every answer on its own side.`
17589
17644
  );
17645
+ } else if (chosenName) {
17646
+ lines.push(`${c.green("\u2713")} On \u2014 answering with ${chosenName}.`);
17647
+ } else {
17648
+ lines.push(`${c.yellow("!")} On, but no model has been picked yet.`);
17590
17649
  }
17591
- const unpushed = (payload.atRisk ?? []).filter(
17592
- (item) => item.classification === "unpushed"
17650
+ lines.push(
17651
+ models.length === 0 ? `No models recorded on this computer yet.` : `${models.length} model${models.length === 1 ? "" : "s"} recorded on this computer.`
17593
17652
  );
17594
- if (unpushed.length > 0) {
17595
- const commits = unpushed.reduce(
17596
- (sum, item) => sum + (item.aheadMain ?? 0),
17597
- 0
17653
+ if (payload.available === false) {
17654
+ lines.push(
17655
+ `${c.yellow("!")} Your account is not in the group this is switched on for yet.`
17598
17656
  );
17599
- const scale = commits > 0 ? `${commits} commit${commits === 1 ? "" : "s"} on ${unpushed.length} branch${unpushed.length === 1 ? "" : "es"}` : `${unpushed.length} branch${unpushed.length === 1 ? "" : "es"}`;
17600
- lines.push(`${c.yellow("!")} ${scale} exist on this machine only`);
17601
- const first = unpushed[0];
17602
- if (first?.branch) {
17603
- lines.push(
17604
- ` ${c.dim("\u2192")} ${c.cyan(`git push -u origin ${first.branch}`)}`
17605
- );
17657
+ if (payload.availability_note) {
17658
+ lines.push(` ${c.dim(payload.availability_note)}`);
17606
17659
  }
17607
17660
  }
17608
- for (const item of payload.needsYou.slice(0, 2)) {
17609
- lines.push(`${c.yellow("!")} ${item.title}`);
17610
- if (item.signalKey) printed.push(item.signalKey);
17611
- if (item.action) {
17612
- lines.push(` ${c.dim("\u2192")} ${c.cyan(item.action)}`);
17613
- } else {
17614
- const url = glanceItemUrl(item.href, apiUrl);
17615
- if (url) lines.push(` ${c.dim("\u2192")} ${c.cyan(url)}`);
17616
- }
17661
+ if (payload.usage) {
17662
+ lines.push("");
17663
+ lines.push(
17664
+ formatLocalUsageLine({
17665
+ answers: payload.usage.answers ?? 0,
17666
+ days: payload.usage.days ?? LOCAL_USAGE_DEFAULT_DAYS,
17667
+ lastAnswerAt: null,
17668
+ models: []
17669
+ })
17670
+ );
17617
17671
  }
17618
- if (lines.length === 0) {
17619
- const integration = payload.integrations[0];
17620
- if (integration) {
17621
- const stale = integration.staleFor ? ` (stale ${integration.staleFor})` : "";
17622
- lines.push(`${c.yellow("!")} ${integration.kind}${stale}`);
17623
- if (integration.refresh) {
17624
- lines.push(` ${c.dim("\u2192")} ${c.cyan(integration.refresh)}`);
17672
+ lines.push("");
17673
+ lines.push(
17674
+ `${c.dim("\u2192")} ${c.cyan("gad local check")} to look again \xB7 ${c.cyan("gad local off")} to stop.`
17675
+ );
17676
+ return brandedBlock("on this computer", lines);
17677
+ }
17678
+ function offCommand() {
17679
+ return new Command("off").description("Stop answering with a model on this computer").action(async (_options, command) => {
17680
+ const g = globalOutputOpts(command);
17681
+ const auth = await resolveAuth();
17682
+ const client = new GadClient({ token: auth.token, apiUrl: auth.apiUrl });
17683
+ const fmt = createFormatter({
17684
+ json: g.json,
17685
+ quiet: g.quiet,
17686
+ isTTY: isTTY(),
17687
+ noColor: g.noColor
17688
+ });
17689
+ const saved = await client.mcpCall(
17690
+ "model_local_set",
17691
+ { enabled: false },
17692
+ CHECK_TIMEOUT_MS
17693
+ );
17694
+ if (g.json) {
17695
+ process.stdout.write(JSON.stringify(saved) + "\n");
17696
+ return;
17697
+ }
17698
+ throwIfRefused(saved, "turn this off");
17699
+ fmt.success(
17700
+ "Great Arrow will write every answer on its own side from now on. Your models stay on this computer \u2014 gad local check turns it back on."
17701
+ );
17702
+ });
17703
+ }
17704
+ function askHereCommand() {
17705
+ return new Command("ask").description("Answer a question with a model on this computer").argument("<question>", "What you want to know").option("--session <id>", "Continue an existing conversation").action(async (question, options, command) => {
17706
+ const g = globalOutputOpts(command);
17707
+ const auth = await resolveAuth();
17708
+ let report;
17709
+ try {
17710
+ report = await answerOnThisComputer({
17711
+ apiUrl: auth.apiUrl,
17712
+ token: auth.token,
17713
+ question,
17714
+ sessionId: typeof options.session === "string" ? options.session : null,
17715
+ timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
17716
+ ...g.json ? {} : { onWords: (delta) => process.stdout.write(delta) }
17717
+ });
17718
+ } catch (err) {
17719
+ if (err instanceof LocalTurnFailed) {
17720
+ throw new CliError(
17721
+ err.message,
17722
+ 2 /* NETWORK_ERROR */,
17723
+ err.closed ? void 0 : "Your conversation may show this one as unfinished."
17724
+ );
17625
17725
  }
17726
+ throw err;
17727
+ }
17728
+ if (g.json) {
17729
+ process.stdout.write(JSON.stringify(report) + "\n");
17730
+ return;
17731
+ }
17732
+ if (report.answeredHere) process.stdout.write("\n");
17733
+ if (!g.quiet) {
17734
+ process.stderr.write(
17735
+ "\n" + renderVenue(report, g.noColor || !isTTY()) + "\n"
17736
+ );
17737
+ }
17738
+ });
17739
+ }
17740
+ function renderVenue(report, plain) {
17741
+ const c = createColor(plain);
17742
+ const lines = [];
17743
+ if (report.answeredHere) {
17744
+ lines.push(
17745
+ `${c.green("\u2713")} Written on this computer by ${report.modelLabel}. It cost nothing.`
17746
+ );
17747
+ if (report.appsUsed > 0) {
17748
+ lines.push(
17749
+ `${c.dim("\xB7")} It looked up ${report.appsUsed} thing${report.appsUsed === 1 ? "" : "s"} in your workspace.`
17750
+ );
17626
17751
  }
17752
+ lines.push(
17753
+ report.recorded ? `${c.dim("\xB7")} Saved to your conversation.` : `${c.yellow("!")} We could not save it to your conversation.`
17754
+ );
17755
+ } else {
17756
+ lines.push(
17757
+ `${c.dim("\xB7")} Written by Great Arrow, not on this computer \u2014 it keeps the harder ones. The reply is in your conversation.`
17758
+ );
17627
17759
  }
17628
- if (lines.length === 0) return [];
17629
- lines.push(`${c.dim("\u2192")} ${c.cyan("gad status")} for the full picture.`);
17630
- process.stderr.write("\n" + brandedBlock("needs you", lines) + "\n");
17631
- return printed;
17760
+ return brandedBlock("where this was answered", lines);
17632
17761
  }
17633
- var GAD_MARK = "\u{1F3F9}";
17634
- function brandedBlock(title, lines) {
17635
- const header = `${GAD_MARK} Great Arrow \xB7 ${title}`;
17636
- const rule = "\u2500".repeat(Math.min(60, [...header].length));
17637
- return [header, rule, ...lines].join("\n");
17762
+ function localCommand() {
17763
+ return new Command("local").description("Answer with a model running on this computer").addCommand(checkCommand()).addCommand(statusCommand2()).addCommand(offCommand()).addCommand(askHereCommand());
17764
+ }
17765
+
17766
+ // src/lib/hyperlink.ts
17767
+ var SUPPORTED_TERM_PROGRAMS = /* @__PURE__ */ new Set([
17768
+ "ghostty",
17769
+ "iterm.app",
17770
+ "wezterm",
17771
+ "vscode",
17772
+ "hyper",
17773
+ "warpterminal",
17774
+ "rio",
17775
+ "contour",
17776
+ "tabby"
17777
+ ]);
17778
+ var SUPPORTED_TERMS = /* @__PURE__ */ new Set([
17779
+ "xterm-kitty",
17780
+ "alacritty",
17781
+ "foot",
17782
+ "contour"
17783
+ ]);
17784
+ var UNSUPPORTED_TERM_PROGRAMS = /* @__PURE__ */ new Set(["apple_terminal"]);
17785
+ var MIN_VTE_VERSION = 5e3;
17786
+ function isTruthyFlag(value) {
17787
+ if (value === void 0) return false;
17788
+ const v = value.trim().toLowerCase();
17789
+ return v !== "" && v !== "0" && v !== "false";
17790
+ }
17791
+ function supportsHyperlinks(env4, isTTY2) {
17792
+ if (isTruthyFlag(env4.FORCE_HYPERLINK)) return true;
17793
+ if (env4.NO_COLOR !== void 0 && env4.NO_COLOR !== "") return false;
17794
+ if (!isTTY2) return false;
17795
+ if (isTruthyFlag(env4.CI)) return false;
17796
+ const term = (env4.TERM ?? "").trim().toLowerCase();
17797
+ if (term === "" || term === "dumb") return false;
17798
+ if (term.startsWith("screen") || term.startsWith("tmux")) return false;
17799
+ const program3 = (env4.TERM_PROGRAM ?? "").trim().toLowerCase();
17800
+ if (UNSUPPORTED_TERM_PROGRAMS.has(program3)) return false;
17801
+ if (SUPPORTED_TERM_PROGRAMS.has(program3)) return true;
17802
+ if (SUPPORTED_TERMS.has(term)) return true;
17803
+ if (isTruthyFlag(env4.WT_SESSION)) return true;
17804
+ if (isTruthyFlag(env4.KONSOLE_VERSION)) return true;
17805
+ if (env4.TERMINAL_EMULATOR === "JetBrains-JediTerm") return true;
17806
+ const vte = Number.parseInt(env4.VTE_VERSION ?? "", 10);
17807
+ if (Number.isFinite(vte) && vte >= MIN_VTE_VERSION) return true;
17808
+ return false;
17809
+ }
17810
+ var OSC = "\x1B]8;;";
17811
+ var ST = "\x1B\\";
17812
+ function hyperlink(text2, url, opts) {
17813
+ if (!opts.enabled) return text2 === url ? url : `${text2} (${url})`;
17814
+ return `${OSC}${url}${ST}${text2}${OSC}${ST}`;
17638
17815
  }
17639
17816
 
17640
17817
  // src/commands/status.ts
17641
- function statusCommand2() {
17818
+ function statusCommand3() {
17642
17819
  const cmd = new Command("status").alias("needs").description(
17643
17820
  "Show what needs you: blockers, Goal progress, stale data, agents"
17644
17821
  ).option("--json", "Output the raw glance payload as JSON").option("--quiet", "Suppress decorative output").option("--no-color", "Disable color output").action(async (options, command) => {
@@ -17674,7 +17851,7 @@ function statusCommand2() {
17674
17851
  fmt.warn("No status available.");
17675
17852
  return;
17676
17853
  }
17677
- renderStatus(payload, g.noColor || g.quiet, auth.apiUrl);
17854
+ renderStatus2(payload, g.noColor || g.quiet, auth.apiUrl);
17678
17855
  await reportSeen({
17679
17856
  apiUrl: auth.apiUrl,
17680
17857
  token: auth.token,
@@ -17683,7 +17860,7 @@ function statusCommand2() {
17683
17860
  });
17684
17861
  return cmd;
17685
17862
  }
17686
- function renderStatus(payload, plain, apiUrl) {
17863
+ function renderStatus2(payload, plain, apiUrl) {
17687
17864
  const c = createColor(plain);
17688
17865
  const links = supportsHyperlinks(process.env, isTTY());
17689
17866
  const link = (text2, url) => c.cyan(hyperlink(text2, url, { enabled: links }));
@@ -21638,7 +21815,7 @@ program2.addCommand(work_default());
21638
21815
  program2.addCommand(worktree_default);
21639
21816
  program2.addCommand(install_hooks_default);
21640
21817
  program2.addCommand(guardrailsCommand());
21641
- program2.addCommand(statusCommand2());
21818
+ program2.addCommand(statusCommand3());
21642
21819
  program2.addCommand(doctorCommand());
21643
21820
  program2.addCommand(integrations_default);
21644
21821
  program2.addCommand(mcp_default);