agentix-cli 0.138.0 → 0.138.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-L5CJF3GH.js → agent-BLRZVUG4.js} +2 -2
- package/dist/{board-dashboard-33NGOGWC.js → board-dashboard-42C7GGD7.js} +119 -119
- package/dist/board-dashboard-42C7GGD7.js.map +1 -0
- package/dist/{chunk-4HHHVWDB.js → chunk-6XMISPQD.js} +16 -16
- package/dist/chunk-6XMISPQD.js.map +1 -0
- package/dist/{chunk-TVW5ZKJY.js → chunk-ADYTED3R.js} +2 -2
- package/dist/{chunk-GAIXI26T.js → chunk-AOV5RMFH.js} +2 -2
- package/dist/{chunk-7YZL5MUL.js → chunk-BKSWOMAM.js} +2 -2
- package/dist/{chunk-UPNKRCFX.js → chunk-J5FNCTG2.js} +5 -5
- package/dist/{chunk-CZZJEFUM.js → chunk-JAML6222.js} +2 -2
- package/dist/{chunk-7DYVNET6.js → chunk-YMX3QCV7.js} +1 -1
- package/dist/chunk-YMX3QCV7.js.map +1 -0
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +1 -1
- package/dist/{program-KMUCHLDU.js → program-5RLTC6CR.js} +4 -4
- package/dist/{push-bridge-276ZLSUT.js → push-bridge-P7HH25VN.js} +2 -2
- package/dist/{registry-IUNSHCOL.js → registry-RH5NFDL7.js} +2 -2
- package/package.json +1 -1
- package/dist/board-dashboard-33NGOGWC.js.map +0 -1
- package/dist/chunk-4HHHVWDB.js.map +0 -1
- package/dist/chunk-7DYVNET6.js.map +0 -1
- /package/dist/{agent-L5CJF3GH.js.map → agent-BLRZVUG4.js.map} +0 -0
- /package/dist/{chunk-TVW5ZKJY.js.map → chunk-ADYTED3R.js.map} +0 -0
- /package/dist/{chunk-GAIXI26T.js.map → chunk-AOV5RMFH.js.map} +0 -0
- /package/dist/{chunk-7YZL5MUL.js.map → chunk-BKSWOMAM.js.map} +0 -0
- /package/dist/{chunk-UPNKRCFX.js.map → chunk-J5FNCTG2.js.map} +0 -0
- /package/dist/{chunk-CZZJEFUM.js.map → chunk-JAML6222.js.map} +0 -0
- /package/dist/{program-KMUCHLDU.js.map → program-5RLTC6CR.js.map} +0 -0
- /package/dist/{push-bridge-276ZLSUT.js.map → push-bridge-P7HH25VN.js.map} +0 -0
- /package/dist/{registry-IUNSHCOL.js.map → registry-RH5NFDL7.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/daemon/app-push.ts","../src/daemon/app-fleet.ts"],"sourcesContent":["import type { IncomingMessage, ServerResponse } from \"http\"\nimport { mkdirSync, readFileSync, renameSync, writeFileSync } from \"fs\"\nimport { dirname, resolve } from \"path\"\nimport type { TokenRecord } from \"./token-store\"\nimport type { PushStore } from \"@/channels/push-store\"\nimport { PUSH_PREFS, type PushPrefName } from \"@/channels/push-prefs\"\nimport { readJson } from \"./app-fleet\"\n\n// --- Phone app: notifications (/api/app/push*, /api/app/alerts) ---\n//\n// Phase 4 of the mobile epic. Runs behind the device-token check in\n// app-routes.ts. A phone subscribes here; the daemon's PushAdapter reads the\n// same table to deliver. Each subscription is tied to the phone's device\n// token, so `agentx app revoke` also stops that phone's notifications.\n//\n// On a node that relays pushes (channels.push.relayTo), `forward` is set and\n// every call goes to the push host instead, through this node's daemon and\n// the mesh (push-bridge.ts), so a phone paired with any node can turn\n// notifications on (#711).\n\nexport interface AppPushDeps {\n /** Null when this node doesn't send pushes itself; `reason` says why. */\n store: () => PushStore | null\n /** VAPID public key the browser subscribes with, or null without keys. */\n publicKey: () => string | null\n keepRecent: number\n /** channels.push.allowedHosts: push services a phone may subscribe with. */\n allowedHosts: string[]\n reason?: string\n /** Set on a relaying node: sends each call to the push host. */\n forward?: (call: AppPushCall) => Promise<AppPushResult>\n}\n\n/** One phone-app push request, as handled here or by the push host. */\nexport interface AppPushCall {\n path: string\n method: string\n body: Record<string, any>\n device: { id: string; name: string }\n}\n\nexport interface AppPushResult {\n status: number\n body: unknown\n}\n\n/** The routes this module answers. */\nexport function isAppPushPath(path: string): boolean {\n return path === \"/api/app/push\" || path.startsWith(\"/api/app/push/\") || path === \"/api/app/alerts\"\n}\n\nconst MAX_ENDPOINT = 2048\nconst B64URL = /^[A-Za-z0-9_-]{8,256}$/\n\nexport async function handleAppPush(\n req: IncomingMessage,\n res: ServerResponse,\n path: string,\n method: string,\n device: TokenRecord,\n deps: AppPushDeps,\n): Promise<boolean> {\n if (!isAppPushPath(path)) return false\n let body: Record<string, any> = {}\n if (method === \"POST\") {\n try { body = await readJson(req) } catch (e: any) { return json(res, 400, { error: e.message }) }\n }\n const call: AppPushCall = { path, method, body, device: { id: device.id, name: device.name } }\n if (!deps.forward) {\n const out = runAppPush(call, deps)\n return json(res, out.status, out.body)\n }\n let out: AppPushResult\n try {\n out = await deps.forward(call)\n relayedPush.note(call, out)\n } catch (e: any) {\n out = unreachable(call, `${deps.reason ?? \"Can't reach the computer that sends notifications\"}: ${e?.message ?? e}`)\n }\n return json(res, out.status, out.body)\n}\n\n/** On a relaying node: what the push host last said about each phone, for\n * the checks that must answer at once (a finish notification, the\n * announcement switch). Filled from the phone's own calls on their way\n * through, so it is as fresh as the phone's last look at Alerts. */\nexport class RelayedPushState {\n private phones = new Map<string, { subscribed: boolean; prefs: Record<string, boolean> }>()\n private file: string | null = null\n\n /** Keeps the state in `file` too, so a dashboard restart doesn't stop\n * finish notifications until the phone next opens Alerts. Loads it the\n * first time; later calls with the same file do nothing. */\n persistTo(file: string): void {\n if (this.file === file) return\n this.file = file\n try {\n const saved = JSON.parse(readFileSync(file, \"utf-8\")) as Record<string, any>\n for (const [id, p] of Object.entries(saved ?? {})) {\n if (p && typeof p === \"object\" && typeof p.subscribed === \"boolean\") {\n this.phones.set(id, { subscribed: p.subscribed, prefs: pickPrefsFrom(p.prefs) })\n }\n }\n } catch { /* none yet, or unreadable: start empty */ }\n }\n\n note(call: AppPushCall, out: AppPushResult): void {\n if (out.status !== 200 || !out.body || typeof out.body !== \"object\") return\n const body = out.body as Record<string, any>\n const phone = this.phones.get(call.device.id) ?? { subscribed: false, prefs: {} }\n if (call.method === \"GET\" && call.path === \"/api/app/push\") {\n phone.subscribed = body.available === true && Number(body.subscriptions) > 0\n phone.prefs = pickPrefs(body)\n } else if (call.path === \"/api/app/push/prefs\") {\n phone.prefs = { ...phone.prefs, ...pickPrefs(body) }\n } else if (call.path === \"/api/app/push/subscribe\") {\n phone.subscribed = true\n } else if (call.path === \"/api/app/push/unsubscribe\") {\n if (body.removed) phone.subscribed = false\n } else {\n return\n }\n this.phones.set(call.device.id, phone)\n this.save()\n }\n\n private save(): void {\n if (!this.file) return\n try {\n mkdirSync(dirname(this.file), { recursive: true })\n const tmp = `${this.file}.${process.pid}.tmp`\n writeFileSync(tmp, JSON.stringify(Object.fromEntries(this.phones)) + \"\\n\", { encoding: \"utf-8\", mode: 0o600 })\n renameSync(tmp, this.file)\n } catch { /* kept in memory; written again at the next change */ }\n }\n\n /** A switch as last seen, or its default. */\n on(deviceId: string, name: PushPrefName): boolean {\n return this.phones.get(deviceId)?.prefs[PUSH_PREFS[name].field] ?? PUSH_PREFS[name].default\n }\n\n /** Subscribed and wanting finish notifications, as far as last seen. */\n finishOn(deviceId: string): boolean {\n return !!this.phones.get(deviceId)?.subscribed && this.on(deviceId, \"finish\")\n }\n}\n\n/** One per dashboard process. */\nexport const relayedPush = new RelayedPushState()\n\n/** relayedPush, kept in .agentx/ of the folder the dashboard runs in. */\nexport function relayedPushHere(): RelayedPushState {\n relayedPush.persistTo(resolve(process.cwd(), \".agentx/push-relayed.json\"))\n return relayedPush\n}\n\nfunction pickPrefs(body: Record<string, any>): Record<string, boolean> {\n const out: Record<string, boolean> = {}\n for (const p of Object.values(PUSH_PREFS)) if (typeof body[p.field] === \"boolean\") out[p.field] = body[p.field]\n return out\n}\n\nfunction pickPrefsFrom(v: unknown): Record<string, boolean> {\n return v && typeof v === \"object\" && !Array.isArray(v) ? pickPrefs(v as Record<string, any>) : {}\n}\n\n/** What a relaying node answers when the push host can't be reached: the\n * Alerts card says why instead of failing to load. */\nfunction unreachable(call: AppPushCall, reason: string): AppPushResult {\n if (call.method === \"GET\" && call.path === \"/api/app/push\") {\n return { status: 200, body: { available: false, reason, publicKey: null, subscriptions: 0, ...prefDefaults() } }\n }\n if (call.method === \"GET\" && call.path === \"/api/app/alerts\") return { status: 200, body: { items: [], error: reason } }\n return { status: 502, body: { error: reason } }\n}\n\n/** Answers one call against this node's own subscriptions table. Used for\n * a phone paired here, and by the push host for a phone paired with a\n * relaying node (push-bridge.ts), whose device id is then scoped to it. */\nexport function runAppPush(call: AppPushCall, deps: AppPushDeps): AppPushResult {\n const { path, method, body, device } = call\n if (!isAppPushPath(path)) return { status: 404, body: { error: \"not found\" } }\n const store = deps.store()\n const publicKey = store ? deps.publicKey() : null\n const unavailable = !store\n ? deps.reason ?? \"Notifications are not set up on this computer.\"\n : !publicKey ? \"This computer has no push keys yet. On it, run: agentx app push-keys\" : undefined\n\n if (method === \"GET\" && path === \"/api/app/push\") {\n return ok(200, {\n available: !unavailable,\n reason: unavailable ?? null,\n publicKey,\n // Only rows made with the current key count, so a phone subscribed\n // before `push-keys --force` sees 0 and subscribes again.\n subscriptions: store && publicKey ? store.list(device.id).filter((s) => s.publicKey === publicKey).length : 0,\n // Per-phone switches (push-prefs.ts): chatFinish, announce.\n ...(store ? store.prefs.all(device.id) : prefDefaults()),\n })\n }\n if (method === \"GET\" && path === \"/api/app/alerts\") {\n return ok(200, { items: store ? store.recent(deps.keepRecent, device.id) : [] })\n }\n if (method !== \"POST\" || (path !== \"/api/app/push/subscribe\" && path !== \"/api/app/push/unsubscribe\" && path !== \"/api/app/push/prefs\")) {\n return ok(404, { error: \"not found\" })\n }\n if (!store || unavailable) return ok(503, { error: unavailable })\n\n if (path === \"/api/app/push/prefs\") {\n // Any of the switches, each true or false; answers with those it set.\n const changes = (Object.keys(PUSH_PREFS) as PushPrefName[]).filter((n) => body[PUSH_PREFS[n].field] !== undefined)\n const fields = changes.map((n) => PUSH_PREFS[n].field).join(\", \")\n const all = Object.values(PUSH_PREFS).map((p) => p.field).join(\" or \")\n if (changes.length === 0) return ok(400, { error: `send ${all}, true or false` })\n if (changes.some((n) => typeof body[PUSH_PREFS[n].field] !== \"boolean\")) return ok(400, { error: `${fields} must be true or false` })\n const out: Record<string, boolean> = {}\n for (const n of changes) {\n store.prefs.set(device.id, n, body[PUSH_PREFS[n].field])\n out[PUSH_PREFS[n].field] = body[PUSH_PREFS[n].field]\n }\n return ok(200, { ok: true, ...out })\n }\n const endpoint = validEndpoint(body.endpoint, deps.allowedHosts)\n if (!endpoint) {\n let host = \"\"\n try { host = new URL(String(body.endpoint)).hostname } catch { /* not a URL */ }\n return ok(400, { error: `not a known push service${host ? `: ${host}` : \"\"} (see channels.push.allowedHosts)` })\n }\n\n if (path === \"/api/app/push/unsubscribe\") {\n return ok(200, { ok: true, removed: store.unsubscribe(endpoint, device.id) })\n }\n const p256dh = body.keys?.p256dh\n const auth = body.keys?.auth\n if (typeof p256dh !== \"string\" || !B64URL.test(p256dh) || typeof auth !== \"string\" || !B64URL.test(auth)) {\n return ok(400, { error: \"keys.p256dh and keys.auth are required\" })\n }\n // An endpoint belongs to one browser. If another device had it (a phone\n // re-paired under a new name), the latest pairing takes it over.\n // The browser subscribed with the key GET /api/app/push just handed it;\n // `publicKey` in the body must match it, so a stale page can't store a\n // subscription made with replaced keys.\n if (body.publicKey !== undefined && body.publicKey !== publicKey) {\n return ok(409, { error: \"this computer's push keys changed; turn notifications on again\" })\n }\n store.subscribe({ endpoint, p256dh, auth, deviceId: device.id, deviceName: device.name, publicKey: publicKey! })\n return ok(200, { ok: true })\n}\n\nfunction ok(status: number, body: unknown): AppPushResult {\n return { status, body }\n}\n\nfunction prefDefaults(): Record<string, boolean> {\n const out: Record<string, boolean> = {}\n for (const p of Object.values(PUSH_PREFS)) out[p.field] = p.default\n return out\n}\n\n/** The endpoint if it is https on an allowed push-service host (or a\n * subdomain of one). The daemon POSTs to whatever is stored, so a name\n * that merely looks public (and may resolve inside the network) is refused. */\nexport function validEndpoint(v: unknown, allowedHosts: string[]): string | null {\n if (typeof v !== \"string\" || v.length > MAX_ENDPOINT) return null\n try {\n const u = new URL(v)\n if (u.protocol !== \"https:\" || u.port || u.username || u.password) return null\n const host = u.hostname.toLowerCase()\n const ok = allowedHosts.some((h) => {\n const allowed = h.toLowerCase().replace(/^\\.+|\\.+$/g, \"\")\n return !!allowed && (host === allowed || host.endsWith(\".\" + allowed))\n })\n return ok ? v : null\n } catch {\n return null\n }\n}\n\nfunction json(res: ServerResponse, status: number, body: unknown): true {\n res.writeHead(status, { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" })\n res.end(JSON.stringify(body))\n return true\n}\n","import type { IncomingMessage, ServerResponse } from \"http\"\n\n// --- Phone app: fleet, activity and control (/api/app/fleet, …) ---\n//\n// Phase 3 of the mobile epic. Runs behind the device-token check in\n// app-routes.ts, so every handler here may assume a paired phone.\n//\n// Reads reuse the dashboard's live snapshot (every node the dashboard can\n// see, including peers found through /mesh) and trim it to what a phone\n// shows: short previews, never full prompts, replies or errors. Writes go\n// to a node daemon through the dashboard's allowlisted, token-carrying POST\n// (AppFleetDeps.nodePost), the same path the desktop task and restart\n// buttons use, so the phone gets no power the dashboard doesn't already have.\n\nexport const PREVIEW_CHARS = 160\n\nexport interface SnapshotNode {\n id: string\n name: string\n url: string\n reachable: boolean\n error?: string\n uptimeSec?: number\n inflight?: number\n restart?: { state: string; requestedAt?: string; deadline?: string }\n agents: Array<{\n id: string\n name: string\n tier?: string\n color?: string\n active: number\n errors: number\n lastActive?: string\n lastSummary?: { text: string; at: string; ok: boolean }\n runningTasks?: Array<{ id: string; traceId?: string; messagePreview: string; channel: string; chatId?: string; sender?: string; startedAt: string }>\n }>\n crons?: Array<{ id: string; enabled: boolean; schedule: string; agent: string; kind?: string; nextRun?: string; consecutiveErrors: number }>\n cronRuns?: Array<{ jobId: string; startedAt: string; status: string; responseSummary?: string; errorSummary?: string; isRetry?: boolean }>\n}\n\nexport interface ApprovalItem {\n key: string\n title: string\n ask?: string\n recommend?: string\n /** What yes and no do, in words. */\n yes?: string\n no?: string\n raisedBy?: string\n expires?: string\n /** Cards: the ready-made answers; yes must pick one (#743). */\n choices?: string[]\n /** Cards: the suggested message, `{choice}` not filled in yet. */\n draft?: string\n /** A short excerpt of what is being decided, for the Desk (#959). */\n detail?: string\n createdAt?: string\n}\n\n/** A card's pick (1-based number or label) and the message as edited. */\nexport interface ChoiceAnswer { choice?: string | number; text?: string }\n\nexport interface NodeApprovals {\n node: string\n nodeName: string\n items: ApprovalItem[]\n error?: string\n}\n\nexport interface NodeReply { status: number; body: any }\n\nexport interface AppFleetDeps {\n snapshot(day?: { date: string; timezone: string }): Promise<{ ts: string; nodes: SnapshotNode[] }>\n /** POST to a node daemon on the dashboard's allowlist, with its token. */\n nodePost(nodeUrl: string, path: string, body: unknown): Promise<NodeReply>\n approvals(): Promise<NodeApprovals[]>\n /** `by` names the phone, e.g. \"operator (phone: My phone)\". */\n decide(nodeUrl: string, key: string, action: \"yes\" | \"no\" | \"later\", by: string, answer?: ChoiceAnswer): Promise<NodeReply>\n}\n\nexport function clip(text: string | undefined, max = PREVIEW_CHARS): string | undefined {\n if (!text) return text\n const flat = text.replace(/\\s+/g, \" \").trim()\n return flat.length > max ? flat.slice(0, max - 1) + \"…\" : flat\n}\n\n/** One node, trimmed for the Fleet tab. Cron outcomes come from the node's\n * persisted run files (cronRuns), never the scheduler's counters. */\nexport function summarizeNode(n: SnapshotNode) {\n const lastRun = new Map<string, NonNullable<SnapshotNode[\"cronRuns\"]>[number]>()\n for (const r of n.cronRuns ?? []) {\n const prev = lastRun.get(r.jobId)\n if (!prev || prev.startedAt < r.startedAt) lastRun.set(r.jobId, r)\n }\n const today = { success: 0, failed: 0 }\n for (const r of n.cronRuns ?? []) {\n if (r.status === \"success\") today.success++\n else today.failed++\n }\n return {\n id: n.id,\n name: n.name,\n url: n.url,\n reachable: n.reachable,\n error: clip(n.error),\n uptimeSec: n.uptimeSec,\n inflight: n.inflight,\n restart: n.restart?.state && n.restart.state !== \"none\" ? n.restart : undefined,\n agents: n.agents.map((a) => ({\n id: a.id,\n name: a.name,\n tier: a.tier,\n active: a.active,\n errors: a.errors,\n lastActive: a.lastActive,\n last: a.lastSummary ? { text: clip(a.lastSummary.text), at: a.lastSummary.at, ok: a.lastSummary.ok } : undefined,\n })),\n crons: {\n today,\n items: (n.crons ?? []).map((c) => {\n const r = lastRun.get(c.id)\n return {\n id: c.id,\n enabled: c.enabled,\n schedule: c.schedule,\n agent: c.agent,\n nextRun: c.nextRun,\n consecutiveErrors: c.consecutiveErrors,\n last: r ? { status: r.status, at: r.startedAt, text: clip(r.status === \"success\" ? r.responseSummary : r.errorSummary) } : undefined,\n }\n }),\n },\n }\n}\n\n/** Every running task across the fleet, newest first. */\nexport function summarizeActivity(nodes: SnapshotNode[]) {\n const tasks = []\n for (const n of nodes) {\n for (const a of n.agents) {\n for (const t of a.runningTasks ?? []) {\n tasks.push({\n node: n.url,\n nodeName: n.name,\n agentId: a.id,\n agentName: a.name,\n taskId: t.id,\n preview: clip(t.messagePreview),\n channel: t.channel,\n startedAt: t.startedAt,\n })\n }\n }\n }\n return tasks.sort((x, y) => (x.startedAt < y.startedAt ? 1 : -1))\n}\n\nconst TASK_ACTION = /^\\/api\\/app\\/tasks\\/(cancel|followup)$/\n\n/** Handles /api/app/{fleet,activity,tasks,nodes,crons,approvals}. Returns\n * false for any other path so the caller can fall through. */\nexport async function handleAppFleet(\n req: IncomingMessage,\n res: ServerResponse,\n path: string,\n method: string,\n device: string,\n deps: AppFleetDeps,\n): Promise<boolean> {\n const url = new URL(req.url || path, \"http://localhost\")\n\n if (method === \"GET\" && (path === \"/api/app/fleet\" || path === \"/api/app/activity\")) {\n const timezone = validTimezone(url.searchParams.get(\"timezone\"))\n const snap = await deps.snapshot({ date: dateIn(timezone), timezone })\n if (path === \"/api/app/activity\") return json(res, 200, { ts: snap.ts, tasks: summarizeActivity(snap.nodes) })\n return json(res, 200, { ts: snap.ts, nodes: snap.nodes.map(summarizeNode) })\n }\n\n if (method === \"GET\" && path === \"/api/app/approvals\") {\n return json(res, 200, { nodes: await deps.approvals() })\n }\n\n if (method !== \"POST\") return false\n const taskAction = path.match(TASK_ACTION)\n const known = taskAction || [\n \"/api/app/nodes/restart\", \"/api/app/nodes/reload\", \"/api/app/crons/toggle\", \"/api/app/approvals/decide\",\n ].includes(path)\n if (!known) return false\n\n let body: Record<string, unknown>\n try { body = await readJson(req) } catch (e: any) { return json(res, 400, { error: e.message }) }\n const node = str(body.node)\n if (!node) return json(res, 400, { error: \"node is required\" })\n const by = `operator (phone: ${device})`\n\n let reply: NodeReply\n if (taskAction) {\n const taskId = str(body.taskId)\n if (!taskId) return json(res, 400, { error: \"taskId is required\" })\n const upstream = `/api/tasks/${encodeURIComponent(taskId)}/${taskAction[1]}`\n if (taskAction[1] === \"cancel\") {\n reply = await deps.nodePost(node, upstream, { reason: `cancelled by ${by}` })\n } else {\n const message = str(body.message)\n if (!message) return json(res, 400, { error: \"message is required\" })\n reply = await deps.nodePost(node, upstream, { message, sender: by })\n }\n } else if (path === \"/api/app/nodes/restart\") {\n reply = await deps.nodePost(node, body.cancel === true ? \"/daemon/restart/cancel\" : \"/daemon/restart\", {})\n } else if (path === \"/api/app/nodes/reload\") {\n reply = await deps.nodePost(node, \"/reload\", {})\n } else if (path === \"/api/app/crons/toggle\") {\n const cronId = str(body.cronId)\n if (!cronId || typeof body.enabled !== \"boolean\") return json(res, 400, { error: \"cronId and enabled (true or false) are required\" })\n reply = await deps.nodePost(node, `/crons/${encodeURIComponent(cronId)}/enabled`, { enabled: body.enabled })\n } else {\n const key = str(body.key)\n const action = body.action\n if (!key || (action !== \"yes\" && action !== \"no\" && action !== \"later\")) {\n return json(res, 400, { error: \"key and action (yes, no or later) are required\" })\n }\n const choice = typeof body.choice === \"number\" ? body.choice : str(body.choice)\n const text = typeof body.text === \"string\" && body.text.trim() ? body.text : \"\"\n const answer: ChoiceAnswer = { ...(choice !== \"\" ? { choice } : {}), ...(text ? { text } : {}) }\n reply = await deps.decide(node, key, action, by, answer)\n }\n return json(res, reply.status, reply.body)\n}\n\nfunction str(v: unknown): string {\n return typeof v === \"string\" ? v.trim() : \"\"\n}\n\nfunction validTimezone(tz: string | null): string {\n if (!tz) return \"UTC\"\n try { new Intl.DateTimeFormat(\"en-US\", { timeZone: tz }); return tz } catch { return \"UTC\" }\n}\n\n/** YYYY-MM-DD for \"today\" in the phone's time zone. */\nexport function dateIn(timezone: string, now = new Date()): string {\n return new Intl.DateTimeFormat(\"en-CA\", { timeZone: timezone, year: \"numeric\", month: \"2-digit\", day: \"2-digit\" }).format(now)\n}\n\nexport async function readJson(req: IncomingMessage, limit = 16 * 1024): Promise<Record<string, unknown>> {\n let size = 0\n const chunks: Buffer[] = []\n for await (const chunk of req) {\n size += (chunk as Buffer).length\n if (size > limit) throw new Error(\"body too large\")\n chunks.push(chunk as Buffer)\n }\n const raw = Buffer.concat(chunks).toString(\"utf-8\").trim()\n if (!raw) return {}\n const parsed = JSON.parse(raw)\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) throw new Error(\"expected a JSON object\")\n return parsed\n}\n\nfunction json(res: ServerResponse, status: number, body: unknown): true {\n res.writeHead(status, { \"Content-Type\": \"application/json\", \"Cache-Control\": \"no-store\" })\n res.end(JSON.stringify(body))\n return true\n}\n"],"mappings":"wCACA,OAAS,aAAAA,EAAW,gBAAAC,EAAc,cAAAC,EAAY,iBAAAC,MAAqB,KACnE,OAAS,WAAAC,EAAS,WAAAC,MAAe,OC8E1B,SAASC,EAAKC,EAA0BC,EAAM,IAAmC,CACtF,GAAI,CAACD,EAAM,OAAOA,EAClB,IAAME,EAAOF,EAAK,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAC5C,OAAOE,EAAK,OAASD,EAAMC,EAAK,MAAM,EAAGD,EAAM,CAAC,EAAI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EAAI,IAClB,MAAE,CACA,OAAO,IACT,CACF,CAEA,SAASzB,EAAKP,EAAqBiD,EAAgB7C,EAAqB,CACtE,OAAAJ,EAAI,UAAUiD,EAAQ,CAAE,eAAgB,mBAAoB,gBAAiB,UAAW,CAAC,EACzFjD,EAAI,IAAI,KAAK,UAAUI,CAAI,CAAC,EACrB,EACT","names":["mkdirSync","readFileSync","renameSync","writeFileSync","dirname","resolve","clip","text","max","flat","summarizeNode","n","lastRun","r","prev","today","a","c","summarizeActivity","nodes","tasks","t","x","y","TASK_ACTION","handleAppFleet","req","res","path","method","device","deps","url","timezone","validTimezone","snap","dateIn","json","taskAction","body","readJson","e","node","str","by","reply","taskId","upstream","message","cronId","key","action","choice","answer","v","tz","now","limit","size","chunks","chunk","raw","parsed","status","isAppPushPath","path","MAX_ENDPOINT","B64URL","handleAppPush","req","res","method","device","deps","body","readJson","e","json","call","out","runAppPush","relayedPush","unreachable","RelayedPushState","file","saved","readFileSync","id","p","pickPrefsFrom","phone","pickPrefs","mkdirSync","dirname","tmp","writeFileSync","renameSync","deviceId","name","PUSH_PREFS","relayedPushHere","resolve","v","reason","prefDefaults","store","publicKey","unavailable","ok","s","changes","n","fields","all","endpoint","validEndpoint","host","p256dh","auth","status","allowedHosts","u","h","allowed"]}
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-
|
|
2
|
+
import{b as o}from"./chunk-JXF54PT7.js";import"./chunk-QIJLFPWE.js";var e=o(process.versions.node);e&&(console.error(e),process.exit(1));var{buildProgram:s}=await import("./program-5RLTC6CR.js"),{installCliSignalExit:r}=await import("./signal-exit-WL7G3EEZ.js"),{applyConnectAttemptTimeout:i,configPathFromArgv:a,readConnectAttemptTimeout:n}=await import("./net-family-X2P3OVDP.js");r();i(n(process.cwd(),a(process.argv.slice(2))));var t=await s();process.argv.slice(2).length===0?t.outputHelp():t.parse();
|
|
3
3
|
//# sourceMappingURL=cli.js.map
|
package/dist/index.d.ts
CHANGED
|
@@ -14820,6 +14820,10 @@ declare class RunStore {
|
|
|
14820
14820
|
interface RunningTask {
|
|
14821
14821
|
/** Unique id for this execution (timestamp-based). */
|
|
14822
14822
|
id: string;
|
|
14823
|
+
/** The id the run's trace is kept under, and the one `task:started`
|
|
14824
|
+
* carries: what a request's run link holds. Absent until the trace
|
|
14825
|
+
* is allocated. */
|
|
14826
|
+
traceId?: string;
|
|
14823
14827
|
/** First 200 chars of the user message, for dense lists. */
|
|
14824
14828
|
messagePreview: string;
|
|
14825
14829
|
/** The whole request. A task page shows what was actually asked, and the
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-
|
|
1
|
+
import{a as St,b as kt,c as vt,d as xt,e as $t,f as Ct,g as Pt,h as bt,la as Tt,ma as Mt}from"./chunk-J5FNCTG2.js";import"./chunk-BKSWOMAM.js";import"./chunk-GTJIKXDB.js";import"./chunk-LA6P3TUK.js";import"./chunk-7LN4VKDU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import"./chunk-S2GAEH2F.js";import"./chunk-UNIXYV3U.js";import"./chunk-AKWBDCMU.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import"./chunk-EKJG63EJ.js";import"./chunk-EMGB23H5.js";import"./chunk-JAML6222.js";import"./chunk-YMX3QCV7.js";import"./chunk-JWDJMFU6.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-LQE73AZR.js";import"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-A5GYG56I.js";import"./chunk-6VP2KMUM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{ca as yt,m as lt,n as ct,o as dt,p as mt,q as pt}from"./chunk-6XMISPQD.js";import"./chunk-7V73QTQ7.js";import"./chunk-QSKG754X.js";import"./chunk-MEFPXHQJ.js";import{a as L}from"./chunk-UG2OF2EI.js";import{A as D,B as z,C as V,a as ye,b as we,c as Se,d as Ae,e as Ie,f as Oe,g as Ne,h as He,i as je,j as Ue,k as _e,l as I,m as q,n as Be,o as qe,p as Ye,q as O,r as ze,s as Ve,t as Xe,u as x,v as Y,w as Qe,x as Ze,y as et,z as wt}from"./chunk-AOV5RMFH.js";import{a as B,b as M,c as F}from"./chunk-SFQUP3BP.js";import"./chunk-Y4CYQV7G.js";import"./chunk-LLNPKE7H.js";import"./chunk-SHEUCITK.js";import"./chunk-6AUWEL6V.js";import"./chunk-SZDACK6O.js";import"./chunk-HF5EF335.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{s as ut}from"./chunk-DBJUGKX2.js";import"./chunk-JIJDBCV7.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-TFH6S7IT.js";import{a as ht}from"./chunk-XVYIPVSC.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-SK47VJMQ.js";import"./chunk-SKSYII3K.js";import{f as gt,g as ft}from"./chunk-VVX4RXMV.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-QGSUENRK.js";import{j as it,k as rt,l as at}from"./chunk-MTDVAO5C.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import{a as ke,b as ve,c as xe,d as $e,e as Ce,f as Pe,g as be,h as Te,i as Me,j as Re,l as Ee,m as Ge,o as T,p as W}from"./chunk-2PJKGZWP.js";import{a as m,b as G}from"./chunk-7I7IEX4S.js";import{b as Fe,c as Le,d as A,e as De}from"./chunk-JHCI6XCJ.js";import{a as Ke,b as Je,e as We}from"./chunk-DSYKYZMT.js";import{Aa as nt,qa as tt,sa as st,ta as ot}from"./chunk-HJCFLGVT.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";W();G();import{execa as Rt}from"execa";import{existsSync as se,promises as X}from"fs";import S from"path";import ie from"node-fetch";async function Et(o,e){let t=o.split("/");if(t.length<2)throw new Error(`Invalid skill package ID: ${o}. Expected format: owner/repo`);let s=t[0],i=t[1],n=t[2];try{let a=n?`${s}/${i}/${n}`:`${s}/${i}`;await Rt("npx",["-y","skills","add",a],{cwd:e,stdio:"pipe"}),m.success(`Installed skill package: ${o}`);let r=S.resolve(e,".skills",`${s}_${i}`);if(se(r))return await ne(r,o);let d=S.resolve(e,".skills");return se(d)?await ne(d,o):[]}catch{return m.info(`Fetching skills directly from GitHub: ${s}/${i}`),await Gt(s,i,n,e)}}async function Gt(o,e,t,s){let i=[];try{let n=`https://api.github.com/repos/${o}/${e}/git/trees/main?recursive=1`,a=await ie(n);if(!a.ok)throw new Error(`GitHub API error: ${a.status}`);let d=(await a.json()).tree.filter(p=>p.type==="blob"&&p.path.endsWith("SKILL.md"));if(t){let p=d.find(f=>f.path.includes(`/${t}/`)||f.path===`${t}/SKILL.md`);if(p){let f=await oe(o,e,p.path,s);f&&i.push(f)}}else for(let p of d){let f=await oe(o,e,p.path,s);f&&i.push(f)}}catch(n){m.error(`Failed to fetch skills from GitHub: ${n.message}`)}return i}async function oe(o,e,t,s){try{let i=`https://raw.githubusercontent.com/${o}/${e}/main/${t}`,n=await ie(i);if(!n.ok)return null;let a=await n.text(),r=A(a);if(r){r.source="remote",r.packageId=`${o}/${e}`;let d=S.dirname(t),p=S.resolve(s,".skills",`${o}_${e}`,d);await X.mkdir(p,{recursive:!0}),await X.writeFile(S.resolve(p,"SKILL.md"),a),r.path=S.resolve(p,"SKILL.md")}return r}catch{return null}}async function ne(o,e){let t=[],{default:s}=await import("fast-glob"),i=await s.glob("**/SKILL.md",{cwd:o,deep:5});for(let n of i)try{let a=S.resolve(o,n),r=await X.readFile(a,"utf8"),d=A(r);d&&(d.source="remote",d.path=a,d.packageId=e,t.push(d))}catch{}return t}async function At(o,e,t,s,i){let n=["---",`name: ${o}`,`description: ${e}`];if(s?.length){n.push("tags:");for(let a of s)n.push(` - ${a}`)}if(i?.length){n.push("globs:");for(let a of i)n.push(` - ${a}`)}return n.push("---"),`${n.join(`
|
|
2
2
|
`)}
|
|
3
3
|
|
|
4
4
|
${t}`}async function It(o){let{loadLocalSkills:e}=await import("./loader-YFVSSYSL.js");return e(o)}async function Ot(o,e,t,s,i){let a=[{role:"system",content:`You are a skill author for the Agent Skills ecosystem (skills.sh).
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as xm,b as Mr,g as Sm}from"./chunk-UPQTTOVQ.js";import{b as bm}from"./chunk-Y7IHOQC7.js";import{A as gm,B as mm,D as Oa,E as um,G as pm,H as fm,I as hm,a as Jg,e as Ht,f as zg,g as Yg,h as Qg,i as Zg,k as em,l as tm,m as om,n as Ea,o as nm,t as sm,u as rm,v as Ca,w as im,z as dm}from"./chunk-
|
|
1
|
+
import{a as xm,b as Mr,g as Sm}from"./chunk-UPQTTOVQ.js";import{b as bm}from"./chunk-Y7IHOQC7.js";import{A as gm,B as mm,D as Oa,E as um,G as pm,H as fm,I as hm,a as Jg,e as Ht,f as zg,g as Yg,h as Qg,i as Zg,k as em,l as tm,m as om,n as Ea,o as nm,t as sm,u as rm,v as Ca,w as im,z as dm}from"./chunk-ADYTED3R.js";import{n as Ta}from"./chunk-EGPCEQJN.js";import{a as ym,b as wm,d as xs,e as $m}from"./chunk-375MXG3H.js";import{a as km,b as vm}from"./chunk-HQH44RGL.js";import"./chunk-H4NSB54D.js";import"./chunk-MTX4UPNB.js";import{d as Vg,e as Aa,h as Xg,i as Kg}from"./chunk-YXFTUOZR.js";import{a as am,c as cm,d as lm}from"./chunk-5NTWGUSJ.js";import"./chunk-QAWKN2N4.js";import"./chunk-B2QYMUTD.js";import{a as vt}from"./chunk-AGQYUOZY.js";import{a as Gg,c as Hg}from"./chunk-XBARUCG5.js";import{a as xa}from"./chunk-LNY6N73E.js";import{a as ra,b as ud}from"./chunk-RKPAVWXF.js";import{$ as Pg,A as ug,B as ua,C as pg,D as fg,E as hg,F as yg,G as wg,H as $g,I as bg,J as kg,K as Og,L as Ir,M as no,N as wo,O as Tn,P as Nr,Q as jr,R as wa,S as Tg,T as Rg,U as Ig,V as Ng,W as jg,X as _g,Y as Rn,Z as In,_ as Dg,a as kd,aa as tt,b as vd,ba as _r,ca as vs,da as $a,ea as Mg,fa as qg,ga as va,h as yr,ha as Wg,i as Ed,ia as Dr,j as $s,ja as Nn,k as wr,ka as Pr,l as Od,la as Sa,m as Td,ma as Bg,n as Ud,o as Wd,p as Sr,q as da,r as Vd,s as og,t as ng,u as rg,v as ig,w as lg,x as dg,y as gg,z as mg}from"./chunk-J5FNCTG2.js";import{$ as pa,A as eg,D as tg,E as Or,J as sg,Pa as Lg,Qa as ba,Ra as Fg,Sa as ka,Y as bs,aa as Tr,ba as vg,eb as Gt,gb as Ug,ia as yo,ja as xg,ka as fa,ma as ha,oa as Sg,pa as Ag,qa as ks,ua as Rr,x as Zd,xa as Eg,ya as Cg,z as ma,za as ya}from"./chunk-BKSWOMAM.js";import"./chunk-GTJIKXDB.js";import{a as xd,c as aa,e as Sd,f as Ad}from"./chunk-LA6P3TUK.js";import"./chunk-7LN4VKDU.js";import"./chunk-IMLAPB7G.js";import"./chunk-ZVP6GB4G.js";import{a as $r,b as br,c as Rd,d as Id,e as Nd,g as jd,h as _d,j as Dd,k as Pd,l as Md,m as Ld,p as kr,s as Fd,t as qd}from"./chunk-S2GAEH2F.js";import"./chunk-UNIXYV3U.js";import{a as Xd,b as Wo,c as Kd,d as Ar,e as Qd,f as ga,i as Er,j as Bo,k as Cr}from"./chunk-AKWBDCMU.js";import"./chunk-PPUN7YHA.js";import"./chunk-VZLIBDLH.js";import{a as ag,b as cg}from"./chunk-EKJG63EJ.js";import{b as kt}from"./chunk-EMGB23H5.js";import{c as Bd}from"./chunk-JAML6222.js";import"./chunk-YMX3QCV7.js";import"./chunk-JWDJMFU6.js";import{b as la}from"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import{c as Jd,e as vr,g as xr}from"./chunk-LQE73AZR.js";import{a as Gd,b as Hd,c as zd,d as Yd}from"./chunk-2D3RYIDU.js";import"./chunk-MRIVENBY.js";import"./chunk-A5GYG56I.js";import{a as ca,p as Cd}from"./chunk-6VP2KMUM.js";import"./chunk-2AXFYDWF.js";import"./chunk-AQASR6KR.js";import{L as ho,R as cd,ca as dd,g as Bl,r as Jl,y as oa,z as Vl}from"./chunk-6XMISPQD.js";import{F as id,U as ad,W as ld,b as xn,g as Sn,h as pr,i as fr,j as An,k as Xl,l as fo,n as qo}from"./chunk-7V73QTQ7.js";import{e as od,f as Uo,k as Cn}from"./chunk-QSKG754X.js";import{b as Fo}from"./chunk-MEFPXHQJ.js";import"./chunk-AOV5RMFH.js";import"./chunk-SFQUP3BP.js";import{a as oo}from"./chunk-Y4CYQV7G.js";import{b as ws}from"./chunk-LLNPKE7H.js";import{a as gd,b as md}from"./chunk-SHEUCITK.js";import{a as ia,e as pd,f as fd,h as hd,i as yd,k as wd,l as $d,m as bd}from"./chunk-6AUWEL6V.js";import{c as Ql}from"./chunk-SZDACK6O.js";import{f as Zl,g as ed,h as na}from"./chunk-HF5EF335.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import{a as zl,k as td}from"./chunk-DBJUGKX2.js";import{a as hr,b as ge,c as We,d as On,e as nd}from"./chunk-JIJDBCV7.js";import{a as sd,b as sa,h as rd}from"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import{a as ta,b as Hl}from"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import{j as Yl}from"./chunk-X5C5W3E4.js";import{a as En}from"./chunk-GV7S5BAX.js";import{e as Kl}from"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import{a as ea}from"./chunk-TFH6S7IT.js";import"./chunk-XVYIPVSC.js";import{c as Gl}from"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-SK47VJMQ.js";import"./chunk-SKSYII3K.js";import{g as po,i as ur}from"./chunk-VVX4RXMV.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-QGSUENRK.js";import{a as Vi,b as kl,c as ty,d as lr,e as vl,f as Dl,g as cy,h as Pl,i as ly,m as vn,n as Ll,q as Fl,u as ql,y as Jt,z as ys}from"./chunk-MTDVAO5C.js";import{a as to,b as kn,e as Nl,f as hs}from"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import{a as mr,b as Ml}from"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import{g as uo,i as Ul}from"./chunk-6TURWSMN.js";import{n as Wl}from"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-JXF54PT7.js";import"./chunk-2PJKGZWP.js";import{a as Bt,b as ey}from"./chunk-7I7IEX4S.js";import"./chunk-JHCI6XCJ.js";import"./chunk-DSYKYZMT.js";import{Aa as le,D as Ol,E as sy,S as Tl,T as Ki,V as Qi,aa as ry,ba as Zi,da as Rl,ea as iy,h as xl,i as Sl,j as Al,k as El,l as Cl,m as oy,qa as Il,ra as dr,sa as O,ta as gr,v as Xi,w as ny}from"./chunk-HJCFLGVT.js";import"./chunk-BRK6M6LA.js";import{f as bt,n as fs}from"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import{g as jl,k as _l,l as ay}from"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";import{Command as dy}from"commander";var Am=new dy().name("a2a").description("start an A2A (Agent-to-Agent) protocol server for external agent integration").option("--port <port>","server port","3171").option("--host <host>","server host","0.0.0.0").option("-p, --provider <provider>","AI provider","claude-code").option("-m, --model <model>","model to use").option("--api-key <key>","API key for the provider").option("-c, --cwd <cwd>","working directory",process.cwd()).option("--no-cors","disable CORS headers").action(async e=>{await new vd({port:parseInt(e.port,10),host:e.host,provider:e.provider,model:e.model,apiKey:e.apiKey,cwd:e.cwd,cors:e.cors!==!1}).start()});le();import{Command as gy}from"commander";import{execFileSync as Tt}from"node:child_process";import{cpSync as Em,existsSync as Na,mkdirSync as Ra,mkdtempSync as my,readdirSync as uy,rmSync as Cm,writeFileSync as Om}from"node:fs";import{dirname as Tm,join as ot}from"node:path";import{homedir as Lr,release as py,tmpdir as fy}from"node:os";import{setTimeout as hy}from"node:timers/promises";function Fr(){let e=Rd(process.platform,process.arch,py());if(e)throw new Error(e)}function qr(){let e=ot(Lr(),"Library/LaunchAgents"),t=[];try{t=uy(e).filter(jd)}catch{}let o=t.flatMap(n=>{let s=ot(e,n);try{return[{file:s,plist:Tt("plutil",["-convert","xml1","-o","-",s],{encoding:"utf8",stdio:["ignore","pipe","ignore"]})}]}catch{return[]}});return _d(e,o)}function Ss(e){return`gui/${process.getuid()}/${e.label}`}async function Ia(e){try{Tt("launchctl",["bootout",Ss(e)],{stdio:"pipe"})}catch{}for(let t=0;t<30;t++){try{Tt("launchctl",["print",Ss(e)],{stdio:"pipe"})}catch{return}await hy(200)}throw new Error("The desktop login service did not stop. Retry agentx desktop stop before installing.")}function Rm(e){if(!Na(e.file))throw new Error("Run agentx desktop install first.");let t=!0;try{Tt("launchctl",["print",Ss(e)],{stdio:"pipe"})}catch{t=!1}t||Tt("launchctl",["bootstrap",`gui/${process.getuid()}`,e.file],{stdio:"pipe"}),Tt("launchctl",["kickstart",Ss(e)],{stdio:"pipe"})}function yy(){let e=Ld();if(e&&Na(ot(e,"apps/mac-voice/build.sh")))return e;throw new Error("Desktop sources are missing from this installation. Update AgentX to a release containing apps/mac-voice and apps/mac-helper.")}var jn=new gy("desktop").description("install and control the macOS desktop assistant");jn.command("install").description("build, install, and start voice and computer-use helpers at login").option("--agent <id>","pin this agent; without it, pick the agent from the menu-bar icon").option("--dry-run","show the installation plan without building or changing login items").action(async e=>{Fr();let t=O(),o=Id(t.agents,e.agent),n=e.agent,s=t.dashboard?.daemonUrl||`http://${t.node.bind.replace(/^0\.0\.0\.0:/,"127.0.0.1:")}`,r=yy(),i=ot(Lr(),"Applications"),{keep:a,remove:c}=qr();if(console.log(`Desktop assistant \u2192 ${ot(i,$r)}
|
|
2
2
|
Computer-use helper \u2192 ${ot(i,br)}
|
|
3
3
|
Agent \u2192 ${n?`${o} (pinned)`:"picked from the menu-bar icon"}
|
|
4
4
|
Daemon \u2192 ${s}
|
|
@@ -493,7 +493,7 @@ return aid ?? null`}function Zb(e,t){if(e.kind==="path"){let s=e.pts,r=s[Math.fl
|
|
|
493
493
|
Plan ${V.dim(`[${s.state}] by ${s.createdBy}, ${Xn(s.createdAt)}`)}`),df(n.steps(e)),console.log(`
|
|
494
494
|
Log`);for(let r of n.events(e))console.log(V.dim(` ${Xn(r.at)} ${r.step?`step ${r.step} `:""}${r.kind}: ${r.detail}`))}});gn.command("step <id> <step>").description("move a step of a request's plan on: --retry, --skip or --done").option("--retry","hand the step to its agent again, with a fresh count of nudges (approves a message whose card expired)").option("--skip","leave the step out; the plan goes on with the next one").option("--done","mark the step done yourself").option("--note <text>","why, or the evidence for --done").action((e,t,o)=>{let n=["retry","skip","done"].filter(c=>o[c]);if(n.length!==1){console.error(V.red(" give one of --retry, --skip or --done")),process.exitCode=1;return}let s=vi();if(!s)return;let r=lf();if(!r){process.exitCode=1;return}let i=Number(t),a=ng(s,r,{requestId:e,step:i,action:n[0],detail:o.note},Date.now());if(a){console.error(V.red(` ${a}`)),process.exitCode=1;return}console.log(V.green(` \u2713 step ${i} of ${e}: ${n[0]==="retry"?"handed over again":n[0]==="skip"?"skipped":"done"}`)+V.dim(" (the daemon goes on within a minute)")),df(r.steps(e))});function mf(e,t,o,n){gn.command(`${e} <id>`).description(t).option(o,e==="done"?"link to the proof: PR, issue, message, deploy":"why it is dropped").action((s,r)=>{let i=vi();if(!i)return;let a=e==="done"?r.evidence:r.reason??"dropped by the owner";if(!a){console.error(V.red(` ${n}`)),process.exitCode=1;return}let c=i.get(s);if(!c||c.state==="candidate"){console.error(V.red(` no request "${s}"`)),process.exitCode=1;return}if(!i.close(s,e==="done"?"done":"dropped",a,Date.now())){console.error(V.red(` ${s} is already closed (${cf[c.state]??c.state})`)),process.exitCode=1;return}console.log(V.green(` \u2713 ${s} ${e==="done"?"closed as done":"dropped"}`))})}mf("done","close a request as finished, with a link to the evidence","--evidence <link>","a finished request needs --evidence <link>");mf("drop","drop a request you no longer want","--reason <text>","");gn.command("settings").description("show or change the requests settings").option("--enabled <on|off>","record and follow your requests").option("--from <id,...>",'who counts as you on channels other people can reach, as channel:id (your login on GitLab and GitHub, your sender id elsewhere); "none" to clear').option("--channels <name,...>",'channels to record on; "all" for every channel a person writes on').option("--stale-hours <n>","hours without activity before an open request comes back to you").option("--retention-days <n>","days a closed request is kept").option("--plans <on|off>","follow requests of two or more steps as tracked plans").option("--stall-minutes <n>","minutes without progress before a plan step's agent is nudged").option("--max-nudges <n>","nudges per step before it counts as blocked and you are told").option("--approve-kinds <kind,...>",'step kinds you approve once when the plan is made; "none" to clear').option("--plans-off-for <agent,...>",'agents that may not open a plan; "none" to clear').action(async e=>{let t={};try{let s=(a,c)=>{if(c===void 0)return;let l=Number(c);if(!(l>0))throw new Error(`${a} must be a positive number`);return l},r=(a,c)=>a===void 0?void 0:a===c?[]:a.split(",").map(l=>l.trim()).filter(Boolean);if(e.enabled!==void 0){if(e.enabled!=="on"&&e.enabled!=="off")throw new Error("--enabled takes on or off");t.enabled=e.enabled==="on"}t.from=r(e.from,"none"),t.channels=r(e.channels,"all"),t.staleAfterHours=s("--stale-hours",e.staleHours),t.retentionDays=s("--retention-days",e.retentionDays);let i={};if(e.plans!==void 0){if(e.plans!=="on"&&e.plans!=="off")throw new Error("--plans takes on or off");i.enabled=e.plans==="on"}if(i.stallMinutes=s("--stall-minutes",e.stallMinutes),e.maxNudges!==void 0){let a=Number(e.maxNudges);if(!Number.isInteger(a)||a<0)throw new Error("--max-nudges must be a whole number, 0 or more");i.maxNudges=a}i.approveKinds=r(e.approveKinds,"none"),i.disabledAgents=r(e.plansOffFor,"none"),Object.values(i).some(a=>a!==void 0)&&(t.plans=i)}catch(s){console.error(V.red(` ${s.message}`)),process.exitCode=1;return}if(Object.values(t).some(s=>s!==void 0)){let s=await eg(t);if(!s.success){console.error(V.red(` ${s.error}`)),process.exitCode=1;return}console.log(V.green(" \u2713 saved")+(s.reloaded?V.dim(" (daemon reloaded)"):""))}let o=ma();console.log(` Requests ${o.enabled?"on":"off"}`),console.log(` Channels ${o.channels.length?o.channels.join(", "):"every channel a person writes on"}`),console.log(` Counts as you ${o.from.length?o.from.join(", "):"only voice, the app and the dashboard on this machine"}`),console.log(` Comes back after ${o.staleAfterHours} hour(s) without activity`),console.log(` Closed requests kept ${o.retentionDays} day(s)`);let n=o.plans??og;console.log(` Plans ${n.enabled?"on":"off"}`),console.log(` Nudge a quiet step after ${n.stallMinutes} minute(s), up to ${n.maxNudges} time(s)`),console.log(` You approve up front ${n.approveKinds.length?n.approveKinds.join(", "):"nothing"}`),console.log(` Plans off for ${n.disabledAgents.length?n.disabledAgents.join(", "):"no agent"}`)});import{Command as Sv}from"commander";import Kn from"chalk";le();var uf=new Sv("request-status").description("show each person the state of their request in the thread where they asked (GitLab, GitHub)").argument("[channel]",Ca.join(" or ")).argument("[state]","on or off").action(async(e,t)=>{if(e!==void 0){t!=="on"&&t!=="off"&&(console.error(Kn.red("\u2717 say on or off, for example: agentx request-status gitlab on")),process.exit(1));let n="",s=await ge(r=>{n=im(r,e,t==="on")});s.success||(console.error(Kn.red(`\u2717 ${s.error}`)),process.exit(1)),console.log(Kn.green(`\u2713 ${n}`)),s.reloaded&&console.log(Kn.dim(" daemon hot-reloaded"))}let o=O().requestStatus.channels.map(n=>n.toLowerCase());for(let n of Ca)console.log(` ${n.padEnd(8)} ${o.includes(n)?Kn.green("on"):Kn.dim("off")}`)});import{Command as zv}from"commander";import Qn from"chalk";import ye from"chalk";import zs from"prompts";import{readFileSync as Av,writeFileSync as Ev,existsSync as Cv}from"fs";import{resolve as pf}from"path";var Ov=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;function Tv(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function jc(e){return/[\s#"'\\]/.test(e)||e===""?JSON.stringify(e):e}function ff(e=".env"){let t=pf(e);if(!Cv(t))return[];let o=Av(t,"utf-8"),n=[];for(let s of o.split(/\r?\n/)){if(s.trim()===""){n.push({kind:"blank",raw:s});continue}if(s.trim().startsWith("#")){n.push({kind:"comment",raw:s});continue}let r=s.match(Ov);r?n.push({kind:"kv",key:r[1],value:Tv(r[2]),raw:s}):n.push({kind:"comment",raw:s})}return n.length&&n[n.length-1].kind==="blank"&&n.pop(),n}function Rv(e){return e.map(t=>t.kind==="kv"?`${t.key}=${jc(t.value)}`:t.raw).join(`
|
|
495
495
|
`)+`
|
|
496
|
-
`}function Hs(e,t,o=".env"){let n=pf(o),s=ff(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${jc(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${jc(t)}`})),Ev(n,Rv(s))}function _c(e,t=".env"){return ff(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var hf="https://t.me/BotFather";async function Iv(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function Nv(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function yf(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${hf}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await zs({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ho(hf);let{token:o}=await zs({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Iv(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ye.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await zs({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await zs({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Hs(p,o.trim()),process.env[p]=o.trim();let u=await ge(b=>{We(b,"channels.telegram.enabled",!0),We(b,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let v=On(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),We(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await zs({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let y=await Nv(o.trim(),9e4);if(!y){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let $=await ge(b=>{We(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:f})},{configPath:e.configPath});if(!$.success){console.log(ye.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Ce from"chalk";import Dc from"prompts";import{existsSync as Mc,mkdirSync as jv,readdirSync as _v,readFileSync as wf}from"fs";import{resolve as Pc}from"path";var Dv=".agentx/whatsapp-sessions";function Pv(){let e=Pc(process.cwd(),".agentx/daemon.pid");if(!Mc(e))return!1;try{let t=parseInt(wf(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Mv(e){if(!Mc(e))return!1;try{return _v(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Lv(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Ce.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Ce.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;jv(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Ce.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Ce.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Ce.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Ce.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function $f(e={}){if(console.log(),console.log(Ce.bold(" Connect WhatsApp")),console.log(),Pv()){console.log(Ce.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Ce.dim(" agentx daemon stop")),console.log();let{cont:l}=await Dc({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Ce.red(" Aborted")),process.exit(1))}let t=e.configPath||Pc(process.cwd(),"agentx.json");Mc(t)||(console.log(Ce.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(wf(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Dv,s=Pc(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Dc({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Ce.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Mv(s)&&a){let{keep:l}=await Dc({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Ce.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Lv(s,g=>console.log(g))||(console.log(Ce.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ge(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Ce.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Ce.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Ce.dim(` Session: ${n}`)),console.log(Ce.dim(" Start the daemon to begin receiving:")),console.log(Ce.dim(" agentx daemon start")),console.log(Ce.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Ce.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Ce.dim(" Add routes later with:")),console.log(Ce.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as Fv}from"crypto";import Fe from"chalk";import bf from"prompts";var xi="agentx-mesh:",Si="//join/";function qv(e){return Buffer.from(e,"utf-8").toString("base64url")}function Uv(e){return Buffer.from(e,"base64url").toString("utf-8")}function Wv(e){return`${xi}${Si}${qv(JSON.stringify(e))}`}function Bv(e){if(!e.startsWith(`${xi}${Si}`))throw new Error(`Not a mesh invite link \u2014 expected ${xi}${Si}\u2026`);let t=e.slice(xi.length+Si.length),o=JSON.parse(Uv(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function Jv(){return Fv(32).toString("hex")}function Gv(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Hv(e){return e?.node?.name||e?.node?.id||"node"}async function kf(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Fe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=_c("MESH_TOKEN");i||(i=Jv(),Hs("MESH_TOKEN",i),console.log(Fe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Gv(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await bf({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Fe.red(" Aborted")),process.exit(1)),a=d}let l=await ge(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Fe.red(` \u2717 ${l.error}`)),process.exit(1));let g=Wv({url:a,token:i,name:Hv(r),version:1});console.log(),console.log(Fe.bold(" Mesh invite")),console.log(),console.log(` ${Fe.cyan(g)}`),console.log(),console.log(Fe.dim(" Run on the other node:")),console.log(Fe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Fe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function vf(e,t={}){let o;try{o=Bv(e)}catch(r){console.log(Fe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=_c("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await bf({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Fe.red(" Aborted (keeping existing .env)")),process.exit(1))}Hs("MESH_TOKEN",o.token);let s=await ge(r=>{We(r,"mesh.enabled",!0);let i=On(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Fe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Fe.green(" \u2713 Joined mesh")),console.log(Fe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Fe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Fe.dim(" Daemon hot-reloaded.")):console.log(Fe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Fe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Fe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Fe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Zn=new zv().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Zn.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await yf({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Zn.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await $f({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var xf=Zn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");xf.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await kf({url:e.url,configPath:e.config})});xf.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await vf(e,{configPath:t.config})});Zn.action(()=>{console.log(),console.log(Qn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Qn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Qn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Qn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Qn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Qn.dim(" GitLab connect is the next slice.")),console.log()});le();import{Command as Yv}from"commander";import te from"chalk";var mn=new Yv().name("usage").description("token usage analysis and reporting");mn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(te.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(te.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${te.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${te.red(String(s.totalErrors))}`),console.log(),console.log(te.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${te.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${te.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${e.message}`))}});mn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:te.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(te.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(te.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?te.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(te.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${t.message}`))}});mn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(te.red(` Script not found: ${s}`)),console.log(te.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(te.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(te.red(" Analysis failed. Is Python 3 installed?"))}});mn.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(te.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(te.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(te.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(te.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(te.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let $=r(h),b=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l($).padStart(9)}`;if(c){let v=r(y),A=$!==null&&v?`${(($-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${A.padStart(7)}`}console.log(b)}console.log(),c&&console.log(te.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(te.dim(` Saved ${e.save}`)),console.log()});mn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-WSY4SHHL.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-KMUCHLDU.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(te.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${te.dim("\xB7")} ${d}`);console.log(),console.log(te.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(te.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(te.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(te.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(te.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(te.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=te.dim(`${r.days}d`);console.log(` ${te.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(te.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Vv}from"commander";import Pe from"chalk";import{readFileSync as Xv}from"fs";import{resolve as Kv}from"path";le();var Io=new Vv().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Io.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ul(Kv(process.cwd(),".env"))}catch{}let t=Qv(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-33NGOGWC.js");o(t)}catch(t){console.log(Pe.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Pe.dim(t.stack)),process.exit(1)}});function Qv(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Pe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Pe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
496
|
+
`}function Hs(e,t,o=".env"){let n=pf(o),s=ff(n),r=s.findIndex(i=>i.kind==="kv"&&i.key===e);r>=0?s[r]={kind:"kv",key:e,value:t,raw:`${e}=${jc(t)}`}:(s.length&&s[s.length-1].kind!=="blank"&&s.push({kind:"blank",raw:""}),s.push({kind:"kv",key:e,value:t,raw:`${e}=${jc(t)}`})),Ev(n,Rv(s))}function _c(e,t=".env"){return ff(t).find(s=>s.kind==="kv"&&s.key===e)?.value}var hf="https://t.me/BotFather";async function Iv(e){try{let t=await fetch(`https://api.telegram.org/bot${e}/getMe`,{signal:AbortSignal.timeout(8e3)});if(!t.ok)return null;let o=await t.json();return o?.ok?o.result:null}catch{return null}}async function Nv(e,t){let o=Date.now()+t,n=0;try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=-1&timeout=0`,{signal:AbortSignal.timeout(5e3)})).json();r?.result?.length&&(n=r.result[0].update_id+1)}catch{}for(;Date.now()<o;)try{let r=await(await fetch(`https://api.telegram.org/bot${e}/getUpdates?offset=${n}&timeout=10`,{signal:AbortSignal.timeout(15e3)})).json();for(let i of r?.result||[]){n=Math.max(n,i.update_id+1);let a=i.message||i.edited_message||i.channel_post;if(a?.chat?.id)return{chatId:a.chat.id,chatTitle:a.chat.title||a.chat.username||a.chat.first_name,from:a.from?.first_name||a.from?.username||"unknown"}}}catch{}return null}async function yf(e={}){console.log(),console.log(ye.bold(" Connect Telegram")),console.log(),console.log(ye.dim(` 1. Open ${hf}`)),console.log(ye.dim(" /newbot (or /mybots \u2192 pick existing \u2192 API Token)")),console.log(ye.dim(" 2. Copy the HTTP API token \u2014 looks like 123456789:ABCdef...")),console.log();let{wantsBrowser:t}=await zs({type:"confirm",name:"wantsBrowser",message:"Open BotFather in your browser?",initial:!0});t&&Ho(hf);let{token:o}=await zs({type:"password",name:"token",message:"Paste the bot token from BotFather:",validate:b=>/^\d+:[A-Za-z0-9_-]{20,}$/.test(b.trim())||"That doesn't look like a Telegram token"});o||(console.log(ye.red(" Aborted")),process.exit(1)),process.stdout.write(" Verifying token... ");let n=await Iv(o.trim());n||(console.log(ye.red("\u2717 invalid or revoked")),process.exit(1)),console.log(ye.green(`\u2713 ${n.first_name} (@${n.username})`));let{readFileSync:s,existsSync:r}=await import("fs"),{resolve:i}=await import("path"),a=e.configPath||i(process.cwd(),"agentx.json");r(a)||(console.log(ye.red(` No agentx.json at ${a}. Run: agentx init`)),process.exit(1));let c=JSON.parse(s(a,"utf-8")),l=Object.keys(c.agents||{});l.length===0&&(console.log(ye.red(" No agents configured. Run: agentx agent add")),process.exit(1));let g=e.agent;g||(g=(await zs({type:"select",name:"agent",message:"Bind this bot to which agent?",choices:l.map(v=>({title:v,value:v})),initial:0})).agent),g||(console.log(ye.red(" Aborted")),process.exit(1));let d=c.channels?.telegram?.accounts||{},f=e.account||g;d[f]&&d[f].agentBinding!==g&&(f=(await zs({type:"text",name:"account",message:`Account "${f}" is already in use. Pick a different label:`,initial:`${g}-2`,validate:v=>/^[a-z0-9-]+$/i.test(v)||"lowercase letters, digits, hyphens only"})).account),f||(console.log(ye.red(" Aborted")),process.exit(1));let p=`TG_${f.toUpperCase().replace(/-/g,"_")}_BOT_TOKEN`;Hs(p,o.trim()),process.env[p]=o.trim();let u=await ge(b=>{We(b,"channels.telegram.enabled",!0),We(b,`channels.telegram.accounts.${f}`,{token:`\${${p}}`,agentBinding:g});let v=On(b,`agents.${g}.mentions`)||[],A=`@${n.username}`;v.includes(A)||(v.push(A),We(b,`agents.${g}.mentions`,v))},{configPath:e.configPath});if(u.success||(console.log(ye.red(` \u2717 ${u.error}`)),process.exit(1)),console.log(),console.log(ye.green(` \u2713 Bot @${n.username} bound to agent "${g}"`)),console.log(ye.dim(` Token stored in .env as ${p}`)),console.log(ye.dim(` Mentions updated to include @${n.username}`)),u.reloaded?console.log(ye.dim(" Daemon hot-reloaded.")):console.log(ye.dim(" Start the daemon to begin polling (agentx daemon start)")),e.skipChatCapture)return;console.log();let{capture:h}=await zs({type:"confirm",name:"capture",message:"Listen for a message so we can set this as your default --notify target?",initial:!0});if(!h)return;console.log(),console.log(ye.dim(` Send any message to @${n.username} from the chat you want to use.`)),console.log(ye.dim(" Waiting up to 90s..."));let y=await Nv(o.trim(),9e4);if(!y){console.log(ye.yellow(" No message received \u2014 skipping. You can set it later with:")),console.log(ye.dim(" agentx config set notifications.destination.channel telegram")),console.log(ye.dim(" agentx config set notifications.destination.chatId <chatId>")),console.log(ye.dim(` agentx config set notifications.destination.accountId ${f}`));return}let $=await ge(b=>{We(b,"notifications.destination",{channel:"telegram",chatId:String(y.chatId),accountId:f})},{configPath:e.configPath});if(!$.success){console.log(ye.red(` \u2717 failed to save destination: ${$.error}`));return}console.log(ye.green(" \u2713 Default --notify target set")),console.log(ye.dim(` Chat: ${y.chatTitle||y.chatId} (from ${y.from})`)),console.log(ye.dim(" From now on, --notify me resolves to this chat.")),$.reloaded&&console.log(ye.dim(" Daemon hot-reloaded."))}import Ce from"chalk";import Dc from"prompts";import{existsSync as Mc,mkdirSync as jv,readdirSync as _v,readFileSync as wf}from"fs";import{resolve as Pc}from"path";var Dv=".agentx/whatsapp-sessions";function Pv(){let e=Pc(process.cwd(),".agentx/daemon.pid");if(!Mc(e))return!1;try{let t=parseInt(wf(e,"utf-8").trim(),10);return t?(process.kill(t,0),!0):!1}catch{return!1}}function Mv(e){if(!Mc(e))return!1;try{return _v(e).some(t=>t.includes("creds")||t.endsWith(".json"))}catch{return!1}}async function Lv(e,t){let o;try{o=await import("@whiskeysockets/baileys")}catch{return t(Ce.red(" WhatsApp pairing needs @whiskeysockets/baileys.")),t(Ce.red(" Install with: pnpm add @whiskeysockets/baileys (or npm install)")),!1}let{makeWASocket:n,useMultiFileAuthState:s}=o.default||o;jv(e,{recursive:!0});let{state:r,saveCreds:i}=await s(e),a;try{a=(await o.fetchLatestBaileysVersion()).version}catch{}let c={level:"silent",trace:()=>{},debug:()=>{},info:()=>{},warn:()=>{},fatal:()=>{},error:()=>{},child:()=>c},l=n({auth:{creds:r.creds,keys:o.makeCacheableSignalKeyStore?o.makeCacheableSignalKeyStore(r.keys,c):r.keys},...a?{version:a}:{},logger:c,printQRInTerminal:!1,browser:["agentx-connect","pairing","1.0"],syncFullHistory:!1,markOnlineOnConnect:!1});return l.ev.on("creds.update",i),await new Promise(g=>{let f=setTimeout(()=>{t(Ce.yellow(" Timed out waiting for scan (2min)."));try{l.end(void 0)}catch{}g(!1)},12e4);l.ev.on("connection.update",async p=>{if(p.qr){t(Ce.dim(" Scan this QR with WhatsApp \u2192 Linked devices \u2192 Link a device:")),t("");try{let{default:u}=await import("qrcode-terminal");u.generate(p.qr,{small:!0})}catch{t(` QR: ${p.qr}`)}t("")}if(p.connection==="open"){clearTimeout(f),t(Ce.green(" \u2713 Paired"));try{l.end(void 0)}catch{}g(!0)}p.connection==="close"&&!p.qr&&p.lastDisconnect?.error?.output?.statusCode===401&&(clearTimeout(f),t(Ce.red(" \u2717 Authorization failed \u2014 rescan required")),g(!1))})})}async function $f(e={}){if(console.log(),console.log(Ce.bold(" Connect WhatsApp")),console.log(),Pv()){console.log(Ce.yellow(" \u26A0 The daemon is running. Stop it first so pairing can open a fresh Baileys session:")),console.log(Ce.dim(" agentx daemon stop")),console.log();let{cont:l}=await Dc({type:"confirm",name:"cont",message:"Continue anyway? (expect errors)",initial:!1});l||(console.log(Ce.red(" Aborted")),process.exit(1))}let t=e.configPath||Pc(process.cwd(),"agentx.json");Mc(t)||(console.log(Ce.red(` No agentx.json at ${t}. Run: agentx init`)),process.exit(1));let o=JSON.parse(wf(t,"utf-8")),n=e.sessionDir||o.channels?.whatsapp?.sessionDir||Dv,s=Pc(process.cwd(),n),r=Object.keys(o.agents||{});r.length===0&&(console.log(Ce.red(" No agents configured. Run: agentx agent add")),process.exit(1));let i=e.agent;i||(i=(await Dc({type:"select",name:"agent",message:"Default agent for incoming messages:",choices:r.map(g=>({title:g,value:g})),initial:0})).agent),i||(console.log(Ce.red(" Aborted")),process.exit(1));let a=!e.skipPair;if(Mv(s)&&a){let{keep:l}=await Dc({type:"confirm",name:"keep",message:`An existing session was found at ${n}. Keep it (recommended), or pair again?`,initial:!0});a=!l,l&&console.log(Ce.dim(" Keeping existing session \u2014 skipping QR pair."))}a&&(await Lv(s,g=>console.log(g))||(console.log(Ce.red(" Pairing failed. You can retry with `agentx connect whatsapp`.")),process.exit(1)));let c=await ge(l=>{We(l,"channels.whatsapp.enabled",!0),We(l,"channels.whatsapp.sessionDir",n),We(l,"channels.whatsapp.defaultAgent",i)},{configPath:e.configPath});c.success||(console.log(Ce.red(` \u2717 ${c.error}`)),process.exit(1)),console.log(),console.log(Ce.green(` \u2713 WhatsApp bound to agent "${i}"`)),console.log(Ce.dim(` Session: ${n}`)),console.log(Ce.dim(" Start the daemon to begin receiving:")),console.log(Ce.dim(" agentx daemon start")),console.log(Ce.yellow(" No chat is answered until you list the allowed numbers (add your own to talk from your self-chat):")),console.log(Ce.dim(` agentx config set channels.whatsapp.allowFrom '["+15550001111"]'`)),console.log(Ce.dim(" Add routes later with:")),console.log(Ce.dim(` agentx config set channels.whatsapp.routes '[{"contact":"+1234567890","agent":"${i}"}]'`)),console.log()}import{randomBytes as Fv}from"crypto";import Fe from"chalk";import bf from"prompts";var xi="agentx-mesh:",Si="//join/";function qv(e){return Buffer.from(e,"utf-8").toString("base64url")}function Uv(e){return Buffer.from(e,"base64url").toString("utf-8")}function Wv(e){return`${xi}${Si}${qv(JSON.stringify(e))}`}function Bv(e){if(!e.startsWith(`${xi}${Si}`))throw new Error(`Not a mesh invite link \u2014 expected ${xi}${Si}\u2026`);let t=e.slice(xi.length+Si.length),o=JSON.parse(Uv(t));if(o.version!==1)throw new Error(`Unsupported invite version: ${o.version}`);if(typeof o.url!="string"||typeof o.token!="string"||typeof o.name!="string")throw new Error("Invite payload missing required fields (url, token, name)");return o}function Jv(){return Fv(32).toString("hex")}function Gv(e){let t=e?.node?.bind||"127.0.0.1:18800",[o,n]=t.split(":");return`http://${o}:${n}`}function Hv(e){return e?.node?.name||e?.node?.id||"node"}async function kf(e){let{readFileSync:t,existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=e.configPath||n(process.cwd(),"agentx.json");o(s)||(console.log(Fe.red(` No agentx.json at ${s}. Run: agentx init`)),process.exit(1));let r=JSON.parse(t(s,"utf-8")),i=_c("MESH_TOKEN");i||(i=Jv(),Hs("MESH_TOKEN",i),console.log(Fe.dim(" Generated new MESH_TOKEN (32 bytes) and saved to .env")));let a=e.url||Gv(r);if((a.includes("0.0.0.0")||a.includes("127.0.0.1")||a.includes("localhost"))&&!e.url){let{url:d}=await bf({type:"text",name:"url",message:"This node's URL as peers should reach it (e.g. http://100.x.x.x:18800):",initial:a,validate:f=>/^https?:\/\//.test(f)||"must start with http:// or https://"});d||(console.log(Fe.red(" Aborted")),process.exit(1)),a=d}let l=await ge(d=>{We(d,"mesh.enabled",!0)},{configPath:e.configPath});l.success||(console.log(Fe.red(` \u2717 ${l.error}`)),process.exit(1));let g=Wv({url:a,token:i,name:Hv(r),version:1});console.log(),console.log(Fe.bold(" Mesh invite")),console.log(),console.log(` ${Fe.cyan(g)}`),console.log(),console.log(Fe.dim(" Run on the other node:")),console.log(Fe.dim(` agentx connect mesh join "${g}"`)),console.log(),console.log(Fe.yellow(" Share over a trusted channel only \u2014 whoever holds this link can join your mesh.")),console.log()}async function vf(e,t={}){let o;try{o=Bv(e)}catch(r){console.log(Fe.red(` \u2717 ${r.message}`)),process.exit(1)}let n=_c("MESH_TOKEN");if(n&&n!==o.token){let{overwrite:r}=await bf({type:"confirm",name:"overwrite",message:"A different MESH_TOKEN already exists in .env. Overwrite with the invite's token?",initial:!1});r||(console.log(Fe.red(" Aborted (keeping existing .env)")),process.exit(1))}Hs("MESH_TOKEN",o.token);let s=await ge(r=>{We(r,"mesh.enabled",!0);let i=On(r,"mesh.peers")||[],a=i.findIndex(l=>l.name===o.name),c={name:o.name,url:o.url,token:"${MESH_TOKEN}"};a>=0?i[a]=c:i.push(c),We(r,"mesh.peers",i)},{configPath:t.configPath});s.success||(console.log(Fe.red(` \u2717 ${s.error}`)),process.exit(1)),console.log(Fe.green(" \u2713 Joined mesh")),console.log(Fe.dim(` Peer: ${o.name} @ ${o.url}`)),console.log(Fe.dim(" Shared token stored in .env as MESH_TOKEN")),s.reloaded?console.log(Fe.dim(" Daemon hot-reloaded.")):console.log(Fe.dim(" Restart the daemon to start the mesh (agentx daemon start).")),console.log();try{let r=await fetch(`${o.url.replace(/\/$/,"")}/.well-known/agent-card.json`,{signal:AbortSignal.timeout(5e3)});if(r.ok){let i=await r.json(),a=Array.isArray(i.agents)?i.agents.length:"?";console.log(Fe.dim(` Reachable \u2014 ${o.name} exposes ${a} agents`))}else console.log(Fe.yellow(` Peer returned HTTP ${r.status} \u2014 double-check the URL`))}catch(r){console.log(Fe.yellow(` Could not reach ${o.url} right now (${r?.cause?.code||r.message}) \u2014 verify VPN / Tailscale when the peer daemon is up`))}}var Zn=new zv().name("connect").description("connect a channel or mesh peer \u2014 no manual file editing required");Zn.command("telegram").description("pair a Telegram bot \u2014 persists token in .env, binds to an agent, auto-detects default chat").option("--agent <id>","agent to bind the bot to (skips the prompt)").option("--account <name>","account label in channels.telegram.accounts (defaults to agent id)").option("--skip-chat-capture","don't listen for the first message after pairing").option("-c, --config <path>","path to agentx.json").action(async e=>{await yf({agent:e.agent,account:e.account,configPath:e.config,skipChatCapture:!!e.skipChatCapture})});Zn.command("whatsapp").description("pair WhatsApp via QR (prints in terminal), then writes channels.whatsapp config").option("--agent <id>","default agent for inbound messages").option("--session-dir <path>","session directory (default: .agentx/whatsapp-sessions)").option("--skip-pair","skip QR pairing (use when session already exists)").option("-c, --config <path>","path to agentx.json").action(async e=>{await $f({agent:e.agent,sessionDir:e.sessionDir,skipPair:!!e.skipPair,configPath:e.config})});var xf=Zn.command("mesh").description("mesh invite + join \u2014 replaces manual MESH_TOKEN copy-paste");xf.command("invite").description("emit a single-use join link for another AgentX node").option("--url <url>","this node's URL as peers should reach it (Tailscale IP etc.)").option("-c, --config <path>","path to agentx.json").action(async e=>{await kf({url:e.url,configPath:e.config})});xf.command("join <link>").description("accept an invite link from another AgentX node").option("-c, --config <path>","path to agentx.json").action(async(e,t)=>{await vf(e,{configPath:t.config})});Zn.action(()=>{console.log(),console.log(Qn.bold(" agentx connect \u2014 which channel?")),console.log(),console.log(` ${Qn.cyan("agentx connect telegram")} \u2014 pair a Telegram bot`),console.log(` ${Qn.cyan("agentx connect whatsapp")} \u2014 pair WhatsApp via QR`),console.log(` ${Qn.cyan("agentx connect mesh invite")} \u2014 emit a mesh join link for another node`),console.log(` ${Qn.cyan("agentx connect mesh join <link>")} \u2014 accept a mesh invite`),console.log(),console.log(Qn.dim(" GitLab connect is the next slice.")),console.log()});le();import{Command as Yv}from"commander";import te from"chalk";var mn=new Yv().name("usage").description("token usage analysis and reporting");mn.command("today",{isDefault:!0}).description("show today's token usage").action(async()=>{try{let e=O(),[t,o]=e.node.bind.split(":"),s=await(await fetch(`http://${t||"127.0.0.1"}:${o}/usage`,{signal:AbortSignal.timeout(3e3)})).json();if(console.log(),console.log(te.bold(" Token Usage (last 7 days)")),console.log(),s.totalTasks===0){console.log(te.dim(" No tasks recorded yet")),console.log();return}let r=a=>a.toLocaleString();console.log(` Total: ${te.bold(r(s.totalTokens))} tokens across ${s.totalTasks} tasks`),console.log(` Input: ${r(s.totalInput)}`),console.log(` Output: ${r(s.totalOutput)}`),console.log(` Cache read: ${r(s.totalCacheRead)}`),console.log(` Cache create: ${r(s.totalCacheCreate)}`),s.cacheHitRatio>0&&console.log(` Cache hit: ${(s.cacheHitRatio*100).toFixed(1)}%`),s.totalErrors>0&&console.log(` Errors: ${te.red(String(s.totalErrors))}`),console.log(),console.log(te.bold(" By Agent:"));let i=Object.entries(s.byAgent||{});i.sort((a,c)=>c[1].total-a[1].total);for(let[a,c]of i){let l=r(c.total||c.input+c.output+c.cacheRead+c.cacheCreate),g=c.avgDuration?`${(c.avgDuration/1e3).toFixed(1)}s avg`:"";console.log(` ${te.cyan(a)}: ${l} tokens (${c.tasks} tasks) ${te.dim(g)}`)}console.log()}catch(e){e.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${e.message}`))}});mn.command("plan").description("show the Claude plan windows as Claude Code last reported them, and any hold on fresh sessions").option("--lift","lift the hold on fresh sessions now, without waiting for the reset time").option("--json","raw JSON output").action(async e=>{try{let t=O(),[o,n]=t.node.bind.split(":"),s=`http://${o||"127.0.0.1"}:${n}`,r=e.lift?await fetch(`${s}/usage/plan/lift`,{method:"POST",signal:AbortSignal.timeout(3e3)}):await fetch(`${s}/usage/plan`,{signal:AbortSignal.timeout(3e3)});if(!r.ok)throw new Error(`Daemon answered ${r.status}. It may be older than this command; restart it.`);let i=await r.json();if(e.json){console.log(JSON.stringify(i,null,2));return}let a=d=>d.replace(/_/g," ");if(console.log(),e.lift){let d=i.lifted.map(f=>a(f.window));console.log(d.length?` Lifted the hold on: ${d.join(", ")}. The next fresh session asks Claude again.`:te.dim(" No hold to lift.")),console.log();return}let c=i.now,l=new Set(i.holds.map(d=>d.window));console.log(te.bold(" Claude plan (as Claude Code last reported it)")),console.log(),i.provider.length===0&&console.log(te.dim(" No report yet. Claude Code reports on each turn; the list is empty after a daemon restart."));for(let d of i.provider){let f=d.usingOverage?"extra usage":d.status==="allowed_warning"?"nearly full":d.status,p=typeof d.utilization=="number"?`${Math.round(d.utilization*100)}% used`:"",u=Math.max(1,Math.round((d.resetsAt-c)/6e4)),h=d.resetsAt>c?u<60?`resets in ${u} min`:u<48*60?`resets in ${Math.round(u/60)} h`:`resets in ${Math.round(u/1440)} days`:"",y=l.has(d.window)?te.red("holding fresh sessions"):"";console.log(` ${a(d.window).padEnd(18)} ${f.padEnd(12)} ${[p,h,y].filter(Boolean).join(", ")}`)}console.log();let g=d=>d?` of ${d}`:"";console.log(` Fresh sessions started: ${i.lastHour}${g(i.maxPerHour)} in the last hour, ${i.last5h}${g(i.maxPer5h)} in the last 5 hours`),l.size&&console.log(te.dim(" To try again now: agentx usage plan --lift")),console.log()}catch(t){t.cause?.code==="ECONNREFUSED"?console.log(te.red(" Daemon not running. Start with: agentx daemon start")):console.log(te.red(` ${t.message}`))}});mn.command("report").description("run full session analysis (parses Claude Code JSONL files)").option("--days <n>","analyze last N days","7").action(async e=>{let{execSync:t}=await import("child_process"),{existsSync:o}=await import("fs"),{resolve:n}=await import("path"),s=n(process.cwd(),"scripts/token-report.py");if(!o(s)){console.log(te.red(` Script not found: ${s}`)),console.log(te.dim(" The token analyzer script should be at scripts/token-report.py"));return}console.log(te.dim(" Analyzing Claude Code sessions..."));try{t(`SINCE_DAYS=${e.days} python3 "${s}"`,{stdio:"inherit"})}catch{console.log(te.red(" Analysis failed. Is Python 3 installed?"))}});mn.command("channels").description("cost per channel over a fixed range of days, next to a saved baseline").requiredOption("--from <date>","first day, YYYY-MM-DD").requiredOption("--to <date>","last day, YYYY-MM-DD").option("--save <file>","write this range's figures to a JSON file").option("--baseline <file>","a file written by --save, shown beside this range").option("--json","raw JSON output").action(async e=>{let{readFileSync:t,writeFileSync:o}=await import("fs"),{TokenTracker:n}=await import("./token-tracker-W7DFDEFN.js"),{channelCosts:s,costPerTask:r}=await import("./usage-channels-KBLEC4NE.js"),i=u=>/^\d{4}-\d{2}-\d{2}$/.test(u)&&!Number.isNaN(Date.parse(u));if(!i(e.from)||!i(e.to)||e.from>e.to){console.log(te.red(" --from and --to must be YYYY-MM-DD, with --from not after --to")),process.exitCode=1;return}let a=s(new n,e.from,e.to);e.save&&o(e.save,JSON.stringify(a,null,2));let c=null;if(e.baseline)try{c=JSON.parse(t(e.baseline,"utf-8"))}catch(u){console.log(te.red(` Cannot read baseline ${e.baseline}: ${u.message}`)),process.exitCode=1;return}if(e.json){console.log(JSON.stringify(c?{baseline:c,current:a}:a,null,2));return}let l=u=>u===null?"-":`$${u.toFixed(u<10?3:2)}`,g=u=>`${(u/1e6).toFixed(1)}M`;console.log(),console.log(te.bold(` Cost per channel, ${a.from} to ${a.to} (${a.days} day(s) with data)`)),c&&console.log(te.dim(` Baseline: ${c.from} to ${c.to} (${c.days} day(s) with data)`)),console.log();let d=` ${"channel".padEnd(14)} ${"tasks".padStart(6)} ${"cache read".padStart(11)} ${"cache write".padStart(11)} ${"output".padStart(8)} ${"cost".padStart(10)} ${"per task".padStart(9)}`;console.log(te.dim(c?`${d} ${"baseline".padStart(9)} ${"change".padStart(7)}`:d));let p=[...new Set([...Object.keys(a.channels),...Object.keys(c?.channels||{})])].map(u=>[u,a.channels[u],c?.channels[u]]).sort((u,h)=>(h[1]?.cost||0)-(u[1]?.cost||0));p.push(["TOTAL",a.total,c?.total]);for(let[u,h,y]of p){let $=r(h),b=` ${u.padEnd(14)} ${String(h?.tasks||0).padStart(6)} ${g(h?.cacheRead||0).padStart(11)} ${g(h?.cacheCreate||0).padStart(11)} ${g(h?.output||0).padStart(8)} ${l(h?.cost||0).padStart(10)} ${l($).padStart(9)}`;if(c){let v=r(y),A=$!==null&&v?`${(($-v)/v*100).toFixed(0)}%`:"-";b+=` ${l(v).padStart(9)} ${A.padStart(7)}`}console.log(b)}console.log(),c&&console.log(te.dim(" change = cost per task against the baseline; the two ranges do not have the same tasks.")),e.save&&console.log(te.dim(` Saved ${e.save}`)),console.log()});mn.command("surfaces").description("which CLI commands and dashboard pages are actually used").option("--days <n>","window in days","30").option("--kind <kind>","cli | page (default: both)").option("--unused","list registered surfaces with ZERO recorded use instead").option("--json","raw JSON output").action(async e=>{let{listSurfaceUse:t}=await import("./surface-usage-WSY4SHHL.js"),o=e.kind==="cli"||e.kind==="page"?e.kind:void 0,n=t({kind:o,sinceDays:Number(e.days)||30});if(e.unused){let{buildProgram:r}=await import("./program-5RLTC6CR.js"),i=await r(),a=new Set(n.filter(d=>d.kind==="cli").map(d=>d.name)),c=[],l=(d,f)=>{for(let p of d.commands??[]){let u=f?`${f} ${p.name()}`:p.name();c.push(u),l(p,u)}};l(i,"");let g=c.filter(d=>!a.has(d)).sort();if(e.json){console.log(JSON.stringify({windowDays:Number(e.days)||30,unused:g},null,2));return}console.log(),console.log(te.bold(` Never used in the last ${e.days} days (${g.length}/${c.length})`)),console.log();for(let d of g)console.log(` ${te.dim("\xB7")} ${d}`);console.log(),console.log(te.dim(" Zero use is necessary but not sufficient to remove a surface \u2014")),console.log(te.dim(" it must also fail the impact test. See docs/architecture/surface-reduction.md")),console.log();return}if(e.json){console.log(JSON.stringify(n,null,2));return}if(n.length===0){console.log(),console.log(te.dim(` No surface usage recorded in the last ${e.days} days.`)),console.log(te.dim(" Counting starts once this build has been running for a while.")),console.log();return}console.log(),console.log(te.bold(` Surface usage \u2014 last ${e.days} days`)),console.log();let s="";for(let r of n){r.kind!==s&&(console.log(te.dim(` ${r.kind==="cli"?"CLI commands":"Dashboard pages"}`)),s=r.kind);let i=String(r.count).padStart(6),a=te.dim(`${r.days}d`);console.log(` ${te.cyan(i)} ${r.name.padEnd(28)} ${a}`)}console.log(),console.log(te.dim(` ${n.length} surface(s) with recorded use. See --unused for the rest.`)),console.log()});import{Command as Vv}from"commander";import Pe from"chalk";import{readFileSync as Xv}from"fs";import{resolve as Kv}from"path";le();var Io=new Vv().name("board").description("kanban board dashboard \u2014 visual work view over configured sources");Io.command("serve",{isDefault:!0}).description("start the dashboard server (live view always; boards if configured)").option("--port <n>","override dashboard.port").option("--bind <host>","override dashboard.bind (e.g. 0.0.0.0)").action(async e=>{try{try{Ul(Kv(process.cwd(),".env"))}catch{}let t=Qv(e.port,e.bind),{startBoardDashboard:o}=await import("./board-dashboard-42C7GGD7.js");o(t)}catch(t){console.log(Pe.red(` ${t.message}`)),process.env.DEBUG&&t.stack&&console.log(Pe.dim(t.stack)),process.exit(1)}});function Qv(e,t){try{let o=O();return e&&(o.dashboard.port=parseInt(e,10)),t&&(o.dashboard.bind=t),o}catch{return console.log(Pe.yellow(" No agentx.json found \u2014 starting dashboard in setup-only mode.")),console.log(Pe.dim(" Visit http://127.0.0.1:"+(e||"4202")+` to run the wizard.
|
|
497
497
|
`)),{node:{id:"setup",name:"Setup",bind:"127.0.0.1:18800"},providers:{},agents:{},channels:{},crons:{},mesh:{enabled:!1,peers:[],discovery:"static",healthCheck:{interval:60,timeout:10}},boards:[],dashboard:{enabled:!0,port:e?parseInt(e,10):4202,bind:t||"127.0.0.1",daemonUrl:"http://localhost:18800",daemons:[]},business:void 0,session:{staleMinutes:120}}}}Io.command("list").description("list configured boards").action(()=>{try{let e=O();if(!e.boards?.length){console.log(Pe.dim(`
|
|
498
498
|
No boards configured.
|
|
499
499
|
`));return}console.log();for(let t of e.boards){console.log(` ${Pe.cyan(t.id)} \u2014 ${t.name}`);let o=t.source;console.log(Pe.dim(` source: ${o.type}${o.projects?" ("+o.projects.join(", ")+")":""}`)),t.primaryToolLabel&&console.log(Pe.dim(` primary label: ${t.primaryToolLabel}`)),console.log(Pe.dim(` window: ${t.timeRangeDays} days`))}console.log()}catch(e){console.log(Pe.red(` ${e.message}`)),process.exit(1)}});Io.command("add <id>").description("add a GitLab board to agentx.json").requiredOption("--name <name>","human-readable board name").requiredOption("--projects <paths>","comma-separated GitLab project paths (e.g. 'globex/system,globex/website')").option("--label <label>","primary tool label ANDed into every query (e.g. 'Tool::Claude')").option("--days <n>","open-window time range in days","30").option("--closed-days <n>","closed-window in days","30").action((e,t)=>{try{Ys(o=>{if(Array.isArray(o.boards)||(o.boards=[]),o.boards.find(r=>r.id===e))throw new Error(`board "${e}" already exists`);let n=String(t.projects).split(",").map(r=>r.trim()).filter(Boolean);if(n.length===0)throw new Error("--projects must include at least one path");let s={id:e,name:t.name,source:{type:"gitlab",projects:n},timeRangeDays:parseInt(t.days,10)||30,closedWindowDays:parseInt(t.closedDays,10)||30};return t.label&&(s.primaryToolLabel=t.label),o.boards.push(s),`added board "${e}" (${n.join(", ")})`})}catch(o){console.log(Pe.red(` ${o.message}`)),process.exit(1)}});Io.command("edit <id>").description("edit board fields without re-creating it").option("--name <name>","rename").option("--projects <paths>","comma-separated GitLab project paths (replaces the list)").option("--label <label>","primary tool label (set to '-' to clear)").option("--days <n>","open-window time range in days").option("--closed-days <n>","closed-window in days").action((e,t)=>{try{Ys(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=[];if(t.name&&(s.name=t.name,r.push(`name="${t.name}"`)),t.projects){let i=String(t.projects).split(",").map(a=>a.trim()).filter(Boolean);if(i.length===0)throw new Error("--projects must include at least one path");s.source={...s.source||{type:"gitlab"},type:"gitlab",projects:i},r.push(`projects=${i.length}`)}if(t.label!==void 0&&(t.label==="-"?(delete s.primaryToolLabel,r.push("label cleared")):(s.primaryToolLabel=t.label,r.push(`label="${t.label}"`))),t.days&&(s.timeRangeDays=parseInt(t.days,10)||s.timeRangeDays,r.push(`days=${s.timeRangeDays}`)),t.closedDays&&(s.closedWindowDays=parseInt(t.closedDays,10)||s.closedWindowDays,r.push(`closed-days=${s.closedWindowDays}`)),r.length===0)throw new Error("no changes \u2014 pass at least one option");return`board "${e}" updated (${r.join(", ")})`})}catch(o){console.log(Pe.red(` ${o.message}`)),process.exit(1)}});var Lc=Io.command("column").description("manage a board's columns (add / remove / edit / list)");Lc.command("list <boardId>").description("list columns on a board, in order").action(e=>{try{let o=(JSON.parse(Xv("agentx.json","utf-8")).boards||[]).find(s=>s.id===e);if(!o)throw new Error(`board "${e}" not found`);let n=o.columns||[];if(n.length===0){console.log(Pe.dim(" no columns (board falls back to GitLab default flow)"));return}for(let s of n){let r=s.kind==="scoped-label"?`scoped="${s.scopedLabel}"`:s.kind==="label"?`label="${s.mapsToLabel||""}"`:s.kind==="open-backlog"?`prefix="${s.scopedPrefix}"`:s.kind;console.log(` ${Pe.cyan(s.id.padEnd(12))} ${s.title.padEnd(14)} ${Pe.dim(r)}`)}}catch(t){console.log(Pe.red(` ${t.message}`)),process.exit(1)}});Lc.command("add <boardId> <columnId>").description("add a column to a board").requiredOption("--title <title>","column title").option("--kind <kind>","open-backlog | scoped-label | closed | label","scoped-label").option("--scoped <label>","for kind=scoped-label, the full label (e.g. 'Status::Doing')").option("--label <label>","for kind=label, the label name to add/remove").option("--scoped-prefix <prefix>","for kind=open-backlog/scoped-label","Status").option("--accent <color>","hex/CSS color for the column accent bar").action((e,t,o)=>{try{Ys(n=>{let r=(Array.isArray(n.boards)?n.boards:[]).find(a=>a.id===e);if(!r)throw new Error(`board "${e}" not found`);if(r.columns=r.columns||[],r.columns.find(a=>a.id===t))throw new Error(`column "${t}" already exists on board "${e}"`);let i={id:t,title:o.title,kind:o.kind,scopedPrefix:o.scopedPrefix};if(o.kind==="scoped-label"){if(!o.scoped)throw new Error("--scoped required for kind=scoped-label");i.scopedLabel=o.scoped}if(o.kind==="label"){if(!o.label)throw new Error("--label required for kind=label");i.mapsToLabel=o.label}return o.accent&&(i.accent=o.accent),r.columns.push(i),`column "${t}" added to board "${e}"`})}catch(n){console.log(Pe.red(` ${n.message}`)),process.exit(1)}});Lc.command("remove <boardId> <columnId>").alias("rm").description("remove a column from a board").action((e,t)=>{try{Ys(o=>{let s=(Array.isArray(o.boards)?o.boards:[]).find(i=>i.id===e);if(!s)throw new Error(`board "${e}" not found`);let r=(s.columns||[]).length;if(s.columns=(s.columns||[]).filter(i=>i.id!==t),s.columns.length===r)throw new Error(`column "${t}" not found`);return`column "${t}" removed from board "${e}"`})}catch(o){console.log(Pe.red(` ${o.message}`)),process.exit(1)}});Io.command("remove <id>").alias("rm").description("remove a board from agentx.json").action(e=>{try{Ys(t=>{if(!Array.isArray(t.boards)||t.boards.length===0)throw new Error("no boards configured");let o=t.boards.length;if(t.boards=t.boards.filter(n=>n.id!==e),t.boards.length===o)throw new Error(`board "${e}" not found`);return`removed board "${e}"`})}catch(t){console.log(Pe.red(` ${t.message}`)),process.exit(1)}});function Ys(e){let{summary:t,backupPath:o}=vt(n=>e(n));console.log(Pe.green(`
|
|
@@ -757,7 +757,7 @@ Restart the daemon to activate.
|
|
|
757
757
|
dist/
|
|
758
758
|
*.log
|
|
759
759
|
.env
|
|
760
|
-
`}import{Command as gS}from"commander";import Ke from"chalk";import{writeFileSync as mS,mkdirSync as uS,existsSync as Gi,readFileSync as Fh,appendFileSync as qh}from"fs";import{resolve as ms,dirname as Bh}from"path";import{homedir as pl}from"os";var Jh=new gS().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-
|
|
760
|
+
`}import{Command as gS}from"commander";import Ke from"chalk";import{writeFileSync as mS,mkdirSync as uS,existsSync as Gi,readFileSync as Fh,appendFileSync as qh}from"fs";import{resolve as ms,dirname as Bh}from"path";import{homedir as pl}from"os";var Jh=new gS().name("completion").description("generate a shell completion script for agentx").option("-s, --shell <shell>","shell to generate completion for: zsh|bash|fish","zsh").option("-i, --install","install the completion script to a default path for the shell").option("-o, --output <path>","write the script to this path (overrides default install path)").option("-y, --yes","skip confirmation prompts (non-interactive)").action(async e=>{let{buildProgram:t}=await import("./program-5RLTC6CR.js"),o=await t(),n=String(e.shell||"zsh").toLowerCase(),s;switch(n){case"zsh":s=hS(o);break;case"bash":s=kS(o);break;case"fish":s=vS(o);break;default:console.error(Ke.red(`unsupported shell: ${n}`)),console.error(Ke.dim("supported: zsh, bash, fish")),process.exit(1)}if(!e.install&&!e.output){process.stdout.write(s);return}let r=e.output?ms(String(e.output)):pS(n);uS(Bh(r),{recursive:!0}),mS(r,s),console.log(Ke.green(`\u2713 Wrote ${n} completion to:`)),console.log(` ${r}`),console.log(),fS(n,r,!!e.yes)});function pS(e){let t=pl();switch(e){case"zsh":return ms(t,".zsh","completions","_agentx");case"bash":return ms(t,".bash_completion.d","agentx.bash");case"fish":return ms(t,".config","fish","completions","agentx.fish");default:throw new Error(`unsupported shell: ${e}`)}}function fS(e,t,o){if(e==="zsh"){let n=ms(pl(),".zshrc"),s=Bh(t),r=`fpath=(${s} $fpath)`,i="autoload -U compinit && compinit",a=Gi(n)?Fh(n,"utf-8"):"",c=!a.includes(s),l=!/autoload\s+-U\s+compinit/.test(a);if(!c&&!l){console.log(Ke.dim("~/.zshrc already has fpath + compinit wired up. Run `exec zsh` to pick up the new script."));return}if(o&&Gi(n)){let g=["","# agentx completion"];c&&g.push(r),l&&g.push(i),qh(n,g.join(`
|
|
761
761
|
`)+`
|
|
762
762
|
`),console.log(Ke.green("\u2713 Patched ~/.zshrc")),console.log(Ke.dim("Reload your shell: exec zsh"));return}console.log(Ke.dim("Add this to ~/.zshrc if not already present:")),c&&console.log(Ke.cyan(` ${r}`)),l&&console.log(Ke.cyan(` ${i}`)),console.log(),console.log(Ke.dim("Then reload: exec zsh")),console.log(Ke.dim("Or rerun with --yes to auto-patch ~/.zshrc"));return}if(e==="bash"){let n=ms(pl(),".bashrc"),s=`[ -f "${t}" ] && source "${t}"`;if((Gi(n)?Fh(n,"utf-8"):"").includes(t)){console.log(Ke.dim("~/.bashrc already sources this file. Start a new shell to pick it up."));return}if(o&&Gi(n)){qh(n,`
|
|
763
763
|
# agentx completion
|
|
@@ -773,4 +773,4 @@ ${xS({...t,category:e.category})}`),g&&a.set(l.id,g)}let c=`https://github.com/$
|
|
|
773
773
|
${o.url}`)}catch(t){console.error(ps.red(` ${t.message}`)),process.exitCode=1}});ar.command("draft <file>").description("turn a draft JSON file ({category, title, fields}) into a pre-filled issue form link; '-' reads stdin").requiredOption("--model <model>","the model that wrote the draft").option("--models <pathOrUrl>","model list to read",hl).action(async(e,t)=>{try{let o=await $l(t.models);if(!yl(t.model,o)){console.log(wl(t.model,o)),process.exitCode=1;return}let n=e==="-"?await ES():await AS(e,"utf8"),s=JSON.parse(n),{version:r}=await yr(),i=Yh({...s,fields:s.fields??{}},{model:t.model,version:r??"unknown"});console.log(i)}catch(o){console.error(ps.red(` ${o.message}`)),process.exitCode=1}});async function ES(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString("utf8")}async function HM(){let e=await yr(),t=new CS().name("agentx").description("self-hosted multi-agent orchestrator \u2014 Telegram, WhatsApp, crons, A2A mesh, wiki knowledge").version(e.version||"1.0.0","-v, --version","display the version number");t.hook("preAction",(o,n)=>{let s=cm(n);lm(s)&&am("cli",s)});for(let o of[Xm,Vm,Zn,jn,zo,Rt,Hg,Yo,Hr,ro,ao,gn,uf,Ro,Gr,fh,Eo,Pu,Mu,Hu,Us,np,ap,_u,dp,gp,Op,Np,jp,Et,mn,kh,Ts,ko,Jh,ar])t.addCommand(o);for(let o of Xh)t.addCommand(o,{hidden:!0});return t.addHelpText("after",()=>{let o=Xh.map(n=>n.name()).sort();return["",`Advanced (${o.length}, hidden \u2014 run \`agentx <command> --help\` for any of them):`,OS(o,74," "),""].join(`
|
|
774
774
|
`)}),t}var Xh=[J,os,lo,Ut,Ns,zn,Ve,co,Io,ln,is,as,So,ut,Fn,ri,bi,cn,mh,uh,so,xt,Am,Xo,rr,Ja,_o,yt,Mn,Ga,Li,Zt,go,jh,_h,$h];function OS(e,t,o){let n=[],s="";for(let r of e)s&&s.length+r.length+2>t&&(n.push(o+s),s=""),s+=(s?", ":"")+r;return s&&n.push(o+s),n.join(`
|
|
775
775
|
`)}export{HM as buildProgram};
|
|
776
|
-
//# sourceMappingURL=program-
|
|
776
|
+
//# sourceMappingURL=program-5RLTC6CR.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a,b,c,d,e,f,g,h,i}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=push-bridge-
|
|
1
|
+
import{a,b,c,d,e,f,g,h,i}from"./chunk-JAML6222.js";import"./chunk-YMX3QCV7.js";import"./chunk-JWDJMFU6.js";import"./chunk-5HLD66CW.js";import"./chunk-IS2IWRP7.js";import"./chunk-QIJLFPWE.js";export{i as PushRosterSync,a as ROSTER_CHECK_MS,b as ROSTER_RESEND_MS,h as handlePushBridge,g as peerOrigins,d as pushBridgeCaller,c as pushOrigin,f as relayTokenProblem,e as scopedPushTarget};
|
|
2
|
+
//# sourceMappingURL=push-bridge-P7HH25VN.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=registry-
|
|
1
|
+
import{$ as j,S as a,T as b,U as c,V as d,W as e,X as f,Y as g,Z as h,_ as i,aa as k,ba as l,ca as m,da as n}from"./chunk-6XMISPQD.js";import"./chunk-7V73QTQ7.js";import"./chunk-QSKG754X.js";import"./chunk-MEFPXHQJ.js";import"./chunk-SZDACK6O.js";import"./chunk-W4YR2RO2.js";import"./chunk-AFRHKA7B.js";import"./chunk-DBJUGKX2.js";import"./chunk-JIJDBCV7.js";import"./chunk-3UOTLMXD.js";import"./chunk-36AXN6ZB.js";import"./chunk-PE5V2LI7.js";import"./chunk-GQ76J72O.js";import"./chunk-ILEC3IAV.js";import"./chunk-J3SOEFRE.js";import"./chunk-SIU6STB2.js";import"./chunk-X5C5W3E4.js";import"./chunk-GV7S5BAX.js";import"./chunk-GSX4NK2N.js";import"./chunk-VWTBHLMX.js";import"./chunk-TFH6S7IT.js";import"./chunk-XVYIPVSC.js";import"./chunk-OWNQ2FD4.js";import"./chunk-KEXBEUSU.js";import"./chunk-ROLSSYXE.js";import"./chunk-SK47VJMQ.js";import"./chunk-SKSYII3K.js";import"./chunk-VVX4RXMV.js";import"./chunk-WPNRDEHW.js";import"./chunk-MWNCS57L.js";import"./chunk-4LWFJ4MZ.js";import"./chunk-BIJHMWXK.js";import"./chunk-QGSUENRK.js";import"./chunk-MTDVAO5C.js";import"./chunk-72SZI2UW.js";import"./chunk-FCPTN6NF.js";import"./chunk-MCI3DIWW.js";import"./chunk-MYVHVJWZ.js";import"./chunk-6TURWSMN.js";import"./chunk-AV7T3SYT.js";import"./chunk-Y5MFVVTM.js";import"./chunk-QD6IICK7.js";import"./chunk-QOYAX2FT.js";import"./chunk-2PJKGZWP.js";import"./chunk-7I7IEX4S.js";import"./chunk-DSYKYZMT.js";import"./chunk-HJCFLGVT.js";import"./chunk-BRK6M6LA.js";import"./chunk-UIBUZ2N3.js";import"./chunk-2QNT5JDS.js";import"./chunk-RGDKHYY2.js";import"./chunk-QIJLFPWE.js";export{m as AgentRegistry,a as EDIT_TOOL_INSTRUCTION,h as TRACE_STEP_SUMMARY_BYTES,e as buildEntryMeta,f as buildEventDigest,g as buildWikiContext,i as clipForTrace,b as codingInstructions,l as emitTraceStepsFromStreamEvent,k as firstMissingRequiredTool,d as getGlobalRegistry,n as richReplyPrompt,c as setGlobalRegistry,j as tallyToolUses};
|
|
2
|
+
//# sourceMappingURL=registry-RH5NFDL7.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "agentix-cli",
|
|
3
|
-
"version": "0.138.
|
|
3
|
+
"version": "0.138.1",
|
|
4
4
|
"description": "AI operations layer for small and medium businesses. Routes Telegram, WhatsApp, GitLab, GitHub, crons, webhooks, and mesh tasks to AI agents. Web wizard for operators, CLI for engineers. Self-hosted.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|