@sma1lboy/rove 0.9.252 → 0.9.253
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli/{chunk-952aedqm.js → chunk-02h0488p.js} +1 -1
- package/dist/cli/{chunk-r0etyq15.js → chunk-08ycv55d.js} +1 -1
- package/dist/cli/{chunk-namxa4wy.js → chunk-0x7zcw52.js} +1 -1
- package/dist/cli/{chunk-gaf6n1ea.js → chunk-19h18xca.js} +1 -1
- package/dist/cli/{chunk-07jq0271.js → chunk-1mpheecn.js} +1 -1
- package/dist/cli/{chunk-md094j05.js → chunk-278sc87n.js} +1 -1
- package/dist/cli/{chunk-zzzm2cfx.js → chunk-2bmebw8q.js} +2 -2
- package/dist/cli/{chunk-jwnhthx9.js → chunk-2nfz06mq.js} +1 -1
- package/dist/cli/chunk-34vpdm19.js +2 -0
- package/dist/cli/{chunk-qyfmfpjg.js → chunk-3dgghmjv.js} +1 -1
- package/dist/cli/chunk-3j1x55tc.js +2 -0
- package/dist/cli/{chunk-q854fweb.js → chunk-3jnw3ftt.js} +1 -1
- package/dist/cli/chunk-3r4ekafa.js +2 -0
- package/dist/cli/{chunk-sgegp9x9.js → chunk-4zhmbqt3.js} +1 -1
- package/dist/cli/{chunk-2s762g8n.js → chunk-65tbvcjj.js} +1 -1
- package/dist/cli/{chunk-zcadc92x.js → chunk-67q0qw7z.js} +1 -1
- package/dist/cli/{chunk-q2fnt7gm.js → chunk-68gxqtse.js} +1 -1
- package/dist/cli/{chunk-rxge7bh5.js → chunk-6e54q8g5.js} +1 -1
- package/dist/cli/chunk-6k424rbf.js +2 -0
- package/dist/cli/{chunk-2n1n70f2.js → chunk-6r84zkcz.js} +1 -1
- package/dist/cli/{chunk-s5k3g5ra.js → chunk-6ygwq4w5.js} +1 -1
- package/dist/cli/{chunk-j6t7xvm3.js → chunk-75zg2k73.js} +1 -1
- package/dist/cli/{chunk-2bxts9pp.js → chunk-76adkzyf.js} +1 -1
- package/dist/cli/{chunk-axmpjma9.js → chunk-7cd1epfw.js} +1 -1
- package/dist/cli/chunk-7ghwdjdc.js +3 -0
- package/dist/cli/{chunk-cvrtapqt.js → chunk-7hkkjx6g.js} +1 -1
- package/dist/cli/{chunk-e8pv3b92.js → chunk-814ktvx2.js} +1 -1
- package/dist/cli/chunk-8je3dmzq.js +2 -0
- package/dist/cli/{chunk-25867jnk.js → chunk-8wze6dnr.js} +1 -1
- package/dist/cli/{chunk-0gxa04rx.js → chunk-97vsqj97.js} +1 -1
- package/dist/cli/chunk-9g7gneek.js +30 -0
- package/dist/cli/chunk-9jbcfrse.js +2 -0
- package/dist/cli/{chunk-kqv7t8jk.js → chunk-9r6x8mh4.js} +1 -1
- package/dist/cli/chunk-9vd6fv1k.js +3 -0
- package/dist/cli/{chunk-phpt1d3e.js → chunk-9wkf17yd.js} +1 -1
- package/dist/cli/{chunk-9sta3ak4.js → chunk-ad5gbdcf.js} +1 -1
- package/dist/cli/{chunk-vd8qqev9.js → chunk-admwmjjy.js} +1 -1
- package/dist/cli/{chunk-tntdcyra.js → chunk-afwh7as3.js} +1 -1
- package/dist/cli/{chunk-57wm48dh.js → chunk-avdg2rrh.js} +1 -1
- package/dist/cli/chunk-avz72132.js +3 -0
- package/dist/cli/chunk-ax7wzcam.js +2 -0
- package/dist/cli/{chunk-zk5qkkb1.js → chunk-axxf5dkq.js} +1 -1
- package/dist/cli/{chunk-p2jeq98m.js → chunk-b18pnmsv.js} +1 -1
- package/dist/cli/chunk-b1mk33gy.js +2 -0
- package/dist/cli/{chunk-a7kq09ke.js → chunk-b31cte10.js} +1 -1
- package/dist/cli/{chunk-032g0ahy.js → chunk-b3j5s2jb.js} +1 -1
- package/dist/cli/{chunk-va0n5rwm.js → chunk-bdvqjzwh.js} +1 -1
- package/dist/cli/{chunk-tfqrc2v1.js → chunk-bk4pfjs0.js} +3 -3
- package/dist/cli/{chunk-fktvtdkb.js → chunk-bphs6am4.js} +1 -1
- package/dist/cli/chunk-bq0xsdqx.js +3 -0
- package/dist/cli/{chunk-m3bz62v4.js → chunk-c3d36ryd.js} +1 -1
- package/dist/cli/chunk-c4e149yb.js +2 -0
- package/dist/cli/chunk-cgy92ks5.js +2 -0
- package/dist/cli/chunk-cjxvb9vg.js +2 -0
- package/dist/cli/{chunk-resmnaxq.js → chunk-dehnv06q.js} +1 -1
- package/dist/cli/{chunk-y1cb8pj5.js → chunk-dk0hffvd.js} +1 -1
- package/dist/cli/{chunk-ebhbtvhd.js → chunk-dkb8nj75.js} +1 -1
- package/dist/cli/chunk-dx72asyw.js +2 -0
- package/dist/cli/{chunk-qh4y4e27.js → chunk-epyw87gt.js} +1 -1
- package/dist/cli/{chunk-s2t9acrv.js → chunk-f6836h0n.js} +1 -1
- package/dist/cli/{chunk-npb9xz3y.js → chunk-ffjwgbck.js} +1 -1
- package/dist/cli/chunk-ft6ftksv.js +2 -0
- package/dist/cli/{chunk-7h7270rz.js → chunk-g3wdrhxk.js} +2 -2
- package/dist/cli/{chunk-ra40m849.js → chunk-gb3qb83h.js} +1 -1
- package/dist/cli/chunk-ghyz3fd7.js +4 -0
- package/dist/cli/chunk-gt1vbz3f.js +5 -0
- package/dist/cli/{chunk-pgmv2hwf.js → chunk-hbq7nqnp.js} +2 -2
- package/dist/cli/{chunk-jp31bpgp.js → chunk-hm7t9gkb.js} +1 -1
- package/dist/cli/{chunk-kda565xs.js → chunk-hqzgejfj.js} +1 -1
- package/dist/cli/{chunk-b67pjyyg.js → chunk-j26zqrnq.js} +1 -1
- package/dist/cli/{chunk-1tebqkdv.js → chunk-jbqpyp76.js} +1 -1
- package/dist/cli/{chunk-9e21z4gn.js → chunk-jk9b9ztf.js} +1 -1
- package/dist/cli/{chunk-w2sp489k.js → chunk-k3wzznqw.js} +1 -1
- package/dist/cli/{chunk-zb5d61xa.js → chunk-k8dm013e.js} +1 -1
- package/dist/cli/{chunk-a7m7w6d1.js → chunk-m6qv5rsv.js} +1 -1
- package/dist/cli/{chunk-34468esa.js → chunk-mrtfvgb2.js} +1 -1
- package/dist/cli/{chunk-t3v57v42.js → chunk-mt8vtz20.js} +2 -2
- package/dist/cli/{chunk-2ks86x2d.js → chunk-mw35vd6g.js} +1 -1
- package/dist/cli/{chunk-36pkmg07.js → chunk-mwm63vz3.js} +9 -9
- package/dist/cli/chunk-n7dtvega.js +2 -0
- package/dist/cli/chunk-nhpadsbv.js +2 -0
- package/dist/cli/{chunk-4ays3krf.js → chunk-p8d9va1w.js} +2 -2
- package/dist/cli/{chunk-7j00hbq5.js → chunk-p98w5ffk.js} +1 -1
- package/dist/cli/chunk-parvvj8h.js +2 -0
- package/dist/cli/{chunk-jn7vr075.js → chunk-pcyatg4b.js} +1 -1
- package/dist/cli/{chunk-rc8baevh.js → chunk-pkq8n3gs.js} +2 -2
- package/dist/cli/chunk-pwybgztt.js +2 -0
- package/dist/cli/chunk-q1e0qqmd.js +3 -0
- package/dist/cli/{chunk-5q08srg6.js → chunk-q349ydch.js} +1 -1
- package/dist/cli/chunk-qb6ktr8a.js +2 -0
- package/dist/cli/{chunk-a1wjg2cv.js → chunk-qc06psqb.js} +1 -1
- package/dist/cli/{chunk-mw0ysrpd.js → chunk-qk5f6p3e.js} +1 -1
- package/dist/cli/chunk-r2pd9tv9.js +3 -0
- package/dist/cli/{chunk-h7y9v8k1.js → chunk-r4bn0mtb.js} +1 -1
- package/dist/cli/{chunk-4e1wcgw7.js → chunk-rm2wy5hf.js} +3 -3
- package/dist/cli/chunk-rpm771v5.js +15 -0
- package/dist/cli/{chunk-24dryfqb.js → chunk-s21t29qn.js} +1 -1
- package/dist/cli/{chunk-ccn7pq03.js → chunk-sb2xg6py.js} +2 -2
- package/dist/cli/{chunk-ayhkcv0w.js → chunk-sk3h2pzj.js} +2 -2
- package/dist/cli/{chunk-6a4xqzqf.js → chunk-sncjkw3g.js} +3 -3
- package/dist/cli/chunk-t6j3pmpp.js +2 -0
- package/dist/cli/{chunk-1v8y9xtk.js → chunk-tmz0wzq8.js} +1 -1
- package/dist/cli/{chunk-nz9nmp4v.js → chunk-tq1hrd9n.js} +1 -1
- package/dist/cli/{chunk-x0rvg54z.js → chunk-v0jvt60f.js} +1 -1
- package/dist/cli/chunk-v8s0s21v.js +2 -0
- package/dist/cli/{chunk-2rfyjb3y.js → chunk-v9avfsxq.js} +1 -1
- package/dist/cli/{chunk-t5qayy7m.js → chunk-v9dcyjmj.js} +1 -1
- package/dist/cli/{chunk-trjve2xz.js → chunk-vcq9hb2a.js} +1 -1
- package/dist/cli/chunk-vx4e787s.js +3 -0
- package/dist/cli/{chunk-vgknea9y.js → chunk-wbtebbrv.js} +1 -1
- package/dist/cli/{chunk-meyfwc50.js → chunk-wkk63qck.js} +1 -1
- package/dist/cli/{chunk-m2t2n474.js → chunk-wq6pfbek.js} +2 -2
- package/dist/cli/{chunk-x8pk5cyf.js → chunk-x2c8f2qz.js} +1 -1
- package/dist/cli/{chunk-0y4qgnby.js → chunk-x5ymh8ev.js} +1 -1
- package/dist/cli/{chunk-568q390y.js → chunk-x7r75e3p.js} +2 -2
- package/dist/cli/chunk-xg6zg6kz.js +2 -0
- package/dist/cli/chunk-xgq5ycyn.js +2 -0
- package/dist/cli/{chunk-21ek142k.js → chunk-xkr7fwvb.js} +1 -1
- package/dist/cli/{chunk-5hhr44fc.js → chunk-xmf4053m.js} +1 -1
- package/dist/cli/{chunk-nqtvthqg.js → chunk-xpxxgzw9.js} +1 -1
- package/dist/cli/{chunk-s5a5dyab.js → chunk-y33j54yr.js} +2 -2
- package/dist/cli/{chunk-hq9tbzqa.js → chunk-y55zpren.js} +1 -1
- package/dist/cli/{chunk-h3q3r1py.js → chunk-yjk0465m.js} +1 -1
- package/dist/cli/chunk-yq99x0r6.js +2 -0
- package/dist/cli/{chunk-qstjfseh.js → chunk-yshp8cmx.js} +1 -1
- package/dist/cli/chunk-z3zaa155.js +3 -0
- package/dist/cli/{chunk-npwzmmv9.js → chunk-z7zm8h1q.js} +2 -2
- package/dist/cli/chunk-zfjqy7hp.js +52 -0
- package/dist/cli/{chunk-cbd6y9at.js → chunk-zmw0v18d.js} +1 -1
- package/dist/cli/chunk-zy20hzvh.js +4 -0
- package/dist/cli/index.js +8 -8
- package/dist/cli/pty-host-node.mjs +3 -0
- package/dist/cli/rove-run.js +1 -1
- package/dist/cli/rove.js +1 -1
- package/dist/completions/rove.bash +1 -1
- package/dist/completions/rove.fish +1 -1
- package/dist/completions/rove.zsh +1 -1
- package/dist/skills/rove/SKILL.md +50 -2
- package/dist/skills/rove/references/api-flags.md +38 -7
- package/dist/web/assets/{index-DHlgMx7L.js → index-DmRZRttZ.js} +2 -2
- package/dist/web/index.html +1 -1
- package/package.json +3 -3
- package/dist/cli/chunk-17pg88dq.js +0 -22
- package/dist/cli/chunk-1zwp3ase.js +0 -2
- package/dist/cli/chunk-2bp01vf2.js +0 -2
- package/dist/cli/chunk-2g2w5vvn.js +0 -2
- package/dist/cli/chunk-564jgrb3.js +0 -2
- package/dist/cli/chunk-5qxp7xx3.js +0 -2
- package/dist/cli/chunk-6f01fsje.js +0 -2
- package/dist/cli/chunk-7zxf47xb.js +0 -2
- package/dist/cli/chunk-8e0nmegv.js +0 -2
- package/dist/cli/chunk-9dregrj6.js +0 -5
- package/dist/cli/chunk-9h940gnr.js +0 -2
- package/dist/cli/chunk-9mcpqrx8.js +0 -2
- package/dist/cli/chunk-bhm24ne6.js +0 -9
- package/dist/cli/chunk-c0ksxg3z.js +0 -3
- package/dist/cli/chunk-cb1dg7nz.js +0 -2
- package/dist/cli/chunk-cpv1rpc7.js +0 -2
- package/dist/cli/chunk-csdttpme.js +0 -52
- package/dist/cli/chunk-fz0xfw86.js +0 -2
- package/dist/cli/chunk-h89ghyex.js +0 -2
- package/dist/cli/chunk-jnj2kk2h.js +0 -3
- package/dist/cli/chunk-kx0wzjj4.js +0 -2
- package/dist/cli/chunk-n2xemv4a.js +0 -2
- package/dist/cli/chunk-n92fz0hn.js +0 -2
- package/dist/cli/chunk-nj53wrzz.js +0 -2
- package/dist/cli/chunk-pdvyfz3n.js +0 -3
- package/dist/cli/chunk-pj3gnkfr.js +0 -3
- package/dist/cli/chunk-q3xt0mqt.js +0 -3
- package/dist/cli/chunk-qzsahxd9.js +0 -3
- package/dist/cli/chunk-r2c5nbcq.js +0 -4
- package/dist/cli/chunk-rf0jrh3q.js +0 -2
- package/dist/cli/chunk-rj7fwa30.js +0 -2
- package/dist/cli/chunk-sbn5pbz9.js +0 -2
- package/dist/cli/chunk-va5am5n6.js +0 -2
- package/dist/cli/chunk-vwpcv7j1.js +0 -4
- package/dist/cli/chunk-yknavm97.js +0 -3
- package/dist/cli/chunk-yt24rrvx.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{errorMessage}from"./chunk-2brn8e1y.js";import{JsonHookAdapter,bobAuthSecretsPath,claudeGlobalConfigPath,codexAuthPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,
|
|
2
|
+
import{errorMessage}from"./chunk-2brn8e1y.js";import{JsonHookAdapter,bobAuthSecretsPath,claudeGlobalConfigPath,codexAuthPath,copilotConfigPath,editJsonSettings,hookCommandQuoting,isRoveHook,kimiCredentialsPath,readTextFileSyncBounded,roveHookArgs,roveHookInvocation}from"./chunk-gt1vbz3f.js";import{quoteShellArgv}from"./chunk-7kysxgbq.js";import{isObject}from"./chunk-7ghwdjdc.js";import{getCustomEngineIds,getDisabledEngineIds}from"./chunk-xkr7fwvb.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync}from"fs";import{homedir}from"os";import{dirname,join}from"path";function parseFlatHooks(raw){if(raw===void 0)return{ok:!0,doc:{}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{ok:!1,reason:`not valid JSON (${err instanceof Error?err.message:String(err)})`}}if(!isObject(parsed))return{ok:!1,reason:"top level is not a JSON object"};if(parsed.hooks===void 0)return{ok:!0,doc:parsed};if(!isObject(parsed.hooks))return{ok:!1,reason:'"hooks" is not an object'};for(let[event,entries]of Object.entries(parsed.hooks))if(!Array.isArray(entries))return{ok:!1,reason:`"hooks.${event}" is not an array`};return{ok:!0,doc:parsed}}function mergeFlatHooks(format,current,install,inv=roveHookInvocation()){let verbs=format.eventMap.map((spec)=>spec.verb),{hooks:rawHooks,...rest}=current,hooks=isObject(rawHooks)?{...rawHooks}:{},quoting=hookCommandQuoting();for(let{event,verb}of format.eventMap){let kept=(Array.isArray(hooks[event])?hooks[event]:[]).filter((entry)=>!isRoveHook(entry,verbs));if(install){let command=quoteShellArgv([...inv,"hook",verb,...roveHookArgs(format.vendor)],quoting);kept.push(format.withType?{type:"command",command}:{command})}if(kept.length>0)hooks[event]=kept;else delete hooks[event]}return{version:1,...rest,hooks}}var CURSOR_HOOK_EVENT_MAP=[{event:"sessionStart",verb:"session-start"}],CURSOR_FORMAT={vendor:"cursor",eventMap:CURSOR_HOOK_EVENT_MAP};function cursorHooksPath(home=homedir()){let override=process.env.CURSOR_CONFIG_DIR?.trim();return join(override||join(home,".cursor"),"hooks.json")}function parseCursorHooks(raw){return parseFlatHooks(raw)}function mergeCursorHooks(current,install,inv=roveHookInvocation()){return mergeFlatHooks(CURSOR_FORMAT,current,install,inv)}class CursorHookAdapter{vendor="cursor";supportsHooks(){return!0}globalSettingsPath(){return cursorHooksPath()}activityDetailFromPayload(){return}cwdFromPayload(payload){let roots=payload.workspace_roots;return Array.isArray(roots)?firstString(...roots):void 0}sessionFromPayload(payload){let sessionId=firstString(payload.session_id,payload.conversation_id);if(!sessionId)return;let transcriptPath=firstString(payload.transcript_path);return{sessionId,...transcriptPath?{transcriptPath}:{}}}async installActivityHooks(settingsFilePath,opts={}){if(!existsSync(dirname(settingsFilePath)))return{ok:!0};let outcome=await editJsonSettings(settingsFilePath,(cur)=>mergeCursorHooks(cur,!0),parseCursorHooks);if(!outcome.ok&&!opts.quiet)process.stderr.write(`[rove hooks] cursor: skipped ${outcome.file}: ${outcome.reason}
|
|
3
3
|
`);return outcome}async removeActivityHooks(settingsFilePath){if(!existsSync(settingsFilePath))return;await editJsonSettings(settingsFilePath,(cur)=>mergeCursorHooks(cur,!1),parseCursorHooks)}hookConfigRefusal(raw){let parsed=parseCursorHooks(raw);return parsed.ok?void 0:parsed.reason}supportsWorktreeSync(){return!1}async removeWorktreeSyncHook(){}async removeWorktreeWatchHook(){}}function firstString(...values){for(let value of values)if(typeof value==="string"&&value)return value;return}import{homedir as homedir2}from"os";import{join as join2}from"path";import{existsSync as existsSync2}from"fs";import{dirname as dirname2}from"path";function sessionStartOnly(matcher){return[{event:"SessionStart",verb:"session-start",...matcher?{matcher}:{}}]}class SessionStartHookAdapter extends JsonHookAdapter{async installActivityHooks(settingsFilePath,opts={}){if(!existsSync2(dirname2(settingsFilePath)))return{ok:!0};return super.installActivityHooks(settingsFilePath,opts)}async removeActivityHooks(settingsFilePath){if(!existsSync2(settingsFilePath))return;await super.removeActivityHooks(settingsFilePath)}sessionFromPayload(payload){if(typeof payload.session_id!=="string"||!payload.session_id)return;return{sessionId:payload.session_id,...typeof payload.transcript_path==="string"&&payload.transcript_path?{transcriptPath:payload.transcript_path}:{}}}}var DEVIN_HOOK_EVENT_MAP=sessionStartOnly();function devinSettingsPath(home=homedir2()){let xdg=process.env.XDG_CONFIG_HOME?.trim();return join2(xdg||join2(home,".config"),"devin","config.json")}class DevinHookAdapter extends SessionStartHookAdapter{vendor="devin";eventMap=DEVIN_HOOK_EVENT_MAP;globalSettingsPath(){return devinSettingsPath()}}import{homedir as homedir3}from"os";import{join as join3}from"path";var DROID_HOOK_EVENT_MAP=sessionStartOnly();function droidSettingsPath(home=homedir3()){return join3(home,".factory","settings.json")}class DroidHookAdapter extends SessionStartHookAdapter{vendor="droid";eventMap=DROID_HOOK_EVENT_MAP;globalSettingsPath(){return droidSettingsPath()}}import{homedir as homedir4}from"os";import{join as join4}from"path";var QODERCLI_HOOK_EVENT_MAP=sessionStartOnly("*");function qodercliSettingsPath(home=homedir4()){let override=process.env.QODERCLI_CONFIG_DIR?.trim();return join4(override||join4(home,".qoder"),"settings.json")}class QodercliHookAdapter extends SessionStartHookAdapter{vendor="qodercli";eventMap=QODERCLI_HOOK_EVENT_MAP;globalSettingsPath(){return qodercliSettingsPath()}}var pluginEngines=new Map;function registerPluginEngine(id,spec){if(Object.hasOwn(CONTRIB_ENGINES,id))return!1;return pluginEngines.set(id,spec),!0}function clearPluginEngines(){pluginEngines.clear()}function pluginEngineIds(){return[...pluginEngines.keys()]}var GEMINI={rules:[{state:"blocked",any:["\u2502 apply this change","\u2502 allow execution","waiting for user confirmation"]},{state:"blocked",all:["do you want to proceed"],any:["yes"]},{state:"working",any:["esc to cancel"]}]},OPENCODE={rules:[{state:"blocked",any:["\u25B3 permission required"]},{state:"blocked",all:["esc dismiss"],any:["enter confirm","enter submit","enter toggle"]},{state:"working",any:["esc interrupt","esc to interrupt","ctrl+c to interrupt","esc again to interrupt"]},{state:"idle",any:["enter send"]}]},CURSOR={rules:[{state:"blocked",any:["press any key to log in"]},{state:"blocked",all:["proceed (y)"]},{state:"blocked",any:["run this command?","waiting for approval","skip (esc or n)","(y) (enter)"]},{state:"working",any:["esc to cancel","ctrl+c to stop"]}]},GROK={rules:[{state:"blocked",any:["\u26A0 action required","ctrl+o:yolo"]},{state:"blocked",all:["\u2503"],lineRegex:["^\\s*\u2503\\s+\\S+\\s+\\(\u25CB\\)"]},{state:"working",any:["[stop]"],lineRegex:["^\\s*[\\u2800-\\u28FF]"]}]},DROID={rules:[{state:"blocked",all:["enter to select","esc to cancel"],any:["> yes, allow","> no, cancel"]},{state:"blocked",all:["enter select","esc cancel"]},{state:"working",any:["esc to stop"]}]},AMP={rules:[{state:"blocked",any:["waiting for approval","run this command?","allow editing file:","allow creating file:","confirm tool call"]},{state:"working",lineRegex:["^\\s*\u2570\\s+\\S+\\s+(thinking|streaming|running tools|waiting)\\s+\u2500"]}]},CLINE={rules:[{state:"blocked",any:["let cline use this tool"]},{state:"blocked",all:["execute command?","yes"],any:["[act mode]","[plan mode]"]},{state:"blocked",all:["use this tool?","yes"],any:["[act mode]","[plan mode]"]}]},KIRO={rules:[{state:"blocked",all:["requires approval"],any:["yes, single permission","trust, always allow","no (tab to edit)","esc to close"]},{state:"blocked",all:["pending from subagents","tool approval"],any:["approve all pending","configure individually","exit (cancel subagents)"]},{state:"working",any:["kiro is working"]},{state:"working",all:["esc to cancel"],lineRegex:["^\\s*[\u25D4\u25D1\u25D5\u25CF]\\s+[A-Za-z]"]}]},MAKI={rules:[{state:"blocked",all:["permission required","y allow","n deny"]},{state:"blocked",all:["permission required"],any:["confirm allow","confirm deny"]},{state:"blocked",all:["permission required","enter deny","esc cancel"]},{state:"blocked",all:["plan complete","enter confirm"],any:["space toggle parallel","edit plan"]},{state:"working",bottomLines:1,lineRegex:["^( [\\u2800-\\u28FF]){1,2} \\[(BUILD|PLAN|BASH)\\]"]},{state:"idle",bottomLines:1,lineRegex:["^ \\[(BUILD|PLAN|BASH)\\]"]}]},ANTIGRAVITY={rules:[{state:"blocked",all:["requesting permission for:","do you want to proceed?"]},{state:"blocked",all:["requesting permission for:","tab amend","edit command"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]+\\s+[A-Za-z]+\\w*ing\\b"]},{state:"working",bottomLines:5,lineRegex:["\xB7\\s*[1-9][0-9]*\\s+task"]}]},DEVIN={rules:[{state:"blocked",bottomLines:8,all:["do you trust the authors of this directory?","yes, trust "]},{state:"blocked",bottomLines:8,all:["approve once","select","confirm","esc cancel"]},{state:"working",bottomLines:8,all:["running tools","esc to interrupt"]},{state:"working",bottomLines:6,all:["guide devin while it works"]},{state:"working",bottomLines:8,all:["reading shell ","timeout:"]},{state:"idle",bottomLines:8,all:["ask devin to build","features, fix bugs","your code"],lineRegex:["^\\s*\u276D Ask Devin to build"]},{state:"idle",bottomLines:6,all:["context:"],lineRegex:["^\\s*\u276D"]}]},QODERCLI={rules:[{state:"blocked",all:["waiting for user confirmation"],any:["yes","no","allow","reject"]},{state:"blocked",all:["awaiting approval"],any:["allow","reject"]},{state:"blocked",any:["permission required","allow once or always?","asking user","enter your response","review your answers:","shell awaiting input"]},{state:"working",any:["(esc to cancel,"]},{state:"working",lineRegex:["^\\s*[\\u2800-\\u28FF]\\s+.*[A-Za-z]"]}]},CONTRIB_ENGINES={gemini:{displayName:"Gemini CLI",defaultCommand:["gemini"],screenManifest:GEMINI},opencode:{displayName:"OpenCode",defaultCommand:["opencode"],screenManifest:OPENCODE,firstMessageDelivery:"paste"},cursor:{displayName:"Cursor Agent",defaultCommand:["cursor-agent"],screenManifest:CURSOR,createHookAdapter:()=>new CursorHookAdapter},grok:{displayName:"Grok CLI",defaultCommand:["grok"],screenManifest:GROK},droid:{displayName:"Droid",defaultCommand:["droid"],screenManifest:DROID,createHookAdapter:()=>new DroidHookAdapter},amp:{displayName:"Amp",defaultCommand:["amp"],screenManifest:AMP},devin:{displayName:"Devin",defaultCommand:["devin"],processNames:["devin-cli"],screenManifest:DEVIN,createHookAdapter:()=>new DevinHookAdapter},qodercli:{displayName:"Qoder CLI",defaultCommand:["qodercli"],processNames:["qoder","qoderclicn","qodercn"],screenManifest:QODERCLI,createHookAdapter:()=>new QodercliHookAdapter},cline:{displayName:"Cline",defaultCommand:["cline"],screenManifest:CLINE},kiro:{displayName:"Kiro CLI",defaultCommand:["kiro-cli"],processNames:["kiro"],screenManifest:KIRO},maki:{displayName:"Maki",defaultCommand:["maki"],screenManifest:MAKI},antigravity:{displayName:"Antigravity",defaultCommand:["agy"],processNames:["antigravity","antigravity-cli"],screenManifest:ANTIGRAVITY}};function isContribEngine(id){return Object.hasOwn(CONTRIB_ENGINES,id)||pluginEngines.has(id)}var CONTRIB_ENGINE_IDS=Object.keys(CONTRIB_ENGINES);function contribEngineEntry(id,base){let spec=CONTRIB_ENGINES[id]??pluginEngines.get(id);if(!spec)return base;return{...base,displayName:spec.displayName,defaultCommand:spec.defaultCommand,...spec.processNames?{processNames:spec.processNames}:{},screenManifest:spec.screenManifest,...spec.identity?{identity:spec.identity}:{},...spec.firstMessageDelivery?{firstMessageDelivery:spec.firstMessageDelivery}:{},...spec.createHookAdapter?{createHookAdapter:spec.createHookAdapter}:{}}}import{homedir as homedir6}from"os";import{spawnSync}from"child_process";import{existsSync as existsSync3,statSync}from"fs";import{homedir as homedir5}from"os";import path from"path";var defaultBinaryDeps={fileExists(p){try{return statSync(p).isFile()}catch{return!1}},env(name){return process.env[name]},home(){return homedir5()},which(name){let cmd=process.platform==="win32"?"where":"which",out=spawnSync(cmd,[name],{encoding:"utf8"});if(out.status!==0)return;let first=out.stdout.split(`
|
|
4
|
-
`).map((l)=>l.trim()).filter(Boolean)[0];if(!first)return;if(first.startsWith(`${name}:`)&&first.includes("aliased to")){let aliasTarget=first.split("aliased to")[1]?.trim();return aliasTarget&&existsSync3(aliasTarget)?aliasTarget:void 0}return first},readdir(p){try{return __require("fs").readdirSync(p)}catch{return[]}}};class BinaryNotFoundError extends Error{checkedPaths;constructor(label,hint,checkedPaths){super(`${label} not found. Checked: ${checkedPaths.join(", ")}. ${hint}`);this.name="BinaryNotFoundError",this.checkedPaths=checkedPaths}}function npmStyleDirs({deps,home},locations=["system","nvm","windowsNpm","npmGlobal","local","bun","bin"]){return locations.flatMap((location)=>{switch(location){case"system":return["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"];case"homebrew":return["/opt/homebrew/bin","/usr/local/bin"];case"nvm":{let bin=deps.env("NVM_BIN");return bin?[bin]:[]}case"windowsNpm":{if((deps.platform?.()??process.platform)!=="win32")return[];let appData=deps.env("APPDATA"),localAppData=deps.env("LOCALAPPDATA");return[...localAppData?[path.join(localAppData,"npm")]:[],...appData?[path.join(appData,"npm")]:[],path.join(home,"AppData/Roaming/npm")]}case"npmGlobal":return[path.join(home,".npm-global/bin")];case"local":return[path.join(home,".local/bin")];case"yarn":return[path.join(home,".yarn/bin")];case"bun":return[path.join(home,".bun/bin")];case"bin":return[path.join(home,"bin")]}})}function npmStyleBinaryCandidates(ctx,name){let names=(ctx.deps.platform?.()??process.platform)==="win32"?[`${name}.exe`,`${name}.cmd`,name]:[name];return npmStyleDirs(ctx).flatMap((dir)=>names.map((n)=>path.join(dir,n)))}function createBinaryFinder(spec){return async function(deps=defaultBinaryDeps){let checked=[],whichResult=deps.which(spec.name);if(whichResult){if(checked.push(`which:${whichResult}`),deps.fileExists(whichResult))return whichResult}for(let candidate of spec.candidates({deps,home:deps.home()}))if(checked.push(candidate),deps.fileExists(candidate))return candidate;throw spec.notFound(checked)}}class BobBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("IBM Bob Shell binary","Ensure 'bob' is on PATH (for example `curl -fsSL https://bob.ibm.com/download/bobshell.sh | bash`).",checkedPaths);this.name="BobBinaryNotFoundError"}}var findBobBinary=createBinaryFinder({name:"bob",candidates:(ctx)=>npmStyleBinaryCandidates(ctx,"bob"),notFound:(checked)=>new BobBinaryNotFoundError(checked)});import path2 from"path";class ClaudeBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Claude Code binary","Ensure 'claude' is on PATH, or install at ~/.claude/local/claude.",checkedPaths);this.name="ClaudeBinaryNotFoundError"}}var findClaudeBinary=createBinaryFinder({name:"claude",candidates({deps,home}){let out=[path2.join(home,".claude","local","claude")];out.push(...npmStyleDirs({deps,home},["nvm"]).map((dir)=>path2.join(dir,"claude")));let nvmRoot=path2.join(home,".nvm","versions","node"),versions=(deps.readdir?.(nvmRoot)??[]).sort((a,b)=>b.localeCompare(a,void 0,{numeric:!0}));for(let v of versions)out.push(path2.join(nvmRoot,v,"bin","claude"));return out.push(...npmStyleDirs({deps,home},["system","local","npmGlobal","yarn","bun","bin"]).map((dir)=>path2.join(dir,"claude"))),out},notFound:(checked)=>new ClaudeBinaryNotFoundError(checked)});import path3 from"path";class CodexBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Codex CLI binary","Ensure 'codex' is on PATH (e.g. `brew install codex` or the official installer).",checkedPaths);this.name="CodexBinaryNotFoundError"}}var findCodexBinary=createBinaryFinder({name:"codex",candidates({deps,home}){return npmStyleDirs({deps,home},["system","nvm","local","bun","bin"]).map((dir)=>path3.join(dir,"codex"))},notFound:(checked)=>new CodexBinaryNotFoundError(checked)});class CopilotBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("GitHub Copilot CLI binary","Ensure 'copilot' is on PATH (for example `npm install -g @github/copilot` or `brew install copilot-cli`).",checkedPaths);this.name="CopilotBinaryNotFoundError"}}var findCopilotBinary=createBinaryFinder({name:"copilot",candidates:(ctx)=>npmStyleBinaryCandidates(ctx,"copilot"),notFound:(checked)=>new CopilotBinaryNotFoundError(checked)});import path4 from"path";class KimiBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Kimi Code CLI binary","Ensure 'kimi' is on PATH or installed at ~/.kimi-code/bin/kimi.",checkedPaths);this.name="KimiBinaryNotFoundError"}}var findKimiBinary=createBinaryFinder({name:"kimi",candidates:(ctx)=>[path4.join(ctx.home,".kimi-code/bin"),...npmStyleDirs(ctx,["local","bin","homebrew"])].map((dir)=>path4.join(dir,"kimi")),notFound:(checked)=>new KimiBinaryNotFoundError(checked)});import path5 from"path";class PiFamilyBinaryNotFoundError extends BinaryNotFoundError{constructor(name,checkedPaths){super(`${name} CLI binary`,`Ensure '${name}' is on PATH (e.g. \`brew install ${name}\`, or \`npm i -g ${name==="omp"?"@oh-my-pi/pi-coding-agent":"@earendil-works/pi-coding-agent"}\`).`,checkedPaths);this.name="PiFamilyBinaryNotFoundError"}}function candidatesFor(name,ctx){let{home}=ctx,out=npmStyleDirs(ctx,["system","local","bun","bin"]).map((dir)=>path5.join(dir,name)),packageName=name==="omp"?"@oh-my-pi/pi-coding-agent":"@earendil-works/pi-coding-agent";for(let prefix of[path5.join(home,".npm-global"),"/usr/local","/opt/homebrew"])out.push(path5.join(prefix,"bin",name)),out.push(path5.join(prefix,"lib/node_modules",packageName,"dist","cli.js"));return out}var findPiBinary=createBinaryFinder({name:"pi",candidates:(ctx)=>candidatesFor("pi",ctx),notFound:(checked)=>new PiFamilyBinaryNotFoundError("pi",checked)}),findOmpBinary=createBinaryFinder({name:"omp",candidates:(ctx)=>candidatesFor("omp",ctx),notFound:(checked)=>new PiFamilyBinaryNotFoundError("omp",checked)});var defaultDeps={readFile(p){return readTextFileSyncBounded(p)},env(name){return process.env[name]},home(){return homedir6()},findClaudeBinary(){return findClaudeBinary()},findCodexBinary(){return findCodexBinary()},findBobBinary(){return findBobBinary()},findCopilotBinary(){return findCopilotBinary()},findKimiBinary(){return findKimiBinary()},findPiBinary(){return findPiBinary()},findOmpBinary(){return findOmpBinary()}};function decodeJwtPayload(jwt){let parts=jwt.split(".");if(parts.length!==3)return null;let payload=parts[1];if(!payload)return null;let b64=payload.replace(/-/g,"+").replace(/_/g,"/"),padded=b64+"=".repeat((4-b64.length%4)%4);try{let json=Buffer.from(padded,"base64").toString("utf8"),obj=JSON.parse(json);return typeof obj==="object"&&obj!==null?obj:null}catch{return null}}async function probeBinary(probe){try{return{found:!0,path:await probe()}}catch(err){if(err instanceof BinaryNotFoundError)return{found:!1,error:"not found on PATH"};return{found:!1,error:errorMessage(err)}}}var cachedDefaultVendors=null;async function probeAvailableVendors(deps){return(await Promise.all([["claude",()=>deps.findClaudeBinary()],["codex",()=>deps.findCodexBinary()],["copilot",()=>deps.findCopilotBinary()],["kimi",()=>deps.findKimiBinary()],["pi",()=>deps.findPiBinary()],["omp",()=>deps.findOmpBinary()]].map(async([vendor,probe])=>(await probeBinary(probe)).found?vendor:null))).filter((v)=>v!==null)}function detectAvailableVendors(deps=defaultDeps){if(deps!==defaultDeps)return probeAvailableVendors(deps);if(cachedDefaultVendors)return cachedDefaultVendors;let pending=probeAvailableVendors(deps).catch((err)=>{throw cachedDefaultVendors=null,err});return cachedDefaultVendors=pending,pending}function resetAvailableVendorsCache(){cachedDefaultVendors=null,cachedContribEngines=null}async function installedEngineIds(deps=defaultDeps){let builtins=await detectAvailableVendors(deps),contrib=await detectContribEngines();return[...new Set([...builtins,...getCustomEngineIds(),...contrib])]}async function availableEngineIds(deps=defaultDeps){let disabled=new Set(getDisabledEngineIds());return(await installedEngineIds(deps)).filter((id)=>!disabled.has(id))}var cachedContribEngines=null;function detectContribEngines(){if(cachedContribEngines)return cachedContribEngines;let which=globalThis.Bun?.which;return cachedContribEngines=Promise.resolve([...which?CONTRIB_ENGINE_IDS.filter((id)=>{let bin=CONTRIB_ENGINES[id]?.defaultCommand[0];return bin?which(bin)!==null:!1}):[],...pluginEngineIds()]),cachedContribEngines}async function detectClaudeAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findClaudeBinary()),configPath=claudeGlobalConfigPath(deps.env,deps.home()),raw;try{raw=deps.readFile(configPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${configPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${configPath}: ${errorMessage(err)}`}}let oauth=parsed?.oauthAccount;if(!oauth||typeof oauth!=="object")return{binary,account:{kind:"none"}};let o=oauth,email=typeof o.emailAddress==="string"?o.emailAddress:void 0;if(!email)return{binary,account:{kind:"none"}};return{binary,account:{kind:"oauth",email,organization:typeof o.organizationName==="string"?o.organizationName:void 0,displayName:typeof o.displayName==="string"?o.displayName:void 0,billingType:typeof o.billingType==="string"?o.billingType:void 0}}}async function detectCodexAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findCodexBinary()),authPath=codexAuthPath(deps.env,deps.home()),raw;try{raw=deps.readFile(authPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${authPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${authPath}: ${errorMessage(err)}`}}let obj=parsed??{},tokens=obj.tokens,idToken=typeof tokens?.id_token==="string"?tokens.id_token:void 0;if(idToken){let payload=decodeJwtPayload(idToken);if(!payload)return{binary,account:{kind:"none"},accountError:"codex id_token: malformed JWT"};let email=typeof payload.email==="string"?payload.email:void 0,authClaimRaw=payload["https://api.openai.com/auth"],authClaim=typeof authClaimRaw==="object"&&authClaimRaw!==null&&!Array.isArray(authClaimRaw)?authClaimRaw:void 0,plan=typeof authClaim?.chatgpt_plan_type==="string"?authClaim.chatgpt_plan_type:void 0;if(email)return{binary,account:{kind:"chatgpt",email,plan}};return{binary,account:{kind:"none"},accountError:"codex id_token: no email claim"}}let apiKey=obj.OPENAI_API_KEY;if(typeof apiKey==="string"&&apiKey.length>0)return{binary,account:{kind:"apikey"}};return{binary,account:{kind:"none"}}}async function detectCopilotAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findCopilotBinary());for(let source of["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"])if(deps.env(source)?.trim())return{binary,account:{kind:"token",source}};let configPath=copilotConfigPath(deps.env,deps.home()),raw;try{raw=deps.readFile(configPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${configPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${configPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};if(hasStringDeep(parsed,["github_token","oauth_token","access_token","token","selectedUser","currentUser","user"]))return{binary,account:{kind:"oauth"}};return{binary,account:{kind:"none"}}}async function detectBobAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findBobBinary()),secretsPath=bobAuthSecretsPath(deps.home()),raw;try{raw=deps.readFile(secretsPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${secretsPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${secretsPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};let signedIn=Object.entries(parsed).some(([key,value])=>key.startsWith("bob.auth.tokens-")&&typeof value==="string"&&value.length>0);return{binary,account:signedIn?{kind:"oauth"}:{kind:"none"}}}async function detectKimiAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findKimiBinary()),credPath=kimiCredentialsPath(deps.env,deps.home()),raw;try{raw=deps.readFile(credPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${credPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${credPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};let token=parsed.access_token;if(typeof token==="string"&&token.length>0)return{binary,account:{kind:"oauth"}};return{binary,account:{kind:"none"}}}function hasStringDeep(value,interestingKeys,depth=0){if(depth>4||!isObject(value))return!1;for(let[key,entry]of Object.entries(value)){if(interestingKeys.includes(key)&&typeof entry==="string"&&entry.length>0)return!0;if(isObject(entry)&&hasStringDeep(entry,interestingKeys,depth+1))return!0}return!1}
|
|
4
|
+
`).map((l)=>l.trim()).filter(Boolean)[0];if(!first)return;if(first.startsWith(`${name}:`)&&first.includes("aliased to")){let aliasTarget=first.split("aliased to")[1]?.trim();return aliasTarget&&existsSync3(aliasTarget)?aliasTarget:void 0}return first},readdir(p){try{return __require("fs").readdirSync(p)}catch{return[]}}};class BinaryNotFoundError extends Error{checkedPaths;constructor(label,hint,checkedPaths){super(`${label} not found. Checked: ${checkedPaths.join(", ")}. ${hint}`);this.name="BinaryNotFoundError",this.checkedPaths=checkedPaths}}function npmStyleDirs({deps,home},locations=["system","nvm","windowsNpm","npmGlobal","local","bun","bin"]){return locations.flatMap((location)=>{switch(location){case"system":return["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"];case"homebrew":return["/opt/homebrew/bin","/usr/local/bin"];case"nvm":{let bin=deps.env("NVM_BIN");return bin?[bin]:[]}case"windowsNpm":{if((deps.platform?.()??process.platform)!=="win32")return[];let appData=deps.env("APPDATA"),localAppData=deps.env("LOCALAPPDATA");return[...localAppData?[path.join(localAppData,"npm")]:[],...appData?[path.join(appData,"npm")]:[],path.join(home,"AppData/Roaming/npm")]}case"npmGlobal":return[path.join(home,".npm-global/bin")];case"local":return[path.join(home,".local/bin")];case"yarn":return[path.join(home,".yarn/bin")];case"bun":return[path.join(home,".bun/bin")];case"bin":return[path.join(home,"bin")]}})}function npmStyleBinaryCandidates(ctx,name){let names=(ctx.deps.platform?.()??process.platform)==="win32"?[`${name}.exe`,`${name}.cmd`,name]:[name];return npmStyleDirs(ctx).flatMap((dir)=>names.map((n)=>path.join(dir,n)))}function createBinaryFinder(spec){return async function(deps=defaultBinaryDeps){let checked=[],whichResult=deps.which(spec.name);if(whichResult){if(checked.push(`which:${whichResult}`),deps.fileExists(whichResult))return whichResult}for(let candidate of spec.candidates({deps,home:deps.home()}))if(checked.push(candidate),deps.fileExists(candidate))return candidate;throw spec.notFound(checked)}}class BobBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("IBM Bob Shell binary","Ensure 'bob' is on PATH (for example `curl -fsSL https://bob.ibm.com/download/bobshell.sh | bash`).",checkedPaths);this.name="BobBinaryNotFoundError"}}var findBobBinary=createBinaryFinder({name:"bob",candidates:(ctx)=>npmStyleBinaryCandidates(ctx,"bob"),notFound:(checked)=>new BobBinaryNotFoundError(checked)});import path2 from"path";class ClaudeBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Claude Code binary","Ensure 'claude' is on PATH, or install at ~/.claude/local/claude.",checkedPaths);this.name="ClaudeBinaryNotFoundError"}}var findClaudeBinary=createBinaryFinder({name:"claude",candidates({deps,home}){let out=[path2.join(home,".claude","local","claude")];out.push(...npmStyleDirs({deps,home},["nvm"]).map((dir)=>path2.join(dir,"claude")));let nvmRoot=path2.join(home,".nvm","versions","node"),versions=(deps.readdir?.(nvmRoot)??[]).sort((a,b)=>b.localeCompare(a,void 0,{numeric:!0}));for(let v of versions)out.push(path2.join(nvmRoot,v,"bin","claude"));return out.push(...npmStyleDirs({deps,home},["system","local","npmGlobal","yarn","bun","bin"]).map((dir)=>path2.join(dir,"claude"))),out},notFound:(checked)=>new ClaudeBinaryNotFoundError(checked)});import path3 from"path";class CodexBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Codex CLI binary","Ensure 'codex' is on PATH (e.g. `brew install codex` or the official installer).",checkedPaths);this.name="CodexBinaryNotFoundError"}}var findCodexBinary=createBinaryFinder({name:"codex",candidates({deps,home}){return npmStyleDirs({deps,home},["system","nvm","local","bun","bin"]).map((dir)=>path3.join(dir,"codex"))},notFound:(checked)=>new CodexBinaryNotFoundError(checked)});class CopilotBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("GitHub Copilot CLI binary","Ensure 'copilot' is on PATH (for example `npm install -g @github/copilot` or `brew install copilot-cli`).",checkedPaths);this.name="CopilotBinaryNotFoundError"}}var findCopilotBinary=createBinaryFinder({name:"copilot",candidates:(ctx)=>npmStyleBinaryCandidates(ctx,"copilot"),notFound:(checked)=>new CopilotBinaryNotFoundError(checked)});import path4 from"path";class KimiBinaryNotFoundError extends BinaryNotFoundError{constructor(checkedPaths){super("Kimi Code CLI binary","Ensure 'kimi' is on PATH or installed at ~/.kimi-code/bin/kimi.",checkedPaths);this.name="KimiBinaryNotFoundError"}}var findKimiBinary=createBinaryFinder({name:"kimi",candidates:(ctx)=>[path4.join(ctx.home,".kimi-code/bin"),...npmStyleDirs(ctx,["local","bin","homebrew"])].map((dir)=>path4.join(dir,"kimi")),notFound:(checked)=>new KimiBinaryNotFoundError(checked)});import path5 from"path";class PiFamilyBinaryNotFoundError extends BinaryNotFoundError{constructor(name,checkedPaths){super(`${name} CLI binary`,`Ensure '${name}' is on PATH (e.g. \`brew install ${name}\`, or \`npm i -g ${name==="omp"?"@oh-my-pi/pi-coding-agent":"@earendil-works/pi-coding-agent"}\`).`,checkedPaths);this.name="PiFamilyBinaryNotFoundError"}}function candidatesFor(name,ctx){let{home}=ctx,out=npmStyleDirs(ctx,["system","local","bun","bin"]).map((dir)=>path5.join(dir,name)),packageName=name==="omp"?"@oh-my-pi/pi-coding-agent":"@earendil-works/pi-coding-agent";for(let prefix of[path5.join(home,".npm-global"),"/usr/local","/opt/homebrew"])out.push(path5.join(prefix,"bin",name)),out.push(path5.join(prefix,"lib/node_modules",packageName,"dist","cli.js"));return out}var findPiBinary=createBinaryFinder({name:"pi",candidates:(ctx)=>candidatesFor("pi",ctx),notFound:(checked)=>new PiFamilyBinaryNotFoundError("pi",checked)}),findOmpBinary=createBinaryFinder({name:"omp",candidates:(ctx)=>candidatesFor("omp",ctx),notFound:(checked)=>new PiFamilyBinaryNotFoundError("omp",checked)});var defaultDeps={readFile(p){return readTextFileSyncBounded(p)},env(name){return process.env[name]},home(){return homedir6()},findClaudeBinary(){return findClaudeBinary()},findCodexBinary(){return findCodexBinary()},findBobBinary(){return findBobBinary()},findCopilotBinary(){return findCopilotBinary()},findKimiBinary(){return findKimiBinary()},findPiBinary(){return findPiBinary()},findOmpBinary(){return findOmpBinary()}};function decodeJwtPayload(jwt){let parts=jwt.split(".");if(parts.length!==3)return null;let payload=parts[1];if(!payload)return null;let b64=payload.replace(/-/g,"+").replace(/_/g,"/"),padded=b64+"=".repeat((4-b64.length%4)%4);try{let json=Buffer.from(padded,"base64").toString("utf8"),obj=JSON.parse(json);return typeof obj==="object"&&obj!==null?obj:null}catch{return null}}async function probeBinary(probe){try{return{found:!0,path:await probe()}}catch(err){if(err instanceof BinaryNotFoundError)return{found:!1,error:"not found on PATH"};return{found:!1,error:errorMessage(err)}}}var cachedDefaultVendors=null;async function probeAvailableVendors(deps){return(await Promise.all([["claude",()=>deps.findClaudeBinary()],["codex",()=>deps.findCodexBinary()],["copilot",()=>deps.findCopilotBinary()],["kimi",()=>deps.findKimiBinary()],["pi",()=>deps.findPiBinary()],["omp",()=>deps.findOmpBinary()]].map(async([vendor,probe])=>(await probeBinary(probe)).found?vendor:null))).filter((v)=>v!==null)}function detectAvailableVendors(deps=defaultDeps){if(deps!==defaultDeps)return probeAvailableVendors(deps);if(cachedDefaultVendors)return cachedDefaultVendors;let pending=probeAvailableVendors(deps).catch((err)=>{throw cachedDefaultVendors=null,err});return cachedDefaultVendors=pending,pending}function resetAvailableVendorsCache(){cachedDefaultVendors=null,cachedContribEngines=null}async function installedEngineIds(deps=defaultDeps){let builtins=await detectAvailableVendors(deps),contrib=await detectContribEngines();return[...new Set([...builtins,...getCustomEngineIds(),...contrib])]}async function availableEngineIds(deps=defaultDeps){let disabled=new Set(getDisabledEngineIds());return(await installedEngineIds(deps)).filter((id)=>!disabled.has(id))}var cachedContribEngines=null;function detectContribEngines(){if(cachedContribEngines)return cachedContribEngines;let which=globalThis.Bun?.which;return cachedContribEngines=Promise.resolve([...which?CONTRIB_ENGINE_IDS.filter((id)=>{let bin=CONTRIB_ENGINES[id]?.defaultCommand[0];return bin?which(bin)!==null:!1}):[],...pluginEngineIds()]),cachedContribEngines}async function detectClaudeAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findClaudeBinary()),configPath=claudeGlobalConfigPath(deps.env,deps.home()),raw;try{raw=deps.readFile(configPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${configPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${configPath}: ${errorMessage(err)}`}}let oauth=parsed?.oauthAccount;if(!oauth||typeof oauth!=="object")return{binary,account:{kind:"none"}};let o=oauth,email=typeof o.emailAddress==="string"?o.emailAddress:void 0;if(!email)return{binary,account:{kind:"none"}};return{binary,account:{kind:"oauth",email,organization:typeof o.organizationName==="string"?o.organizationName:void 0,displayName:typeof o.displayName==="string"?o.displayName:void 0,billingType:typeof o.billingType==="string"?o.billingType:void 0}}}async function detectCodexAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findCodexBinary()),authPath=codexAuthPath(deps.env,deps.home()),raw;try{raw=deps.readFile(authPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${authPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${authPath}: ${errorMessage(err)}`}}let obj=parsed??{},tokens=obj.tokens,idToken=typeof tokens?.id_token==="string"?tokens.id_token:void 0;if(idToken){let payload=decodeJwtPayload(idToken);if(!payload)return{binary,account:{kind:"none"},accountError:"codex id_token: malformed JWT"};let email=typeof payload.email==="string"?payload.email:void 0,authClaimRaw=payload["https://api.openai.com/auth"],authClaim=isObject(authClaimRaw)?authClaimRaw:void 0,plan=typeof authClaim?.chatgpt_plan_type==="string"?authClaim.chatgpt_plan_type:void 0;if(email)return{binary,account:{kind:"chatgpt",email,plan}};return{binary,account:{kind:"none"},accountError:"codex id_token: no email claim"}}let apiKey=obj.OPENAI_API_KEY;if(typeof apiKey==="string"&&apiKey.length>0)return{binary,account:{kind:"apikey"}};return{binary,account:{kind:"none"}}}async function detectCopilotAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findCopilotBinary());for(let source of["COPILOT_GITHUB_TOKEN","GH_TOKEN","GITHUB_TOKEN"])if(deps.env(source)?.trim())return{binary,account:{kind:"token",source}};let configPath=copilotConfigPath(deps.env,deps.home()),raw;try{raw=deps.readFile(configPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${configPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${configPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};if(hasStringDeep(parsed,["github_token","oauth_token","access_token","token","selectedUser","currentUser","user"]))return{binary,account:{kind:"oauth"}};return{binary,account:{kind:"none"}}}async function detectBobAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findBobBinary()),secretsPath=bobAuthSecretsPath(deps.home()),raw;try{raw=deps.readFile(secretsPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${secretsPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${secretsPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};let signedIn=Object.entries(parsed).some(([key,value])=>key.startsWith("bob.auth.tokens-")&&typeof value==="string"&&value.length>0);return{binary,account:signedIn?{kind:"oauth"}:{kind:"none"}}}async function detectKimiAccount(deps=defaultDeps){let binary=await probeBinary(()=>deps.findKimiBinary()),credPath=kimiCredentialsPath(deps.env,deps.home()),raw;try{raw=deps.readFile(credPath)}catch(err){return{binary,account:{kind:"none"},accountError:`read ${credPath}: ${errorMessage(err)}`}}if(raw===null)return{binary,account:{kind:"none"}};let parsed;try{parsed=JSON.parse(raw)}catch(err){return{binary,account:{kind:"none"},accountError:`parse ${credPath}: ${errorMessage(err)}`}}if(!isObject(parsed))return{binary,account:{kind:"none"}};let token=parsed.access_token;if(typeof token==="string"&&token.length>0)return{binary,account:{kind:"oauth"}};return{binary,account:{kind:"none"}}}function hasStringDeep(value,interestingKeys,depth=0){if(depth>4||!isObject(value))return!1;for(let[key,entry]of Object.entries(value)){if(interestingKeys.includes(key)&&typeof entry==="string"&&entry.length>0)return!0;if(isObject(entry)&&hasStringDeep(entry,interestingKeys,depth+1))return!0}return!1}
|
|
5
5
|
export{parseFlatHooks,mergeFlatHooks,registerPluginEngine,clearPluginEngines,pluginEngineIds,isContribEngine,CONTRIB_ENGINE_IDS,contribEngineEntry,resetAvailableVendorsCache,installedEngineIds,availableEngineIds,detectClaudeAccount,detectCodexAccount,detectCopilotAccount,detectBobAccount,detectKimiAccount};
|
|
@@ -4,5 +4,5 @@ import{generateCompletions,isShellKind,mergeSubVerbs,shippedCompletionsPath}from
|
|
|
4
4
|
|
|
5
5
|
${usage}`),process.exit(2)};if(rest.some((arg)=>HELP_WORDS.includes(arg))){process.stdout.write(usage);return}let flags=rest.filter((arg)=>arg.startsWith("-")),shells=rest.filter((arg)=>!arg.startsWith("-")),unknownFlag=flags.find((flag)=>flag!=="--path"&&flag!=="--install");if(unknownFlag)fail(`unknown option "${unknownFlag}"`);if(new Set(flags).size>1)fail("--path and --install are different things; pass one");let shell=shells.length===1?shells[0]:void 0;if(!isShellKind(shell))fail(`unknown shell "${shells.join(" ")}"`);let scriptPath=shippedCompletionsPath(shell,cliName,deps.shippedDir),shipped=existsSync(scriptPath)?scriptPath:null;if(flags[0]==="--path"){if(!shipped)fail(`no pre-generated ${shell} script at ${scriptPath}
|
|
6
6
|
${cliName} completions ${shell} # print the script to stdout instead`);process.stdout.write(`${shipped}
|
|
7
|
-
`);return}if(flags[0]==="--install"){let[{installCompletions,settleWelcomeInstall},{t}]=await Promise.all([import("./chunk-
|
|
8
|
-
`);return}if(shipped){process.stdout.write(readFileSync(shipped,"utf8"));return}let{API_VERBS}=await import("./chunk-
|
|
7
|
+
`);return}if(flags[0]==="--install"){let[{installCompletions,settleWelcomeInstall},{t}]=await Promise.all([import("./chunk-nhpadsbv.js"),import("./chunk-q349ydch.js")]),completion=installCompletions(shell,deps.home,cliName,shipped);settleWelcomeInstall("completions",shell);let line=completion.installed?"onboarding.appliedCompletions":"onboarding.keptCompletions";process.stdout.write(`${t(line,{path:completion.path})}
|
|
8
|
+
`);return}if(shipped){process.stdout.write(readFileSync(shipped,"utf8"));return}let{API_VERBS}=await import("./chunk-cgy92ks5.js");process.stdout.write(generateCompletions(shell,cliName,mergeSubVerbs(API_VERBS)))}export{runCompletionsSubcommand};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{SUBCOMMAND_VERBS}from"./chunk-1qge84t7.js";import{NPX_MISSING_EXIT,bundledSkillDir,installedSkillDiffersFromBundled,npxSkillsCommand,roveSkillPaths,roveSkillState,runNpxSkillsInstall}from"./chunk-
|
|
2
|
+
import{SUBCOMMAND_VERBS}from"./chunk-1qge84t7.js";import{NPX_MISSING_EXIT,bundledSkillDir,installedSkillDiffersFromBundled,npxSkillsCommand,roveSkillPaths,roveSkillState,runNpxSkillsInstall}from"./chunk-p8d9va1w.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import{ROVE_PRODUCT_NAME}from"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import{__require}from"./chunk-91sykzqq.js";import{existsSync,readFileSync}from"fs";import{join}from"path";var CLI_NAME=ROVE_PRODUCT_NAME,SKILL_VERBS=SUBCOMMAND_VERBS.skill;function skillUsage(){return[`usage: ${CLI_NAME} skill <verb>`,"","verbs:"," install [--global|-g | --project|-p] [--agent NAME]\u2026 Install the Rove agent skill (wraps `npx skills add`)"," status Show whether the skill is installed"," command [--global|-g | --project|-p] [--agent NAME]\u2026 Print the underlying npx command without running it",` print Print the bundled SKILL.md (also: \`${CLI_NAME} --skill\`)`,"",`The skill teaches a coding agent how to drive \`${CLI_NAME} api\`. Installs are`,"global (user-level) by default; --global/-g says so explicitly, --project/-p","installs into the current project instead. With no --agent, the agent-skills","CLI detects your installed agents and asks; repeat --agent to name them","(e.g. --agent claude-code --agent codex)."].join(`
|
|
3
3
|
`)}function parseInstallFlags(rest){let global=!0,agents=[];for(let i=0;i<rest.length;i++){let arg=rest[i];if(arg==="--project"||arg==="-p")global=!1;else if(arg==="--global"||arg==="-g")global=!0;else if(arg==="--agent"){let v=rest[i+1];if(!v||v.startsWith("--"))process.stderr.write(`${CLI_NAME} skill: --agent requires a value
|
|
4
4
|
`),process.exit(2);agents.push(v),i++}else if(arg.startsWith("--agent="))agents.push(arg.slice(8));else process.stderr.write(`${CLI_NAME} skill: unknown flag "${arg}"
|
|
5
5
|
|
|
@@ -11,7 +11,7 @@ ${skillUsage()}
|
|
|
11
11
|
|
|
12
12
|
${skillUsage()}
|
|
13
13
|
`),process.exit(2);if(verb==="print"){let bundled2=bundledSkillDir(),path=bundled2?join(bundled2,"SKILL.md"):roveSkillPaths().find((p)=>existsSync(p));if(!path)process.stderr.write(`${CLI_NAME} skill: no SKILL.md found (not bundled, not installed) \u2014 run \`${CLI_NAME} skill install\`
|
|
14
|
-
`),process.exit(1);process.stdout.write(readFileSync(path,"utf8"));return}if(verb==="status"){let{isRovePluginEnabled}=await import("./chunk-
|
|
14
|
+
`),process.exit(1);process.stdout.write(readFileSync(path,"utf8"));return}if(verb==="status"){let{isRovePluginEnabled}=await import("./chunk-zy20hzvh.js"),state=roveSkillState(),paths=roveSkillPaths(),pluginNote=isRovePluginEnabled()?` note: the Rove Claude Code plugin is enabled \u2014 for Claude Code the skill ships
|
|
15
15
|
inside the plugin and versions with it (staleness prompts are suppressed).
|
|
16
16
|
`:"",head=!state.installed?"\u2717 not installed":state.stale?`\u26A0 out of date (installed ${state.installedVersion===null?"unstamped":`v${state.installedVersion}`}, this Rove wants v${state.currentVersion})`:`\u2713 installed (v${state.installedVersion})`,contentDrift=state.installed&&!state.stale&&!!state.path&&installedSkillDiffersFromBundled(state.path);process.stdout.write([`${CLI_NAME} skill: ${head}`,...contentDrift?[" \u26A0 content differs from the copy bundled with this Rove at the same version \u2014",` run \`${CLI_NAME} --skill > ${state.path}\` to refresh it`]:[],` looked in: ${paths.join(`
|
|
17
17
|
`)}`,state.installed&&!state.stale?"":` \u2192 run \`${CLI_NAME} skill install\` to install / refresh`,""].join(`
|
|
@@ -21,5 +21,5 @@ ${bundled?"":`${CLI_NAME} skill: no bundled skill found \u2014 falling back to a
|
|
|
21
21
|
`}`);let code=await runNpxSkillsInstall(agents,global);if(code!==0){if(code!==NPX_MISSING_EXIT)process.stderr.write(`
|
|
22
22
|
${CLI_NAME} skill install failed (npx exited ${code}).
|
|
23
23
|
You can run it yourself: ${npxSkillsCommand({agent:agents,global})}
|
|
24
|
-
`);process.exit(code||1)}if(global){let{settleWelcomeInstall}=await import("./chunk-
|
|
24
|
+
`);process.exit(code||1)}if(global){let{settleWelcomeInstall}=await import("./chunk-nhpadsbv.js");settleWelcomeInstall("skill")}process.stdout.write(`${CLI_NAME} skill: installed.
|
|
25
25
|
`)}export{runSkillSubcommand};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{PS_PROBE_TIMEOUT_MS,engineProcessIn,foregroundEngine,foregroundEngineIn,hasAncestor,parsePsSnapshot,psSnapshot,psSnapshotWith,vendorFromArgv}from"./chunk-s21t29qn.js";import"./chunk-hm7t9gkb.js";import"./chunk-2tfnscxk.js";import"./chunk-sb2xg6py.js";import"./chunk-w7zv47mp.js";import"./chunk-2brn8e1y.js";import"./chunk-q1e0qqmd.js";import"./chunk-gt1vbz3f.js";import"./chunk-avz72132.js";import"./chunk-xy8be792.js";import"./chunk-7kysxgbq.js";import"./chunk-h2m7em1e.js";import"./chunk-7ghwdjdc.js";import"./chunk-tdhk4dz8.js";import"./chunk-xkr7fwvb.js";import"./chunk-40dgv828.js";import"./chunk-3342qzve.js";import"./chunk-axxf5dkq.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-prqeddy7.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-y55zpren.js";import"./chunk-pn5ygqn6.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import{PsProbeUnavailableError}from"./chunk-pxk2c2vj.js";import"./chunk-91sykzqq.js";export{vendorFromArgv,psSnapshotWith,psSnapshot,parsePsSnapshot,hasAncestor,foregroundEngineIn,foregroundEngine,engineProcessIn,PsProbeUnavailableError,PS_PROBE_TIMEOUT_MS};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{canonicalize}from"./chunk-
|
|
2
|
+
import{canonicalize}from"./chunk-1mpheecn.js";import{applyJitter,exponentialBackoff}from"./chunk-2tfnscxk.js";import{getRemoteRepoConfig,isRemoteRepoKey,resolveRepoRoot}from"./chunk-xkr7fwvb.js";var canonPath=canonicalize;function randomDirTaskSuffix(){return Math.random().toString(36).slice(2,6).padEnd(4,"0")}function titleFromRepo(repo){let segs=repo.split(/[/\\]/).filter(Boolean);return segs.length>0?segs[segs.length-1]??repo:repo}function normalizeMainRepo(repo){let normalized=resolveRepoRoot(repo);return{repo:normalized,key:isRemoteRepoKey(normalized)?normalized:canonPath(normalized)}}function repoWorkingDir(repo){return getRemoteRepoConfig(repo)?.basePath??repo}var GH_PR_VIEW_FIELDS="number,url,title,state,baseRefName,reviewDecision,mergeable,statusCheckRollup";function lifecycleFromState(state,reviewDecision){switch((state??"").toUpperCase()){case"MERGED":return"merged";case"CLOSED":return"closed";case"OPEN":return(reviewDecision??"").toUpperCase()==="APPROVED"?"ready_to_merge":"open";default:return"unknown"}}function entryCheckState(entry){let status=(entry.status??"").toUpperCase(),conclusion=(entry.conclusion??"").toUpperCase(),contextState=(entry.state??"").toUpperCase();if(status&&status!=="COMPLETED")return"pending";if(conclusion){if(conclusion==="SUCCESS"||conclusion==="NEUTRAL"||conclusion==="SKIPPED")return"passing";return"failing"}if(contextState==="SUCCESS")return"passing";if(contextState==="PENDING"||contextState==="EXPECTED")return"pending";if(contextState==="FAILURE"||contextState==="ERROR")return"failing";return"unknown"}function checkStateFromRollup(rollup){if(!rollup||rollup.length===0)return"none";let sawPending=!1,sawUnknown=!1;for(let entry of rollup){let s=entryCheckState(entry);if(s==="failing")return"failing";if(s==="pending")sawPending=!0;else if(s==="unknown")sawUnknown=!0}if(sawPending)return"pending";if(sawUnknown)return"unknown";return"passing"}function mapGhPrView(view,at){if(!view||typeof view.number!=="number")return null;return{provider:"github",lifecycle:lifecycleFromState(view.state,view.reviewDecision),checkState:checkStateFromRollup(view.statusCheckRollup),number:view.number,url:view.url,title:view.title,baseRef:view.baseRefName,reviewDecision:view.reviewDecision||void 0,mergeable:view.mergeable||void 0,lastCheckedAt:at}}function samePrStatus(a,b){if(a===b)return!0;if(!a||!b)return!1;return a.provider===b.provider&&a.lifecycle===b.lifecycle&&a.checkState===b.checkState&&a.number===b.number&&a.url===b.url&&a.title===b.title&&a.baseRef===b.baseRef&&a.reviewDecision===b.reviewDecision&&a.mergeable===b.mergeable}var NO_REMOTE_PATTERNS=["none of the git remotes","no git remote","to use github cli in a github repository","not a github repository"],AUTH_PATTERNS=["gh auth login","authentication required","not logged in","http 401","bad credentials","requires authentication"],NETWORK_PATTERNS=["could not resolve host","no such host","dial tcp","connection refused","connection reset","network is unreachable","i/o timeout","timeout","tls handshake","http 5","rate limit","try again"];function matchesAny(haystack,needles){return needles.some((n)=>haystack.includes(n))}function classifyGhFailure(s){if(s.parseError)return{kind:"error",error:"parse"};if(s.timedOut)return{kind:"error",error:"timeout"};if(s.spawnError)return{kind:"error",error:"missing-binary"};let err=(s.stderr??"").toLowerCase();if(matchesAny(err,NO_REMOTE_PATTERNS))return{kind:"error",error:"no-remote"};if(matchesAny(err,AUTH_PATTERNS))return{kind:"error",error:"auth"};if(matchesAny(err,NETWORK_PATTERNS))return{kind:"error",error:"network"};return{kind:"error",error:"unknown"}}function nextPrPoll(outcome,prevFailures,now,cfg,rand=Math.random){let at=(delay)=>now+applyJitter(delay,cfg.jitterRatio,rand);if(outcome.kind==="pr")return{nextAllowedAt:at(outcome.settled?cfg.settledMs:cfg.tickMs),failures:0};if(outcome.kind==="empty")return{nextAllowedAt:at(cfg.noPrMs),failures:0};if(outcome.error==="no-remote")return{nextAllowedAt:at(cfg.noRemoteMs),failures:0};let failures=prevFailures+1;return{nextAllowedAt:at(exponentialBackoff(cfg.failureBaseMs,failures-1,cfg.failureCapMs)),failures}}function checkResolutionNotify(prev,next){if(prev!=="pending")return null;if(next==="passing"||next==="failing")return next;return null}
|
|
3
3
|
export{GH_PR_VIEW_FIELDS,mapGhPrView,samePrStatus,classifyGhFailure,nextPrPoll,checkResolutionNotify,canonPath,randomDirTaskSuffix,titleFromRepo,normalizeMainRepo,repoWorkingDir};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{CURRENT_VERSION,repoSlug}from"./chunk-
|
|
2
|
+
import{CURRENT_VERSION,repoSlug}from"./chunk-75zg2k73.js";import{spawnSync}from"child_process";var DEFAULT_FEEDBACK_CATEGORY_SLUG="feedback",DISCUSSION_CATEGORY_QUERY=`
|
|
3
3
|
query($owner: String!, $name: String!) {
|
|
4
4
|
repository(owner: $owner, name: $name) {
|
|
5
5
|
id
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{localDaemonSocketPath,localPtySocketPath,machineSocketDir,machineSshArgs}from"./chunk-
|
|
2
|
+
import{localDaemonSocketPath,localPtySocketPath,machineSocketDir,machineSshArgs}from"./chunk-3jnw3ftt.js";import{homeDir}from"./chunk-prqeddy7.js";import{spawn}from"child_process";import{mkdirSync,rmSync}from"fs";import{connect as netConnect}from"net";var DIR_MODE=448,BACKOFF_START_MS=500,BACKOFF_MAX_MS=5000,HEALTH_INTERVAL_MS=1e4;function startTunnel(opts){let home=opts.home??homeDir(),daemonSocketPath=localDaemonSocketPath(opts.alias,home),ptySocketPath=localPtySocketPath(opts.alias,home),listeners=new Set,state="connecting",stopped=!1,backoff=BACKOFF_START_MS,setState=(next)=>{if(state===next)return;state=next;for(let listener of listeners)listener(next)},handle={alias:opts.alias,daemonSocketPath,ptySocketPath,state:()=>state,onState:(listener)=>{return listeners.add(listener),()=>listeners.delete(listener)},stop:()=>{stopped=!0}};if(process.platform==="win32")return setState("unsupported"),handle;let schedule=opts.setTimeoutFn??((fn,ms)=>setTimeout(fn,ms)),ensure=opts.ensureFn??(()=>ensureForwards({alias:opts.alias,config:opts.config,remoteDaemonSocket:opts.remoteDaemonSocket,remotePtySocket:opts.remotePtySocket,home})),check=opts.checkFn??(()=>socketAnswers(daemonSocketPath)),attempt=async()=>{if(stopped)return;let up=await ensure();if(stopped)return;if(up){backoff=BACKOFF_START_MS,setState("online"),schedule(()=>void health(),HEALTH_INTERVAL_MS);return}setState("offline");let wait=backoff;backoff=Math.min(backoff*2,BACKOFF_MAX_MS),schedule(()=>void attempt(),wait)},health=async()=>{if(stopped)return;if(await check()){if(!stopped)schedule(()=>void health(),HEALTH_INTERVAL_MS);return}setState("offline"),attempt()};return attempt(),handle}async function ensureForwards(args){if(process.platform==="win32")return!1;let home=args.home??homeDir(),daemonLocal=localDaemonSocketPath(args.alias,home),ptyLocal=localPtySocketPath(args.alias,home);try{mkdirSync(machineSocketDir(args.alias,home),{recursive:!0,mode:DIR_MODE})}catch{}if(await socketAnswers(daemonLocal))return!0;for(let path of[daemonLocal,ptyLocal])try{rmSync(path,{force:!0})}catch{}let base=machineSshArgs(args.alias,args.config,{home});if(await runSsh([...base,"true"])!==0)return!1;let target=base.at(-1)??args.alias,flags=base.slice(0,-1);return await runSsh([...flags,"-O","forward","-L",`${daemonLocal}:${args.remoteDaemonSocket}`,"-L",`${ptyLocal}:${args.remotePtySocket}`,target])===0&&await socketAnswers(daemonLocal)}function runSsh(argv){return new Promise((resolve)=>{let child=spawn(argv[0]??"ssh",argv.slice(1),{stdio:"ignore"});child.on("error",()=>resolve(-1)),child.on("close",(code)=>resolve(code??-1))})}function socketAnswers(path){return new Promise((resolve)=>{let socket=netConnect(path),done=(answer)=>{socket.destroy(),resolve(answer)};socket.once("connect",()=>done(!0)),socket.once("error",()=>done(!1)),socket.setTimeout(1500,()=>done(!1))})}
|
|
3
3
|
export{startTunnel,ensureForwards};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{TaskIndexStore}from"./chunk-r4bn0mtb.js";import"./chunk-qkehg2c1.js";import"./chunk-avz72132.js";import"./chunk-xy8be792.js";import"./chunk-h2m7em1e.js";import"./chunk-tdhk4dz8.js";import"./chunk-qk5f6p3e.js";import"./chunk-b31cte10.js";import"./chunk-zt7wfnva.js";import"./chunk-yt15y085.js";import"./chunk-y55zpren.js";import"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";export{TaskIndexStore};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-
|
|
2
|
+
import{__require}from"./chunk-91sykzqq.js";var CHANNEL_LOADERS={weixin:async()=>(await import("./chunk-bdvqjzwh.js")).default};async function runChannelCli(id,argv){let load=CHANNEL_LOADERS[id];if(!load)throw Error(`no chat channel "${id}"`);await(await load()).runCli(argv)}async function startChatChannels(ctx){let started=[];for(let[id,load]of Object.entries(CHANNEL_LOADERS))try{let channel=(await load()).createChannel();await channel.start(ctx),started.push(channel)}catch(err){ctx.log("channel",`${id} did not start: ${err instanceof Error?err.message:String(err)}`)}return started}
|
|
3
3
|
export{runChannelCli,startChatChannels};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{machineSocketDir,machineSshArgs,sshTargetOf}from"./chunk-
|
|
2
|
+
import{machineSocketDir,machineSshArgs,sshTargetOf}from"./chunk-3jnw3ftt.js";import{shQuote}from"./chunk-b7xjhgts.js";import{spawn}from"child_process";import{mkdirSync}from"fs";import{posix}from"path";var PATTERNS=[["host-key-changed",/REMOTE HOST IDENTIFICATION HAS CHANGED|Host key for .* has changed/i],["host-key-unverified",/Host key verification failed|No .*host key is known for/i],["auth-denied",/Permission denied \(|Too many authentication failures|no matching host key type/i],["unresolved",/Could not resolve hostname|Name or service not known|nodename nor servname/i],["refused",/Connection refused/i],["timeout",/timed out|Operation timed out|No route to host|Network is unreachable/i]];function classifySshFailure(stderr){for(let[kind,pattern]of PATTERNS)if(pattern.test(stderr))return kind;return"unknown"}function sshFailureRemedy(kind,target){switch(kind){case"unresolved":return`${target} does not resolve to an address. Check the name, or the Host block in ~/.ssh/config; on a tailnet, check \`tailscale status\`.`;case"refused":return`${target} refused the connection: nothing listens for ssh there. Enable Remote Login / start sshd on it, or pass the right --port.`;case"timeout":return`${target} did not answer. Is it awake and on this network (or VPN / tailnet)?`;case"host-key-changed":return`${target}'s host key CHANGED since you last connected. That is either a reinstall or someone in the middle. If you reinstalled it, remove the old key with \`ssh-keygen -R <host>\` and retry; otherwise stop here.`;case"host-key-unverified":return`${target}'s host key is not trusted yet. Run \`rove machine add\` in a terminal to confirm its fingerprint, or connect once with \`ssh ${target}\`.`;case"auth-denied":return`${target} rejected every key ssh offered. Load your key into ssh-agent, pass --identity <key>, or install a key there with \`ssh-copy-id ${target}\`.`;case"unknown":return`ssh to ${target} failed. Run \`ssh ${target} true\` to see why.`}}async function runOnMachine(alias,config,command,opts={}){try{mkdirSync(machineSocketDir(alias,opts.home),{recursive:!0,mode:448})}catch{}let argv=[...machineSshArgs(alias,config,{home:opts.home}),command];return await new Promise((resolve)=>{let stdout="",stderr="",settled=!1,done=(exitCode)=>{if(settled)return;settled=!0,clearTimeout(timer),resolve({stdout,stderr,exitCode})},child=spawn(argv[0]??"ssh",argv.slice(1),{stdio:["ignore","pipe","pipe"]}),timer=setTimeout(()=>{child.kill("SIGKILL"),stderr+=`
|
|
3
3
|
timed out`,done(-1)},opts.timeoutMs??30000);child.stdout?.on("data",(c)=>{stdout+=c.toString()}),child.stderr?.on("data",(c)=>{stderr+=c.toString()}),child.on("error",()=>done(-1)),child.on("close",(code)=>done(code??-1))})}async function discoverMachine(alias,config,opts={}){let found=await probe(alias,config,roveCommand(config.roveBin),opts);if(found.ok||found.code!=="NO_ROVE")return found;let located=parseLocatedRove((await runOnMachine(alias,config,LOCATE_ROVE_SCRIPT,opts)).stdout);if(!located||located===config.roveBin)return found;let retry=await probe(alias,config,roveCommand(located),opts);return retry.ok?{...retry,roveBin:located}:retry}function roveCommand(roveBin){if(!roveBin)return"rove";return`PATH=${shQuote(posix.dirname(roveBin))}:"$PATH" ${shQuote(roveBin)}`}var LOCATE_ROVE_SCRIPT=[`p=$("\${SHELL:-sh}" -lc 'command -v rove' 2>/dev/null)`,'if [ -n "$p" ] && [ -x "$p" ]; then echo "ROVE_BIN=$p"; exit 0; fi','for p in "$HOME/.bun/bin/rove" "$HOME/.npm-global/bin/rove" "$HOME/.local/bin/rove" /opt/homebrew/bin/rove /usr/local/bin/rove "$HOME"/.nvm/versions/node/*/bin/rove; do',' if [ -x "$p" ]; then echo "ROVE_BIN=$p"; exit 0; fi',"done","exit 1"].join(`
|
|
4
4
|
`);function parseLocatedRove(stdout){return/^ROVE_BIN=(\/\S.*)$/m.exec(stdout)?.[1]?.trim()??null}var ROVE_MISSING=/(?:^|\W)rove:? (?:command not found|not found)|command not found:? rove|\/rove:? No such file or directory|no such file or directory: \S*\/rove\b/i;async function probe(alias,config,rove,opts){let first=await runOnMachine(alias,config,`${rove} daemon status --json`,opts),parsed=parseStatusJson(first.stdout);if(parsed)return{ok:!0,status:parsed};let combined=`${first.stdout}
|
|
5
5
|
${first.stderr}`.trim();if(ROVE_MISSING.test(combined))return{ok:!1,code:"NO_ROVE",message:`Rove is not installed on ${alias}: not on its PATH, its login shell's PATH, or the usual bun/npm/nvm install dirs. Install it there with \`npm i -g @sma1lboy/rove\`, then re-run.`};if(first.exitCode===255||first.exitCode===-1){let ssh=classifySshFailure(first.stderr),remedy=sshFailureRemedy(ssh,sshTargetOf(config));return{ok:!1,code:"SSH_FAILED",ssh,message:ssh==="unknown"&&combined?`${remedy}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{RemoteOrchestrator}from"./chunk-
|
|
2
|
+
import{RemoteOrchestrator}from"./chunk-vx4e787s.js";import{startTunnel}from"./chunk-v0jvt60f.js";import{discoverMachine}from"./chunk-v9dcyjmj.js";import{dedupeMachines,duplicateAliasOf,listMachines,readMachines,setMachineIdentity,updateMachine}from"./chunk-3jnw3ftt.js";import{loadStateFile}from"./chunk-axxf5dkq.js";import{createStateCell}from"./chunk-cmp64q4j.js";import{RoveDaemonClient}from"./chunk-y33j54yr.js";import{logClient,logClientError}from"./chunk-y55zpren.js";class MachineHub{local;slots=new Map;machinesAcc=createStateCell([],"machines.status");mergedAcc=createStateCell([],"machines.tasks");localUnsubscribe=null;disposed=!1;constructor(local){this.local=local}machinesSignal(){return this.machinesAcc}tasksSignal(){if(this.slots.size===0)return this.local.tasksSignal();return this.mergedAcc}remoteTaskIds(){let ids=new Set;for(let slot of this.slots.values())for(let task of slot.tasks)ids.add(String(task.id));return ids}attach(){let entries=dedupeMachines(listMachines());if(entries.length===0)return;for(let entry of entries)this.slots.set(entry.alias,{entry,tasks:[]});this.publishStatuses(),this.localUnsubscribe=this.local.tasksSignal().subscribe(()=>this.republishTasks()),this.republishTasks();for(let entry of entries)this.connect(entry)}async connect(entry){let slot=this.slots.get(entry.alias);if(!slot||this.disposed)return;let found=await discoverMachine(entry.alias,entry);if(this.disposed)return;let sockets=found.ok?{daemon:found.status.socketPath,pty:found.status.ptySocketPath}:entry.sockets;if(!sockets){this.setStatus(entry.alias,{state:"offline",error:found.ok?void 0:found.message});return}if(found.ok)updateMachine(entry.alias,{sockets,...found.roveBin?{roveBin:found.roveBin}:{}});let tunnel=startTunnel({alias:entry.alias,config:entry,remoteDaemonSocket:sockets.daemon,remotePtySocket:sockets.pty});if(slot.tunnel=tunnel,tunnel.state()==="unsupported"){this.setStatus(entry.alias,{state:"unsupported",error:"SSH unix-socket forwarding is not available on Windows"});return}if(tunnel.onState((state)=>{if(state==="online")this.openOrchestrator(entry,tunnel);else if(state==="offline")this.setStatus(entry.alias,{state:"offline"}),this.republishTasks()}),tunnel.state()==="online")await this.openOrchestrator(entry,tunnel)}async openOrchestrator(entry,tunnel){let slot=this.slots.get(entry.alias);if(!slot||this.disposed||slot.orchestrator)return;let client=new RoveDaemonClient(tunnel.daemonSocketPath),orchestrator=new RemoteOrchestrator(client,{role:"gui",expectForeignHome:!0,onPeerIdentity:(peer)=>this.onPeerIdentity(entry.alias,peer)});slot.orchestrator=orchestrator;try{await orchestrator.init()}catch(err){let message=err instanceof Error?err.message:String(err);this.setStatus(entry.alias,{state:classifyHandshakeFailure(message),error:message}),logClientError("machines",err);return}let stopTasks=orchestrator.tasksSignal().subscribe(()=>{slot.tasks=orchestrator.tasksSignal().get(),this.republishTasks()}),stopConnection=orchestrator.connectionStateSignal().subscribe(()=>{let connected=orchestrator.connectionStateSignal().get()==="online";if(this.slots.get(entry.alias)!==slot)return;this.setStatus(entry.alias,{state:connected?"online":"offline"}),this.republishTasks()});slot.unsubscribe=()=>{stopTasks(),stopConnection()},slot.tasks=orchestrator.tasksSignal().get(),this.setStatus(entry.alias,{state:"online",version:orchestrator.daemonVersionSignal().get()??void 0}),this.republishTasks(),logClient("machines",`${entry.alias} online (${slot.tasks.length} tasks)`)}onPeerIdentity(alias,peer){if(!peer.hostname&&!peer.homeDir)return;let identity={hostname:peer.hostname,homeDir:peer.homeDir,daemonPid:peer.daemonPid};setMachineIdentity(alias,identity);let duplicate=duplicateAliasOf(readMachines(loadStateFile()),alias,identity);this.setStatus(alias,{hostname:peer.hostname||void 0,version:peer.roveVersion||void 0,...duplicate?{duplicateOf:duplicate}:{}})}setStatus(alias,patch){let next=this.machinesAcc.get().map((row)=>row.alias===alias?{...row,...patch}:row);this.machinesAcc.set(next)}publishStatuses(){this.machinesAcc.set([...this.slots.values()].map((slot)=>({alias:slot.entry.alias,hostLabel:slot.entry.alias,state:"connecting"})))}republishTasks(){let merged=this.local.tasksSignal().get().map((task)=>stampOrigin(task,"local","local"));for(let slot of this.slots.values()){let status=this.machinesAcc.get().find((row)=>row.alias===slot.entry.alias);if(status?.duplicateOf)continue;let hostLabel=status?.hostLabel||slot.entry.alias,stale=status?.state!=="online";for(let task of slot.tasks)merged.push(stampOrigin(task,slot.entry.alias,hostLabel,stale))}this.mergedAcc.set(merged)}dispose(){this.disposed=!0,this.localUnsubscribe?.();for(let slot of this.slots.values())slot.unsubscribe?.(),slot.orchestrator?.dispose(),slot.tunnel?.stop();this.slots.clear()}}function classifyHandshakeFailure(message){return/protocol v\d/i.test(message)?"mismatch":"offline"}function stampOrigin(task,machineId,hostLabel,stale=!1){return{...task,origin:{machineId,hostLabel,...stale?{stale:!0}:{}}}}
|
|
3
3
|
export{MachineHub,classifyHandshakeFailure};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{isRowTokenTone}from"./chunk-atn06ncf.js";import{sameWorktreeChanges}from"./chunk-55ajzrj6.js";import{ensureDaemonReachable,isStaleInstallError}from"./chunk-ad5gbdcf.js";import{toTaskId}from"./chunk-xy8be792.js";import{CURRENT_VERSION}from"./chunk-75zg2k73.js";import{homeDir}from"./chunk-prqeddy7.js";import{createStateCell,mapReadableState}from"./chunk-cmp64q4j.js";import{DAEMON_PROTOCOL_VERSION,MIN_COMPATIBLE_PROTOCOL_VERSION,isAttentionInboxState,isDaemonVersionStale,isForeignDaemonHome,isProtocolCompatible,isRoutineInboxState,parseDaemonStopReason}from"./chunk-y33j54yr.js";import{parseModUiPayload}from"./chunk-278sc87n.js";import{logClient,logClientError}from"./chunk-y55zpren.js";function parseWorktreeChangesPayload(payload){let changes=payload?.changes;if(!changes||typeof changes!=="object"||Array.isArray(changes))return null;let map=new Map;for(let[path,value]of Object.entries(changes)){let counts=value;if(typeof counts?.added!=="number"||typeof counts.deleted!=="number")return null;map.set(path,{added:counts.added,deleted:counts.deleted,...typeof counts.behind==="number"?{behind:counts.behind}:{},...typeof counts.ahead==="number"?{ahead:counts.ahead}:{}})}let unreadable=payload?.unreadable;if(Array.isArray(unreadable)){for(let path of unreadable)if(typeof path==="string"&&path.length>0)map.set(path,null)}return map}function sameWorktreeChangesMap(a,b){if(a.size!==b.size)return!1;for(let[path,counts]of a){if(!b.has(path))return!1;if(!sameWorktreeChanges(counts,b.get(path)??null))return!1}return!0}function parseToken(raw){if(!raw||typeof raw!=="object")return null;let t=raw;if(typeof t.source!=="string"||typeof t.key!=="string")return null;if(typeof t.text!=="string"||t.text.length===0)return null;if(typeof t.expiresAt!=="number"||!Number.isFinite(t.expiresAt))return null;return{source:t.source,key:t.key,text:t.text,...isRowTokenTone(t.tone)?{tone:t.tone}:{},expiresAt:t.expiresAt}}function parseRowTokensPayload(payload){let tokens=payload?.tokens;if(!tokens||typeof tokens!=="object"||Array.isArray(tokens))return null;let out=new Map;for(let[taskId,list]of Object.entries(tokens)){if(!Array.isArray(list))continue;let parsed=list.map(parseToken).filter((token)=>token!==null);if(parsed.length>0)out.set(taskId,parsed)}return out}function sameRowTokenMap(a,b){if(a.size!==b.size)return!1;for(let[taskId,left]of a){let right=b.get(taskId);if(!right||right.length!==left.length)return!1;for(let[i,token]of left.entries()){let other=right[i];if(!other||other.source!==token.source||other.key!==token.key||other.text!==token.text||other.tone!==token.tone||other.expiresAt!==token.expiresAt)return!1}}return!0}function liveRowTokens(map,taskId,now){let tokens=map?.get(taskId);if(!tokens||tokens.length===0)return[];return tokens.filter((token)=>token.expiresAt>now)}function shouldLogReconnectAttempt(attempt){if(attempt>100)return!1;return attempt===1||attempt%10===0}function describePayload(value){if(value===void 0)return"undefined";if(value===null)return"null";let type=Array.isArray(value)?"array":typeof value,text;try{text=typeof value==="string"?value:JSON.stringify(value)}catch{text=String(value)}if(text.length>120)text=`${text.slice(0,120)}\u2026`;return`${type}:${text}`}function decodeUiPrefsPayload(payload){let p=payload;if(!p||typeof p!=="object"||!("theme"in p))return null;if(p.theme!==null&&typeof p.theme!=="string")return null;return{theme:typeof p.theme==="string"&&p.theme.length>0?p.theme:null,..."themeMode"in p?{themeMode:typeof p.themeMode==="string"?p.themeMode:null}:{},transparentBackground:p.transparentBackground!==!1,focusAccent:typeof p.focusAccent==="string"?p.focusAccent:null,locale:typeof p.locale==="string"?p.locale:"",sortMode:p.sortMode==="recent"||p.sortMode==="attention"||p.sortMode==="name"?p.sortMode:"default",keysCollapsed:p.keysCollapsed===!0,projectFilter:typeof p.projectFilter==="string"&&p.projectFilter.length>0?p.projectFilter:null}}var TOKEN_TOTAL_FIELDS=["inputTokens","outputTokens","cacheReadTokens","cacheCreationTokens"];function parseContextUsagePayload(payload){let context=payload?.context;if(!context||typeof context!=="object"||Array.isArray(context))return null;let map=new Map;for(let[key,value]of Object.entries(context)){let v=value;if(typeof v?.contextTokens!=="number")return null;if(v.contextWindowTokens!==void 0&&typeof v.contextWindowTokens!=="number")return null;let totals={};for(let field of TOKEN_TOTAL_FIELDS){let raw=v[field];if(raw===void 0)continue;if(typeof raw!=="number")return null;totals[field]=raw}map.set(key,{contextTokens:v.contextTokens,...typeof v.contextWindowTokens==="number"?{contextWindowTokens:v.contextWindowTokens}:{},...v.approximate===!0?{approximate:!0}:{},...totals})}return map}function sameContextUsageMap(a,b){if(a.size!==b.size)return!1;for(let[key,value]of a){let other=b.get(key);if(!other||other.contextTokens!==value.contextTokens||other.contextWindowTokens!==value.contextWindowTokens||other.approximate!==value.approximate||TOKEN_TOTAL_FIELDS.some((field)=>other[field]!==value[field]))return!1}return!0}function parseUsageSnapshotPayload(payload){let usage=payload?.usage;if(!usage||typeof usage!=="object"||Array.isArray(usage))return null;let map=new Map;for(let[vendor,value]of Object.entries(usage)){let snapshot=value;if(typeof snapshot?.capturedAt!=="number"||!Array.isArray(snapshot.windows))return null;let windows=[];for(let raw of snapshot.windows){let w=raw;if(typeof w?.kind!=="string"||typeof w.label!=="string"||typeof w.percent!=="number")return null;if(w.resetsAt!==null&&typeof w.resetsAt!=="number")return null;windows.push({kind:w.kind,label:w.label,percent:w.percent,resetsAt:w.resetsAt})}map.set(vendor,{windows,capturedAt:snapshot.capturedAt})}return map}function sameUsageSnapshotMap(a,b){if(a.size!==b.size)return!1;for(let[vendor,usage]of a){let other=b.get(vendor);if(!other||other.capturedAt!==usage.capturedAt||other.windows.length!==usage.windows.length)return!1;for(let i=0;i<usage.windows.length;i++){let x=usage.windows[i],y=other.windows[i];if(!x||!y||x.kind!==y.kind||x.label!==y.label||x.percent!==y.percent||x.resetsAt!==y.resetsAt)return!1}}return!0}function parseTranscriptActivityPayload(payload){let activity=payload?.activity;if(!activity||typeof activity!=="object"||Array.isArray(activity))return null;let map=new Map;for(let[path,value]of Object.entries(activity)){let v=value;if(typeof v?.mtimeMs!=="number"||typeof v.completionAt!=="number")return null;if(v.completionId!==null&&typeof v.completionId!=="string")return null;map.set(path,{mtimeMs:v.mtimeMs,completionId:v.completionId,completionAt:v.completionAt})}return map}function sameTranscriptActivityMap(a,b){if(a.size!==b.size)return!1;for(let[path,v]of a){let other=b.get(path);if(!other||other.mtimeMs!==v.mtimeMs||other.completionId!==v.completionId||other.completionAt!==v.completionAt)return!1}return!0}function deserializeTask(s){return{id:toTaskId(s.id),title:s.title,repo:s.repo,branch:s.branch,worktreePath:s.worktreePath,kind:s.kind,...s.scratch?{scratch:!0}:{},...s.routine?{routine:s.routine}:{},status:s.status,pinned:s.pinned,vendor:s.vendor,command:s.command,prStatus:s.prStatus,modelEffort:s.modelEffort,model:s.model,tier:s.tier,groupId:s.groupId,observedLanguage:s.observedLanguage,deletion:s.deletion,quotaResume:s.quotaResume,linkedWorkItem:s.linkedWorkItem,dispatcher:s.dispatcher,requireReport:s.requireReport,prompt:s.prompt,baseRef:s.baseRef,worktreeName:s.worktreeName,report:s.report,createdAt:s.createdAt,updatedAt:s.updatedAt}}async function runReconnectLoop(deps){let delayMs=deps.spawnDaemon?Math.floor(Math.random()*400):500,attempt=0;while(!deps.isDisposed()){if(delayMs>0)await new Promise((r)=>setTimeout(r,delayMs));if(deps.isDisposed())break;attempt++;try{if(deps.spawnDaemon)await deps.ensureReachable();await deps.init(),logClient("orch",`reconnected and re-subscribed after ${attempt} attempt(s) \u2014 task list re-synced`);return}catch(err){if(isStaleInstallError(err)){logClientError("orch-reconnect-fatal",err),deps.onFatal?.(err);return}if(deps.shouldLogAttempt(attempt))logClientError("orch-reconnect",err);delayMs=delayMs===0?500:Math.min(delayMs*2,3000)}}}async function performInit(client,opts,signals){let hello=await client.request("hello",{protocolVersion:DAEMON_PROTOCOL_VERSION,minProtocolVersion:MIN_COMPATIBLE_PROTOCOL_VERSION}),daemonVersion=typeof hello.protocolVersion==="number"?hello.protocolVersion:DAEMON_PROTOCOL_VERSION,daemonMin=typeof hello.minProtocolVersion==="number"?hello.minProtocolVersion:daemonVersion;if(!isProtocolCompatible({localVersion:DAEMON_PROTOCOL_VERSION,localMin:MIN_COMPATIBLE_PROTOCOL_VERSION,remoteVersion:daemonVersion,remoteMin:daemonMin}))throw Error(`Rove daemon is protocol v${daemonVersion} (min v${daemonMin}); this client is v${DAEMON_PROTOCOL_VERSION} (min v${MIN_COMPATIBLE_PROTOCOL_VERSION}). Restart the daemon (\`rove daemon restart\`) or upgrade Rove.`);let clientHome=homeDir();if(!opts.expectForeignHome&&isForeignDaemonHome(hello.homeDir,clientHome))throw Error(`Rove daemon on this socket serves ${hello.homeDir}, but this client uses ${clientHome}. A sandbox or dev daemon has taken the production socket \u2014 stop it (\`rove daemon stop\`), or unset ROVE_DAEMON_SOCKET_PATH / ROVE_DAEMON_SOCKET_PATH before starting it.`);if(signals.setDaemonVersionSig(typeof hello.roveVersion==="string"?hello.roveVersion:null),opts.onPeerIdentity?.({hostname:typeof hello.hostname==="string"?hello.hostname:"",homeDir:typeof hello.homeDir==="string"?hello.homeDir:"",daemonPid:typeof hello.daemonPid==="number"?hello.daemonPid:0,roveVersion:typeof hello.roveVersion==="string"?hello.roveVersion:""}),signals.setDaemonRestartingSig(!1),hello.tasks&&opts.subscribesTasks)signals.setTasks(hello.tasks.map(deserializeTask));if(await client.subscribe({role:opts.role,channels:opts.channels,cellPixelSize:opts.cellPixelSize}),hello.capabilities?.includes("worktree.changes")){if(signals.worktreeChangesAcc()===null)signals.setWorktreeChangesSig(new Map)}else signals.setWorktreeChangesSig(null);if(hello.capabilities?.includes("transcript.activity")){if(signals.transcriptActivityAcc()===null)signals.setTranscriptActivitySig(new Map)}else signals.setTranscriptActivitySig(null);signals.setConnectionState("online"),logClient("orch",`subscribed as ${opts.role} (${signals.tasksAcc().length} tasks)`)}function ordinalOf(tabId,fallback){let match=/^tab-(\d+)$/.exec(tabId);return match?Number(match[1]):fallback}function adoptTabs(state,tabIds){let known=new Set(state.tabs.map((tab)=>tab.id)),fresh=[];for(let id of tabIds){if(known.has(id))continue;known.add(id),fresh.push(id)}if(fresh.length===0)return state;let minted=state.nextOrdinal,adopted=fresh.map((id)=>({kind:"engine",id,title:null,ordinal:ordinalOf(id,minted++),spawned:!0}));adopted.sort((a,b)=>a.ordinal-b.ordinal);let tabs=[...state.tabs,...adopted],maxOrdinal=tabs.reduce((max,tab)=>Math.max(max,tab.ordinal),0);return{tabs,activeId:state.activeId,nextOrdinal:Math.max(state.nextOrdinal,maxOrdinal+1)}}function isAddedTab(raw){if(typeof raw!=="object"||raw===null)return!1;if(!("id"in raw)||typeof raw.id!=="string")return!1;if(!("ordinal"in raw)||typeof raw.ordinal!=="number")return!1;if(!("title"in raw)||raw.title!==null&&typeof raw.title!=="string")return!1;if(!("kind"in raw))return!1;if(raw.kind==="engine")return!0;return raw.kind==="command"&&"command"in raw&&Array.isArray(raw.command)}function absorbTab(state,tab){let nextOrdinal=Math.max(state.nextOrdinal,tab.ordinal+1),known=state.tabs.find((t)=>t.id===tab.id);if(known?.kind===tab.kind){if(Object.entries(tab).every(([key,value])=>JSON.stringify(Reflect.get(known,key))===JSON.stringify(value))&&nextOrdinal===state.nextOrdinal)return state}let merged=known?.kind===tab.kind?{...known,...tab,title:known.title}:tab,tabs=known?state.tabs.map((t)=>t===known?merged:t):[...state.tabs,merged];return{...state,tabs,nextOrdinal}}var MAP_CHANNELS={"usage.snapshot":{what:"usage payload",parse:parseUsageSnapshotPayload,same:sameUsageSnapshotMap,read:(signals)=>signals.usageSnapshotAcc(),write:(signals,next)=>signals.setUsageSnapshotSig(next)},"usage.context":{what:"context payload",parse:parseContextUsagePayload,same:sameContextUsageMap,read:(signals)=>signals.contextUsageAcc(),write:(signals,next)=>signals.setContextUsageSig(next)},"worktree.changes":{what:"changes payload",parse:parseWorktreeChangesPayload,same:sameWorktreeChangesMap,read:(signals)=>signals.worktreeChangesAcc(),write:(signals,next)=>signals.setWorktreeChangesSig(next)},"transcript.activity":{what:"activity payload",parse:parseTranscriptActivityPayload,same:sameTranscriptActivityMap,read:(signals)=>signals.transcriptActivityAcc(),write:(signals,next)=>signals.setTranscriptActivitySig(next)},"mod.ui":{what:"mod pane list",parse:parseModUiPayload,same:(a,b)=>JSON.stringify(a)===JSON.stringify(b),read:(signals)=>signals.modPanesAcc(),write:(signals,next)=>signals.setModPanesSig(next)},"task.tokens":{what:"token map",parse:parseRowTokensPayload,same:sameRowTokenMap,read:(signals)=>signals.rowTokensAcc(),write:(signals,next)=>signals.setRowTokensSig(next)}};function handleMapChannel(name,payload,signals){let channel=MAP_CHANNELS[name];if(!channel)return!1;let next=channel.parse(payload);if(!next)return logClientError("orch",`dropped ${name} event: malformed ${channel.what} (${describePayload(payload)})`),!0;let current=channel.read(signals);if(current&&channel.same(current,next))return!0;return channel.write(signals,next),!0}function writeGraphicsToStdout(data){if(!process.stdout.isTTY)return;process.stdout.write(data)}function pruneEngineState(tasks,signals){let live=new Set(tasks.map((t)=>t.id)),current=signals.engineStateAcc();if(current.size>0){let next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setEngineStateSig(next)}let tabs=signals.engineTabStateAcc();if(tabs.size>0){let nextTabs=null;for(let key of tabs.keys()){if(live.has(key))continue;if(!nextTabs)nextTabs=new Map(tabs);nextTabs.delete(key)}if(nextTabs)signals.setEngineTabStateSig(nextTabs)}let lifecycle=signals.engineLifecycleAcc();if(lifecycle.size>0){let nextLifecycle=null;for(let key of lifecycle.keys()){if(live.has(key))continue;if(!nextLifecycle)nextLifecycle=new Map(lifecycle);nextLifecycle.delete(key)}if(nextLifecycle)signals.setEngineLifecycleSig(nextLifecycle)}}function pruneTaskJobs(tasks,signals){let current=signals.taskJobsAcc();if(current.size===0)return;let live=new Set(tasks.map((t)=>t.id)),next=null;for(let key of current.keys()){if(live.has(key))continue;if(!next)next=new Map(current);next.delete(key)}if(next)signals.setTaskJobsSig(next)}function handleOrchestratorEvent(name,payload,signals){if(name==="task.snapshot"){let value=payload?.tasks;if(Array.isArray(value))signals.setTasks(value.map(deserializeTask)),pruneEngineState(value,signals),pruneTaskJobs(value,signals);else logClientError("orch",`dropped task.snapshot event: tasks is not an array (got ${describePayload(value)})`);return}if(name==="daemon.stopping"){let p=payload;if(typeof p?.roveVersion==="string")signals.setDaemonVersionSig(p.roveVersion);if(parseDaemonStopReason(p?.reason)==="restart")signals.setDaemonRestartingSig(!0);return}if(name==="active-task"){let id=payload?.taskId;signals.setActiveTaskSig(typeof id==="string"?id:null);return}if(name==="update"){let info=payload?.info;signals.setUpdateSig(info??null);return}if(name==="engine-state"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.state!=="string"){logClientError("orch",`dropped engine-state event: taskId/state must be strings (taskId=${describePayload(p?.taskId)}, state=${describePayload(p?.state)})`);return}let tabId=typeof p.tabId==="string"&&p.tabId?p.tabId:void 0,entry={state:p.state,detail:p.detail,...typeof p.sessionId==="string"&&p.sessionId?{sessionId:p.sessionId}:{},...typeof p.transcriptPath==="string"&&p.transcriptPath?{transcriptPath:p.transcriptPath}:{},...tabId?{tabId}:{},at:typeof p.at==="number"?p.at:0},prevTaskState=signals.engineStateAcc().get(p.taskId)?.state;if(!tabId){let next=new Map(signals.engineStateAcc());if(p.state==="idle")next.delete(p.taskId);else next.set(p.taskId,entry);signals.setEngineStateSig(next)}if((p.state==="idle"||p.state==="turn_complete"||p.state==="error"||p.state==="running"&&prevTaskState!=="running")&&signals.engineLifecycleAcc().has(p.taskId)){let lifecycle=new Map(signals.engineLifecycleAcc());lifecycle.delete(p.taskId),signals.setEngineLifecycleSig(lifecycle)}if(tabId){let nextTabs=new Map(signals.engineTabStateAcc()),tabs=new Map(nextTabs.get(p.taskId)??[]);tabs.set(tabId,entry),nextTabs.set(p.taskId,tabs),signals.setEngineTabStateSig(nextTabs)}return}if(name==="attention.inbox"){let items=payload?.items;if(!Array.isArray(items)){logClientError("orch",`dropped attention.inbox event: items is not an array (${describePayload(items)})`);return}let kept=items.filter((item)=>{if(!item||typeof item!=="object"||Array.isArray(item))return!1;let p=item;return(typeof p.taskId==="string"||p.taskId===null&&isRoutineInboxState(p.state))&&(p.tabId===null||typeof p.tabId==="string")&&isAttentionInboxState(p.state)&&(p.unread===void 0||typeof p.unread==="boolean")&&typeof p.at==="number"});if(kept.length!==items.length)logClientError("orch",`dropped ${items.length-kept.length} malformed attention.inbox item(s) of ${items.length} (${describePayload(items)})`);if(kept.length===0&&items.length>0)return;signals.setAttentionInboxSig(kept.map((item)=>({...item,unread:item.unread!==!1})));return}if(name==="task.jobs"){let p=payload;if(typeof p?.taskId!=="string"||p.kind!=="ensureWorktree"){logClientError("orch",`dropped task.jobs event: expected string taskId + kind "ensureWorktree" (taskId=${describePayload(p?.taskId)}, kind=${describePayload(p?.kind)})`);return}let current=signals.taskJobsAcc();if(p.phase==="running"){let next=new Map(current);next.set(p.taskId,{kind:p.kind}),signals.setTaskJobsSig(next);return}if((p.phase==="done"||p.phase==="error")&¤t.has(p.taskId)){let next=new Map(current);next.delete(p.taskId),signals.setTaskJobsSig(next)}return}if(handleMapChannel(name,payload,signals))return;if(name==="tab.open"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.at!=="number"||typeof p.title!=="string"||!Array.isArray(p.argv)){logClientError("orch",`dropped tab.open event: malformed payload (${describePayload(payload)})`);return}signals.setTabOpenSig(p);return}if(name==="tab.close"){let p=payload;if(!(p&&"kind"in p&&p.kind==="terminal-tab"?typeof p.taskId==="string"&&typeof p.tabId==="string"&&typeof p.requestId==="string"&&typeof p.at==="number":typeof p?.taskId==="string"&&typeof p.at==="number"&&("title"in p)&&typeof p.title==="string")){logClientError("orch",`dropped tab.close event: malformed payload (${describePayload(payload)})`);return}signals.setTabCloseSig(p);return}if(name==="tab.rename"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.tabId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped tab.rename event: malformed payload (${describePayload(payload)})`);return}signals.setTabRenameSig(p);return}if(name==="tab.add"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.at!=="number"||!isAddedTab(p.tab)){logClientError("orch",`dropped tab.add event: malformed payload (${describePayload(payload)})`);return}signals.setTabAddSig({taskId:p.taskId,tab:p.tab,at:p.at});return}if(name==="ui.prompt"){let p=payload;if(typeof p?.promptId!=="string"||typeof p.title!=="string"||typeof p.at!=="number"){logClientError("orch",`dropped ui.prompt event: malformed payload (${describePayload(payload)})`);return}signals.setUiPromptSig(p);return}if(name==="engine.lifecycle"){let p=payload;if(typeof p?.taskId!=="string"||typeof p.kind!=="string"){logClientError("orch",`dropped engine.lifecycle event: malformed payload (${describePayload(payload)})`);return}let prev=signals.engineLifecycleAcc(),cur=prev.get(p.taskId)??{subagents:0},entry=p.kind==="subagent-start"?{subagents:cur.subagents+1}:p.kind==="subagent-stop"?{subagents:Math.max(0,cur.subagents-1)}:cur;if(entry===cur&&!prev.has(p.taskId))return;let map=new Map(prev);if(entry.subagents===0)map.delete(p.taskId);else map.set(p.taskId,entry);signals.setEngineLifecycleSig(map);return}if(name==="graphics.write"){let p=payload;if(typeof p?.data!=="string"||typeof p.imageId!=="number"||typeof p.at!=="number"){logClientError("orch",`dropped graphics.write event: malformed payload (${describePayload(payload)})`);return}signals.writeGraphics(Buffer.from(p.data,"base64"));return}if(name==="notice.event"){let p=payload;if(typeof p?.title!=="string"||typeof p.at!=="number"||typeof p.kind!=="string"){logClientError("orch",`dropped notice.event: malformed payload (${describePayload(payload)})`);return}signals.setNoticeSig(p);return}if(name==="ui-prefs"){let decoded=decodeUiPrefsPayload(payload);if(!decoded){let theme=payload?.theme;logClientError("orch",`dropped ui-prefs event: theme must be a string (got ${describePayload(theme)})`);return}signals.setUiPrefsSig(decoded);return}if(name==="keybindings"){let p=payload;if(typeof p?.rev!=="number"){logClientError("orch",`dropped keybindings event: rev must be a number (got ${describePayload(p?.rev)})`);return}signals.setKeybindingsRevSig(p.rev)}}function subscribeTasksOp(tasks,listener){try{listener(tasks())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw on subscribe:",err)}return tasks.subscribe(()=>{try{listener(tasks.get())}catch(err){console.error("[rove RemoteOrchestrator] task listener threw:",err)}})}async function createTaskOp(client,input){let{modelEffort,...rest}=input,res=await client.request("task.create",{...rest,effort:modelEffort});return deserializeTask(res.task)}async function ensureMainTaskOp(client,repo){let res=await client.request("task.ensureMain",{repo});return deserializeTask(res.task)}async function openDirectoryTaskOp(client,input){let res=await client.request("task.openDir",input);return deserializeTask(res.task)}async function adoptScratchRepoOp(client,id,repo){await client.request("task.adoptScratchRepo",{taskId:String(id),repo})}async function ensureWorktreeOp(client,id){return(await client.request("task.ensureWorktree",{taskId:String(id)})).worktreePath}async function forgetProjectOp(client,repo){await client.request("project.forget",{repo})}function reportEngineInterruptOp(client,taskId,tabId){client.request("engine.reportEvent",{kind:"turn-interrupted",taskId,tabId}).catch(()=>{})}async function setTitleOp(client,id,title){await client.request("task.rename",{taskId:String(id),title})}async function setBranchOp(client,id,branch){await client.request("task.setBranch",{taskId:String(id),branch})}async function setVendorOp(client,id,vendor,effort,model){await client.request("task.setVendor",{taskId:String(id),vendor,...effort!==void 0?{effort}:{},...model!==void 0?{model}:{}})}async function setCommandOp(client,id,command,vendor){await client.request("task.setCommand",{taskId:String(id),command,...vendor?{vendor}:{}})}async function setPinnedOp(client,id,pinned){await client.request("task.pin",{taskId:String(id),pinned})}async function moveTaskOp(client,id,delta){await client.request("task.move",{taskId:String(id),direction:delta<0?"up":"down"})}async function moveTaskToTopOp(client,id){await client.request("task.move",{taskId:String(id),direction:"top"})}async function setPromptOp(client,id,prompt){await client.request("task.setPrompt",{taskId:String(id),prompt})}async function setStatusOp(client,id,status){await client.request("task.status",{taskId:String(id),status})}async function deleteTaskOp(client,id,opts){await client.request("task.delete",{taskId:String(id),force:opts?.force,deleteBranch:opts?.deleteBranch})}async function dismissAttentionOp(client,taskId,tabId,at,deliveryId){return(await client.request("attention.dismiss",{taskId:String(taskId),...tabId!==null?{tabId}:{},at,...deliveryId!==void 0?{deliveryId}:{}})).deleted}async function dismissRoutineAttentionOp(client,automationId){return(await client.request("attention.dismissRoutine",{automationId})).deleted}async function answerGateOp(client,gateId,answer){return{delivered:(await client.request("gate.answer",{gateId,...answer,by:"tui"})).delivered}}async function withdrawGateOp(client,gateId){await client.request("gate.withdraw",{gateId})}async function markAttentionReadOp(client,taskId,tabId,at){return(await client.request("attention.read",{taskId:String(taskId),...tabId!==null?{tabId}:{},at})).updated}async function landPreflightOp(client,id){return(await client.request("task.landPreflight",{taskId:String(id)})).result}async function landTaskOp(client,id,opts){return(await client.request("task.land",{taskId:String(id),strategy:opts?.strategy,deleteBranch:opts?.deleteBranch,removeWorktree:opts?.removeWorktree,callerCwd:opts?.callerCwd})).result}async function discoverAdoptableWorktreesOp(client,repo){return(await client.request("worktree.discoverAdoptable",{repo})).worktrees}async function adoptWorktreeOp(client,input){let res=await client.request("worktree.adopt",input);return deserializeTask(res.task)}async function listWorktreesOp(client,opts){return(await client.request("worktree.list",{network:opts?.network!==!1})).projects}async function removeWorktreeOp(client,path,force){return(await client.request("worktree.remove",{path,force})).residue??null}async function syncBaseOp(client,taskId){return(await client.request("task.syncBase",{taskId})).result}async function failingChecksOp(client,taskId){let res=await client.request("pr.failingChecks",{taskId});return{checks:res.checks??[],totalFailing:res.totalFailing??0,...res.unavailable?{unavailable:res.unavailable}:{}}}async function rerunFailedChecksOp(client,taskId){let res=await client.request("pr.rerunFailedChecks",{taskId});return{rerunRuns:res.rerunRuns??0,external:res.external??0,...res.refused?{refused:res.refused}:{},...res.unavailable?{unavailable:res.unavailable}:{}}}async function listIssuesOp(client,repoRoot){return client.request("issue.list",{repoRoot})}async function listIssueReposOp(client){return(await client.request("issue.repos",{})).repos??[]}async function listFieldNotesOp(client,repo){return(await client.request("note.list",{repo})).notes??[]}async function deleteFieldNoteOp(client,repo,id){return(await client.request("note.delete",{repo,id})).deleted===!0}async function mutateIssueOp(client,repoRoot,op){return client.request("issue.mutate",{repoRoot,op})}async function listAutomationsOp(client){return client.request("automation.list",{})}async function createAutomationOp(client,input){return client.request("automation.create",input)}async function automationRunsOp(client,id){return client.request("automation.runs",{id})}async function setAutomationEnabledOp(client,id,enabled){return client.request("automation.update",{id,enabled})}async function runAutomationNowOp(client,id){return client.request("automation.runNow",{id})}async function deleteAutomationOp(client,id){return client.request("automation.delete",{id})}async function listWorkItemsOp(client,args){return client.request("workitem.list",args)}async function startWorkItemOp(client,args){return client.request("workitem.start",args)}async function setActiveTaskOp(client,id){await client.request("task.setActive",{taskId:id===null?null:String(id)})}function replyTabCloseOp(client,requestId,closed){client.request("terminalTab.closeReply",{requestId,closed}).catch(()=>{})}function replyPromptOp(client,promptId,value){client.request("ui.promptReply",{promptId,...value!==void 0?{value}:{}}).catch(()=>{})}function reportUiEventOp(client,kind,taskId,detail){client.request("ui.reportEvent",{kind,...taskId?{taskId}:{},...detail?{detail}:{}}).catch(()=>{})}function recentTaskEventsOp(client,id){return client.request("task.recentEvents",{taskId:String(id)})}class RemoteOrchestrator{client;tasksAcc=createStateCell([],"orchestrator.tasks");activeTaskAcc=createStateCell(null,"orchestrator.active-task");updateAcc=createStateCell(null);daemonVersionAcc=createStateCell(null);daemonRestartingAcc=createStateCell(!1);daemonStaleAcc=mapReadableState(this.daemonVersionAcc,(version)=>isDaemonVersionStale(version??void 0,CURRENT_VERSION));engineStateAcc=createStateCell(new Map);engineTabStateAcc=createStateCell(new Map);attentionInboxAcc=createStateCell([]);taskJobsAcc=createStateCell(new Map);rowTokensAcc=createStateCell(new Map);modPanesAcc=createStateCell([]);worktreeChangesAcc=createStateCell(null);usageSnapshotAcc=createStateCell(null);contextUsageAcc=createStateCell(null);transcriptActivityAcc=createStateCell(null);noticeAcc=createStateCell(null);tabOpenAcc=createStateCell(null);tabCloseAcc=createStateCell(null);tabRenameAcc=createStateCell(null);tabAddAcc=createStateCell(null);uiPromptAcc=createStateCell(null);engineLifecycleAcc=createStateCell(new Map);uiPrefsAcc=createStateCell(null);keybindingsRevAcc=createStateCell(null);connectionStateAcc=createStateCell("online","orchestrator.connection");staleInstallAcc=createStateCell(null);ensureReachable;role;cellPixelSize;channels;subscribesTasks;expectForeignHome;onPeerIdentity;reconnectTask=null;signals;constructor(client,options={}){this.client=client;this.ensureReachable=options.ensureReachable??ensureDaemonReachable,this.role=options.role??"pane",this.cellPixelSize=options.cellPixelSize??null,this.channels=options.channels,this.subscribesTasks=!options.channels||options.channels.includes("task.snapshot"),this.expectForeignHome=options.expectForeignHome===!0,this.onPeerIdentity=options.onPeerIdentity,this.signals={writeGraphics:options.graphicsOut??(this.role==="gui"?writeGraphicsToStdout:()=>{}),tasksAcc:this.tasksAcc,setTasks:this.tasksAcc.set,setActiveTaskSig:this.activeTaskAcc.set,setUpdateSig:this.updateAcc.set,setDaemonVersionSig:this.daemonVersionAcc.set,setDaemonRestartingSig:this.daemonRestartingAcc.set,engineStateAcc:this.engineStateAcc,setEngineStateSig:this.engineStateAcc.set,engineTabStateAcc:this.engineTabStateAcc,setEngineTabStateSig:this.engineTabStateAcc.set,setAttentionInboxSig:this.attentionInboxAcc.set,taskJobsAcc:this.taskJobsAcc,setTaskJobsSig:this.taskJobsAcc.set,rowTokensAcc:this.rowTokensAcc,setRowTokensSig:this.rowTokensAcc.set,modPanesAcc:this.modPanesAcc,setModPanesSig:this.modPanesAcc.set,worktreeChangesAcc:this.worktreeChangesAcc,setWorktreeChangesSig:this.worktreeChangesAcc.set,usageSnapshotAcc:this.usageSnapshotAcc,setUsageSnapshotSig:this.usageSnapshotAcc.set,contextUsageAcc:this.contextUsageAcc,setContextUsageSig:this.contextUsageAcc.set,transcriptActivityAcc:this.transcriptActivityAcc,setTranscriptActivitySig:this.transcriptActivityAcc.set,setNoticeSig:this.noticeAcc.set,setTabOpenSig:this.tabOpenAcc.set,setTabCloseSig:this.tabCloseAcc.set,setTabRenameSig:this.tabRenameAcc.set,setTabAddSig:this.tabAddAcc.set,setUiPromptSig:this.uiPromptAcc.set,engineLifecycleAcc:this.engineLifecycleAcc,setEngineLifecycleSig:this.engineLifecycleAcc.set,setUiPrefsSig:this.uiPrefsAcc.set,setKeybindingsRevSig:this.keybindingsRevAcc.set,setConnectionState:this.connectionStateAcc.set},this.client.on("*",(frame)=>handleOrchestratorEvent(frame.name,frame.payload,this.signals)),this.client.onLifecycle("close",()=>{this.connectionStateAcc.set("disconnected");let spawnDaemon=this.role==="gui";logClient("orch",spawnDaemon?"daemon socket closed \u2014 starting silent spawning reconnect loop":"daemon socket closed \u2014 starting non-spawning reconnect loop"),this.reconnectLoop(spawnDaemon)})}reconnectLoop(spawnDaemon){if(this.reconnectTask)return this.reconnectTask;let task=runReconnectLoop({isDisposed:()=>this.client.isDisposed,spawnDaemon,ensureReachable:this.ensureReachable,init:()=>this.init(),shouldLogAttempt:shouldLogReconnectAttempt,onFatal:(err)=>this.staleInstallAcc.set(err instanceof Error?err.message:String(err))});this.reconnectTask=task;let clear=()=>{if(this.reconnectTask===task)this.reconnectTask=null};return task.then(clear,clear),task}writeGraphics(data){this.signals.writeGraphics(data)}async init(){await performInit(this.client,{role:this.role,cellPixelSize:this.cellPixelSize,channels:this.channels,subscribesTasks:this.subscribesTasks,expectForeignHome:this.expectForeignHome,onPeerIdentity:this.onPeerIdentity},this.signals)}connectionStateSignal(){return this.connectionStateAcc}staleInstallSignal(){return this.staleInstallAcc}async manualReconnect(){this.client.forceDisconnect(),await this.reconnectLoop(!0)}dispose(){this.client.close()}tasksSignal=()=>this.tasksAcc;activeTaskSignal=()=>this.activeTaskAcc;updateSignal=()=>this.updateAcc;daemonVersionSignal=()=>this.daemonVersionAcc;daemonStaleSignal=()=>this.daemonStaleAcc;daemonRestartingSignal=()=>this.daemonRestartingAcc;async restartDaemon(){await this.client.request("daemon.stop",{reason:"restart"}).catch(()=>{})}engineStateSignal=()=>this.engineStateAcc;engineTabStatesSignal=()=>this.engineTabStateAcc;attentionInboxSignal=()=>this.attentionInboxAcc;taskJobsSignal=()=>this.taskJobsAcc;rowTokensSignal=()=>this.rowTokensAcc;modPanesSignal=()=>this.modPanesAcc;pressMod=(plugin,pane,key)=>this.client.request("mod.press",{plugin,pane,key});submitMod=(plugin,pane,key,value)=>this.client.request("mod.submit",{plugin,pane,key,value});worktreeChangesSignal=()=>this.worktreeChangesAcc;usageSnapshotSignal=()=>this.usageSnapshotAcc;contextUsageSignal=()=>this.contextUsageAcc;transcriptActivitySignal=()=>this.transcriptActivityAcc;transcriptActivityStore=()=>this.transcriptActivityAcc;noticeStore=()=>this.noticeAcc;tabOpenStore=()=>this.tabOpenAcc;tabCloseStore=()=>this.tabCloseAcc;tabRenameStore=()=>this.tabRenameAcc;tabAddStore=()=>this.tabAddAcc;rpc={request:(name,payload)=>this.client.request(name,payload)};replyTerminalTabClose=(requestId,closed)=>replyTabCloseOp(this.client,requestId,closed);uiPromptStore=()=>this.uiPromptAcc;replyPrompt=(promptId,value)=>replyPromptOp(this.client,promptId,value);engineLifecycleSignal=()=>this.engineLifecycleAcc;recentTaskEvents(id){return recentTaskEventsOp(this.client,id)}reportUiEvent=(kind,taskId,detail)=>reportUiEventOp(this.client,kind,taskId,detail);reportScreenInput=async(taskId,tabId,blocked)=>{await this.client.request("engine.reportEvent",{source:"screen",taskId,tabId,blocked})};reportEngineInterrupt=(taskId,tabId)=>reportEngineInterruptOp(this.client,String(taskId),tabId);uiPrefsSignal=()=>this.uiPrefsAcc;uiPrefsStore=()=>this.uiPrefsAcc;keybindingsRevSignal=()=>this.keybindingsRevAcc;keybindingsRevStore=()=>this.keybindingsRevAcc;listTasks=()=>this.tasksAcc();getTask=(id)=>this.tasksAcc().find((task)=>task.id===id);subscribeTasks(listener){return subscribeTasksOp(this.tasksAcc,listener)}createTask=(input)=>createTaskOp(this.client,input);ensureMainTask=(repo)=>ensureMainTaskOp(this.client,repo);openDirectoryTask=(input)=>openDirectoryTaskOp(this.client,input);adoptScratchRepo=(id,repo)=>adoptScratchRepoOp(this.client,id,repo);ensureWorktree=(id)=>ensureWorktreeOp(this.client,id);forgetProject=(repo)=>forgetProjectOp(this.client,repo);setTitle=(id,title)=>setTitleOp(this.client,id,title);setBranch=(id,branch)=>setBranchOp(this.client,id,branch);setVendor=(id,vendor,effort,model)=>setVendorOp(this.client,id,vendor,effort,model);setCommand=(id,command,vendor)=>setCommandOp(this.client,id,command,vendor);setPinned=(id,pinned)=>setPinnedOp(this.client,id,pinned);moveTask=(id,delta)=>moveTaskOp(this.client,id,delta);moveTaskToTop=(id)=>moveTaskToTopOp(this.client,id);setStatus=(id,status)=>setStatusOp(this.client,id,status);setPrompt=(id,prompt)=>setPromptOp(this.client,id,prompt);deleteTask=(id,opts)=>deleteTaskOp(this.client,id,opts);dismissAttention=(taskId,tabId,at,deliveryId)=>dismissAttentionOp(this.client,taskId,tabId,at,deliveryId);dismissRoutineAttention=(automationId)=>dismissRoutineAttentionOp(this.client,automationId);markAttentionRead=(taskId,tabId,at)=>markAttentionReadOp(this.client,taskId,tabId,at);answerGate=(gateId,answer)=>answerGateOp(this.client,gateId,answer);withdrawGate=(gateId)=>withdrawGateOp(this.client,gateId);landPreflight(id){return landPreflightOp(this.client,id)}landTask(id,opts){return landTaskOp(this.client,id,opts)}discoverAdoptableWorktrees(repo){return discoverAdoptableWorktreesOp(this.client,repo)}adoptWorktree(input){return adoptWorktreeOp(this.client,input)}listWorktrees(opts){return listWorktreesOp(this.client,opts)}listIssues(repoRoot){return listIssuesOp(this.client,repoRoot)}listIssueRepos(){return listIssueReposOp(this.client)}mutateIssue(repoRoot,op){return mutateIssueOp(this.client,repoRoot,op)}listAutomations=()=>listAutomationsOp(this.client);createAutomation=(i)=>createAutomationOp(this.client,i);automationRuns=(id)=>automationRunsOp(this.client,id);setAutomationEnabled=(id,on)=>setAutomationEnabledOp(this.client,id,on);runAutomationNow=(id)=>runAutomationNowOp(this.client,id);deleteAutomation=(id)=>deleteAutomationOp(this.client,id);listWorkItems=(a)=>listWorkItemsOp(this.client,a);listFieldNotes=(repo)=>listFieldNotesOp(this.client,repo);deleteFieldNote=(repo,id)=>deleteFieldNoteOp(this.client,repo,id);failingChecks=(taskId)=>failingChecksOp(this.client,taskId);rerunFailedChecks=(taskId)=>rerunFailedChecksOp(this.client,taskId);syncBase=(taskId)=>syncBaseOp(this.client,taskId);startWorkItem=(a)=>startWorkItemOp(this.client,a);removeWorktree(path,force){return removeWorktreeOp(this.client,path,force)}setActiveTask(id){return setActiveTaskOp(this.client,id)}}
|
|
3
|
+
export{liveRowTokens,adoptTabs,absorbTab,RemoteOrchestrator};
|
|
@@ -6,6 +6,6 @@ ${EXPORT_USAGE}
|
|
|
6
6
|
`),process.exit(2)}function parseFormat(args){let format="json";for(let i=0;i<args.length;i++){let a=args[i];if(a==="--json")format="json";else if(a==="--csv")format="csv";else if(a==="--format"){let v=args[++i];if(v===void 0)usageError("--format requires a value (json, csv, or table)");format=coerceFormat(v)}else if(a.startsWith("--format="))format=coerceFormat(a.slice(9));else usageError(`unexpected argument "${a}"`)}return format}function coerceFormat(value){if(value==="json"||value==="csv"||value==="table")return value;usageError(`unknown format "${value}" (expected json, csv, or table)`)}function csvCell(value){if(/[",\r\n]/.test(value))return`"${value.replace(/"/g,'""')}"`;return value}function renderCsv(rows){let lines=[COLUMNS.join(",")];for(let row of rows)lines.push(COLUMNS.map((c)=>csvCell(row[c])).join(","));return lines.join(`
|
|
7
7
|
`)}function padCell(cell,width){return cell+" ".repeat(Math.max(0,width-displayWidth(cell)))}function renderTable(rows){let widths={};for(let c of COLUMNS)widths[c]=Math.max(displayWidth(c),...rows.map((r)=>displayWidth(r[c])));let line=(cells)=>COLUMNS.map((c)=>padCell(cells[c],widths[c])).join(" ").trimEnd(),header={};for(let c of COLUMNS)header[c]=c;return[line(header),...rows.map(line)].join(`
|
|
8
8
|
`)}function renderExport(tasks,format){let rows=tasks.map(toRow);if(format==="json")return JSON.stringify(rows,null,2);if(format==="csv")return renderCsv(rows);return renderTable(rows)}async function runExportSubcommand(args){if(args.includes("--help")||args.includes("-h")||args.includes("help")){process.stdout.write(`${EXPORT_USAGE}
|
|
9
|
-
`);return}let format=parseFormat(args),{TaskIndexStore}=await import("./chunk-
|
|
9
|
+
`);return}let format=parseFormat(args),{TaskIndexStore}=await import("./chunk-v8s0s21v.js"),store=new TaskIndexStore;await store.load();let tasks=store.list();if(tasks.length===0&&format==="table"){process.stdout.write(`no tasks
|
|
10
10
|
`);return}process.stdout.write(`${renderExport(tasks,format)}
|
|
11
11
|
`)}export{runExportSubcommand,renderExport};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{defaultDaemonLogPath,defaultPtyHostLogPath}from"./chunk-
|
|
2
|
+
import{defaultDaemonLogPath,defaultPtyHostLogPath}from"./chunk-z7zm8h1q.js";import"./chunk-b39sdtt0.js";import"./chunk-nc46gddg.js";import"./chunk-91sykzqq.js";import{mkdirSync,readFileSync,writeFileSync}from"fs";import{dirname,join}from"path";var REPORT_ENV_SUFFIXES=["HOME_DIR","DAEMON_SOCKET_PATH","SOCKET_PATH","PTY_SOCKET_PATH","PTY_PORT","WEB_HOST","BIN_PATH","DEV","DEBUG","TERMINAL_BACKEND","TASK_ID","TAB_ID"],REPORT_ENV_KEYS=["SHELL","TERM","TERM_PROGRAM","TERM_PROGRAM_VERSION","COLORTERM","VISUAL","EDITOR",...REPORT_ENV_SUFFIXES.flatMap((suffix)=>[`ROVE_${suffix}`,`ROVE_${suffix}`]),"ROVE_INVOKED_AS"],LOG_TAIL_LINES=200;function logTail(path,count){try{return readFileSync(path,"utf8").split(`
|
|
3
3
|
`).filter((line)=>line.trim().length>0).slice(-count).join(`
|
|
4
4
|
`)}catch{return""}}function reportEnvLines(env){let shown=new Set(REPORT_ENV_KEYS),keys=new Set(shown);for(let key of Object.keys(env))if(key.startsWith("ROVE_")||key.startsWith("ROVE_"))keys.add(key);return[...keys].sort().map((key)=>{let value=env[key];if(value===void 0)return`${key}=(unset)`;return shown.has(key)?`${key}=${value}`:`${key}=(set)`})}function buildReportBundle(doctorLines,parts){return["# Rove doctor report",`generated: ${parts.generatedAt}`,"","## diagnosis",...doctorLines,"","## environment",...reportEnvLines(parts.env),"",`## daemon.log (last ${LOG_TAIL_LINES} lines)`,parts.daemonLog||"(empty or absent)","",`## pty.log (last ${LOG_TAIL_LINES} lines)`,parts.ptyLog||"(empty or absent)",""].join(`
|
|
5
5
|
`)}function writeReportBundle(doctorLines){let dir=dirname(defaultDaemonLogPath());mkdirSync(dir,{recursive:!0});let path=join(dir,"rove-doctor-report.txt");return writeFileSync(path,buildReportBundle(doctorLines,{generatedAt:new Date().toISOString(),env:process.env,daemonLog:logTail(defaultDaemonLogPath(),LOG_TAIL_LINES),ptyLog:logTail(defaultPtyHostLogPath(),LOG_TAIL_LINES)})),path}export{writeReportBundle,reportEnvLines,buildReportBundle};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,runVerb,successEnvelope,toApiError}from"./chunk-
|
|
2
|
+
import{booleanFlagsOf,callVerb,errorBody,errorEnvelope,repeatableFlagsOf,runVerb,successEnvelope,toApiError}from"./chunk-bq0xsdqx.js";import{VerbArgs,apiUsage,findVerb,parseFlags,takeIdentityWarning,unknownVerbError,validateAgainstSpec,verbHelp}from"./chunk-rpm771v5.js";import{ensurePluginEnginesLoaded}from"./chunk-c3d36ryd.js";import{openDaemonSession}from"./chunk-hqzgejfj.js";import{LOCAL_MACHINE,forwardVerb,requireMachine,routeTarget}from"./chunk-qc06psqb.js";import{ApiError}from"./chunk-x7r75e3p.js";import{argvHasFlag}from"./chunk-zsfyj36g.js";import{errorMessage}from"./chunk-2brn8e1y.js";import{ROVE_API_VERSION}from"./chunk-278sc87n.js";function takeMachineFlag(argv){let rest=[],machine;for(let i=0;i<argv.length;i++){let arg=argv[i];if(arg==="--machine")machine=argv[i+1],i+=1;else if(arg.startsWith("--machine="))machine=arg.slice(10);else rest.push(arg)}return{machine:machine||void 0,rest}}function forwardParams(verb,flags){if(!flags.has("prompt-file")||!verb.flags.some((f)=>f.name==="prompt"))return Object.fromEntries(flags);let text=new VerbArgs(verb,flags).promptText(),params=Object.fromEntries([...flags].filter(([name])=>name!=="prompt-file"));return text===void 0?params:{...params,prompt:text}}var envelopeMode=!1;function writeJson(value,pretty,stream=process.stdout){stream.write(`${pretty?JSON.stringify(value,null,2):JSON.stringify(value)}
|
|
3
3
|
`)}function emit(value,pretty){let warning=takeIdentityWarning(),payload=warning&&value&&typeof value==="object"&&!Array.isArray(value)?{...value,identityWarning:warning}:value;writeJson(envelopeMode?successEnvelope(payload):payload,pretty)}function fail(message,code,exitCode=1,data){let error=errorBody(new ApiError(message,code,data));if(envelopeMode)writeJson({apiVersion:ROVE_API_VERSION,ok:!1,error},!1);else writeJson({error},!1,process.stderr);process.exit(exitCode)}var USAGE_ERROR_CODES=new Set(["BAD_VERB","UNKNOWN_VERB","BAD_FLAG","MISSING_FLAG","MISSING_VERB","BAD_DAEMON","UNKNOWN_MACHINE"]);async function invokeVerb(verbName,argv,deps){return runVerb(verbName,{argv},deps)}async function runApiSubcommand(argv){let[verbName,...withMachine]=argv,{machine,rest}=takeMachineFlag(withMachine);if(envelopeMode=argvHasFlag(rest,"--envelope"),!verbName||verbName==="--help"||verbName==="-h"||verbName==="help"){if(!verbName)fail(apiUsage(),"MISSING_VERB",2);process.stdout.write(`${apiUsage()}
|
|
4
4
|
`);return}ensurePluginEnginesLoaded();let verb=findVerb(verbName);if(!verb){let err=unknownVerbError(verbName);fail(`${err.message}
|
|
5
|
-
${apiUsage()}`,err.code,2,err.data)}let parsed;try{parsed=parseFlags(rest,booleanFlagsOf(verb))}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data);fail(errorMessage(err),"BAD_FLAG",2)}if(parsed.help){process.stdout.write(`${verbHelp(verb)}
|
|
5
|
+
${apiUsage()}`,err.code,2,err.data)}let parsed;try{parsed=parseFlags(rest,booleanFlagsOf(verb),repeatableFlagsOf(verb))}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data);fail(errorMessage(err),"BAD_FLAG",2)}if(parsed.help){process.stdout.write(`${verbHelp(verb)}
|
|
6
6
|
`);return}try{validateAgainstSpec(verb,parsed.flags)}catch(err){if(err instanceof ApiError)fail(err.message,err.code,2,err.data);fail(errorMessage(err),"BAD_FLAG",2)}if(machine!==void 0&&machine!==LOCAL_MACHINE){await runForwarded(verb,parsed,async()=>requireMachine(machine));return}let session=null;if(!verb.offline)try{session=await openDaemonSession()}catch(err){fail(`could not reach or start the Rove daemon: ${errorMessage(err)}`,"BAD_DAEMON",2,{hint:"check whether the daemon is up (and why it is not), then retry the same command",nextCommandArgs:["daemon","status"]})}let taskId=machine===LOCAL_MACHINE?void 0:parsed.flags.get("task-id"),client=session?.client??null,target=taskId&&client?await machineHolding(taskId,client):null;if(target){session?.close(),await runForwarded(verb,parsed,async()=>target);return}try{let result=await callVerb(verb,parsed.flags,{client:session?.client??null});emit(result,parsed.pretty)}catch(err){if(err instanceof ApiError&&err.code==="PARTIAL_FANOUT"){if(envelopeMode)writeJson(errorEnvelope(err),parsed.pretty);else emit(err.data,parsed.pretty);session?.close(),process.exit(3)}let apiErr=toApiError(err);fail(apiErr.message,apiErr.code,USAGE_ERROR_CODES.has(apiErr.code)?2:1,apiErr.data)}finally{session?.close()}}async function machineHolding(taskId,client){try{return await routeTarget({taskId,isLocalTask:async(id)=>{try{return await client.request("task.get",{taskId:id}),!0}catch{return!1}}})}catch(err){let apiErr=toApiError(err);fail(apiErr.message,apiErr.code,1,apiErr.data)}}async function runForwarded(verb,parsed,resolve){let envelope;try{let entry=await resolve();envelope=await forwardVerb(entry,verb.name,forwardParams(verb,parsed.flags))}catch(err){let apiErr=toApiError(err);fail(apiErr.message,apiErr.code,USAGE_ERROR_CODES.has(apiErr.code)?2:1,apiErr.data)}if(envelope.ok){emit(envelope.result,parsed.pretty);return}let{message,code,...data}=envelope.error;if(code==="PARTIAL_FANOUT"){if(envelopeMode)writeJson(envelope,parsed.pretty);else emit(data,parsed.pretty);process.exit(3)}fail(message,code,USAGE_ERROR_CODES.has(code)?2:1,data)}export{invokeVerb,runApiSubcommand};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{closeTab,engineTabArgv,initialTabs,setTabTitle,tabPtyKeyFor,terminalTabsKey}from"./chunk-namxa4wy.js";import{awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,enginePresence,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,initMarkerSaysFinished,isHostedTaskKey,killHostedSessions,listHostedSessions,listHostedSessionsOrNull,openHostedSessionHost,pastePromptWhenEngineUp,readPersistedTerminalDefaultColors,sessionArgvNamesEngine}from"./chunk-952aedqm.js";import{engineLaunchArgv}from"./chunk-cbd6y9at.js";import{engineProcessIn,parsePsSnapshot,psSnapshot,vendorFromArgv}from"./chunk-24dryfqb.js";import{ApiError}from"./chunk-568q390y.js";import{loadStateFile,patchStateFile,updateStateFile}from"./chunk-zk5qkkb1.js";import{basename}from"path";function wireNode(node){if(node.kind==="leaf")return{kind:"leaf",id:node.id,title:node.title??null,own:node.content===null};return{kind:"group",orientation:node.orientation,children:node.children.map(wireNode)}}function wireSplit(tree){return tree?{root:wireNode(tree.root),activeLeafId:tree.activeLeafId}:null}function taskEngineArgv(task){return engineLaunchArgv({command:task.command,vendor:task.vendor})}function readTabsSnapshot(taskId){try{let snap=loadStateFile()[terminalTabsKey(taskId)];return snap&&Array.isArray(snap.tabs)?snap:void 0}catch{return}}function closeTabsSnapshot(taskId,tabId){let closing,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(closing=state.tabs.find((tab)=>tab.id===tabId),!closing)return!1;let{state:next,closedId}=closeTab(state,tabId,{allowEmpty:!0});if(!closedId)return closing=void 0,!1;store[key]=next;return}),closing}function renameTabsSnapshot(taskId,tabId,title){let found=!1,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(!state.tabs.some((tab)=>tab.id===tabId))return!1;found=!0;let next=setTabTitle(state,tabId,title);if(next===state)return!1;store[key]=next;return}),found}var aliveKeysOf=(sessions)=>new Set(sessions.filter((s)=>s.alive).map((s)=>s.key));function unregisteredTabIds(snapshot,taskId,sessions){let known=new Set((snapshot?.tabs??[]).map((t)=>t.id)),prefix=`${taskId}::`,out=[];for(let s of sessions){if(!s.alive||!s.key.startsWith(prefix))continue;let tabId=s.key.slice(prefix.length);if(tabId.includes("::"))continue;if(!known.has(tabId)&&!out.includes(tabId))out.push(tabId)}return out}var abnormalExit=(exit)=>exit&&(exit.code!==0||exit.signal!==null)?exit:null;function joinTaskTabs(snapshot,taskId,sessions,persistedExits={},liveVendors,engineAlive){let unknown=sessions===null,rows0=sessions??[],alive=aliveKeysOf(rows0),sessionExits=new Map(rows0.map((s)=>[s.key,s.exit])),deadExit=(key)=>{let ex=abnormalExit(sessionExits.get(key)??persistedExits[key]);if(!ex)return null;let record=persistedExits[key],sameDeath=record?.at===ex.at,tail=sameDeath?record?.tail:void 0,code=ex.code??(sameDeath?record?.code??null:null),layer=record?.layer??"pty";return{code,signal:ex.signal,at:ex.at,layer,...tail&&tail.length>0?{tail}:{}}},engineExit=(key)=>{let record=persistedExits[`${key}#engine`];if(!record)return null;let{code,signal,at,tail,atApproximate}=record;return{code,signal,at,layer:"engine",...atApproximate?{atApproximate}:{},...tail&&tail.length>0?{tail}:{}}},rows=(snapshot?.tabs??[]).map((t)=>{let key=tabPtyKeyFor(taskId,t),isAlive=unknown?null:alive.has(key),walked=isAlive===!0&&liveVendors?.has(key)===!0?liveVendors.get(key)??null:void 0,engineIsAlive=engineAliveOf(key,isAlive,engineAlive);return{id:t.id,kind:t.kind,title:t.title??null,vendor:t.vendor??null,liveVendor:walked!==void 0?walked:t.liveVendor??null,lastTitle:t.lastTitle??null,autoTitle:t.autoTitle??null,alive:isAlive,engineAlive:engineIsAlive,exit:isAlive===!1?deadExit(key):engineIsAlive===!1?engineExit(key):null,...t.splitTree?{split:wireSplit(t.splitTree)}:{},...t.kind==="engine"&&t.ptyTask?{viewOf:t.ptyTask.id}:{}}});for(let tabId of unregisteredTabIds(snapshot,taskId,rows0))rows.push({id:tabId,kind:"engine",title:null,vendor:null,liveVendor:null,lastTitle:null,autoTitle:null,alive:!0,engineAlive:engineAliveOf(`${taskId}::${tabId}`,!0,engineAlive),exit:null,unregistered:!0});return rows}function engineAliveOf(key,isAlive,engineAlive){if(isAlive===null)return null;if(!isAlive)return!1;return engineAlive?.has(key)===!0?engineAlive.get(key)??null:null}function publishCliTabSnapshot(taskId,sessionId){if(!taskId)return;try{let key=terminalTabsKey(taskId);if(loadStateFile()[key]!==void 0)return;let seeded=initialTabs();patchStateFile({[key]:sessionId?{...seeded,tabs:seeded.tabs.map((t)=>t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}:seeded})}catch{}}function markCliTabSession(taskId,tabId,sessionId){try{let key=terminalTabsKey(taskId);updateStateFile((store)=>{let existing=store[key];if(!existing||!Array.isArray(existing.tabs))return!1;store[key]={...existing,tabs:existing.tabs.map((t)=>t.id===tabId&&t.kind==="engine"?{...t,...sessionId?{sessionId}:{},spawned:!0}:t)};return})}catch{}}function allocateTab(taskId,build,taken=new Set){let key=terminalTabsKey(taskId),out={};if(updateStateFile((store)=>{let existing=store[key],state=existing&&Array.isArray(existing.tabs)&&existing.tabs.length>0?existing:initialTabs(),ordinal=typeof state.nextOrdinal==="number"&&state.nextOrdinal>1?state.nextOrdinal:2;while(taken.has(`tab-${ordinal}`)||state.tabs.some((t)=>t.id===`tab-${ordinal}`))ordinal++;let tab=build(`tab-${ordinal}`,ordinal);out.tab=tab,store[key]={...state,tabs:[...state.tabs,tab],activeId:tab.id,nextOrdinal:ordinal+1};return}),!out.tab)throw Error(`tab allocation for ${taskId} did not run`);return out.tab}function mintCliTab(taskId,vendor,command){try{return allocateTab(taskId,(id,ordinal)=>({kind:"engine",id,title:null,ordinal,...vendor?{vendor}:{},...command?{engineCommand:command}:{}})).id}catch{return`tab-cli-${Date.now().toString(36)}`}}async function countLiveEngineSessions(sessions,snapshot=psSnapshot){let tabs=sessions.filter((s)=>s.alive&&s.key.split("::").length===2);if(!tabs.length)return 0;let rows;try{if(rows=parsePsSnapshot(await snapshot(tabs.flatMap((s)=>s.pid?[s.pid]:[]))),!rows.length)return tabs.length}catch{return tabs.length}return tabs.filter((s)=>{if(!s.pid)return!0;let root=rows.find((row)=>row.pid===s.pid);if(!root)return!0;if(engineProcessIn(rows,s.pid)||vendorFromArgv(root.args))return!0;let[taskId,tabId]=s.key.split("::"),labelled=readTabsSnapshot(taskId)?.tabs.some((tab)=>tab.id===tabId&&tab.kind==="engine");if(tabId!=="tab-1"&&!labelled&&!sessionArgvNamesEngine(s.command))return!1;let executable=basename(root.args.split(/\s+/)[0]).toLowerCase().replace(/^-/,"").replace(/\.exe$/,"");if(["sh","bash","zsh","fish","dash","ash","ksh","mksh"].includes(executable))return/^\S+\s+-[a-zA-Z]*c\b/.test(root.args);return!0}).length}async function openAdmittedEngine(rpc,spec,opts){let limit=opts.maxLiveEngines;if(limit===void 0)return rpc.request("pty.open",spec);for(let attempt=0;attempt<20;attempt++){let{sessions,admissionToken}=await rpc.request("pty.list",{});if(typeof admissionToken!=="string")throw new ApiError("the PTY host must be updated before enforcing engine.maxLiveSessions","ENGINE_ADMISSION_UNAVAILABLE",{taskId:opts.taskId,hint:"the running PTY host predates atomic admission; update and restart the PTY host before retrying",nextCommandArgs:opts.retryArgs});let live=await countLiveEngineSessions(sessions,opts.snapshot);if(!sessions.some((s)=>s.key===spec.key&&s.alive)&&live>=limit)throw new ApiError(`${live} engine sessions are already running (engine.maxLiveSessions is ${limit})`,"ENGINE_LIMIT",{taskId:opts.taskId,live,limit,hint:"wait for an engine to finish or close a tab, then retry; raise engine.maxLiveSessions in state.json to allow more",nextCommandArgs:opts.retryArgs});let result=await rpc.request("pty.openChecked",{...spec,admissionToken});if(result.kind==="opened")return result.open}throw new ApiError("PTY inventory kept changing during engine admission; retry the send","ENGINE_ADMISSION_BUSY",{taskId:opts.taskId,nextCommandArgs:opts.retryArgs})}function restoredTabsOf(sessions,taskId,exceptKey){let prefix=`${taskId}::`,ids=[];for(let s of sessions){if(s.alive||s.restored!==!0||s.key===exceptKey||!s.key.startsWith(prefix))continue;let tab=s.key.slice(prefix.length);if(tab.includes("::"))continue;if(!ids.includes(tab))ids.push(tab)}let tabs=readTabsSnapshot(taskId)?.tabs??[];return ids.map((tab)=>{let sessionId=tabs.find((t)=>t.id===tab)?.sessionId;return sessionId?{tab,sessionId}:{tab}})}function restoredTabLaunch(task,tabId,worktreePath,shell){let tab=readTabsSnapshot(task.id)?.tabs.find((t)=>t.id===tabId&&t.kind==="engine");if(!tab)return null;let base=engineLaunchArgv({command:tab.engineCommand??(tab.vendor?void 0:task.command),vendor:tab.vendor??task.vendor,effort:task.modelEffort,model:tab.engineCommand||tab.vendor?void 0:task.model});return buildEngineSessionLaunch({task:{id:task.id,kind:task.kind??"task",vendor:tab.vendor??task.vendor,repo:task.repo},worktreePath,shell,argv:engineTabArgv(tab,base,!1,task.vendor),promptIntent:{kind:"none"},tabId})}var isTaskKey=isHostedTaskKey,findEngineKey=findHostedEngineKey,taskKeys=hostedTaskKeys,openPtyHost=openHostedSessionHost,ensurePtyHost=ensureHostedSessionHost,listSessions=listHostedSessions,listSessionsOrNull=listHostedSessionsOrNull,deliverToKey=deliverToHostedKey,ENGINE_START_PROBE_MS=3000,ENGINE_START_POLL_MS=150,ENGINE_NOT_OBSERVED_REASON=`no engine process appeared in the session within ${ENGINE_START_PROBE_MS}ms`;function outcomeFields(outcome){if(!outcome)return{engineReady:!1,delivered:!1};return{engineReady:outcome.ready,delivered:!0,bytes:outcome.bytes,promptEcho:outcome.confirmed?"confirmed":"unconfirmed"}}async function deliverHostedPrompt(rpc,target,cwd,prompt,launch,opts){let{sessions=[]}=await rpc.request("pty.list",{}),existingKey=opts?.forceNew?null:findEngineKey(sessions,target.id,target.engineBin);if(existingKey){let pid=sessions.find((s)=>s.key===existingKey)?.pid,presence=await enginePresence(pid,target.engineBin,opts?.snapshot);if(presence.kind==="unknown")throw new ApiError(`could not read the process table, so task ${target.id}'s engine tab (${existingKey}) could not be checked for a live engine`,"ENGINE_PROBE_FAILED",{hint:"the `ps` probe failed or timed out; retry, or check the machine's process table",nextCommandArgs:["api","pty-list"]});if(presence.kind!=="engine")throw new ApiError(`task ${target.id}'s engine tab (${existingKey}) has no live engine process \u2014 its engine exited into a plain shell`,"ENGINE_NOT_RUNNING",{hint:"spawn a fresh engine tab for this prompt with --tab new",nextCommandArgs:["api","send","--task-id",target.id,"--tab","new","--plain","--prompt",prompt]});let outcome=await deliverToKey(rpc,existingKey,prompt,{vendor:presence.vendor});return{session:existingKey,pane:existingKey,started:!1,...outcomeFields(outcome)}}if(!opts?.forceNew){let aliveTabs=sessions.filter((s)=>s.alive&&isTaskKey(s.key,target.id)).map((s)=>s.key);if(aliveTabs.length>0)throw new ApiError(`task ${target.id} has live tabs (${aliveTabs.join(", ")}) but none resolves as its engine tab \u2014 refusing to spawn a new engine`,"NO_ENGINE_TAB",{hint:"address a live engine tab explicitly with --tab <tab-N> (see pty-list), or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","pty-list"]})}let frozen=restoredTabsOf(sessions,target.id,launch.key),disclose=frozen.length>0?{frozenTabs:frozen}:{},staleCanonical=sessions.find((session)=>session.key===launch.key&&!session.alive);if(staleCanonical&&staleCanonical.restored!==!0)await rpc.request("pty.kill",{key:launch.key});let open=await openAdmittedEngine(rpc,{key:launch.key,cwd,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:opts?.maxLiveEngines,snapshot:opts?.snapshot,taskId:target.id,retryArgs:opts?.retryArgs??["api","send","--task-id",target.id,...opts?.forceNew?["--tab","new"]:[],"--plain","--prompt",prompt]});try{if(!open.alive)return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,engineReady:!1,delivered:!1,...disclose};if(launch.firstMessage){let outcome=await pastePromptWhenEngineUp(rpc,launch.key,target.engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs});return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,...outcomeFields(outcome),...disclose}}let started=open.created!==!1||open.respawned===!0;if(open.created===!1&&open.respawned!==!0){let outcome=await pastePromptWhenEngineUp(rpc,launch.key,target.engineBin,prompt,{snapshot:opts?.snapshot});return{session:launch.key,pane:launch.key,started,...outcomeFields(outcome),...disclose}}let pendingInit={session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!0,reason:"repo init script is still running; the engine has not started yet",...disclose};if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;if(await awaitEngineProcess(rpc,launch.key,target.engineBin,{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS,snapshot:opts?.snapshot})===null){if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath)&&(await listSessions(rpc)).some((session)=>session.key===launch.key&&session.alive)&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;return{session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!1,reason:await hostedSessionFailureLine(rpc,launch.key)??ENGINE_NOT_OBSERVED_REASON,...disclose}}return{session:launch.key,pane:launch.key,started,engineReady:!0,delivered:!0,...disclose}}finally{await rpc.request("pty.detach",{key:launch.key}).catch(()=>{})}}var killTaskSessions=killHostedSessions;
|
|
2
|
+
import{closeTab,engineTabArgv,initialTabs,setTabTitle,tabPtyKeyFor,terminalTabsKey}from"./chunk-0x7zcw52.js";import{awaitEngineProcess,buildEngineSessionLaunch,deliverToHostedKey,enginePresence,ensureHostedSessionHost,findHostedEngineKey,hostedSessionFailureLine,hostedTaskKeys,initMarkerSaysFinished,isHostedTaskKey,killHostedSessions,listHostedSessions,listHostedSessionsOrNull,openHostedSessionHost,pastePromptWhenEngineUp,readPersistedTerminalDefaultColors,sessionArgvNamesEngine}from"./chunk-02h0488p.js";import{engineLaunchArgv}from"./chunk-zmw0v18d.js";import{engineProcessIn,parsePsSnapshot,psSnapshot,vendorFromArgv}from"./chunk-s21t29qn.js";import{ApiError}from"./chunk-x7r75e3p.js";import{loadStateFile,patchStateFile,updateStateFile}from"./chunk-axxf5dkq.js";import{basename}from"path";function wireNode(node){if(node.kind==="leaf")return{kind:"leaf",id:node.id,title:node.title??null,own:node.content===null};return{kind:"group",orientation:node.orientation,children:node.children.map(wireNode)}}function wireSplit(tree){return tree?{root:wireNode(tree.root),activeLeafId:tree.activeLeafId}:null}function taskEngineArgv(task){return engineLaunchArgv({command:task.command,vendor:task.vendor})}function readTabsSnapshot(taskId){try{let snap=loadStateFile()[terminalTabsKey(taskId)];return snap&&Array.isArray(snap.tabs)?snap:void 0}catch{return}}function closeTabsSnapshot(taskId,tabId){let closing,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(closing=state.tabs.find((tab)=>tab.id===tabId),!closing)return!1;let{state:next,closedId}=closeTab(state,tabId,{allowEmpty:!0});if(!closedId)return closing=void 0,!1;store[key]=next;return}),closing}function renameTabsSnapshot(taskId,tabId,title){let found=!1,key=terminalTabsKey(taskId);return updateStateFile((store)=>{let state=store[key];if(!state||!Array.isArray(state.tabs))return!1;if(!state.tabs.some((tab)=>tab.id===tabId))return!1;found=!0;let next=setTabTitle(state,tabId,title);if(next===state)return!1;store[key]=next;return}),found}var aliveKeysOf=(sessions)=>new Set(sessions.filter((s)=>s.alive).map((s)=>s.key));function unregisteredTabIds(snapshot,taskId,sessions){let known=new Set((snapshot?.tabs??[]).map((t)=>t.id)),prefix=`${taskId}::`,out=[];for(let s of sessions){if(!s.alive||!s.key.startsWith(prefix))continue;let tabId=s.key.slice(prefix.length);if(tabId.includes("::"))continue;if(!known.has(tabId)&&!out.includes(tabId))out.push(tabId)}return out}var abnormalExit=(exit)=>exit&&(exit.code!==0||exit.signal!==null)?exit:null;function joinTaskTabs(snapshot,taskId,sessions,persistedExits={},liveVendors,engineAlive){let unknown=sessions===null,rows0=sessions??[],alive=aliveKeysOf(rows0),sessionExits=new Map(rows0.map((s)=>[s.key,s.exit])),deadExit=(key)=>{let ex=abnormalExit(sessionExits.get(key)??persistedExits[key]);if(!ex)return null;let record=persistedExits[key],sameDeath=record?.at===ex.at,tail=sameDeath?record?.tail:void 0,code=ex.code??(sameDeath?record?.code??null:null),layer=record?.layer??"pty";return{code,signal:ex.signal,at:ex.at,layer,...tail&&tail.length>0?{tail}:{}}},engineExit=(key)=>{let record=persistedExits[`${key}#engine`];if(!record)return null;let{code,signal,at,tail,atApproximate}=record;return{code,signal,at,layer:"engine",...atApproximate?{atApproximate}:{},...tail&&tail.length>0?{tail}:{}}},rows=(snapshot?.tabs??[]).map((t)=>{let key=tabPtyKeyFor(taskId,t),isAlive=unknown?null:alive.has(key),walked=isAlive===!0&&liveVendors?.has(key)===!0?liveVendors.get(key)??null:void 0,engineIsAlive=engineAliveOf(key,isAlive,engineAlive);return{id:t.id,kind:t.kind,title:t.title??null,vendor:t.vendor??null,liveVendor:walked!==void 0?walked:t.liveVendor??null,lastTitle:t.lastTitle??null,autoTitle:t.autoTitle??null,alive:isAlive,engineAlive:engineIsAlive,exit:isAlive===!1?deadExit(key):engineIsAlive===!1?engineExit(key):null,...t.splitTree?{split:wireSplit(t.splitTree)}:{},...t.kind==="engine"&&t.ptyTask?{viewOf:t.ptyTask.id}:{}}});for(let tabId of unregisteredTabIds(snapshot,taskId,rows0))rows.push({id:tabId,kind:"engine",title:null,vendor:null,liveVendor:null,lastTitle:null,autoTitle:null,alive:!0,engineAlive:engineAliveOf(`${taskId}::${tabId}`,!0,engineAlive),exit:null,unregistered:!0});return rows}function engineAliveOf(key,isAlive,engineAlive){if(isAlive===null)return null;if(!isAlive)return!1;return engineAlive?.has(key)===!0?engineAlive.get(key)??null:null}function publishCliTabSnapshot(taskId,sessionId){if(!taskId)return;try{let key=terminalTabsKey(taskId);if(loadStateFile()[key]!==void 0)return;let seeded=initialTabs();patchStateFile({[key]:sessionId?{...seeded,tabs:seeded.tabs.map((t)=>t.kind==="engine"?{...t,sessionId,spawned:!0}:t)}:seeded})}catch{}}function markCliTabSession(taskId,tabId,sessionId){try{let key=terminalTabsKey(taskId);updateStateFile((store)=>{let existing=store[key];if(!existing||!Array.isArray(existing.tabs))return!1;store[key]={...existing,tabs:existing.tabs.map((t)=>t.id===tabId&&t.kind==="engine"?{...t,...sessionId?{sessionId}:{},spawned:!0}:t)};return})}catch{}}function allocateTab(taskId,build,taken=new Set){let key=terminalTabsKey(taskId),out={};if(updateStateFile((store)=>{let existing=store[key],state=existing&&Array.isArray(existing.tabs)&&existing.tabs.length>0?existing:initialTabs(),ordinal=typeof state.nextOrdinal==="number"&&state.nextOrdinal>1?state.nextOrdinal:2;while(taken.has(`tab-${ordinal}`)||state.tabs.some((t)=>t.id===`tab-${ordinal}`))ordinal++;let tab=build(`tab-${ordinal}`,ordinal);out.tab=tab,store[key]={...state,tabs:[...state.tabs,tab],activeId:tab.id,nextOrdinal:ordinal+1};return}),!out.tab)throw Error(`tab allocation for ${taskId} did not run`);return out.tab}function mintCliTab(taskId,vendor,command){try{return allocateTab(taskId,(id,ordinal)=>({kind:"engine",id,title:null,ordinal,...vendor?{vendor}:{},...command?{engineCommand:command}:{}})).id}catch{return`tab-cli-${Date.now().toString(36)}`}}async function countLiveEngineSessions(sessions,snapshot=psSnapshot){let tabs=sessions.filter((s)=>s.alive&&s.key.split("::").length===2);if(!tabs.length)return 0;let rows;try{if(rows=parsePsSnapshot(await snapshot(tabs.flatMap((s)=>s.pid?[s.pid]:[]))),!rows.length)return tabs.length}catch{return tabs.length}return tabs.filter((s)=>{if(!s.pid)return!0;let root=rows.find((row)=>row.pid===s.pid);if(!root)return!0;if(engineProcessIn(rows,s.pid)||vendorFromArgv(root.args))return!0;let[taskId,tabId]=s.key.split("::"),labelled=readTabsSnapshot(taskId)?.tabs.some((tab)=>tab.id===tabId&&tab.kind==="engine");if(tabId!=="tab-1"&&!labelled&&!sessionArgvNamesEngine(s.command))return!1;let executable=basename(root.args.split(/\s+/)[0]).toLowerCase().replace(/^-/,"").replace(/\.exe$/,"");if(["sh","bash","zsh","fish","dash","ash","ksh","mksh"].includes(executable))return/^\S+\s+-[a-zA-Z]*c\b/.test(root.args);return!0}).length}async function openAdmittedEngine(rpc,spec,opts){let limit=opts.maxLiveEngines;if(limit===void 0)return rpc.request("pty.open",spec);for(let attempt=0;attempt<20;attempt++){let{sessions,admissionToken}=await rpc.request("pty.list",{});if(typeof admissionToken!=="string")throw new ApiError("the PTY host must be updated before enforcing engine.maxLiveSessions","ENGINE_ADMISSION_UNAVAILABLE",{taskId:opts.taskId,hint:"the running PTY host predates atomic admission; update and restart the PTY host before retrying",nextCommandArgs:opts.retryArgs});let live=await countLiveEngineSessions(sessions,opts.snapshot);if(!sessions.some((s)=>s.key===spec.key&&s.alive)&&live>=limit)throw new ApiError(`${live} engine sessions are already running (engine.maxLiveSessions is ${limit})`,"ENGINE_LIMIT",{taskId:opts.taskId,live,limit,hint:"wait for an engine to finish or close a tab, then retry; raise engine.maxLiveSessions in state.json to allow more",nextCommandArgs:opts.retryArgs});let result=await rpc.request("pty.openChecked",{...spec,admissionToken});if(result.kind==="opened")return result.open}throw new ApiError("PTY inventory kept changing during engine admission; retry the send","ENGINE_ADMISSION_BUSY",{taskId:opts.taskId,nextCommandArgs:opts.retryArgs})}function restoredTabsOf(sessions,taskId,exceptKey){let prefix=`${taskId}::`,ids=[];for(let s of sessions){if(s.alive||s.restored!==!0||s.key===exceptKey||!s.key.startsWith(prefix))continue;let tab=s.key.slice(prefix.length);if(tab.includes("::"))continue;if(!ids.includes(tab))ids.push(tab)}let tabs=readTabsSnapshot(taskId)?.tabs??[];return ids.map((tab)=>{let sessionId=tabs.find((t)=>t.id===tab)?.sessionId;return sessionId?{tab,sessionId}:{tab}})}function restoredTabLaunch(task,tabId,worktreePath,shell){let tab=readTabsSnapshot(task.id)?.tabs.find((t)=>t.id===tabId&&t.kind==="engine");if(!tab)return null;let base=engineLaunchArgv({command:tab.engineCommand??(tab.vendor?void 0:task.command),vendor:tab.vendor??task.vendor,effort:task.modelEffort,model:tab.engineCommand||tab.vendor?void 0:task.model});return buildEngineSessionLaunch({task:{id:task.id,kind:task.kind??"task",vendor:tab.vendor??task.vendor,repo:task.repo},worktreePath,shell,argv:engineTabArgv(tab,base,!1,task.vendor),promptIntent:{kind:"none"},tabId})}var isTaskKey=isHostedTaskKey,findEngineKey=findHostedEngineKey,taskKeys=hostedTaskKeys,openPtyHost=openHostedSessionHost,ensurePtyHost=ensureHostedSessionHost,listSessions=listHostedSessions,listSessionsOrNull=listHostedSessionsOrNull,deliverToKey=deliverToHostedKey,ENGINE_START_PROBE_MS=3000,ENGINE_START_POLL_MS=150,ENGINE_NOT_OBSERVED_REASON=`no engine process appeared in the session within ${ENGINE_START_PROBE_MS}ms`;function outcomeFields(outcome){if(!outcome)return{engineReady:!1,delivered:!1};return{engineReady:outcome.ready,delivered:!0,bytes:outcome.bytes,promptEcho:outcome.confirmed?"confirmed":"unconfirmed"}}async function deliverHostedPrompt(rpc,target,cwd,prompt,launch,opts){let{sessions=[]}=await rpc.request("pty.list",{}),existingKey=opts?.forceNew?null:findEngineKey(sessions,target.id,target.engineBin);if(existingKey){let pid=sessions.find((s)=>s.key===existingKey)?.pid,presence=await enginePresence(pid,target.engineBin,opts?.snapshot);if(presence.kind==="unknown")throw new ApiError(`could not read the process table, so task ${target.id}'s engine tab (${existingKey}) could not be checked for a live engine`,"ENGINE_PROBE_FAILED",{hint:"the `ps` probe failed or timed out; retry, or check the machine's process table",nextCommandArgs:["api","pty-list"]});if(presence.kind!=="engine")throw new ApiError(`task ${target.id}'s engine tab (${existingKey}) has no live engine process \u2014 its engine exited into a plain shell`,"ENGINE_NOT_RUNNING",{hint:"spawn a fresh engine tab for this prompt with --tab new",nextCommandArgs:["api","send","--task-id",target.id,"--tab","new","--plain","--prompt",prompt]});let outcome=await deliverToKey(rpc,existingKey,prompt,{vendor:presence.vendor});return{session:existingKey,pane:existingKey,started:!1,...outcomeFields(outcome)}}if(!opts?.forceNew){let aliveTabs=sessions.filter((s)=>s.alive&&isTaskKey(s.key,target.id)).map((s)=>s.key);if(aliveTabs.length>0)throw new ApiError(`task ${target.id} has live tabs (${aliveTabs.join(", ")}) but none resolves as its engine tab \u2014 refusing to spawn a new engine`,"NO_ENGINE_TAB",{hint:"address a live engine tab explicitly with --tab <tab-N> (see pty-list), or spawn a fresh engine tab with --tab new",nextCommandArgs:["api","pty-list"]})}let frozen=restoredTabsOf(sessions,target.id,launch.key),disclose=frozen.length>0?{frozenTabs:frozen}:{},staleCanonical=sessions.find((session)=>session.key===launch.key&&!session.alive);if(staleCanonical&&staleCanonical.restored!==!0)await rpc.request("pty.kill",{key:launch.key});let open=await openAdmittedEngine(rpc,{key:launch.key,cwd,command:launch.command,defaultColors:readPersistedTerminalDefaultColors()},{maxLiveEngines:opts?.maxLiveEngines,snapshot:opts?.snapshot,taskId:target.id,retryArgs:opts?.retryArgs??["api","send","--task-id",target.id,...opts?.forceNew?["--tab","new"]:[],"--plain","--prompt",prompt]});try{if(!open.alive)return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,engineReady:!1,delivered:!1,...disclose};if(launch.firstMessage){let outcome=await pastePromptWhenEngineUp(rpc,launch.key,target.engineBin,launch.firstMessage,{initMarkerPath:launch.initMarkerPath,initTimeoutMs:launch.initTimeoutMs});return{session:launch.key,pane:launch.key,started:open.created!==!1||open.respawned===!0,...outcomeFields(outcome),...disclose}}let started=open.created!==!1||open.respawned===!0;if(open.created===!1&&open.respawned!==!0){let outcome=await pastePromptWhenEngineUp(rpc,launch.key,target.engineBin,prompt,{snapshot:opts?.snapshot});return{session:launch.key,pane:launch.key,started,...outcomeFields(outcome),...disclose}}let pendingInit={session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!0,reason:"repo init script is still running; the engine has not started yet",...disclose};if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;if(await awaitEngineProcess(rpc,launch.key,target.engineBin,{timeoutMs:ENGINE_START_PROBE_MS,intervalMs:ENGINE_START_POLL_MS,snapshot:opts?.snapshot})===null){if(launch.initMarkerPath&&!initMarkerSaysFinished(launch.initMarkerPath)&&(await listSessions(rpc)).some((session)=>session.key===launch.key&&session.alive)&&!initMarkerSaysFinished(launch.initMarkerPath))return pendingInit;return{session:launch.key,pane:launch.key,started,engineReady:!1,delivered:!1,reason:await hostedSessionFailureLine(rpc,launch.key)??ENGINE_NOT_OBSERVED_REASON,...disclose}}return{session:launch.key,pane:launch.key,started,engineReady:!0,delivered:!0,...disclose}}finally{await rpc.request("pty.detach",{key:launch.key}).catch(()=>{})}}var killTaskSessions=killHostedSessions;
|
|
3
3
|
export{wireSplit,taskEngineArgv,readTabsSnapshot,closeTabsSnapshot,renameTabsSnapshot,unregisteredTabIds,joinTaskTabs,publishCliTabSnapshot,markCliTabSession,allocateTab,mintCliTab,openAdmittedEngine,restoredTabLaunch,isTaskKey,findEngineKey,taskKeys,openPtyHost,ensurePtyHost,listSessions,listSessionsOrNull,deliverToKey,ENGINE_START_PROBE_MS,ENGINE_START_POLL_MS,ENGINE_NOT_OBSERVED_REASON,outcomeFields,deliverHostedPrompt,killTaskSessions};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{DEFAULT_TERMINAL_COLORS}from"./chunk-4250pw6r.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE,tightenDirPermissionsSync,tightenFilePermissionsSync}from"./chunk-yt15y085.js";import{defaultPtyFreezeDir}from"./chunk-
|
|
2
|
+
import{DEFAULT_TERMINAL_COLORS}from"./chunk-4250pw6r.js";import{OWNER_ONLY_DIR_MODE,OWNER_ONLY_FILE_MODE,tightenDirPermissionsSync,tightenFilePermissionsSync}from"./chunk-yt15y085.js";import{defaultPtyFreezeDir}from"./chunk-z7zm8h1q.js";import{randomUUID}from"crypto";import{mkdirSync,readFileSync,readdirSync,renameSync,rmSync,statSync,writeFileSync}from"fs";import{join}from"path";import{StringDecoder}from"string_decoder";var DEFAULT_MODES={applicationCursorKeys:!1,applicationKeypad:!1,origin:!1,wraparound:!0,reverseWraparound:!1,cursorBlink:!1,cursorVisible:!0,insertMode:!1,sendFocus:!1,bracketedPaste:!1,synchronizedOutput:!1,altScreen:!1,mouseProtocol:"none",mouseEncoding:"default"},MOUSE_PROTOCOLS={9:"x10",1000:"vt200",1002:"drag",1003:"any"},MOUSE_ENCODINGS={1006:"sgr",1016:"sgr-pixels"};function freshModeTrack(modes={...DEFAULT_MODES}){return{modes,carry:""}}function normalizeTerminalModes(raw){let modes={...DEFAULT_MODES};if(typeof raw!=="object"||raw===null)return modes;let record=raw;for(let key of Object.keys(DEFAULT_MODES))if(typeof record[key]==="boolean"&&typeof modes[key]==="boolean")modes[key]=record[key];if(Object.values(MOUSE_PROTOCOLS).includes(record.mouseProtocol))modes.mouseProtocol=record.mouseProtocol;if(Object.values(MOUSE_ENCODINGS).includes(record.mouseEncoding))modes.mouseEncoding=record.mouseEncoding;return modes}function scanTerminalModes(track,chunk){let text=track.carry+chunk;track.carry="";let replies=[],i=text.indexOf("\x1B");while(i!==-1){if(i+1>=text.length){track.carry="\x1B";break}let next=text.charCodeAt(i+1);if(next===91){let end=csiEnd(text,i+2);if(end===-1){if(text.length-i<=64)track.carry=text.slice(i);break}if(end>=0)applyCsi(track.modes,text.slice(i+2,end),text[end],replies);i=text.indexOf("\x1B",end>=0?end+1:i+2);continue}if(next===61)track.modes.applicationKeypad=!0;else if(next===62)track.modes.applicationKeypad=!1;else if(next===99)track.modes={...DEFAULT_MODES};i=text.indexOf("\x1B",i+1)}return replies}function terminalModePreamble(modes){let set=[],reset=[];if(modes.applicationCursorKeys)set.push(1);if(modes.origin)set.push(6);if(!modes.wraparound)reset.push(7);if(modes.cursorBlink)set.push(12);if(!modes.cursorVisible)reset.push(25);if(modes.reverseWraparound)set.push(45);for(let[mode,protocol]of Object.entries(MOUSE_PROTOCOLS))if(modes.mouseProtocol===protocol)set.push(+mode);for(let[mode,encoding]of Object.entries(MOUSE_ENCODINGS))if(modes.mouseEncoding===encoding)set.push(+mode);if(modes.sendFocus)set.push(1004);if(modes.bracketedPaste)set.push(2004);let out=modes.altScreen?"\x1B[?1049h":"";if(set.length>0)out+=`\x1B[?${set.join(";")}h`;if(reset.length>0)out+=`\x1B[?${reset.join(";")}l`;if(modes.applicationKeypad)out+="\x1B=";if(modes.insertMode)out+="\x1B[4h";return out}function csiEnd(text,from){for(let j=from;j<text.length;j++){let c=text.charCodeAt(j);if(c>=64&&c<=126)return j;if(c<32||c>63)return-2}return-1}function applyCsi(modes,body,final,replies){let start=0,prefix="",first=body.charCodeAt(0);if(first>=60&&first<=63)prefix=body[0],start=1;let end=body.length;while(end>start&&body.charCodeAt(end-1)<=47)end--;let intermediates=body.slice(end),params=body.slice(start,end).split(";").map((param)=>Number.parseInt(param.split(":")[0]??"",10)||0);if(intermediates===""&&(final==="h"||final==="l")){let on=final==="h";if(prefix==="?")for(let mode of params)setPrivateMode(modes,mode,on);else if(prefix===""&¶ms.includes(4))modes.insertMode=on}else if(intermediates==="$"&&final==="p"&&(prefix==="?"||prefix==="")){let mode=params[0]??0,value=prefix==="?"?privateModeValue(modes,mode):ansiModeValue(modes,mode);replies.push(`\x1B[${prefix}${mode};${value}$y`)}else if(intermediates==="!"&&final==="p"&&prefix==="")softReset(modes);else if(intermediates===""&&final==="c"&&prefix===""&&(params[0]??0)===0)replies.push("\x1B[?1;2c")}function setPrivateMode(modes,mode,on){if(mode in MOUSE_PROTOCOLS){modes.mouseProtocol=on?MOUSE_PROTOCOLS[mode]:"none";return}if(mode in MOUSE_ENCODINGS){modes.mouseEncoding=on?MOUSE_ENCODINGS[mode]:"default";return}switch(mode){case 1:modes.applicationCursorKeys=on;break;case 6:modes.origin=on;break;case 7:modes.wraparound=on;break;case 12:modes.cursorBlink=on;break;case 25:modes.cursorVisible=on;break;case 45:modes.reverseWraparound=on;break;case 66:modes.applicationKeypad=on;break;case 1004:modes.sendFocus=on;break;case 47:case 1047:case 1049:modes.altScreen=on;break;case 2004:modes.bracketedPaste=on;break;case 2026:modes.synchronizedOutput=on;break}}function softReset(modes){Object.assign(modes,{applicationCursorKeys:!1,applicationKeypad:!1,origin:!1,wraparound:!0,reverseWraparound:!1,cursorVisible:!0,insertMode:!1,sendFocus:!1,bracketedPaste:!1,synchronizedOutput:!1})}var NOT_RECOGNIZED=0,SET=1,RESET=2,PERMANENTLY_SET=3,PERMANENTLY_RESET=4,flag=(on)=>on?SET:RESET;function privateModeValue(modes,mode){if(mode in MOUSE_PROTOCOLS)return flag(modes.mouseProtocol===MOUSE_PROTOCOLS[mode]);if(mode in MOUSE_ENCODINGS)return flag(modes.mouseEncoding===MOUSE_ENCODINGS[mode]);switch(mode){case 1:return flag(modes.applicationCursorKeys);case 6:return flag(modes.origin);case 7:return flag(modes.wraparound);case 8:return PERMANENTLY_SET;case 12:return flag(modes.cursorBlink);case 25:return flag(modes.cursorVisible);case 45:return flag(modes.reverseWraparound);case 66:return flag(modes.applicationKeypad);case 67:case 1005:case 1015:return PERMANENTLY_RESET;case 1004:return flag(modes.sendFocus);case 1048:return SET;case 47:case 1047:case 1049:return flag(modes.altScreen);case 2004:return flag(modes.bracketedPaste);case 2026:return flag(modes.synchronizedOutput);default:return NOT_RECOGNIZED}}function ansiModeValue(modes,mode){switch(mode){case 2:return PERMANENTLY_RESET;case 4:return flag(modes.insertMode);case 12:return PERMANENTLY_SET;case 20:return RESET;default:return NOT_RECOGNIZED}}var FREEZE_VERSION=1;function freezeSession(session,now=new Date){return{v:FREEZE_VERSION,key:session.key,cwd:session.cwd,command:[...session.command],cols:session.cols,rows:session.rows,title:session.title,totalBytes:session.totalBytes,exit:session.exit,ringB64:Buffer.concat(session.chunks).toString("base64"),...session.ringModes?{ringModes:session.ringModes.modes}:{},updatedAt:now.toISOString()}}function thawRing(record,cap){let ring;try{ring=Buffer.from(record.ringB64,"base64")}catch{return null}let cut=Math.max(0,ring.byteLength-cap),trimmed=ring.subarray(cut),ringModes=freshModeTrack(normalizeTerminalModes(record.ringModes));if(cut>0)scanTerminalModes(ringModes,ring.subarray(0,cut).toString("latin1"));return{chunks:trimmed.byteLength>0?[trimmed]:[],bytes:trimmed.byteLength,ringModes}}function thawSession(record,cap){let ring=thawRing(record,cap);if(!ring)return null;let modes=freshModeTrack({...ring.ringModes.modes});for(let chunk of ring.chunks)scanTerminalModes(modes,chunk.toString("latin1"));return{key:record.key,generation:randomUUID(),cwd:record.cwd,proc:null,alive:!1,chunks:[...ring.chunks],bytes:ring.bytes,totalBytes:Math.max(record.totalBytes,ring.bytes),cols:record.cols,rows:record.rows,command:record.command,title:record.title,titleCarry:"",titleDecoder:new StringDecoder("utf8"),colorQueryCarry:"",defaultColors:DEFAULT_TERMINAL_COLORS,modes,ringModes:ring.ringModes,sinks:new Map,emulatorSinks:new Set,parked:!1,parkedScreenBytes:0,exit:record.exit,restored:!0,lastFreezeAtMs:0}}function recordFile(dir,key){return join(dir,`${encodeURIComponent(key)}.json`)}function parseRecord(raw){try{let parsed=JSON.parse(raw);if(parsed?.v!==FREEZE_VERSION)return null;if(typeof parsed.key!=="string"||parsed.key.length===0)return null;if(parsed.key.startsWith("::"))return null;if(typeof parsed.cwd!=="string"||!Array.isArray(parsed.command))return null;if(typeof parsed.ringB64!=="string"||typeof parsed.totalBytes!=="number")return null;return parsed}catch{return null}}var FREEZE_TTL_MS=1209600000,FREEZE_RESTORE_MAX_BYTES=67108864;function updatedAtMs(record){let t=Date.parse(record.updatedAt);return Number.isFinite(t)?t:0}function loadFrozenSessions(dir=defaultPtyFreezeDir(),now=Date.now(),report){let names;try{names=readdirSync(dir)}catch{return[]}let entries=[];for(let name of names){if(!name.endsWith(".json"))continue;try{let st=statSync(join(dir,name));entries.push({name,size:st.size,mtimeMs:st.mtimeMs})}catch{}}entries.sort((a,b)=>b.mtimeMs-a.mtimeMs);let kept=[],stale=[],bytesRead=0,deferred=0,unreadable=0;for(let entry of entries){if(now-entry.mtimeMs>FREEZE_TTL_MS){stale.push(entry.name);continue}if(bytesRead+entry.size>FREEZE_RESTORE_MAX_BYTES&&kept.length>0){deferred++;continue}let record=null;try{record=parseRecord(readFileSync(join(dir,entry.name),"utf8"))}catch{}if(bytesRead+=entry.size,!record){unreadable++;continue}if(now-updatedAtMs(record)>FREEZE_TTL_MS)stale.push(entry.name);else kept.push(record)}for(let name of stale)try{rmSync(join(dir,name),{force:!0})}catch{}return kept.sort((a,b)=>updatedAtMs(b)-updatedAtMs(a)),report?.({restored:kept.length,bytesRead,deferred,expired:stale.length,unreadable}),kept}function tightenExistingPermissions(dir){tightenDirPermissionsSync(dir);let names;try{names=readdirSync(dir)}catch{return}for(let name of names)if(name.endsWith(".json"))tightenFilePermissionsSync(join(dir,name))}function fileFreezeSink(dir=defaultPtyFreezeDir()){return tightenExistingPermissions(dir),{save(record){try{mkdirSync(dir,{recursive:!0,mode:OWNER_ONLY_DIR_MODE});let target=recordFile(dir,record.key),staging=`${target}.${process.pid}.tmp`;writeFileSync(staging,JSON.stringify(record),{encoding:"utf8",mode:OWNER_ONLY_FILE_MODE}),renameSync(staging,target)}catch{}},drop(key){try{rmSync(recordFile(dir,key),{force:!0})}catch{}}}}function clearFrozenSessions(dir=defaultPtyFreezeDir()){try{rmSync(dir,{recursive:!0,force:!0})}catch{}}
|
|
3
3
|
export{freshModeTrack,scanTerminalModes,terminalModePreamble,freezeSession,thawSession,FREEZE_TTL_MS,FREEZE_RESTORE_MAX_BYTES,loadFrozenSessions,fileFreezeSink,clearFrozenSessions};
|