dispach 0.1.2 → 0.1.3
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/README.md +134 -85
- package/dist/App-qfqvx9c7.js +11 -0
- package/dist/{App-b1yrwrcq.js.map → App-qfqvx9c7.js.map} +6 -7
- package/dist/ConfigEditor-apcnj4nj.js +6 -0
- package/dist/{ConfigEditor-n8hdw6r7.js.map → ConfigEditor-apcnj4nj.js.map} +2 -2
- package/dist/KeyProbe-ya5t3v3v.js +5 -0
- package/dist/{KeyProbe-9jjeze5r.js.map → KeyProbe-ya5t3v3v.js.map} +2 -2
- package/dist/Picker-b7mn0mjg.js +5 -0
- package/dist/{Picker-hfeh1g6m.js.map → Picker-b7mn0mjg.js.map} +1 -1
- package/dist/SessionPicker-vacfwczg.js +5 -0
- package/dist/{SessionPicker-zyqkg4dn.js.map → SessionPicker-vacfwczg.js.map} +2 -2
- package/dist/SkillBrowser-66ntwaa9.js +5 -0
- package/dist/{SkillBrowser-3qdp8080.js.map → SkillBrowser-66ntwaa9.js.map} +1 -1
- package/dist/WizardApp-123998yh.js +5 -0
- package/dist/{WizardApp-vzpbydy3.js.map → WizardApp-123998yh.js.map} +3 -3
- package/dist/agents.d.ts +19 -3
- package/dist/agents.d.ts.map +1 -1
- package/dist/channels-q4fwqq87.js +31 -0
- package/dist/channels-q4fwqq87.js.map +10 -0
- package/dist/channels.d.ts +26 -0
- package/dist/channels.d.ts.map +1 -0
- package/dist/client.js +10 -10
- package/dist/client.js.map +3 -3
- package/dist/config-64q4mgxc.js +24 -0
- package/dist/{config-g7za9x13.js.map → config-64q4mgxc.js.map} +2 -2
- package/dist/{credential-npr6z8c8.js → credential-2sj7vsmw.js} +5 -5
- package/dist/{credential-npr6z8c8.js.map → credential-2sj7vsmw.js.map} +1 -1
- package/dist/daemon.d.ts.map +1 -1
- package/dist/index-0k3w2mxf.js +6 -0
- package/dist/{index-hwpvhaza.js.map → index-0k3w2mxf.js.map} +1 -1
- package/dist/index-1s81qstp.js +6 -0
- package/dist/{index-v8e92nfw.js.map → index-1s81qstp.js.map} +1 -1
- package/dist/index-2rycma8x.js +12 -0
- package/dist/{index-258d8bzg.js.map → index-2rycma8x.js.map} +4 -3
- package/dist/index-2zye08c4.js +6 -0
- package/dist/{index-vgc3y3rm.js.map → index-2zye08c4.js.map} +2 -2
- package/dist/{index-gme2egyq.js → index-3km1jwh7.js} +4 -4
- package/dist/{index-gme2egyq.js.map → index-3km1jwh7.js.map} +1 -1
- package/dist/index-3mtgcvkq.js +429 -0
- package/dist/index-3mtgcvkq.js.map +11 -0
- package/dist/index-4knb5vjm.js +90 -0
- package/dist/index-4knb5vjm.js.map +13 -0
- package/dist/{index-3g3ny01d.js → index-5nwwekk0.js} +4 -4
- package/dist/{index-3g3ny01d.js.map → index-5nwwekk0.js.map} +1 -1
- package/dist/index-5rm7dwq4.js +6 -0
- package/dist/index-5rm7dwq4.js.map +11 -0
- package/dist/index-79epttpm.js +6 -0
- package/dist/index-79epttpm.js.map +10 -0
- package/dist/{index-4cf6v9nb.js → index-7yk1zvds.js} +4 -4
- package/dist/{index-4cf6v9nb.js.map → index-7yk1zvds.js.map} +1 -1
- package/dist/index-81gb4ey4.js +6 -0
- package/dist/{index-4z7axw4r.js.map → index-81gb4ey4.js.map} +1 -1
- package/dist/index-8a5d8sfe.js +6 -0
- package/dist/{index-0d93hyfc.js.map → index-8a5d8sfe.js.map} +1 -1
- package/dist/index-a21zyy54.js +6 -0
- package/dist/index-a21zyy54.js.map +9 -0
- package/dist/index-b6da6c16.js +92 -0
- package/dist/index-b6da6c16.js.map +15 -0
- package/dist/index-byxrc961.js +903 -0
- package/dist/{index-tv4yv7d2.js.map → index-byxrc961.js.map} +16 -15
- package/dist/{index-ammv5st7.js → index-cgfg6t5a.js} +6 -6
- package/dist/{index-ammv5st7.js.map → index-cgfg6t5a.js.map} +1 -1
- package/dist/{index-s9mbq7h6.js → index-ehzwdnc3.js} +4 -4
- package/dist/{index-s9mbq7h6.js.map → index-ehzwdnc3.js.map} +1 -1
- package/dist/index-fzmmhmk2.js +7 -0
- package/dist/index-fzmmhmk2.js.map +11 -0
- package/dist/index-g3pk0kc0.js +6 -0
- package/dist/{index-9r0wyj6w.js.map → index-g3pk0kc0.js.map} +2 -2
- package/dist/index-h828nk24.js +153 -0
- package/dist/index-h828nk24.js.map +20 -0
- package/dist/{index-02dn6m2j.js → index-jq999vcw.js} +5 -5
- package/dist/{index-02dn6m2j.js.map → index-jq999vcw.js.map} +2 -2
- package/dist/index-k2aq5bg0.js +9 -0
- package/dist/{index-6p999cx4.js.map → index-k2aq5bg0.js.map} +4 -6
- package/dist/{index-cqqb6gaq.js → index-k3y8y3wj.js} +5 -5
- package/dist/{index-cqqb6gaq.js.map → index-k3y8y3wj.js.map} +1 -1
- package/dist/index-k59wwdgz.js +9 -0
- package/dist/{index-ff514z3y.js.map → index-k59wwdgz.js.map} +3 -5
- package/dist/index-nmnnwa02.js +6 -0
- package/dist/{index-6q4wf8e3.js.map → index-nmnnwa02.js.map} +1 -1
- package/dist/index-nn3tk25c.js +6 -0
- package/dist/{index-d4x6yvqh.js.map → index-nn3tk25c.js.map} +3 -4
- package/dist/index-q0hxh57v.js +126 -0
- package/dist/index-q0hxh57v.js.map +14 -0
- package/dist/index-srmhk9g5.js +11 -0
- package/dist/index-srmhk9g5.js.map +11 -0
- package/dist/index-swtyfhha.js +6 -0
- package/dist/{index-fex44816.js.map → index-swtyfhha.js.map} +2 -2
- package/dist/index-whq42sat.js +6 -0
- package/dist/{index-h9mw7b9d.js.map → index-whq42sat.js.map} +1 -1
- package/dist/{index-j7gyr5nx.js → index-wzsmh5j0.js} +7 -7
- package/dist/{index-j7gyr5nx.js.map → index-wzsmh5j0.js.map} +1 -1
- package/dist/{index-j55s3ehk.js → index-x7v1zq89.js} +7 -7
- package/dist/{index-j55s3ehk.js.map → index-x7v1zq89.js.map} +2 -2
- package/dist/index-xhzmv4dh.js +66 -0
- package/dist/index-xhzmv4dh.js.map +12 -0
- package/dist/index-xmv47vs0.js +6 -0
- package/dist/{index-gz9x25tz.js.map → index-xmv47vs0.js.map} +2 -2
- package/dist/index-y4c32wn7.js +6 -0
- package/dist/{index-qdbq8crg.js.map → index-y4c32wn7.js.map} +2 -2
- package/dist/index-yjcdp72k.js +6 -0
- package/dist/{index-tf71ap9v.js.map → index-yjcdp72k.js.map} +1 -1
- package/dist/index-zn24991r.js +6 -0
- package/dist/index-zn24991r.js.map +10 -0
- package/dist/index.js +374 -443
- package/dist/index.js.map +23 -27
- package/dist/init.d.ts.map +1 -1
- package/dist/lib/channel-actions.d.ts +103 -0
- package/dist/lib/channel-actions.d.ts.map +1 -0
- package/dist/lib/chat-frame.d.ts +12 -1
- package/dist/lib/chat-frame.d.ts.map +1 -1
- package/dist/lib/commands.d.ts +13 -0
- package/dist/lib/commands.d.ts.map +1 -1
- package/dist/lib/const.d.ts +1 -1
- package/dist/lib/host-actions.d.ts +121 -0
- package/dist/lib/host-actions.d.ts.map +1 -0
- package/dist/lib/init-flow.d.ts +32 -0
- package/dist/lib/init-flow.d.ts.map +1 -1
- package/dist/lib/init-whatsapp.d.ts +52 -0
- package/dist/lib/init-whatsapp.d.ts.map +1 -0
- package/dist/lib/plugin-install.d.ts +120 -0
- package/dist/lib/plugin-install.d.ts.map +1 -0
- package/dist/lib/providers.d.ts.map +1 -1
- package/dist/lib/provision.d.ts.map +1 -1
- package/dist/lib/readme-table.d.ts +15 -0
- package/dist/lib/readme-table.d.ts.map +1 -0
- package/dist/lib/sandbox.d.ts +15 -0
- package/dist/lib/sandbox.d.ts.map +1 -1
- package/dist/lib/schema.d.ts +34 -1
- package/dist/lib/schema.d.ts.map +1 -1
- package/dist/lib/subcommand.d.ts.map +1 -1
- package/dist/lib/web-url.d.ts +15 -0
- package/dist/lib/web-url.d.ts.map +1 -0
- package/dist/lib/wizard.d.ts.map +1 -1
- package/dist/memory.d.ts.map +1 -1
- package/dist/model.d.ts.map +1 -1
- package/dist/plugins.d.ts +27 -8
- package/dist/plugins.d.ts.map +1 -1
- package/dist/restart.d.ts +21 -0
- package/dist/restart.d.ts.map +1 -0
- package/dist/run.d.ts.map +1 -1
- package/dist/schedules.d.ts.map +1 -1
- package/dist/serve.d.ts.map +1 -1
- package/dist/sessions.d.ts.map +1 -1
- package/dist/skills.d.ts.map +1 -1
- package/dist/status.d.ts +16 -0
- package/dist/status.d.ts.map +1 -0
- package/dist/tools.d.ts.map +1 -1
- package/dist/validate.d.ts.map +1 -1
- package/dist/web-923c7f5e.js +14 -0
- package/dist/{web-vkb16r62.js.map → web-923c7f5e.js.map} +3 -3
- package/dist/web.d.ts +2 -13
- package/dist/web.d.ts.map +1 -1
- package/dist/workspace.d.ts.map +1 -1
- package/dist/wrapper-0w9b3my0.js +11 -0
- package/dist/wrapper-0w9b3my0.js.map +23 -0
- package/package.json +6 -3
- package/dist/App-b1yrwrcq.js +0 -11
- package/dist/ConfigEditor-n8hdw6r7.js +0 -6
- package/dist/KeyProbe-9jjeze5r.js +0 -5
- package/dist/Picker-hfeh1g6m.js +0 -5
- package/dist/SessionPicker-zyqkg4dn.js +0 -5
- package/dist/SkillBrowser-3qdp8080.js +0 -5
- package/dist/WizardApp-vzpbydy3.js +0 -5
- package/dist/config-g7za9x13.js +0 -24
- package/dist/index-0d93hyfc.js +0 -6
- package/dist/index-1c5113t4.js +0 -66
- package/dist/index-1c5113t4.js.map +0 -12
- package/dist/index-258d8bzg.js +0 -12
- package/dist/index-4z7axw4r.js +0 -6
- package/dist/index-6p999cx4.js +0 -9
- package/dist/index-6q4wf8e3.js +0 -6
- package/dist/index-9r0wyj6w.js +0 -6
- package/dist/index-d4x6yvqh.js +0 -6
- package/dist/index-fecm8xe7.js +0 -77
- package/dist/index-fecm8xe7.js.map +0 -12
- package/dist/index-fex44816.js +0 -6
- package/dist/index-ff514z3y.js +0 -14
- package/dist/index-gz9x25tz.js +0 -6
- package/dist/index-h9mw7b9d.js +0 -6
- package/dist/index-hwpvhaza.js +0 -6
- package/dist/index-mtn0g9vc.js +0 -7
- package/dist/index-mtn0g9vc.js.map +0 -11
- package/dist/index-qdbq8crg.js +0 -6
- package/dist/index-tf71ap9v.js +0 -6
- package/dist/index-ttwyrdjs.js +0 -427
- package/dist/index-ttwyrdjs.js.map +0 -11
- package/dist/index-tv4yv7d2.js +0 -903
- package/dist/index-ty24n0jh.js +0 -167
- package/dist/index-ty24n0jh.js.map +0 -19
- package/dist/index-v8e92nfw.js +0 -6
- package/dist/index-vgc3y3rm.js +0 -6
- package/dist/index-whaw4b18.js +0 -6
- package/dist/index-whaw4b18.js.map +0 -10
- package/dist/web-vkb16r62.js +0 -14
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createInterface as w}from"node:readline";async function
|
|
3
|
-
${u} [y/N] `,t)});return/^y(es)?$/i.test(s.trim())}finally{i.close()}}async function
|
|
4
|
-
${u} `,a)})).trim()===o}finally{s.close()}}async function
|
|
2
|
+
import{createInterface as w}from"node:readline";async function CA(u,o={}){let e=o.input??process.stdin,r=o.output??process.stdout;if(e.isTTY!==!0)return!1;let i=w({input:e,output:r});try{let s=await new Promise((t)=>{i.question(`
|
|
3
|
+
${u} [y/N] `,t)});return/^y(es)?$/i.test(s.trim())}finally{i.close()}}async function vo(u,o,e={}){let r=e.input??process.stdin,i=e.output??process.stdout;if(r.isTTY!==!0)return!1;let s=w({input:r,output:i});try{return(await new Promise((a)=>{s.question(`
|
|
4
|
+
${u} `,a)})).trim()===o}finally{s.close()}}async function ut(u,o={}){let e=o.input??process.stdin,r=o.output??process.stdout;if(e.isTTY!==!0)return;r.write(`
|
|
5
5
|
${u} `);let i=typeof e.setRawMode==="function";if(i)e.setRawMode?.(!0);e.resume?.();try{return await new Promise((s)=>{let t="",a=!1,d=!1,l=(f)=>{e.removeListener("data",p),r.write(`
|
|
6
6
|
`),s(f)},p=(f)=>{let m=typeof f==="string"?f:f.toString("utf8");for(let c of m){let n=c.charCodeAt(0);if(d){if(n>=64&&n<=126)d=!1;continue}if(a){if(a=!1,c==="["||c==="O")d=!0;continue}if(n===27){a=!0;continue}if(n===13||n===10)return l(t);if(n===3)return l(void 0);if(n===4)return l(t===""?void 0:t);if(n===127||n===8){if(t.length>0)t=t.slice(0,-1),r.write("\b \b");continue}if(n<32)continue;t+=c,r.write("*")}};e.on("data",p)})}finally{if(i)e.setRawMode?.(!1)}}
|
|
7
|
-
export{
|
|
7
|
+
export{CA,vo,ut};
|
|
8
8
|
|
|
9
|
-
//# debugId=
|
|
10
|
-
//# sourceMappingURL=index-
|
|
9
|
+
//# debugId=FD67341C37D00B3064756E2164756E21
|
|
10
|
+
//# sourceMappingURL=index-cgfg6t5a.js.map
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * A yes/no question on the plain path.\n *\n * One question, one place. The wizard has its own confirm *screen* under Ink and the picker has a\n * selection; what was missing was the shape a single command needs before doing something outside its\n * own workspace — and the only current caller, `terminal-setup`, is the only command that does that.\n *\n * **Not a TTY means no.** A piped or CI run cannot answer, so the safe answer is the one that changes\n * nothing — and the caller reports that nothing was written rather than treating it as a failure.\n * Defaulting to yes here would make a redirected invocation edit somebody's editor keybindings, which is\n * the kind of surprise that is only discovered later.\n *\n * Deliberately not a general prompt library. A second kind of question can have a second function; a\n * configurable one would grow options nobody needs and hide the TTY rule above inside them. There are\n * three now — `askExactly` is a different bar, and `askSecret` is a different *channel*, because a\n * value that must not be echoed cannot go through readline at all.\n */\n\nimport { createInterface } from \"node:readline\"\n\nexport interface ConfirmOptions {\n /** Injected by tests. The process streams otherwise. */\n readonly input?: NodeJS.ReadableStream & { isTTY?: boolean }\n readonly output?: NodeJS.WritableStream\n}\n\nexport async function askYesNo(question: string, options: ConfirmOptions = {}): Promise<boolean> {\n const input = options.input ?? process.stdin\n const output = options.output ?? process.stdout\n if (input.isTTY !== true) return false\n\n const rl = createInterface({ input, output })\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(`\\n${question} [y/N] `, resolve)\n })\n return /^y(es)?$/i.test(answer.trim())\n } finally {\n // Always closed: a readline left open holds the event loop and the process never exits.\n rl.close()\n }\n}\n\n/**\n * A question answered only by typing something back exactly.\n *\n * The bar for an irreversible, multi-part deletion. `askYesNo` is one keypress, which is right for\n * \"shall I edit your keybindings\" and too cheap for \"delete this agent, its conversations and its\n * memory\" — a stray `y` against the wrong listing is a mistake with nothing to undo it, and the whole\n * point of showing the listing first is that somebody reads it. Typing the name is what proves they did.\n *\n * Compared after trimming and nothing else. Case is **not** folded: an agent's ref is the name of a\n * directory, so `Milo` and `milo` are two different agents on a case-sensitive filesystem, and\n * accepting either here would accept the wrong one somewhere else.\n *\n * Not a TTY means no, for the reason `askYesNo` has it: a piped or CI run cannot answer, and the safe\n * answer is the one that changes nothing. The caller reports that nothing was deleted, and `--yes` is\n * how a script says it meant it.\n */\nexport async function askExactly(\n question: string,\n expected: string,\n options: ConfirmOptions = {},\n): Promise<boolean> {\n const input = options.input ?? process.stdin\n const output = options.output ?? process.stdout\n if (input.isTTY !== true) return false\n\n const rl = createInterface({ input, output })\n try {\n const answer = await new Promise<string>((resolve) => {\n rl.question(`\\n${question} `, resolve)\n })\n return answer.trim() === expected\n } finally {\n rl.close()\n }\n}\n\n/**\n * A value typed at a prompt and never echoed. `undefined` means cancelled or unavailable.\n *\n * ## Why this is not readline\n *\n * readline echoes what it reads, and the documented way to stop it is to overwrite a private method on\n * the interface — which needs a cast this codebase does not allow. Reading the bytes is a dozen more\n * lines and it is the honest version: raw mode on, one `*` written per character, raw mode off in a\n * `finally` so a thrown error cannot leave the terminal unable to echo anything the person types next.\n *\n * ## Why a secret never comes from an argument\n *\n * The alternative was `--value`, and it puts the secret in two places nobody intends: the shell's\n * history file, and `ps` output, where every local process can read it for the lifetime of the call.\n * That is the same exposure `renderPlist` throws to prevent — launchd echoes a job's environment in\n * plaintext, so a plist carries no secret — and the reasoning does not change because the process is\n * short-lived. Not a TTY returns `undefined` rather than reading a pipe, so a CI run is *told* that\n * nothing was written instead of a secret arriving from somewhere the caller did not audit.\n *\n * ^C cancels and ^D on an empty line cancels; both return `undefined`, and the caller reports that\n * nothing changed. Backspace is honoured because a mistyped key in a value you cannot see is otherwise\n * unrecoverable without starting the command again.\n */\n/**\n * The narrow surface `askSecret` touches, rather than a widened `ConfirmOptions.input`.\n *\n * `process.stdin`'s declared `on` is a union of overloads, and intersecting that with an object type\n * makes it uncallable — the compiler cannot pick a signature. Declaring only what is used and asserting\n * the real stream against it once keeps the check where it is useful: anything else this function\n * reached for would be a type error here rather than a runtime surprise.\n */\nexport interface SecretInput {\n readonly isTTY?: boolean\n setRawMode?: (mode: boolean) => unknown\n resume?: () => unknown\n on(event: \"data\", listener: (chunk: Buffer | string) => void): unknown\n removeListener(event: \"data\", listener: (chunk: Buffer | string) => void): unknown\n}\n\nexport interface SecretOptions {\n readonly input?: SecretInput\n readonly output?: NodeJS.WritableStream\n}\n\nexport async function askSecret(\n question: string,\n options: SecretOptions = {},\n): Promise<string | undefined> {\n const input = options.input ?? (process.stdin as unknown as SecretInput)\n const output = options.output ?? process.stdout\n if (input.isTTY !== true) return undefined\n\n output.write(`\\n${question} `)\n const raw = typeof input.setRawMode === \"function\"\n if (raw) input.setRawMode?.(true)\n input.resume?.()\n\n try {\n return await new Promise<string | undefined>((resolve) => {\n let value = \"\"\n // Escape-sequence state. Dropping only the escape *byte* left `[A` in the value for an\n // arrow key — two characters of junk in a string nobody can see, which is worse than three\n // because it looks like nothing happened. CSI runs until a byte in 0x40–0x7e ends it.\n let escaped = false\n let csi = false\n const finish = (result: string | undefined) => {\n input.removeListener(\"data\", onData)\n output.write(\"\\n\")\n resolve(result)\n }\n const onData = (chunk: Buffer | string) => {\n const text = typeof chunk === \"string\" ? chunk : chunk.toString(\"utf8\")\n for (const char of text) {\n const code = char.charCodeAt(0)\n if (csi) {\n // The final byte of a CSI sequence, and the end of it.\n if (code >= 0x40 && code <= 0x7e) csi = false\n continue\n }\n if (escaped) {\n escaped = false\n // `[` opens CSI and `O` opens SS3, which is how some terminals send arrows.\n if (char === \"[\" || char === \"O\") csi = true\n continue\n }\n if (code === 27) {\n escaped = true\n continue\n }\n if (code === 13 || code === 10) return finish(value)\n // ^C always cancels; ^D cancels only an empty line, so it cannot silently\n // truncate a value somebody was halfway through typing.\n if (code === 3) return finish(undefined)\n if (code === 4) return finish(value === \"\" ? undefined : value)\n if (code === 127 || code === 8) {\n if (value.length > 0) {\n value = value.slice(0, -1)\n output.write(\"\\b \\b\")\n }\n continue\n }\n // Any remaining control byte is a chord, and a secret has none in it.\n if (code < 32) continue\n value += char\n output.write(\"*\")\n }\n }\n input.on(\"data\", onData)\n })\n } finally {\n // Always restored. A thrown error that left raw mode on would leave the shell that follows\n // unable to echo anything at all, which reads as a hung terminal rather than a failed command.\n if (raw) input.setRawMode?.(false)\n }\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAkBA,0BAAS,sBAQT,eAAsB,EAAQ,CAAC,EAAkB,EAA0B,CAAC,EAAqB,CAC7F,IAAM,EAAQ,EAAQ,OAAS,QAAQ,MACjC,EAAS,EAAQ,QAAU,QAAQ,OACzC,GAAI,EAAM,QAAU,GAAM,MAAO,GAEjC,IAAM,EAAK,EAAgB,CAAE,QAAO,QAAO,CAAC,EAC5C,GAAI,CACA,IAAM,EAAS,MAAM,IAAI,QAAgB,CAAC,IAAY,CAClD,EAAG,SAAS;AAAA,EAAK,WAAmB,CAAO,EAC9C,EACD,MAAO,YAAY,KAAK,EAAO,KAAK,CAAC,SACvC,CAEE,EAAG,MAAM,GAoBjB,eAAsB,EAAU,CAC5B,EACA,EACA,EAA0B,CAAC,EACX,CAChB,IAAM,EAAQ,EAAQ,OAAS,QAAQ,MACjC,EAAS,EAAQ,QAAU,QAAQ,OACzC,GAAI,EAAM,QAAU,GAAM,MAAO,GAEjC,IAAM,EAAK,EAAgB,CAAE,QAAO,QAAO,CAAC,EAC5C,GAAI,CAIA,OAHe,MAAM,IAAI,QAAgB,CAAC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AAI,SACf,GAAS,EACT,EAAO,MAAM,GAAG,IAGxB,EAAM,GAAG,OAAQ,CAAM,EAC1B,SACH,CAGE,GAAI,EAAK,EAAM,aAAa,EAAK",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "FD67341C37D00B3064756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{spawn as s,spawnSync as f}from"node:child_process";function
|
|
3
|
-
export{
|
|
2
|
+
import{spawn as s,spawnSync as f}from"node:child_process";function ri(n){let e=f(n.command,[...n.args],{encoding:"utf8",...n.input===void 0?{}:{input:n.input},...n.cwd===void 0?{}:{cwd:n.cwd},...n.env===void 0?{}:{env:n.env},...n.timeoutMs===void 0?{}:{timeout:n.timeoutMs},...n.maxBuffer===void 0?{}:{maxBuffer:n.maxBuffer}}),d=e.error?.code;return{code:e.status??1,stdout:e.stdout??"",stderr:e.stderr??"",signalled:e.signal!==null,notFound:d==="ENOENT"}}function ye(n){return new Promise((e)=>{let d=s(n.command,[...n.args],{...n.cwd===void 0?{}:{cwd:n.cwd},...n.env===void 0?{}:{env:n.env},stdio:[n.input===void 0?"ignore":"pipe","pipe","pipe"]});if(n.input!==void 0)d.stdin?.end(n.input);let t="",a="",r=!1,u=n.maxBuffer??33554432;d.stdout?.on("data",(o)=>{if(t.length<u)t+=o.toString("utf8")}),d.stderr?.on("data",(o)=>{if(a.length<u)a+=o.toString("utf8")});let i=n.timeoutMs===void 0?void 0:setTimeout(()=>{r=!0,d.kill("SIGTERM")},n.timeoutMs);d.on("error",(o)=>{if(i!==void 0)clearTimeout(i);e({code:1,stdout:t,stderr:o.message,signalled:r,notFound:o.code==="ENOENT"})}),d.on("close",(o,l)=>{if(i!==void 0)clearTimeout(i);e({code:o??1,stdout:t,stderr:a,signalled:r||l!==null,notFound:!1})})})}
|
|
3
|
+
export{ri,ye};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
6
|
-
//# sourceMappingURL=index-
|
|
5
|
+
//# debugId=05652F12342158F164756E2164756E21
|
|
6
|
+
//# sourceMappingURL=index-ehzwdnc3.js.map
|
|
@@ -5,6 +5,6 @@
|
|
|
5
5
|
"/**\n * The one place in this package that starts a process.\n *\n * There were two callers before this file existed and the second one is what created it: `lib/service.ts`\n * ran `launchctl`, and fetching a skill source needs `git`. The rule the boundaries test enforces is\n * \"exactly one module imports `node:child_process`\", and its stated reason is that a second call site is a\n * second place a test has to intercept — the first one that forgets reaches somebody's real machine. Two\n * callers of one seam keeps that property; an allowlist with two entries in it loses it, and would go on\n * losing it once per phase.\n *\n * Deliberately thin, and deliberately not clever. Everything specific to a tool — git's four ways of\n * being told not to prompt, launchd's exit-status decoding — belongs to the caller that knows about it.\n * What lives here is \"run this, capture what it said, and tell me honestly how it ended\".\n *\n * `notFound` is a field rather than an exception because the two callers want different sentences for it:\n * a missing `git` has a remedy the person can act on, and a missing `launchctl` means this is not the\n * operating system the caller thought it was. A shared error message would be wrong for both.\n */\n\nimport { spawn, spawnSync } from \"node:child_process\"\n\nexport interface SpawnRequest {\n readonly command: string\n readonly args: readonly string[]\n readonly cwd?: string\n /** Replaces the environment entirely when given. Callers spread `process.env` themselves. */\n readonly env?: Readonly<Record<string, string | undefined>>\n readonly timeoutMs?: number\n readonly maxBuffer?: number\n /**\n * Text to write to the child's stdin, which is then closed.\n *\n * Added for the clipboard: `pbcopy` reads what it copies from stdin and there is no argument form. The\n * alternative was a temporary file, which puts whatever was selected on disk — and a selection is\n * routinely the most sensitive thing on the screen. The seam grows rather than the caller working\n * around it, per the rule about first-party code not getting private escape hatches.\n */\n readonly input?: string\n}\n\nexport interface SpawnResult {\n readonly code: number\n readonly stdout: string\n readonly stderr: string\n /** True when a timeout or a signal ended it, rather than the process choosing to exit. */\n readonly signalled: boolean\n /** True when the command is not on PATH at all. */\n readonly notFound: boolean\n}\n\nexport function spawnCapture(request: SpawnRequest): SpawnResult {\n const result = spawnSync(request.command, [...request.args], {\n encoding: \"utf8\",\n ...(request.input === undefined ? {} : { input: request.input }),\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n ...(request.env === undefined ? {} : { env: request.env as NodeJS.ProcessEnv }),\n ...(request.timeoutMs === undefined ? {} : { timeout: request.timeoutMs }),\n ...(request.maxBuffer === undefined ? {} : { maxBuffer: request.maxBuffer }),\n })\n const code = (result.error as NodeJS.ErrnoException | undefined)?.code\n return {\n code: result.status ?? 1,\n stdout: result.stdout ?? \"\",\n stderr: result.stderr ?? \"\",\n signalled: result.signal !== null,\n notFound: code === \"ENOENT\",\n }\n}\n\n/**\n * The same thing, without blocking the event loop.\n *\n * Exists because `spawnSync` inside an Ink app freezes the whole terminal: no spinner frame advances, and\n * the keypresses that arrive during a twenty-second `git clone` are echoed by the tty instead of being\n * consumed by the app — which is how `^[[B^[[A` ended up printed in the middle of a fetch progress line.\n * Anything a rendered screen waits on has to be awaited, not blocked on.\n */\nexport function spawnCaptureAsync(request: SpawnRequest): Promise<SpawnResult> {\n return new Promise((resolve) => {\n const child = spawn(request.command, [...request.args], {\n ...(request.cwd === undefined ? {} : { cwd: request.cwd }),\n ...(request.env === undefined ? {} : { env: request.env as NodeJS.ProcessEnv }),\n // Never inherit: a child that writes to the terminal would paint over the rendered frame, and\n // one that reads from it would steal the keys the app is listening for.\n // A pipe only when there is something to write. `ignore` otherwise, for the reason below.\n stdio: [request.input === undefined ? \"ignore\" : \"pipe\", \"pipe\", \"pipe\"],\n })\n if (request.input !== undefined) {\n // Ended immediately: a child reading stdin waits for EOF, so a pipe left open is a process\n // that never exits and a promise that never settles.\n child.stdin?.end(request.input)\n }\n let stdout = \"\"\n let stderr = \"\"\n let signalled = false\n const cap = request.maxBuffer ?? 32 * 1024 * 1024\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n if (stdout.length < cap) stdout += chunk.toString(\"utf8\")\n })\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n if (stderr.length < cap) stderr += chunk.toString(\"utf8\")\n })\n const timer =\n request.timeoutMs === undefined\n ? undefined\n : setTimeout(() => {\n signalled = true\n // The group, not the pid: `git clone` spawns helpers, and killing only the parent\n // leaves them running with nothing referencing them.\n child.kill(\"SIGTERM\")\n }, request.timeoutMs)\n child.on(\"error\", (error: NodeJS.ErrnoException) => {\n if (timer !== undefined) clearTimeout(timer)\n resolve({\n code: 1,\n stdout,\n stderr: error.message,\n signalled,\n notFound: error.code === \"ENOENT\",\n })\n })\n child.on(\"close\", (code, signal) => {\n if (timer !== undefined) clearTimeout(timer)\n resolve({\n code: code ?? 1,\n stdout,\n stderr,\n signalled: signalled || signal !== null,\n notFound: false,\n })\n })\n })\n}\n"
|
|
6
6
|
],
|
|
7
7
|
"mappings": ";AAmBA,gBAAS,eAAO,2BA+BT,SAAS,EAAY,CAAC,EAAoC,CAC7D,IAAM,EAAS,EAAU,EAAQ,QAAS,CAAC,GAAG,EAAQ,IAAI,EAAG,CACzD,SAAU,UACN,EAAQ,QAAU,OAAY,CAAC,EAAI,CAAE,MAAO,EAAQ,KAAM,KAC1D,EAAQ,MAAQ,OAAY,CAAC,EAAI,CAAE,IAAK,EAAQ,GAAI,KACpD,EAAQ,MAAQ,OAAY,CAAC,EAAI,CAAE,IAAK,EAAQ,GAAyB,KACzE,EAAQ,YAAc,OAAY,CAAC,EAAI,CAAE,QAAS,EAAQ,SAAU,KACpE,EAAQ,YAAc,OAAY,CAAC,EAAI,CAAE,UAAW,EAAQ,SAAU,CAC9E,CAAC,EACK,EAAQ,EAAO,OAA6C,KAClE,MAAO,CACH,KAAM,EAAO,QAAU,EACvB,OAAQ,EAAO,QAAU,GACzB,OAAQ,EAAO,QAAU,GACzB,UAAW,EAAO,SAAW,KAC7B,SAAU,IAAS,QACvB,EAWG,SAAS,EAAiB,CAAC,EAA6C,CAC3E,OAAO,IAAI,QAAQ,CAAC,IAAY,CAC5B,IAAM,EAAQ,EAAM,EAAQ,QAAS,CAAC,GAAG,EAAQ,IAAI,EAAG,IAChD,EAAQ,MAAQ,OAAY,CAAC,EAAI,CAAE,IAAK,EAAQ,GAAI,KACpD,EAAQ,MAAQ,OAAY,CAAC,EAAI,CAAE,IAAK,EAAQ,GAAyB,EAI7E,MAAO,CAAC,EAAQ,QAAU,OAAY,SAAW,OAAQ,OAAQ,MAAM,CAC3E,CAAC,EACD,GAAI,EAAQ,QAAU,OAGlB,EAAM,OAAO,IAAI,EAAQ,KAAK,EAElC,IAAI,EAAS,GACT,EAAS,GACT,EAAY,GACV,EAAM,EAAQ,WAAa,SACjC,EAAM,QAAQ,GAAG,OAAQ,CAAC,IAAkB,CACxC,GAAI,EAAO,OAAS,EAAK,GAAU,EAAM,SAAS,MAAM,EAC3D,EACD,EAAM,QAAQ,GAAG,OAAQ,CAAC,IAAkB,CACxC,GAAI,EAAO,OAAS,EAAK,GAAU,EAAM,SAAS,MAAM,EAC3D,EACD,IAAM,EACF,EAAQ,YAAc,OAChB,OACA,WAAW,IAAM,CACb,EAAY,GAGZ,EAAM,KAAK,SAAS,GACrB,EAAQ,SAAS,EAC9B,EAAM,GAAG,QAAS,CAAC,IAAiC,CAChD,GAAI,IAAU,OAAW,aAAa,CAAK,EAC3C,EAAQ,CACJ,KAAM,EACN,SACA,OAAQ,EAAM,QACd,YACA,SAAU,EAAM,OAAS,QAC7B,CAAC,EACJ,EACD,EAAM,GAAG,QAAS,CAAC,EAAM,IAAW,CAChC,GAAI,IAAU,OAAW,aAAa,CAAK,EAC3C,EAAQ,CACJ,KAAM,GAAQ,EACd,SACA,SACA,UAAW,GAAa,IAAW,KACnC,SAAU,EACd,CAAC,EACJ,EACJ",
|
|
8
|
-
"debugId": "
|
|
8
|
+
"debugId": "05652F12342158F164756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{e,S,A,p}from"./index-byxrc961.js";function m(n){return n!==void 0&&n!==""}function Fe(n=process.env){return{noColor:m(n.NO_COLOR),dumbTerminal:n.TERM==="dumb",ci:m(n.CI)&&n.CI!=="false",debug:m(n.DEBUG),sandboxHome:m(n[`${e.envPrefix}HOME`])?n[`${e.envPrefix}HOME`]:void 0,noEnhancedKeys:m(n[`${e.envPrefix}NO_CSI_U`])}}import{existsSync as c,readdirSync as x,statSync as y}from"node:fs";import{homedir as w}from"node:os";import{isAbsolute as P,join as i,resolve as f,sep as b}from"node:path";function z(n=process.env){return Fe(n).sandboxHome??i(w(),e.stateDir)}function _(n){return i(z(n),"agents")}function Q(n){return i(z(n),"store.db")}function O(n){return i(z(n),"plugins")}function Fn(n,r){return i(O(r),n)}function Mt(n){let r=i(z(n),"logs","server");return{out:i(r,"out.log"),err:i(r,"err.log")}}function _A(n,r){let o=i(z(r),"logs");return{out:i(o,`${n}.out.log`),err:i(o,`${n}.err.log`)}}function E(n,r){let o=f(_(r)),s=f(n);return s===o||s.startsWith(o+b)}function si(n,r){if(E(n,r))return;return`note: ${f(n)} is outside the sandbox (${_(r)}) — this agent has no bare name, so every later command needs its path. Omit --dir to put it in the sandbox.`}function R(n){let r=_(n),o;try{o=x(r)}catch{return[]}let s=[];for(let t of o.sort()){let u=i(r,t),a=i(u,"agent.yaml");try{if(!y(u).isDirectory())continue}catch{continue}if(!c(a))continue;let h=0;try{h=y(a).mtimeMs}catch{}try{let g=p(a);s.push({ref:t,dir:u,manifestPath:a,mtimeMs:h,...g.id===void 0?{}:{id:g.id},...g.name===void 0?{}:{name:g.name},...g.modelId===void 0?{}:{modelId:g.modelId}})}catch(g){s.push({ref:t,dir:u,manifestPath:a,mtimeMs:h,problem:g instanceof Error?g.message:String(g)})}}let d=new Map;for(let t of s){if(t.id===void 0)continue;d.set(t.id,[...d.get(t.id)??[],t])}let l=s.map((t)=>{if(t.id===void 0||(d.get(t.id)?.length??0)<2)return t;return{...t,problem:`manifest id "${t.id}" is shared with another sandbox agent — their sessions share one history`}});return[...l.filter((t)=>t.problem===void 0),...l.filter((t)=>t.problem!==void 0)]}function Ae(n,r,o=process.cwd()){let s=n.includes(b)||n.includes("/")||n.endsWith(".yaml")||n.endsWith(".yml"),d=P(n)?n:f(o,n);if(!s&&c(d)&&c(i(_(r),n)))process.stderr.write(`note: using ./${n} from the current directory; a sandbox agent "${n}" also exists — run it from elsewhere, or as ${i(_(r),n)}
|
|
3
|
+
`);if(s||c(d)){if(c(d)){if(y(d).isDirectory()){let a=i(d,"agent.yaml");if(c(a))return a;throw new A({code:"cli_agent_dir_without_manifest",message:`${n} is a directory with no agent.yaml inside.`,hint:"Point at the manifest itself, or at a directory that holds one. Sandbox agents are run by bare name, with no path separators."})}return d}throw new A({code:"cli_agent_path_missing",message:`${n} looks like a path, and nothing is there.`,hint:`Paths resolve against the current directory. For an agent in the sandbox, use its bare name — \`${e.slug} run <name>\` — which resolves under ${_(r)}.`})}let l=i(_(r),n,"agent.yaml");if(c(l))return l;let t=R(r).map((a)=>a.ref),u=S(n,t);throw new A({code:"cli_agent_unknown",message:`No agent named "${n}" in the sandbox${t.length===0?", which is empty":""}.`,hint:t.length===0?`Create one with \`${e.slug} init\`, or pass a path to an agent.yaml.`:`Known agents: ${t.join(", ")}.${u===void 0?"":` Did you mean ${u}?`} A path (./dir or file.yaml) is also accepted.`})}
|
|
4
|
+
export{Fe,z,_,Q,O,Fn,Mt,_A,si,R,Ae};
|
|
5
|
+
|
|
6
|
+
//# debugId=0BED868AB836D7B464756E2164756E21
|
|
7
|
+
//# sourceMappingURL=index-fzmmhmk2.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/lib/env.ts", "../src/lib/sandbox.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"/**\n * Every environment read the CLI makes.\n *\n * Centralised for the same reason termheat centralises it: an environment variable consulted deep\n * inside a component is untestable and invisible. Everything downstream takes an `EnvFacts` value,\n * so the interesting logic — `resolveMode` especially — is a pure function of its inputs.\n */\n\nimport { BRAND } from \"@dispach/core\"\nimport type { EnvFacts } from \"#lib/types\"\n\n/**\n * `NO_COLOR` is honoured when present and non-empty, per no-color.org. An exported-but-empty\n * variable is a container passing through something unset, not a stated preference.\n */\nfunction isSet(value: string | undefined): boolean {\n return value !== undefined && value !== \"\"\n}\n\nexport function readEnv(env: Readonly<Record<string, string | undefined>> = process.env): EnvFacts {\n return {\n noColor: isSet(env.NO_COLOR),\n dumbTerminal: env.TERM === \"dumb\",\n // `CI=false` is set by tooling that wants to say \"not CI\", and taking it literally would\n // strip interactivity from a terminal that has it.\n ci: isSet(env.CI) && env.CI !== \"false\",\n debug: isSet(env.DEBUG),\n // The sandbox root override, `<ENVPREFIX>HOME`. Brand-derived so a rename moves it.\n sandboxHome: isSet(env[`${BRAND.envPrefix}HOME`])\n ? env[`${BRAND.envPrefix}HOME`]\n : undefined,\n // Brand-derived like the sandbox root above, so a rename moves it.\n noEnhancedKeys: isSet(env[`${BRAND.envPrefix}NO_CSI_U`]),\n }\n}\n",
|
|
6
|
+
"/**\n * The home sandbox: where agents live when nobody says otherwise.\n *\n * `~/<stateDir>/` (brand-derived, so a rename moves it) holds `agents/<ref>/` for init-created\n * agents and `store.db` for their sessions. One root, one store: the store schema is already\n * keyed by agent id, and a cwd-relative default meant the same agent got a different session\n * history in every directory you happened to be in.\n *\n * Discovery reads manifest *headers*, never `loadManifest`: loading expands env references and\n * checks that key variables are set, so a picker built on it would fail exactly when it is\n * needed most — on a machine where the key is not exported yet. A broken manifest becomes a\n * listed entry with a `problem`, never a broken listing.\n *\n * Tests override the root with `<ENVPREFIX>HOME` pointed at a tmpdir; nothing here touches the\n * real home directory when that is set.\n */\n\nimport { existsSync, readdirSync, statSync } from \"node:fs\"\nimport { homedir } from \"node:os\"\nimport { isAbsolute, join, resolve, sep } from \"node:path\"\nimport { BRAND, HarnessError, nearest, readManifestHeader } from \"@dispach/core\"\nimport { readEnv } from \"#lib/env\"\n\nexport function sandboxRoot(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string {\n const override = readEnv(env).sandboxHome\n return override ?? join(homedir(), BRAND.stateDir)\n}\n\nexport function agentsDir(env?: Readonly<Record<string, string | undefined>>): string {\n return join(sandboxRoot(env), \"agents\")\n}\n\nexport function storePath(env?: Readonly<Record<string, string | undefined>>): string {\n return join(sandboxRoot(env), \"store.db\")\n}\n\n/**\n * Where installed plugins live — one directory per plugin, machine-level.\n *\n * The same shape and the same reasoning as the skills cache (`sources`) beside it: a plugin is code\n * the *person* trusts, fetched once and shared by every agent on the machine, and which agents\n * actually load it is decided by each manifest's own `plugins:` block. That is why there is no\n * registry file here — the manifest is the registry, and a second list of \"installed plugins\" would be\n * exactly the drift this project keeps paying for. `plugins list` reads the loader's own provenance\n * instead.\n *\n * Here rather than computed by a caller, because that is what makes `<ENVPREFIX>HOME` redirect it: a\n * caller that derived its own path wrote three agents into the author's real home directory once.\n */\nexport function pluginRoot(env?: Readonly<Record<string, string | undefined>>): string {\n return join(sandboxRoot(env), \"plugins\")\n}\n\nexport function pluginDir(\n name: string,\n env?: Readonly<Record<string, string | undefined>>,\n): string {\n return join(pluginRoot(env), name)\n}\n\n/**\n * Where a service writes its output, keyed by the agent's **manifest id**.\n *\n * Not by the directory name, which is what `run <ref>` takes — the same split as the store's\n * `agent_id` and the launchd label. Two directories with one manifest id therefore share these files,\n * which `listAgents` already warns about.\n *\n * Here rather than in `daemon.ts`, where it was private, because it is a fact about the sandbox layout\n * and `remove` needs it too. Moved rather than duplicated: a second copy of a path derivation is how\n * one command deletes a file another command is still writing to.\n */\n/**\n * Where the one server unit writes, in a **subdirectory** rather than beside the agent logs.\n *\n * `logs/<id>.err.log` is the per-agent shape, so a flat `logs/server.err.log` would collide with an\n * agent whose id happened to be `server` — and the collision would appear as a service and an agent\n * appending to one file, which is the kind of thing nobody diagnoses from a log.\n */\nexport function serverLogPaths(env?: Readonly<Record<string, string | undefined>>): {\n readonly out: string\n readonly err: string\n} {\n const dir = join(sandboxRoot(env), \"logs\", \"server\")\n return { out: join(dir, \"out.log\"), err: join(dir, \"err.log\") }\n}\n\nexport function logPaths(\n agentId: string,\n env?: Readonly<Record<string, string | undefined>>,\n): { readonly out: string; readonly err: string } {\n const dir = join(sandboxRoot(env), \"logs\")\n return { out: join(dir, `${agentId}.out.log`), err: join(dir, `${agentId}.err.log`) }\n}\n\n/**\n * Is this path inside the sandbox's agents directory?\n *\n * Both sides are resolved first, for the reason `root.ts` already records: an unresolved\n * `<base>/../../elsewhere` passes a prefix test while landing nowhere near the base. The `sep`\n * suffix is what stops `~/.brand/agents-backup` reading as inside `~/.brand/agents`.\n */\nexport function insideSandbox(\n targetDir: string,\n env?: Readonly<Record<string, string | undefined>>,\n): boolean {\n const base = resolve(agentsDir(env))\n const target = resolve(targetDir)\n return target === base || target.startsWith(base + sep)\n}\n\n/**\n * The one-line note an out-of-sandbox target earns, or `undefined` when it is inside.\n *\n * A note rather than a refusal: `init --dir ./examples/scout` is a legitimate thing to want, and a\n * command that refuses it would be one people work around with `mv`. What is *not* legitimate is\n * doing it silently — an agent outside the sandbox has no bare name, so every later `run`, `config`,\n * `daemon` and `schedules` call needs a path, and the reason for that is only obvious at the moment\n * the directory is chosen.\n *\n * Pure and separate from the write so the sentence can be asserted without a filesystem.\n */\nexport function outsideSandboxNote(\n targetDir: string,\n env?: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n if (insideSandbox(targetDir, env)) return undefined\n return `note: ${resolve(targetDir)} is outside the sandbox (${agentsDir(env)}) — this agent has no bare name, so every later command needs its path. Omit --dir to put it in the sandbox.`\n}\n\nexport interface SandboxAgent {\n /** The directory name — what `run <ref>` takes. Filesystem-unique by construction. */\n readonly ref: string\n /** Absolute agent directory. */\n readonly dir: string\n /** Absolute path to its agent.yaml. */\n readonly manifestPath: string\n /** From the manifest header; may differ from `ref` for hand-copied directories. */\n readonly id?: string\n readonly name?: string\n /** Raw — may literally be an unexpanded `${MODEL_ID}` reference. */\n readonly modelId?: string\n /** Modification time of the manifest, for \"recently used\" ordering hints. */\n readonly mtimeMs: number\n /** Present when the manifest could not be read; the entry lists anyway, honestly. */\n readonly problem?: string\n}\n\n/**\n * Every agent directory in the sandbox, alphabetical by ref with broken entries last.\n *\n * Broken means the header could not be read — the entry still appears, carrying the problem,\n * because a listing that silently hides a corrupted agent turns \"why is my agent gone\" into a\n * filesystem investigation. Duplicate manifest ids are marked the same way: both run, but their\n * sessions share a store keyed by that id, which is worth a warning rather than a pretence.\n */\nexport function listAgents(\n env?: Readonly<Record<string, string | undefined>>,\n): readonly SandboxAgent[] {\n const dir = agentsDir(env)\n let entries: string[]\n try {\n entries = readdirSync(dir)\n } catch {\n // No sandbox yet is the normal first-run state, not an error.\n return []\n }\n\n const agents: SandboxAgent[] = []\n for (const ref of entries.sort()) {\n const agentDir = join(dir, ref)\n const manifestPath = join(agentDir, \"agent.yaml\")\n try {\n if (!statSync(agentDir).isDirectory()) continue\n } catch {\n continue\n }\n if (!existsSync(manifestPath)) continue\n\n let mtimeMs = 0\n try {\n mtimeMs = statSync(manifestPath).mtimeMs\n } catch {\n // Raced away between existsSync and statSync; list it with what we have.\n }\n\n try {\n const header = readManifestHeader(manifestPath)\n agents.push({\n ref,\n dir: agentDir,\n manifestPath,\n mtimeMs,\n ...(header.id === undefined ? {} : { id: header.id }),\n ...(header.name === undefined ? {} : { name: header.name }),\n ...(header.modelId === undefined ? {} : { modelId: header.modelId }),\n })\n } catch (error) {\n agents.push({\n ref,\n dir: agentDir,\n manifestPath,\n mtimeMs,\n problem: error instanceof Error ? error.message : String(error),\n })\n }\n }\n\n // Duplicate manifest ids share session history — say so rather than pretend it is fine.\n const byId = new Map<string, SandboxAgent[]>()\n for (const agent of agents) {\n if (agent.id === undefined) continue\n byId.set(agent.id, [...(byId.get(agent.id) ?? []), agent])\n }\n const marked = agents.map((agent) => {\n if (agent.id === undefined || (byId.get(agent.id)?.length ?? 0) < 2) return agent\n return {\n ...agent,\n problem: `manifest id \"${agent.id}\" is shared with another sandbox agent — their sessions share one history`,\n }\n })\n\n return [\n ...marked.filter((a) => a.problem === undefined),\n ...marked.filter((a) => a.problem !== undefined),\n ]\n}\n\n/**\n * Turn what the user typed into a manifest path.\n *\n * The filesystem wins: anything that looks like a path (a separator, a .yaml suffix, or a thing\n * that exists here) is a path, so `./milo` always forces the file even when a sandbox agent\n * `milo` exists — the same rule git applies to pathspec-versus-branch, with the same free escape\n * hatch. Only then is the ref tried as a sandbox agent name.\n */\nexport function resolveAgentRef(\n ref: string,\n env?: Readonly<Record<string, string | undefined>>,\n cwd: string = process.cwd(),\n): string {\n const looksLikePath =\n ref.includes(sep) || ref.includes(\"/\") || ref.endsWith(\".yaml\") || ref.endsWith(\".yml\")\n const asPath = isAbsolute(ref) ? ref : resolve(cwd, ref)\n\n // A bare name that happens to exist in the cwd wins as a path — but silently running the\n // wrong agent is worse than one stderr line. Only fires on genuine ambiguity.\n if (!looksLikePath && existsSync(asPath) && existsSync(join(agentsDir(env), ref))) {\n process.stderr.write(\n `note: using ./${ref} from the current directory; a sandbox agent \"${ref}\" also exists — run it from elsewhere, or as ${join(agentsDir(env), ref)}\\n`,\n )\n }\n\n if (looksLikePath || existsSync(asPath)) {\n if (existsSync(asPath)) {\n if (statSync(asPath).isDirectory()) {\n const inside = join(asPath, \"agent.yaml\")\n if (existsSync(inside)) return inside\n throw new HarnessError({\n code: \"cli_agent_dir_without_manifest\",\n message: `${ref} is a directory with no agent.yaml inside.`,\n hint: \"Point at the manifest itself, or at a directory that holds one. Sandbox agents are run by bare name, with no path separators.\",\n })\n }\n return asPath\n }\n throw new HarnessError({\n code: \"cli_agent_path_missing\",\n message: `${ref} looks like a path, and nothing is there.`,\n hint: `Paths resolve against the current directory. For an agent in the sandbox, use its bare name — \\`${BRAND.slug} run <name>\\` — which resolves under ${agentsDir(env)}.`,\n })\n }\n\n const sandboxManifest = join(agentsDir(env), ref, \"agent.yaml\")\n if (existsSync(sandboxManifest)) return sandboxManifest\n\n const known = listAgents(env).map((agent) => agent.ref)\n const suggestion = nearest(ref, known)\n throw new HarnessError({\n code: \"cli_agent_unknown\",\n message: `No agent named \"${ref}\" in the sandbox${known.length === 0 ? \", which is empty\" : \"\"}.`,\n hint:\n known.length === 0\n ? `Create one with \\`${BRAND.slug} init\\`, or pass a path to an agent.yaml.`\n : `Known agents: ${known.join(\", \")}.${suggestion === undefined ? \"\" : ` Did you mean ${suggestion}?`} A path (./dir or file.yaml) is also accepted.`,\n })\n}\n"
|
|
7
|
+
],
|
|
8
|
+
"mappings": ";yCAeA,SAAS,CAAK,CAAC,EAAoC,CAC/C,OAAO,IAAU,QAAa,IAAU,GAGrC,SAAS,EAAO,CAAC,EAAoD,QAAQ,IAAe,CAC/F,MAAO,CACH,QAAS,EAAM,EAAI,QAAQ,EAC3B,aAAc,EAAI,OAAS,OAG3B,GAAI,EAAM,EAAI,EAAE,GAAK,EAAI,KAAO,QAChC,MAAO,EAAM,EAAI,KAAK,EAEtB,YAAa,EAAM,EAAI,GAAG,EAAM,gBAAgB,EAC1C,EAAI,GAAG,EAAM,iBACb,OAEN,eAAgB,EAAM,EAAI,GAAG,EAAM,oBAAoB,CAC3D,EChBJ,qBAAS,iBAAY,cAAa,gBAClC,kBAAS,gBACT,qBAAS,UAAY,aAAM,SAAS,kBAI7B,SAAS,CAAW,CACvB,EAAoD,QAAQ,IACtD,CAEN,OADiB,GAAQ,CAAG,EAAE,aACX,EAAK,EAAQ,EAAG,EAAM,QAAQ,EAG9C,SAAS,CAAS,CAAC,EAA4D,CAClF,OAAO,EAAK,EAAY,CAAG,EAAG,QAAQ,EAGnC,SAAS,CAAS,CAAC,EAA4D,CAClF,OAAO,EAAK,EAAY,CAAG,EAAG,UAAU,EAgBrC,SAAS,CAAU,CAAC,EAA4D,CACnF,OAAO,EAAK,EAAY,CAAG,EAAG,SAAS,EAGpC,SAAS,EAAS,CACrB,EACA,EACM,CACN,OAAO,EAAK,EAAW,CAAG,EAAG,CAAI,EAqB9B,SAAS,EAAc,CAAC,EAG7B,CACE,IAAM,EAAM,E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Y,EACxC,GAAI,EAAW,CAAM,EAAG,OAAO,EAC/B,MAAM,IAAI,EAAa,CACnB,KAAM,iCACN,QAAS,GAAG,8CACZ,KAAM,+HACV,CAAC,EAEL,OAAO,EAEX,MAAM,IAAI,EAAa,CACnB,KAAM,yBACN,QAAS,GAAG,6CACZ,KAAM,mGAAmG,EAAM,4CAA4C,EAAU,CAAG,IAC5K,CAAC,EAGL,IAAM,EAAkB,EAAK,EAAU,CAAG,EAAG,EAAK,YAAY,EAC9D,GAAI,EAAW,CAAe,EAAG,OAAO,EAExC,IAAM,EAAQ,EAAW,CAAG,EAAE,IAAI,CAAC,IAAU,EAAM,GAAG,EAChD,EAAa,EAAQ,EAAK,CAAK,EACrC,MAAM,IAAI,EAAa,CACnB,KAAM,oBACN,QAAS,mBAAmB,oBAAsB,EAAM,SAAW,EAAI,mBAAqB,MAC5F,KACI,EAAM,SAAW,EACX,qBAAqB,EAAM,gDAC3B,iBAAiB,EAAM,KAAK,IAAI,KAAK,IAAe,OAAY,GAAK,iBAAiB,oDACpG,CAAC",
|
|
9
|
+
"debugId": "0BED868AB836D7B464756E2164756E21",
|
|
10
|
+
"names": []
|
|
11
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{o}from"./index-nn3tk25c.js";import{D}from"./index-zn24991r.js";import{Box as y,Text as h}from"ink";import{jsx as k,jsxs as b}from"react/jsx-runtime";function ft({lines:t}){let r=t.map((n,e)=>({at:e,text:n}));return k(y,{flexDirection:"column",children:r.map((n)=>b(h,{color:o.brand,bold:!0,wrap:"truncate",children:[" ".repeat(EA),n.text]},`mark-${n.at}`))})}var EA=1;var m="#",u={A:[".###.","#...#","#####","#...#","#...#"],B:["####.","#...#","####.","#...#","####."],C:[".####","#....","#....","#....",".####"],D:["####.","#...#","#...#","#...#","####."],E:["#####","#....","####.","#....","#####"],F:["#####","#....","####.","#....","#...."],G:[".####","#....","#..##","#...#",".###."],H:["#...#","#...#","#####","#...#","#...#"],I:["#####","..#..","..#..","..#..","#####"],J:["..###","....#","....#","#...#",".###."],K:["#...#","#..#.","###..","#..#.","#...#"],L:["#....","#....","#....","#....","#####"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#...#","##..#","#.#.#","#..##","#...#"],O:[".###.","#...#","#...#","#...#",".###."],P:["####.","#...#","####.","#....","#...."],Q:[".###.","#...#","#.#.#","#..#.",".##.#"],R:["####.","#...#","####.","#..#.","#...#"],S:[".####","#....",".###.","....#","####."],T:["#####","..#..","..#..","..#..","..#.."],U:["#...#","#...#","#...#","#...#",".###."],V:["#...#","#...#","#...#",".#.#.","..#.."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#...#",".#.#.","..#..",".#.#.","#...#"],Y:["#...#",".#.#.","..#..","..#..","..#.."],Z:["#####","...#.","..#..",".#...","#####"],"0":[".###.","#..##","#.#.#","##..#",".###."],"1":["..#..",".##..","..#..","..#..",".###."],"2":[".###.","#...#","..##.",".#...","#####"],"3":["####.","....#",".###.","....#","####."],"4":["#..#.","#..#.","#####","...#.","...#."],"5":["#####","#....","####.","....#","####."],"6":[".###.","#....","####.","#...#",".###."],"7":["#####","....#","...#.","..#..",".#..."],"8":[".###.","#...#",".###.","#...#",".###."],"9":[".###.","#...#",".####","....#",".###."],".":[".....",".....",".....",".....","..#.."],"-":[".....",".....",".###.",".....","....."]," ":[".....",".....",".....",".....","....."]},w=5,x=1;function T(t){return[...t.toUpperCase()].every((r)=>u[r]!==void 0)}function B(t){let r=[...t.toUpperCase()].map((e)=>u[e]??u[" "]),n=".".repeat(x);return Array.from({length:w},(e,s)=>r.map((a)=>a?.[s]??"").join(n))}function f(t,r,n){let e=r.repeat(n),s=" ".repeat(n);return t.map((a)=>[...a].map((i)=>i===m?e:s).join(""))}function W(t){let r=[".".repeat([...t[0]??""].length),...t],n=[];for(let e=0;e<r.length;e+=2){let s=[...r[e]??""],a=[...r[e+1]??""],i=[];for(let l=0;l<Math.max(s.length,a.length);l+=1){let d=s[l]===m,c=a[l]===m;i.push(d&&c?"█":d?"▀":c?"▄":" ")}n.push(i.join(""))}return n}function g(t,r){return[D([...t.toUpperCase()].join(" "),r)]}function p(t){return t.reduce((r,n)=>Math.max(r,[...n].length),0)}function Et(t,r){let n=t.trim();if(n===""||!T(n)){let i=g(n,r.columns);return{lines:i,tier:"plain",width:p(i)}}let e=B(n),s=[{tier:"wide",lines:f(e,"█",2)},{tier:"block",lines:f(e,"█",1)},{tier:"half",lines:W(e)}];for(let i of s){let l=i.lines.map((c)=>c.replace(/\s+$/,"")),d=p(l);if(d<=r.columns&&l.length<=r.rows)return{lines:l,tier:i.tier,width:d}}let a=g(n,r.columns);return{lines:a,tier:"plain",width:p(a)}}
|
|
3
|
+
export{ft,EA,Et};
|
|
4
|
+
|
|
5
|
+
//# debugId=303BD287BB7BDADB64756E2164756E21
|
|
6
|
+
//# sourceMappingURL=index-g3pk0kc0.js.map
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"/**\n * The product name, large, as the top of a new session.\n *\n * ## Why this is a header and not a screen\n *\n * It was a screen — a `Splash` component the chat swapped itself out for while the conversation was empty —\n * and that shape caused three bugs in a row, all the same bug. `/help` writes a note, the transcript stops\n * being empty, and the entire branch is replaced: the landing screen \"disappeared\" for almost every command.\n * Worse, anything added to the *other* branch was silently missing here — the palette drew nothing on the\n * splash for a day, and `/exit`'s \"press y\" prompt was invisible, because both were rendered in the layout\n * that was not on screen.\n *\n * Two layouts where one belongs is the defect. So there is one frame now, and this is the part of it that\n * changes: the brand mark sits above the ordinary one-line header until the first message is sent, and then\n * only the one-line header remains. Nothing appears or disappears on that transition — a block above it\n * goes.\n *\n * Presentational and controlled: it owns no keyboard, no state, and no opinion about when it is shown.\n */\n\nimport { Box, Text } from \"ink\"\nimport type { BrandmarkProps } from \"#lib/schema\"\nimport { THEME } from \"#lib/theme\"\n\nexport function Brandmark({ lines }: BrandmarkProps) {\n // Row numbers computed before the map, so the key is a position rather than a callback index. Position is\n // the honest identity here: two rows of a wordmark can be identical — `L` draws two the same — and a\n // content key would collapse them into one.\n const rows = lines.map((text, at) => ({ at, text }))\n\n return (\n <Box flexDirection=\"column\">\n {rows.map((row) => (\n <Text key={`mark-${row.at}`} color={THEME.brand} bold wrap=\"truncate\">\n {\" \".repeat(BRAND_INDENT)}\n {row.text}\n </Text>\n ))}\n </Box>\n )\n}\n\n/**\n * Left-aligned, not centred, and exported so the caller wraps to the same width it is drawn at.\n *\n * Centring looked better when this was a screen of its own with a centred composer under it. In the unified\n * frame the line directly beneath it — the one-line header that outlives it — is left-aligned, and the two\n * have to read as one block or the collapse looks like a different screen rather than the same one with less\n * on it.\n */\nexport const BRAND_INDENT = 1\n",
|
|
6
6
|
"/**\n * The product name, drawn large, from a glyph grid.\n *\n * ## Why a grid and not a string\n *\n * Hard rule 3: no brand strings outside `brand.ts`, so that a rename is one commit. An ASCII wordmark is\n * a brand string — a literal one would be the single largest violation in the tree. So this renders\n * whatever `BRAND.name` happens to say, from a table of letters, and a rename changes nothing here.\n *\n * ## The research, and what it settled\n *\n * Three findings shaped this. **5×5 pixels is the floor** for a legible Latin glyph without\n * anti-aliasing, so that is the grid. **A width-aware fallback is mandatory rather than polish** — the\n * big figlet faces (`big`, `ansi-shadow`) pass 120 columns on a nine-letter word, and this CLI's floor is\n * 40. And **half-blocks are the density trick**: one character cell per pixel renders a 5×5 glyph tall and\n * thin, because a cell is roughly 1:2, while packing two pixel rows into one cell with `▀▄█` brings it\n * back to nearly square.\n *\n * A third-party font was the obvious shortcut and is not taken: embedding `.flf` data or another\n * project's bitmap into an Apache-2.0 repo buys a licence question, and 26 letters are verifiable by\n * rendering them.\n *\n * ## One table, four renderings\n *\n * The tiers are parameter changes over the same grid — how many columns a pixel occupies, and whether\n * rows are packed — not four codepaths:\n *\n * | tier | pixel | rows | nine letters |\n * | --- | --- | --- | --- |\n * | `wide` | 2 columns | 5 | 106 columns |\n * | `block` | 1 column | 5 | 53 columns |\n * | `half` | 1 column | 3 | 53 columns |\n * | `plain` | — | 1 | as wide as the name |\n *\n * `plain` is the floor and always fits, because it is the name with spaces in it and gets clipped like\n * any other line. A screen too small for that is a screen with no wordmark, which is a real answer.\n *\n * Pure: text and a size in, lines out. Colour is the component's business.\n */\n\nimport { clip } from \"#lib/rows\"\n\n/** On and off, as authored. `#` reads as ink in the source, which is the only place these are edited. */\nconst ON = \"#\"\n\n/**\n * A 5×5 grid per glyph, authored by hand and verified by rendering.\n *\n * Uppercase only: the input is upper-cased before lookup, because a display face has no lowercase at this\n * size, and inventing one is how a name and its shout become two different-looking products. Digits are\n * here for a version, and `.`/`-`/space for what a name might contain.\n */\nconst GLYPHS: Readonly<Record<string, readonly string[]>> = {\n A: [\".###.\", \"#...#\", \"#####\", \"#...#\", \"#...#\"],\n B: [\"####.\", \"#...#\", \"####.\", \"#...#\", \"####.\"],\n C: [\".####\", \"#....\", \"#....\", \"#....\", \".####\"],\n D: [\"####.\", \"#...#\", \"#...#\", \"#...#\", \"####.\"],\n E: [\"#####\", \"#....\", \"####.\", \"#....\", \"#####\"],\n F: [\"#####\", \"#....\", \"####.\", \"#....\", \"#....\"],\n G: [\".####\", \"#....\", \"#..##\", \"#...#\", \".###.\"],\n H: [\"#...#\", \"#...#\", \"#####\", \"#...#\", \"#...#\"],\n I: [\"#####\", \"..#..\", \"..#..\", \"..#..\", \"#####\"],\n J: [\"..###\", \"....#\", \"....#\", \"#...#\", \".###.\"],\n K: [\"#...#\", \"#..#.\", \"###..\", \"#..#.\", \"#...#\"],\n L: [\"#....\", \"#....\", \"#....\", \"#....\", \"#####\"],\n M: [\"#...#\", \"##.##\", \"#.#.#\", \"#...#\", \"#...#\"],\n N: [\"#...#\", \"##..#\", \"#.#.#\", \"#..##\", \"#...#\"],\n O: [\".###.\", \"#...#\", \"#...#\", \"#...#\", \".###.\"],\n P: [\"####.\", \"#...#\", \"####.\", \"#....\", \"#....\"],\n Q: [\".###.\", \"#...#\", \"#.#.#\", \"#..#.\", \".##.#\"],\n R: [\"####.\", \"#...#\", \"####.\", \"#..#.\", \"#...#\"],\n S: [\".####\", \"#....\", \".###.\", \"....#\", \"####.\"],\n T: [\"#####\", \"..#..\", \"..#..\", \"..#..\", \"..#..\"],\n U: [\"#...#\", \"#...#\", \"#...#\", \"#...#\", \".###.\"],\n V: [\"#...#\", \"#...#\", \"#...#\", \".#.#.\", \"..#..\"],\n W: [\"#...#\", \"#...#\", \"#.#.#\", \"##.##\", \"#...#\"],\n X: [\"#...#\", \".#.#.\", \"..#..\", \".#.#.\", \"#...#\"],\n Y: [\"#...#\", \".#.#.\", \"..#..\", \"..#..\", \"..#..\"],\n Z: [\"#####\", \"...#.\", \"..#..\", \".#...\", \"#####\"],\n \"0\": [\".###.\", \"#..##\", \"#.#.#\", \"##..#\", \".###.\"],\n \"1\": [\"..#..\", \".##..\", \"..#..\", \"..#..\", \".###.\"],\n \"2\": [\".###.\", \"#...#\", \"..##.\", \".#...\", \"#####\"],\n \"3\": [\"####.\", \"....#\", \".###.\", \"....#\", \"####.\"],\n \"4\": [\"#..#.\", \"#..#.\", \"#####\", \"...#.\", \"...#.\"],\n \"5\": [\"#####\", \"#....\", \"####.\", \"....#\", \"####.\"],\n \"6\": [\".###.\", \"#....\", \"####.\", \"#...#\", \".###.\"],\n \"7\": [\"#####\", \"....#\", \"...#.\", \"..#..\", \".#...\"],\n \"8\": [\".###.\", \"#...#\", \".###.\", \"#...#\", \".###.\"],\n \"9\": [\".###.\", \"#...#\", \".####\", \"....#\", \".###.\"],\n \".\": [\".....\", \".....\", \".....\", \".....\", \"..#..\"],\n \"-\": [\".....\", \".....\", \".###.\", \".....\", \".....\"],\n \" \": [\".....\", \".....\", \".....\", \".....\", \".....\"],\n}\n\nconst GLYPH_ROWS = 5\n/** Blank pixel columns between letters. One is enough at this weight; two reads as word spacing. */\nconst TRACKING = 1\n\nexport type WordmarkTier = \"wide\" | \"block\" | \"half\" | \"plain\"\n\nexport interface Wordmark {\n readonly lines: readonly string[]\n readonly tier: WordmarkTier\n /** Code points in the widest line, so a caller can centre it without measuring. */\n readonly width: number\n}\n\n/** Letters this module can draw. A name containing anything else falls back to `plain`. */\nexport function drawable(text: string): boolean {\n return [...text.toUpperCase()].every((char) => GLYPHS[char] !== undefined)\n}\n\n/** The pixel grid for a whole word: rows of `#` and `.`, tracking included. */\nfunction pixels(text: string): readonly string[] {\n const glyphs = [...text.toUpperCase()].map((char) => GLYPHS[char] ?? GLYPHS[\" \"])\n const gap = \".\".repeat(TRACKING)\n return Array.from({ length: GLYPH_ROWS }, (_, row) =>\n glyphs.map((glyph) => glyph?.[row] ?? \"\").join(gap),\n )\n}\n\n/** Every pixel as `columns` cells of the fill character, or of space. */\nfunction solid(grid: readonly string[], fill: string, columns: number): readonly string[] {\n const on = fill.repeat(columns)\n const off = \" \".repeat(columns)\n return grid.map((row) => [...row].map((cell) => (cell === ON ? on : off)).join(\"\"))\n}\n\n/**\n * Two pixel rows to a text row, using the half blocks.\n *\n * This is what makes the compact tier look like type rather than a stretched grid: five pixel rows become\n * three text rows, so a 5-wide glyph is 5×3 cells — near enough square once a cell's own 1:2 ratio is\n * accounted for.\n *\n * Five rows is odd, so one of them pairs with nothing, and **which end gets the blank decides the\n * weight**. Padding the bottom leaves every baseline as a thin `▀`, so the letters sit on a hairline and\n * read light. Padding the *top* puts the blank against the cap line instead: the top stroke becomes `▄`\n * and the baseline becomes a full `█`. Compared side by side that is not a close call — caps want to be\n * bottom-heavy — which is why the blank row is prepended rather than appended.\n */\nfunction packed(grid: readonly string[]): readonly string[] {\n const padded = [\".\".repeat([...(grid[0] ?? \"\")].length), ...grid]\n const lines: string[] = []\n for (let row = 0; row < padded.length; row += 2) {\n const top = [...(padded[row] ?? \"\")]\n const bottom = [...(padded[row + 1] ?? \"\")]\n const cells: string[] = []\n for (let at = 0; at < Math.max(top.length, bottom.length); at += 1) {\n const up = top[at] === ON\n const down = bottom[at] === ON\n cells.push(up && down ? \"█\" : up ? \"▀\" : down ? \"▄\" : \" \")\n }\n lines.push(cells.join(\"\"))\n }\n return lines\n}\n\n/** The name with a space between every letter — the floor, and it always fits because it is clipped. */\nfunction spaced(text: string, columns: number): readonly string[] {\n return [clip([...text.toUpperCase()].join(\" \"), columns)]\n}\n\nfunction widthOf(lines: readonly string[]): number {\n return lines.reduce((widest, line) => Math.max(widest, [...line].length), 0)\n}\n\n/**\n * The largest wordmark that fits, and how it was drawn.\n *\n * Degrades on both axes, because a splash is constrained by both: a 40-column terminal has no room for the\n * grid at any packing, and an 8-row one has no room for five rows of anything. Trailing blank space is\n * trimmed from each line so a caller centring on `width` centres the ink rather than the padding.\n */\nexport function wordmark(\n text: string,\n space: { readonly columns: number; readonly rows: number },\n): Wordmark {\n const trimmed = text.trim()\n if (trimmed === \"\" || !drawable(trimmed)) {\n const lines = spaced(trimmed, space.columns)\n return { lines, tier: \"plain\", width: widthOf(lines) }\n }\n\n const grid = pixels(trimmed)\n const candidates: readonly { tier: WordmarkTier; lines: readonly string[] }[] = [\n { tier: \"wide\", lines: solid(grid, \"█\", 2) },\n { tier: \"block\", lines: solid(grid, \"█\", 1) },\n { tier: \"half\", lines: packed(grid) },\n ]\n\n for (const candidate of candidates) {\n const lines = candidate.lines.map((line) => line.replace(/\\s+$/, \"\"))\n const width = widthOf(lines)\n if (width <= space.columns && lines.length <= space.rows) {\n return { lines, tier: candidate.tier, width }\n }\n }\n\n const lines = spaced(trimmed, space.columns)\n return { lines, tier: \"plain\", width: widthOf(lines) }\n}\n"
|
|
7
7
|
],
|
|
8
|
-
"mappings": ";
|
|
9
|
-
"debugId": "
|
|
8
|
+
"mappings": ";sEAoBA,cAAS,UAAK,8DAIP,SAAS,EAAS,EAAG,SAAyB,CAIjD,IAAM,EAAO,EAAM,IAAI,CAAC,EAAM,KAAQ,CAAE,KAAI,MAAK,EAAE,EAEnD,OACI,EAOE,EAPF,CAAK,cAAc,SAAnB,SACK,EAAK,IAAI,CAAC,IACP,EAGE,EAHF,CAA6B,MAAO,EAAM,MAAO,KAAI,GAA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EAAS,CAAO,EAAG,CACtC,IAAM,EAAQ,EAAO,EAAS,EAAM,OAAO,EAC3C,MAAO,CAAE,QAAO,KAAM,QAAS,MAAO,EAAQ,CAAK,CAAE,EAGzD,IAAM,EAAO,EAAO,CAAO,EACrB,EAA0E,CAC5E,CAAE,KAAM,OAAQ,MAAO,EAAM,EAAM,IAAK,CAAC,CAAE,EAC3C,CAAE,KAAM,QAAS,MAAO,EAAM,EAAM,IAAK,CAAC,CAAE,EAC5C,CAAE,KAAM,OAAQ,MAAO,EAAO,CAAI,CAAE,CACxC,EAEA,QAAW,KAAa,EAAY,CAChC,IAAM,EAAQ,EAAU,MAAM,IAAI,CAAC,IAAS,EAAK,QAAQ,OAAQ,EAAE,CAAC,EAC9D,EAAQ,EAAQ,CAAK,EAC3B,GAAI,GAAS,EAAM,SAAW,EAAM,QAAU,EAAM,KAChD,MAAO,CAAE,QAAO,KAAM,EAAU,KAAM,OAAM,EAIpD,IAAM,EAAQ,EAAO,EAAS,EAAM,OAAO,EAC3C,MAAO,CAAE,QAAO,KAAM,QAAS,MAAO,EAAQ,CAAK,CAAE",
|
|
9
|
+
"debugId": "303BD287BB7BDADB64756E2164756E21",
|
|
10
10
|
"names": []
|
|
11
11
|
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{e,A,ae,be,p,k,L}from"./index-byxrc961.js";import{N}from"./index-b6da6c16.js";import{jn,Ye}from"./index-srmhk9g5.js";import{ne,oe,Oe,H,fe,YA}from"./index-y4c32wn7.js";import{h}from"./index-k2aq5bg0.js";import{ri}from"./index-ehzwdnc3.js";import{z,Q,Mt,_A,R}from"./index-fzmmhmk2.js";import{w}from"./index-a21zyy54.js";import{g,c,iA,ZA,rA}from"./index-wzsmh5j0.js";import{t,i,_i}from"./index-2zye08c4.js";import{closeSync as Je,existsSync as Ee,mkdirSync as Qe,openSync as qe,readFileSync as Ze,readSync as en,statSync as Ae}from"node:fs";import{homedir as X}from"node:os";import{dirname as W,join as Re,resolve as nn}from"node:path";function q(n){let r=[];if(n.problem!==void 0)r.push({code:"daemon_agent_unreadable",severity:"warn",message:`Agent "${n.agentId}" could not be read: ${n.problem}`,hint:"The host skips an agent whose manifest will not load and serves the rest, so this is a warning rather than a refusal — `validate` on that agent says exactly what is wrong with it."});if(n.envFileMode!==void 0&&(n.envFileMode&63)!==0)r.push({code:"daemon_env_world_readable",severity:"warn",message:`${n.agentId}'s .env is mode ${(n.envFileMode&511).toString(8)} and holds its only secrets.`,hint:`Under a service manager that file is the *only* path credentials arrive by — a unit carries none on purpose, because its manager echoes the environment in plaintext. \`chmod 600 ${n.agentDir}/.env\`.`});return r}function Fe(n){let r=[];if(n.gitRoot!==void 0)r.push({code:"daemon_binary_in_checkout",severity:"warn",message:`The binary resolves to ${n.scriptPath}, inside a git checkout at ${n.gitRoot}.`,hint:"A rebuild, a branch switch or a `git clean` changes or breaks what the service runs, and the failure arrives with no obvious connection to the change. Fine for testing; install a released build for a service you intend to leave running."});if(/[/.](nvm|fnm|volta|asdf)\//.test(n.execPath))r.push({code:"daemon_versioned_runtime",severity:"warn",message:`The interpreter is a version-managed install: ${n.execPath}`,hint:"The absolute path is baked into the service definition, so removing that runtime version later kills the service with a message only the log file sees. A system or Homebrew install is more durable."});return r}function Z(n){let r=[];for(let s of n.retiring)r.push({code:"daemon_per_agent_retired",severity:"warn",message:`Retiring ${s} — one service hosts every agent now.`,hint:"It is unloaded, re-enabled and its definition removed. The re-enable is not cosmetic: a `disable` row persists across boots and no verb deletes it, so a label left disabled makes any future job with that name install cleanly and silently never start. Per-agent on/off is `stop <agent>`, which persists in the store instead."});if(n.servedElsewhere.length>0){let s=n.servedElsewhere[0];r.push({code:"daemon_agents_held_elsewhere",severity:"warn",message:`${n.servedElsewhere.length} agent(s) are held by other live processes — ${s?.agentId} by pid ${s?.pid} (${s?.mode}).`,hint:"The service will start and serve everything else, and report those as served elsewhere rather than fighting for them — one listener per bot token is the whole reason the lease exists. `stop` with no agent ends the other processes."})}return r.push(...Fe(n.binary)),r}function He(n,r="serving on"){let s=n.lastIndexOf(r);return s===-1?n:n.slice(s)}function ee(n){let r=He(n),s=[],o=new Set;for(let d of r.matchAll(/denied — Sender "([^"]+)" is not in channel "([^"]+)"/g))if(d[1]!==void 0)o.add(`${d[1]}|${d[2]??""}`);for(let d of o){let[a,l]=d.split("|");s.push({code:"inbound_denied",summary:`messages from ${a} are being refused — they are not on channel "${l}"'s allowFrom list`,fix:`add ${a} to allowFrom in agent.yaml, then restart. An allowlist that is empty, or that has a typo in it, refuses silently from the sender's side: they see nothing at all.`})}if(/channel_telegram_unauthorized|telegram_token_missing/.test(r))s.push({code:"channel_unauthorized",summary:"the channel rejected its token",fix:"check the token in the .env beside the manifest, then restart."});return s}var Ne=3;function te(n,r){let s=We(r),o=[];if(r.pid!==void 0)o.push({label:"state",value:`running · pid ${r.pid}`,...r.uptimeMs===void 0?{}:{note:`up ${ZA(r.uptimeMs)}`}});else if(r.leasePid!==void 0)o.push({label:"state",value:`running in a terminal · pid ${r.leasePid}`,note:"not installed as a service"});if(r.runs!==void 0&&r.runs>1)o.push({label:"starts",value:String(r.runs),...s==="restart-loop"?{note:`launchd has restarted this ${r.runs} times`}:{note:"since the service was installed"}});if(s!=="running"&&r.lastExitCode!==void 0&&r.lastExitCode!==0)o.push({label:"last exit",value:`code ${r.lastExitCode}`});if(r.stderrPath!==void 0)o.push({label:"logs",value:r.stderrPath,...r.stderrBytes===void 0?{}:{note:`(${iA(r.stderrBytes)})`}});return{verdict:s,healthy:s==="running",headline:s==="restart-loop"?`${n} — RESTART LOOP`:`${n} — ${Be(s)}`,rows:o,wantsStderrTail:s==="restart-loop"||s==="failed"||s==="installed-idle"}}function We(n){if(!n.installed)return n.leasePid===void 0?"absent":"running";if(n.pid!==void 0)return"running";if(n.disabled)return"stopped";if((n.runs??0)>=Ne&&(n.lastExitCode??0)!==0)return"restart-loop";if((n.lastExitCode??0)!==0)return"failed";return"installed-idle"}function Be(n){switch(n){case"running":return"running";case"failed":return"STOPPED AFTER A FAILURE";case"restart-loop":return"exited · nothing is running";case"stopped":return"stopped by you";case"installed-idle":return"installed · not running";case"absent":return"not installed"}}function re(n){return`${n.headline}
|
|
3
|
+
${g(n.rows)}`}function T(n){return["HOME","PATH","TMPDIR",`${n}SERVICE`,`${n}HOME`]}class B extends Error{code="daemon_secret_in_service";hint;constructor(n,r,s){super(`The service definition would carry an environment variable named ${n}.`);this.hint=`A ${s} unit is readable and its manager echoes every environment value in plaintext to any process running as this user — so a credential here is a credential published. The agent reads its own secrets from the .env beside its manifest, which is what the service is pointed at. Only these may appear: ${r.join(", ")}.`}}function I(n,r,s){let o=T(r);for(let d of Object.keys(n))if(!o.includes(d))throw new B(d,o,s)}var Ue={Crashed:!0},E=30,O=30;function In(n,r){return`${n}.agent.${r}`}function P(n){return`${n}.server`}function S(n){return n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function M(n,r){I(n.environment,r,"launchd");let s=n.programArguments.map((a)=>` <string>${S(a)}</string>`).join(`
|
|
4
|
+
`),o=Object.entries(n.environment).map(([a,l])=>` <key>${S(a)}</key>
|
|
5
|
+
<string>${S(l)}</string>`).join(`
|
|
6
|
+
`);return`<?xml version="1.0" encoding="UTF-8"?>
|
|
7
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
8
|
+
<!--
|
|
9
|
+
${n.provenance.map((a)=>` ${S(a)}`).join(`
|
|
10
|
+
`)}
|
|
11
|
+
-->
|
|
12
|
+
<plist version="1.0">
|
|
13
|
+
<dict>
|
|
14
|
+
<key>Label</key>
|
|
15
|
+
<string>${S(n.label)}</string>
|
|
16
|
+
<key>ProgramArguments</key>
|
|
17
|
+
<array>
|
|
18
|
+
${s}
|
|
19
|
+
</array>
|
|
20
|
+
<key>RunAtLoad</key>
|
|
21
|
+
<true/>
|
|
22
|
+
<key>KeepAlive</key>
|
|
23
|
+
<dict>
|
|
24
|
+
<key>Crashed</key>
|
|
25
|
+
<${Ue.Crashed}/>
|
|
26
|
+
</dict>
|
|
27
|
+
<key>ThrottleInterval</key>
|
|
28
|
+
<integer>${E}</integer>
|
|
29
|
+
<key>ExitTimeOut</key>
|
|
30
|
+
<integer>${O}</integer>
|
|
31
|
+
<key>ProcessType</key>
|
|
32
|
+
<string>Adaptive</string>
|
|
33
|
+
<key>WorkingDirectory</key>
|
|
34
|
+
<string>${S(n.workingDirectory)}</string>
|
|
35
|
+
<key>StandardOutPath</key>
|
|
36
|
+
<string>${S(n.stdoutPath)}</string>
|
|
37
|
+
<key>StandardErrorPath</key>
|
|
38
|
+
<string>${S(n.stderrPath)}</string>
|
|
39
|
+
<key>EnvironmentVariables</key>
|
|
40
|
+
<dict>
|
|
41
|
+
${o}
|
|
42
|
+
</dict>
|
|
43
|
+
</dict>
|
|
44
|
+
</plist>
|
|
45
|
+
`}function ie(n){let r=[];for(let s of n.split(`
|
|
46
|
+
`)){let o=s.split("\t");if(o.length<3)continue;let[d,a,l]=o;if(l===void 0||l==="Label"||l==="")continue;let u=Number.parseInt(a??"",10);r.push({...d===void 0||d==="-"?{}:{pid:Number.parseInt(d,10)},status:Number.isFinite(u)?u:0,label:l})}return r}function se(n){let r={};for(let s of n.split(`
|
|
47
|
+
`)){let o=s.trim(),d=/^pid = (\d+)$/.exec(o);if(d?.[1]!==void 0)r.pid=Number.parseInt(d[1],10);let a=/^runs = (\d+)$/.exec(o);if(a?.[1]!==void 0)r.runs=Number.parseInt(a[1],10);let l=/^last exit code = (-?\d+)$/.exec(o);if(l?.[1]!==void 0)r.lastExitCode=Number.parseInt(l[1],10);let u=/^state = (.+)$/.exec(o);if(u?.[1]!==void 0)r.jobState=u[1];let f=/^stdout path = (.+)$/.exec(o);if(f?.[1]!==void 0)r.stdoutPath=f[1];let m=/^stderr path = (.+)$/.exec(o);if(m?.[1]!==void 0)r.stderrPath=m[1]}return r}function de(n){let r=[];for(let s of n.split(`
|
|
48
|
+
`)){let o=/^\s*"(.+)"\s*=>\s*(disabled|true)\s*$/.exec(s);if(o?.[1]!==void 0)r.push(o[1])}return r}function je(n,r){if(r<n)return{from:0,to:r,truncated:!0};return{from:n,to:r,truncated:!1}}async function le(n,r,s){let o=new Map(n.map((a)=>[a.path,s.offsets[a.path]??0])),d;while(!r.stopped()){for(let a of n){let l=r.sizeOf(a.path);if(l===void 0)continue;let u=je(o.get(a.path)??0,l);if(o.set(a.path,u.to),u.truncated)r.write(`
|
|
49
|
+
── ${a.label} was emptied ──
|
|
50
|
+
`),d=a.label;if(u.to<=u.from)continue;let f=r.read(a.path,u.from,u.to);if(f==="")continue;if(n.length>1&&a.label!==d)r.write(`
|
|
51
|
+
── ${a.label} ──
|
|
52
|
+
`),d=a.label;r.write(f)}await r.wait(s.intervalMs)}}import{existsSync as Ve,mkdirSync as j,readdirSync as pe,rmSync as ye,writeFileSync as me}from"node:fs";import{basename as Ke,dirname as D,join as ge}from"node:path";import{join as ue}from"node:path";function ce(n,r,s=process.env){let o=s.XDG_CONFIG_HOME,d=o===void 0||o===""?ue(r,".config"):o;return ue(d,"systemd","user",`${n}.service`)}function U(n,r){if(/[\r\n]/.test(n))throw Error(`${r} contains a newline, which systemd cannot express. hint: a unit value runs to end of line, so this would silently truncate rather than fail — rename the path.`)}function Ge(n){if(!/[\s"\\]/.test(n))return n;return`"${n.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function C(n,r){I(n.environment,r,"systemd");for(let a of n.programArguments)U(a,"ExecStart");U(n.workingDirectory,"WorkingDirectory");for(let[a,l]of Object.entries(n.environment))U(l,`Environment=${a}`);let s=n.programArguments.map(Ge).join(" "),o=Object.entries(n.environment).map(([a,l])=>`Environment=${a}=${l}`).join(`
|
|
53
|
+
`);return`${n.provenance.map((a)=>`# ${a}`).join(`
|
|
54
|
+
`)}
|
|
55
|
+
|
|
56
|
+
[Unit]
|
|
57
|
+
Description=${n.label}
|
|
58
|
+
After=network-online.target
|
|
59
|
+
Wants=network-online.target
|
|
60
|
+
|
|
61
|
+
[Service]
|
|
62
|
+
Type=simple
|
|
63
|
+
ExecStart=${s}
|
|
64
|
+
WorkingDirectory=${n.workingDirectory}
|
|
65
|
+
${o}
|
|
66
|
+
# A configuration fault stops the service once rather than retrying into a log nobody opens.
|
|
67
|
+
# Mirrors launchd's KeepAlive: {Crashed: true} — see launchd.ts for why that is structural.
|
|
68
|
+
Restart=on-failure
|
|
69
|
+
RestartSec=${E}
|
|
70
|
+
# Must exceed the runtime's own stop deadline, or the reaper that kills backgrounded exec
|
|
71
|
+
# children never finishes and they outlive the service.
|
|
72
|
+
TimeoutStopSec=${O}
|
|
73
|
+
KillMode=mixed
|
|
74
|
+
|
|
75
|
+
[Install]
|
|
76
|
+
WantedBy=default.target
|
|
77
|
+
`}function he(n,r){return["systemctl --user daemon-reload",`systemctl --user enable --now ${n}`,`loginctl enable-linger ${r}`]}var Xe=6000,ze=200,ve=(n,r)=>{let s=ri({command:n,args:r});return{code:s.code,stdout:s.stdout,stderr:s.stderr}};function PA(n,r){if(n==="darwin")return new xe(r);if(n==="linux")return new $e(r);throw G(n)}function we(n){return n==="darwin"}function G(n,r){let s=r===void 0?"":` For a systemd user unit, the line to write is:
|
|
78
|
+
|
|
79
|
+
${r}
|
|
80
|
+
Restart=on-failure
|
|
81
|
+
RestartSec=30
|
|
82
|
+
|
|
83
|
+
Put no secrets in the unit: the agent reads the .env beside its manifest, and \`systemctl show\` echoes Environment= to anyone.`;return new A({code:"daemon_platform_unsupported",message:`daemon installs a macOS LaunchAgent or a systemd user unit, and this platform is ${n}.`,hint:`No service manager is implemented for this platform.${s} In a container, run \`serve\` in the foreground and let the container runtime supervise it; that is the deployment this runtime is designed around.`})}class $e{id="systemd";#r;#e;#i;#t;constructor(n){this.#r=n.home,this.#e=n.envPrefix,this.#i=n.exec??ve,this.#t=n.env??process.env}unitPath(n){return ce(n,this.#r,this.#t)}install(n){let r=this.unitPath(n.label),s=C(n,this.#e);j(D(r),{recursive:!0}),me(r,s,{encoding:"utf8",mode:384})}uninstall(n){ye(this.unitPath(n),{force:!0})}stop(n){throw this.#n(`systemctl --user stop ${n}`)}start(n){throw this.#n(`systemctl --user start ${n}`)}restart(n){throw this.#n(`systemctl --user restart ${n}`)}state(n){return{installed:Ve(this.unitPath(n)),disabled:!1,liveness:!1}}labels(n){try{return pe(D(this.unitPath(n))).filter((r)=>r.startsWith(n)&&r.endsWith(".service")).map((r)=>r.slice(0,-8)).sort()}catch{return[]}}followUp(n){return he(n,this.#s())}caution(){let n=this.#s(),r=this.#i("loginctl",["show-user",n,"--property=Linger"]);if(r.code===0&&/Linger=yes/i.test(r.stdout))return;return`A systemd user unit stops when your last session ends. \`loginctl enable-linger ${n}\` is what keeps it running after you log out or close an SSH connection.`}#s(){return this.#t.USER??this.#t.LOGNAME??Ke(this.#r)}#n(n){return new A({code:"daemon_manual_step",message:`This has to be run yourself: ${n}`,hint:`Unit files are written and read from here, and the lifecycle is not driven from here — nothing in this project's test environment can run \`systemctl --user\` (a container has no systemd, and a CI runner has no user session bus), and a command that reported success while nothing happened would be worse than this sentence. The unit is at ${this.unitPath(n.split(" ").pop()??"")}.`})}}class xe{id="launchd";#r;#e;#i;#t;constructor(n){this.#r=n.home,this.#e=`gui/${n.uid}`,this.#i=n.envPrefix,this.#t=n.exec??ve}unitPath(n){return ge(this.#r,"Library","LaunchAgents",`${n}.plist`)}install(n){let r=this.unitPath(n.label),s=M(n,this.#i);if(j(D(r),{recursive:!0}),j(D(n.stdoutPath),{recursive:!0}),this.#n(["bootout",`${this.#e}/${n.label}`],{tolerate:!0}),this.#s(n.label),me(r,s,{encoding:"utf8",mode:384}),this.#n(["enable",`${this.#e}/${n.label}`],{tolerate:!0}),this.#n(["bootstrap",this.#e,r]),!this.state(n.label).installed)throw new A({code:"daemon_not_loaded",message:`${n.label} was written to ${r} but launchd did not load it.`,hint:`\`launchctl bootstrap\` returned success and \`launchctl print ${this.#e}/${n.label}\` finds nothing, which usually means an earlier copy was still unloading. Try again in a moment. Over SSH with no desktop session the ${this.#e} domain is unavailable and no LaunchAgent can load at all.`})}#s(n){let r=Date.now()+Xe;while(Date.now()<r){if(this.#t("launchctl",["print",`${this.#e}/${n}`]).code!==0)return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ze)}}uninstall(n){this.#n(["bootout",`${this.#e}/${n}`],{tolerate:!0}),this.#n(["enable",`${this.#e}/${n}`],{tolerate:!0}),ye(this.unitPath(n),{force:!0})}stop(n){this.#n(["disable",`${this.#e}/${n}`],{tolerate:!0}),this.#n(["bootout",`${this.#e}/${n}`],{tolerate:!0})}start(n){this.#n(["enable",`${this.#e}/${n}`],{tolerate:!0}),this.#n(["bootstrap",this.#e,this.unitPath(n)])}restart(n){this.#n(["kickstart","-k",`${this.#e}/${n}`])}state(n){let r=this.#t("launchctl",["print",`${this.#e}/${n}`]),s=de(this.#t("launchctl",["print-disabled",this.#e]).stdout).includes(n);if(r.code!==0)return{installed:!1,disabled:s,liveness:!0};let o=se(r.stdout);return{installed:!0,disabled:s,liveness:!0,print:o,...o.pid===void 0?{}:{pid:o.pid}}}labels(n){let r=ie(this.#t("launchctl",["list"]).stdout).map((o)=>o.label).filter((o)=>o.startsWith(n)),s=[];try{s=pe(ge(this.#r,"Library","LaunchAgents")).filter((o)=>o.startsWith(n)&&o.endsWith(".plist")).map((o)=>o.slice(0,-6))}catch{}return[...new Set([...r,...s])].sort()}followUp(){return[]}caution(){return}#n(n,r={}){let s=this.#t("launchctl",n);if(s.code===0||r.tolerate===!0)return s;throw new A({code:"daemon_launchctl_failed",message:`launchctl ${n.join(" ")} failed (${s.code}): ${s.stderr.trim()||"no output"}`,hint:`Code 5 usually means the service is already loaded — try \`daemon restart\`. Code 37 means an operation is still in progress; wait a moment. Code 125 or 112 means the ${this.#e} domain is unavailable, which happens over SSH with no GUI session: a LaunchAgent needs a logged-in desktop session, and the exit timeout is ${O}s.`})}}var Se=["install","uninstall","start","stop","restart","status","logs"];async function ke(n){if(!Se.includes(n.action))throw new A({code:"cli_daemon_unknown_action",message:`daemon takes one of ${Se.join(", ")}, not "${n.action}".`,hint:`Usage: ${e.slug} daemon <action> <agent>. Run \`${e.slug} daemon --help\` for what each one does.`});let r=n.action;if(n.manifestPath!==void 0&&r!=="status"&&r!=="logs")throw new A({code:"daemon_per_agent_retired",message:`daemon ${r} no longer takes an agent — one service hosts every agent.`,hint:`\`${e.slug} daemon ${r}\` acts on that one service. Per-agent on/off is \`${e.slug} stop <agent>\` and \`${e.slug} start <agent>\`, which persist in the store rather than as a unit — so an agent you switch off stays off across a restart without the host going down with it.`});let s=n.platform??process.platform,o=rn();if(s!=="darwin"&&s!=="linux"&&r!=="status")throw G(s,on(o,n.manifestPath??"<manifest>"));let d=s==="darwin"||s==="linux"?PA(s,{home:X(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...n.exec===void 0?{}:{exec:n.exec},...n.env===void 0?{}:{env:n.env}}):void 0;switch(r){case"status":return await gn(n,d);case"install":return await tn(n,o,d);case"uninstall":return cn(n,d);case"start":case"stop":case"restart":return hn(r,d);case"logs":return await yn(n)}}async function tn(n,r,s){let o=P(e.slug),d=Mt(n.env),a=(s?.labels(`${e.slug}.agent.`)??[]).filter((y)=>y!==o),l=[...Z({binary:r,retiring:a,servedElsewhere:(await Oe(n.store)).map((y)=>({agentId:y.agentId,pid:y.pid,mode:y.mode}))}),...R(n.env).flatMap((y)=>{let v=ln(y.dir);return q({agentId:y.id??y.ref,agentDir:y.dir,...y.problem===void 0?{}:{problem:y.problem},...v===void 0?{}:{envFileMode:v}})})],u={label:o,programArguments:[r.execPath,r.scriptPath,"serve","--store",Q()].filter((y)=>y!==""),workingDirectory:z(n.env),stdoutPath:d.out,stderrPath:d.err,environment:an(o),provenance:[`Generated by \`${e.slug} daemon install\`. One service hosts every agent.`,"Rewritten on every install — it names no agent, so there is nothing here to edit","when you add one. Switch an agent off with `stop <agent>`, which persists.","There are no secrets here and there never will be: a service manager echoes a","unit's environment in plaintext to anything running as this user. Each agent","reads its own credentials from the .env beside its manifest."]};if(n.dryRun===!0){if(process.stdout.write(s?.id==="systemd"?C(u,e.envPrefix):M(u,e.envPrefix)),l.length>0)process.stderr.write(Pe(l));return t}for(let y of a)s?.uninstall(y);if(l.length>0)process.stdout.write(Pe(l));Qe(W(d.out),{recursive:!0}),s?.install(u);let f=s?.followUp(o)??[];if(process.stdout.write(`${o} — ${f.length===0?"service installed":"unit written"}
|
|
84
|
+
${g([{label:"runs",value:`${_(r.execPath)} … serve`},{label:"hosts",value:"every agent in the sandbox that is not stopped"},{label:"logs",value:_(d.err)},{label:"restarts",value:`on crash only, at most one per ${E}s`}])}
|
|
85
|
+
`),f.length>0)process.stdout.write(`
|
|
86
|
+
Not started yet — run these:
|
|
87
|
+
${f.map((y,v)=>` ${v+1}. ${y}`).join(`
|
|
88
|
+
`)}
|
|
89
|
+
`);let m=s?.caution();if(m!==void 0)process.stdout.write(`
|
|
90
|
+
${m}
|
|
91
|
+
`);return process.stdout.write(`
|
|
92
|
+
A configuration error stops it once rather than looping — \`${e.slug} daemon status\` says why.
|
|
93
|
+
`),t}function rn(){let n=V(process.execPath),r=V(process.argv[1]??""),s=sn(W(r));return{execPath:n,scriptPath:r,...s===void 0?{}:{gitRoot:s}}}function V(n){try{return w("node:fs").realpathSync(n)}catch{return n}}function sn(n){let r=n;for(let s=0;s<40;s+=1){if(Ee(Re(r,".git")))return r;let o=W(r);if(o===r)return;r=o}return}function on(n,r){return`ExecStart=${n.execPath} ${n.scriptPath} serve ${r} --store ${Q()}`}function an(n){let r=X(),o=[W(V(process.execPath)),"/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"].filter((l,u,f)=>f.indexOf(l)===u).join(":"),d={HOME:r,PATH:o,[`${e.envPrefix}SERVICE`]:n},a=process.env[`${e.envPrefix}HOME`];if(a!==void 0&&a!=="")d[`${e.envPrefix}HOME`]=a;return d}function ln(n){try{return Ae(Re(n,".env")).mode}catch{return}}function Pe(n){return`${n.map((r)=>`${r.severity==="block"?"refused":"warning"}: ${r.message}
|
|
94
|
+
hint: ${r.hint}`).join(`
|
|
95
|
+
|
|
96
|
+
`)}
|
|
97
|
+
`}function cn(n,r){let s=P(e.slug),o=Mt(n.env);for(let d of(r?.labels(`${e.slug}.agent.`)??[]).filter((a)=>a!==s))r?.uninstall(d),process.stdout.write(` also removed ${d}
|
|
98
|
+
`);return r?.uninstall(s),process.stdout.write(`${s} — service removed
|
|
99
|
+
${g([{label:"logs kept",value:_(o.err)},{label:"agents",value:"unchanged — nothing was switched off"}])}
|
|
100
|
+
`),t}function hn(n,r){let s=P(e.slug);if(r===void 0)return i;if(n==="start")r.start(s);if(n==="stop")r.stop(s);if(n==="restart")r.restart(s);let o=n==="stop"?" — the whole host. It stays stopped across a login until you start it again, and no"+" agent was switched off":"";return process.stdout.write(`${s} — ${n}${n==="stop"?"ped":"ed"}${o}
|
|
101
|
+
`),t}async function gn(n,r){let s=P(e.slug),o=await Oe(n.store);if(n.manifestPath===void 0){if(r?.state(s).installed!==!0&&o.length===0)return process.stdout.write(`no server is installed and nothing is running
|
|
102
|
+
hint: \`${e.slug} daemon install\` keeps one running after you close the terminal. One service hosts every agent.
|
|
103
|
+
`),i}let d=n.manifestPath===void 0?[s]:[_e(n.manifestPath)],a=await Promise.all(d.map((f)=>pn(f,r,{...f===s?{label:s}:{},logs:f===s?Mt(n.env):_A(f),...n.store===void 0?{}:{store:n.store},...f===s&&o[0]!==void 0?{leaseOf:o[0].agentId}:{}}))),l=n.manifestPath===void 0&&o.length>0?o.map((f)=>f.agentId).sort():[],u=(await fn()).filter((f)=>n.manifestPath===void 0||d.includes(f.agentId));if(n.json===!0)process.stdout.write(`${JSON.stringify({agents:a,hosting:l,disabled:u},null,2)}
|
|
104
|
+
`);else{for(let f of a){process.stdout.write(`${re(f.report)}
|
|
105
|
+
`);for(let m of f.attention)process.stdout.write(`
|
|
106
|
+
needs you ${m.summary}
|
|
107
|
+
${m.fix}
|
|
108
|
+
`);if(f.report.wantsStderrTail&&f.tail!=="")process.stdout.write(`
|
|
109
|
+
last lines of stderr:
|
|
110
|
+
${c(f.tail,4)}
|
|
111
|
+
`);if(f.report.verdict==="restart-loop"||f.report.verdict==="failed")process.stdout.write(`
|
|
112
|
+
fix correct the error above, then \`${e.slug} daemon restart ${f.agentId}\`
|
|
113
|
+
`);process.stdout.write(`
|
|
114
|
+
`)}if(l.length>0)process.stdout.write(` hosting ${l.length} ${l.length===1?"agent":"agents"}: ${l.join(", ")}
|
|
115
|
+
`);if(u.length>0){let f=`${u.length} ${u.length===1?"agent":"agents"}`;process.stdout.write(` ${f} switched off, so nothing is hosting them:
|
|
116
|
+
`);for(let m of u)process.stdout.write(` ${m.agentId}${m.reason===void 0?"":` — ${m.reason}`}${m.disabledAt===void 0?"":` (since ${m.disabledAt})`}
|
|
117
|
+
`);process.stdout.write(` \`${e.slug} start <agent>\` switches one back on — a restart alone will not.
|
|
118
|
+
|
|
119
|
+
`)}}return a.every((f)=>f.report.healthy)?t:i}async function fn(){try{let n=await L.open({path:Q()});try{return(await n.agentState.list()).filter((r)=>!r.enabled).map((r)=>({agentId:r.agentId,...r.reason===void 0?{}:{reason:r.reason},...r.disabledAt===void 0?{}:{disabledAt:r.disabledAt}}))}finally{await n.close()}}catch{return[]}}async function pn(n,r,s){let o=s.label,d=o===void 0?void 0:r?.unitPath(o),a=o===void 0?void 0:r?.state(o),l=s.logs,u;try{let x=await L.open({path:s.store??Q()});u=await x.leases.get(s.leaseOf??n),await x.close()}catch{u=void 0}if(u!==void 0&&!k(u.pid))u=void 0;let f=a?.print?.stderrPath??l.err,m=F(f),y={installed:d!==void 0&&Ee(d)||a?.installed===!0,disabled:a?.disabled??!1,...a?.pid===void 0?{}:{pid:a.pid},...a?.print?.runs===void 0?{}:{runs:a.print.runs},...a?.print?.lastExitCode===void 0?{}:{lastExitCode:a.print.lastExitCode},stderrPath:_(f),...m===void 0?{}:{stderrBytes:m},...u===void 0?{}:{leasePid:u.pid,leaseMode:u.mode,leaseStartedAt:u.startedAt,uptimeMs:Date.now()-Date.parse(u.startedAt)}},v=te(n,y),b=ee(K(l.out,200));return{agentId:n,report:v,tail:v.wantsStderrTail?K(f,20):"",attention:b}}async function yn(n){let r=n.manifestPath===void 0?void 0:_e(n.manifestPath),s=r??P(e.slug),o=r===void 0?Mt(n.env):_A(r);if(n.truncate===!0){for(let a of[o.out,o.err])try{w("node:fs").writeFileSync(a,"")}catch{}return process.stdout.write(`${s} — logs truncated
|
|
120
|
+
`),t}let d=K(o.err,n.lines??40);if(process.stdout.write(d===""?`${_(o.err)} is empty
|
|
121
|
+
`:`${d}
|
|
122
|
+
`),n.follow!==!0)return t;return await le([{path:o.err,label:"stderr"},{path:o.out,label:"stdout"}],mn(),{offsets:{[o.err]:F(o.err)??0,[o.out]:F(o.out)??0},intervalMs:_i}),t}function mn(){let n=!1,r,s=()=>{n=!0,r?.()};return process.on("SIGINT",s),h(()=>{process.off("SIGINT",s)}),{sizeOf:(o)=>F(o),read:(o,d,a)=>{try{let l=qe(o,"r");try{let u=Buffer.alloc(a-d),f=en(l,u,0,u.length,d);return u.subarray(0,f).toString("utf8")}finally{Je(l)}}catch{return""}},write:(o)=>void process.stdout.write(o),wait:(o)=>new Promise((d)=>{if(n){d();return}let a=setTimeout(d,o);r=()=>{clearTimeout(a),d()}}),stopped:()=>n}}function _e(n){let r=p(n);if(r.id===void 0||r.id==="")throw new A({code:"cli_daemon_agent_id_missing",message:`${n} declares no id, so there is no stable name to install a service under.`,hint:"A service label is derived from the manifest id and has to survive a rename of the directory. Add `id: <name>` to the manifest."});return r.id}function _(n){return rA(nn(n),X())}function F(n){try{return Ae(n).size}catch{return}}function K(n,r){try{let s=Ze(n,"utf8").trimEnd();if(s==="")return"";return s.split(`
|
|
123
|
+
`).slice(-r).join(`
|
|
124
|
+
`)}catch{return""}}var St=T(e.envPrefix);import{existsSync as vn}from"node:fs";function Jn(n=process.env){return vn("/.dockerenv")||n.container!==void 0}function wn(n){let r=n.env??process.env;if(!n.needsServer)return"command-needs-no-server";if(n.disabled===!0)return"disabled-by-flag";if(r[`${e.envPrefix}SERVICE`]!==void 0)return"is-the-service";if(r[`${e.envPrefix}NO_BOOTSTRAP`]!==void 0)return"disabled-by-env";if(Jn(r))return"in-container";if(r.CI!==void 0)return"in-ci";return}async function un(n){let r=wn(n);if(r!==void 0)return{kind:"skipped",reason:r};if((await Oe(n.store)).length>0)return{kind:"already"};let o=n.platform??process.platform;if(!we(o))return{kind:"manual",lines:[`${e.slug} daemon install`]};let d=n.install;if(d===void 0)return{kind:"failed",message:"no installer was supplied",hint:"This is a wiring mistake rather than a configuration one: `ensureServer` is called with an `install` callback by `index.ts`."};try{return await d()}catch(a){return{kind:"failed",message:a instanceof Error?a.message:String(a),hint:`The command ran anyway. \`${e.slug} daemon install\` reports the same failure with more detail — on macOS over SSH it is usually that a LaunchAgent needs a logged-in desktop session.`}}}function uA(n){switch(n.kind){case"started":return`started the background server · \`${e.slug} daemon uninstall\` to undo
|
|
125
|
+
`;case"manual":return`no server is running · ${n.lines.join(", then ")}
|
|
126
|
+
`;case"failed":return`could not start a background server: ${n.message}
|
|
127
|
+
hint: ${n.hint}
|
|
128
|
+
`;default:return}}async function dn(){let n=process.stdout.write.bind(process.stdout);process.stdout.write=()=>!0;try{let r=await ke({action:"install"});if(r!==t)return{kind:"failed",message:`daemon install exited ${r}`,hint:`Run \`${e.slug} daemon install\` to see what it said.`};return{kind:"started",label:`${e.slug}.server`}}finally{process.stdout.write=n}}var bn=15000,$n=250;async function rt(n={}){let r=await un({needsServer:!0,disabled:n.install===void 0,...n.install===void 0?{}:{install:n.install},...n.store===void 0?{}:{store:n.store},...n.env===void 0?{}:{env:n.env}}),s=Date.now()+(r.kind==="started"?n.waitMs??bn:0);for(;;){let o=await oe(n.store);if(o!==void 0||Date.now()>=s)return{outcome:r,host:o};await new Promise((d)=>setTimeout(d,$n))}}async function dA(n,r,s){let o=H(r),d=await ne(o,s);if(d!==void 0&&d.baseUrl!==void 0)return{ok:!0,status:200,already:!0};return await fe(n,`/v1/agents/${encodeURIComponent(o)}/start`,{},r)}async function st(n,r){let s=H(n),o=await ne(s,r);if(o===void 0||o.baseUrl===void 0)return{kind:"no-host"};let d=await fe(o,`/v1/agents/${encodeURIComponent(s)}/reload`,{},n);if(d.ok){let a=d.body;return{kind:"reloaded",pid:o.pid,adopted:a?.adopted??[]}}if(d.status===409)return{kind:"busy",pid:o.pid};return{kind:"failed",pid:o.pid,status:d.status,...d.detail===void 0?{}:{detail:d.detail},...d.hint===void 0?{}:{hint:d.hint}}}async function UA(n,r){let s=H(n);if(s==="")return;let o=await ne(s,r);if(o===void 0||o.baseUrl===void 0)return;let d=await YA(o,"GET",`/v1/agents/${encodeURIComponent(s)}`,n);if(!d.ok)return;let a=d.body;if(a?.channels===void 0)return;return new Map(a.channels.map((l)=>[l.id,l]))}var xn=25000,Sn=120000,Pn=2000;async function at(n){let r=n.out??((a)=>process.stdout.write(a)),s=n.pollMs??Pn,o,d=Date.now()+(n.codeWaitMs??xn);while(Date.now()<d){let a=(await UA(n.manifestPath,n.store))?.get(n.channelId);if(a?.status==="connected")return r(`Paired. ${n.channelId} is linked.
|
|
129
|
+
`),"paired";if(a?.input!==void 0&&a.input.payload!==o){if(o===void 0)d=Date.now()+(n.pairWaitMs??Sn);o=a.input.payload;let l=o.replace(/(.{4})(?=.)/g,"$1 ");r(`
|
|
130
|
+
${a.detail??"On the phone: WhatsApp › Settings › Linked devices › Link with phone number. Enter this code"}:
|
|
131
|
+
|
|
132
|
+
${l}
|
|
133
|
+
|
|
134
|
+
Waiting — this finishes on its own, or press ctrl-c and pair later.
|
|
135
|
+
`)}await new Promise((l)=>setTimeout(l,s))}return o===void 0?"no-code":"timeout"}var kn=25000,En=120000;async function gt(n){let r=n.out??((v)=>process.stdout.write(v)),s=n.factory??N.whatsapp;if(s===void 0)return"unavailable";let o;try{o=s({id:n.channelId,agentId:"",dir:n.dir,env:{},config:{authDir:n.authDir??"./.whatsapp",pairWith:n.number}})}catch{return"unavailable"}let d,a=!1,l,u,f=()=>{u?.(),u=void 0},m={receive:()=>{},status:(v,b,x)=>{if(v==="needs_input"&&x!==void 0&&d===void 0)d=x.payload,f();if(v==="connected")a=!0,f()},error:(v)=>{let b=v?.message;if(b!==void 0&&l===void 0)l=b}},y=async(v,b)=>{let x=Date.now()+v;while(!b()&&Date.now()<x)await new Promise((Y)=>{let Le=setTimeout(Y,Math.min(500,x-Date.now()));u=()=>{clearTimeout(Le),Y()}})};try{if(await o.start(m),r(`
|
|
136
|
+
Connecting to WhatsApp…
|
|
137
|
+
`),await y(n.codeWaitMs??kn,()=>d!==void 0||a),d===void 0&&!a)return r(`
|
|
138
|
+
No pairing code arrived${l===void 0?"":` — ${l}`}
|
|
139
|
+
`),"no-code";if(d!==void 0&&!a)r(`
|
|
140
|
+
On the phone: WhatsApp › Settings › Linked devices › Link with phone number.
|
|
141
|
+
`+`Enter this code for +${n.number}:
|
|
142
|
+
|
|
143
|
+
${An(d)}
|
|
144
|
+
|
|
145
|
+
`+`Waiting — this finishes on its own, or press ctrl-c and pair later.
|
|
146
|
+
`),await y(n.pairWaitMs??En,()=>a);if(a)return r(`
|
|
147
|
+
Paired. WhatsApp is linked to +${n.number}.
|
|
148
|
+
`),"paired";return"code-shown"}catch{return"no-code"}finally{await o.stop().catch(()=>{})}}function An(n){return n.length===8?`${n.slice(0,4)} ${n.slice(4)}`:n}function Ro(n){return` Pair WhatsApp later: \`${e.slug} channels pair ${n} wa\` — or from the web UI.
|
|
149
|
+
`}import{existsSync as Te,readFileSync as Ie,rmSync as Rn}from"node:fs";import{dirname as Me,isAbsolute as On,join as Ce,resolve as _n}from"node:path";var De=new Map([["telegram","tokenEnv"]]);function Cn(n){let s=p(n).channels??[],o=jn(n),d=Te(o)?be(Ie(o,"utf8")):{};return s.map((a)=>{let l=De.get(a.type),u=l===void 0?void 0:typeof a[l]==="string"?a[l]:void 0;return{id:a.id,type:a.type,enabled:a.enabled!==!1,...u===void 0?{}:{credentialEnv:u},...u===void 0?{}:{credentialSet:(d[u]??"")!==""},...typeof a.pairWith==="string"?{pairWith:a.pairWith}:{},...a.type==="whatsapp"?{paired:Mn(n,a)}:{},...typeof a.authDir==="string"?{authDir:a.authDir}:{},allowFrom:a.allowFrom??[]}})}async function ct(n,r,s){let o=p(n).channels??[],d=o.find((a)=>a.id===r);if(d===void 0)throw J(r,o.map((a)=>a.id));if(d.enabled!==!1===s)return{note:`Channel "${r}" is already ${s?"connected":"disconnected"}.`,changed:!1};return await ae({file:n,path:["channels"],value:o.map((a)=>a.id===r?{...a,enabled:s}:{...a})}),{note:s?`Channel "${r}" is connected — it starts at the agent's next start.`:`Channel "${r}" is disconnected. A disabled channel is never constructed, so it reads no credential and opens no socket.`,changed:!0}}function lt(n,r,s){let o=p(n).channels??[],d=o.find((f)=>f.id===r);if(d===void 0)throw J(r,o.map((f)=>f.id));let a=De.get(d.type),l=a===void 0?void 0:typeof d[a]==="string"?d[a]:void 0;if(l===void 0)throw new A({code:"channel_has_no_credential",message:`Channel "${r}" (type ${d.type}) keeps no credential in the .env.`,hint:d.type==="whatsapp"?"WhatsApp is paired by scanning a QR, not by a value anybody types. Use `channels unpair` to forget the current pairing and scan a new code.":"Only a channel whose manifest entry names an environment variable has one to set. Check the entry's own fields.",field:`channels[${r}]`});return{note:`${Ye(n,l,s).note}. It is read at the agent's next start.`,variable:l}}function J(n,r){return new A({code:"channel_unknown",message:`This agent declares no channel with id "${n}".`,hint:r.length===0?"It declares no channels at all. Add one with `config set <agent> channels`, or answer the channel questions in `init`.":`Declared: ${r.join(", ")}. The id is the channel's own, not its type.`,field:"channelId"})}function It(n,r){let s=p(n).channels??[],o=s.find((a)=>a.id===r);if(o===void 0)throw J(r,s.map((a)=>a.id));let d=Tn(n,o);if(d===void 0)throw new A({code:"channel_has_no_pairing",message:`Channel "${r}" (type ${o.type}) stores no pairing.`,hint:"Only a channel linked by scanning a code has one to forget. A credential somebody typed is changed with `channels credential`, and a channel is switched off with `channels disconnect`.",field:`channels[${r}]`});return Rn(d,{recursive:!0,force:!0}),{note:`Forgot the pairing — deleted ${d}. The next start offers a new code to scan; the old device may still be listed on the phone, which is the only place it can be removed.`}}function Tn(n,r){if(r.type!=="whatsapp")return;let s=typeof r.authDir==="string"?r.authDir:"./.whatsapp";return Ce(Me(n),s)}function Mn(n,r){let s=typeof r.authDir==="string"?r.authDir:"./.whatsapp",o=On(s)?s:_n(Me(n),s),d=Ce(o,"creds.json");if(!Te(d))return!1;try{return JSON.parse(Ie(d,"utf8")).registered===!0}catch{return!1}}
|
|
150
|
+
export{In,PA,ke,Jn,un,uA,dn,rt,dA,st,UA,at,gt,Ro,Cn,ct,lt,It};
|
|
151
|
+
|
|
152
|
+
//# debugId=B3E03F0C31FC776E64756E2164756E21
|
|
153
|
+
//# sourceMappingURL=index-h828nk24.js.map
|