@halcyonlabs/app 0.47.0-halcyon.454 → 0.47.0-halcyon.455
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/index.d.ts +9 -9
- package/package.json +2 -2
- package/server/dist/builtin-plugins/orbit/dist/assets/moonlet/fixed-runner/linux-x64/manifest.json +4 -4
- package/server/dist/builtin-plugins/orbit/dist/assets/moonlet/revision +1 -1
- package/server/dist/builtin-plugins/orbit/dist/server.js +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -83,8 +83,8 @@ declare const appSettingsSchema: z$1.ZodObject<{
|
|
|
83
83
|
providerOrder: z$1.ZodArray<z$1.ZodString>;
|
|
84
84
|
defaultProviderId: z$1.ZodNullable<z$1.ZodString>;
|
|
85
85
|
providerCompletedTurnDisplay: z$1.ZodRecord<z$1.ZodString, z$1.ZodEnum<{
|
|
86
|
-
collapse: "collapse";
|
|
87
86
|
flat: "flat";
|
|
87
|
+
collapse: "collapse";
|
|
88
88
|
}>>;
|
|
89
89
|
streamerMode: z$1.ZodBoolean;
|
|
90
90
|
allowFastServiceTier: z$1.ZodBoolean;
|
|
@@ -105,8 +105,8 @@ declare const appSettingsUpdateSchema: z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
|
105
105
|
providerOrder: z$1.ZodArray<z$1.ZodString>;
|
|
106
106
|
defaultProviderId: z$1.ZodNullable<z$1.ZodString>;
|
|
107
107
|
providerCompletedTurnDisplay: z$1.ZodRecord<z$1.ZodString, z$1.ZodEnum<{
|
|
108
|
-
collapse: "collapse";
|
|
109
108
|
flat: "flat";
|
|
109
|
+
collapse: "collapse";
|
|
110
110
|
}>>;
|
|
111
111
|
streamerMode: z$1.ZodBoolean;
|
|
112
112
|
managedBranchPrefix: z$1.ZodString;
|
|
@@ -143,8 +143,8 @@ declare const appSettingsUpdateSchema: z$1.ZodUnion<readonly [z$1.ZodObject<{
|
|
|
143
143
|
providerOrder: z$1.ZodArray<z$1.ZodString>;
|
|
144
144
|
defaultProviderId: z$1.ZodNullable<z$1.ZodString>;
|
|
145
145
|
providerCompletedTurnDisplay: z$1.ZodRecord<z$1.ZodString, z$1.ZodEnum<{
|
|
146
|
-
collapse: "collapse";
|
|
147
146
|
flat: "flat";
|
|
147
|
+
collapse: "collapse";
|
|
148
148
|
}>>;
|
|
149
149
|
streamerMode: z$1.ZodBoolean;
|
|
150
150
|
machineServerUrl: z$1.ZodNullable<z$1.ZodString>;
|
|
@@ -3008,8 +3008,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
|
|
|
3008
3008
|
}>;
|
|
3009
3009
|
name: z$1.ZodString;
|
|
3010
3010
|
source: z$1.ZodEnum<{
|
|
3011
|
-
command: "command";
|
|
3012
3011
|
skill: "skill";
|
|
3012
|
+
command: "command";
|
|
3013
3013
|
}>;
|
|
3014
3014
|
origin: z$1.ZodEnum<{
|
|
3015
3015
|
user: "user";
|
|
@@ -3098,8 +3098,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
|
|
|
3098
3098
|
}>;
|
|
3099
3099
|
name: z$1.ZodString;
|
|
3100
3100
|
source: z$1.ZodEnum<{
|
|
3101
|
-
command: "command";
|
|
3102
3101
|
skill: "skill";
|
|
3102
|
+
command: "command";
|
|
3103
3103
|
}>;
|
|
3104
3104
|
origin: z$1.ZodEnum<{
|
|
3105
3105
|
user: "user";
|
|
@@ -4016,8 +4016,8 @@ declare const promptTextMentionSchema: z$1.ZodObject<{
|
|
|
4016
4016
|
}>;
|
|
4017
4017
|
name: z$1.ZodString;
|
|
4018
4018
|
source: z$1.ZodEnum<{
|
|
4019
|
-
command: "command";
|
|
4020
4019
|
skill: "skill";
|
|
4020
|
+
command: "command";
|
|
4021
4021
|
}>;
|
|
4022
4022
|
origin: z$1.ZodEnum<{
|
|
4023
4023
|
user: "user";
|
|
@@ -4081,8 +4081,8 @@ declare const promptInputSchema: z$1.ZodDiscriminatedUnion<[z$1.ZodObject<{
|
|
|
4081
4081
|
}>;
|
|
4082
4082
|
name: z$1.ZodString;
|
|
4083
4083
|
source: z$1.ZodEnum<{
|
|
4084
|
-
command: "command";
|
|
4085
4084
|
skill: "skill";
|
|
4085
|
+
command: "command";
|
|
4086
4086
|
}>;
|
|
4087
4087
|
origin: z$1.ZodEnum<{
|
|
4088
4088
|
user: "user";
|
|
@@ -4240,8 +4240,8 @@ declare const providerInfoSchema: z$1.ZodObject<{
|
|
|
4240
4240
|
}, z$1.core.$strip>;
|
|
4241
4241
|
}, z$1.core.$strip>], "kind">>;
|
|
4242
4242
|
completedTurnDisplay: z$1.ZodEnum<{
|
|
4243
|
-
collapse: "collapse";
|
|
4244
4243
|
flat: "flat";
|
|
4244
|
+
collapse: "collapse";
|
|
4245
4245
|
}>;
|
|
4246
4246
|
available: z$1.ZodBoolean;
|
|
4247
4247
|
strings: z$1.ZodOptional<z$1.ZodObject<{
|
|
@@ -4393,8 +4393,8 @@ declare const threadQueuedMessageSchema: z$1.ZodObject<{
|
|
|
4393
4393
|
}>;
|
|
4394
4394
|
name: z$1.ZodString;
|
|
4395
4395
|
source: z$1.ZodEnum<{
|
|
4396
|
-
command: "command";
|
|
4397
4396
|
skill: "skill";
|
|
4397
|
+
command: "command";
|
|
4398
4398
|
}>;
|
|
4399
4399
|
origin: z$1.ZodEnum<{
|
|
4400
4400
|
user: "user";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@halcyonlabs/app",
|
|
3
|
-
"version": "0.47.0-halcyon.
|
|
3
|
+
"version": "0.47.0-halcyon.455",
|
|
4
4
|
"description": "bb app launcher for npx",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"bb",
|
|
@@ -105,7 +105,7 @@
|
|
|
105
105
|
"node": "^22.19.0 || ^24.0.0 || ^26.0.0"
|
|
106
106
|
},
|
|
107
107
|
"moonletRelease": {
|
|
108
|
-
"summary": "Core change:
|
|
108
|
+
"summary": "Core change: open the userland lifecycle to station's threads (#475)"
|
|
109
109
|
},
|
|
110
110
|
"license": "SEE LICENSE IN LICENSE"
|
|
111
111
|
}
|
package/server/dist/builtin-plugins/orbit/dist/assets/moonlet/fixed-runner/linux-x64/manifest.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
|
-
"commit": "
|
|
2
|
+
"commit": "234dc36473f16d2e2e3de0cc9874e699ff2c56c4",
|
|
3
3
|
"file": "orbit-deploy",
|
|
4
4
|
"platform": "linux-x64",
|
|
5
5
|
"provenance": {
|
|
6
|
-
"artifactId":
|
|
7
|
-
"artifactName": "linux-bundle-
|
|
6
|
+
"artifactId": 14673159410,
|
|
7
|
+
"artifactName": "linux-bundle-234dc36473f16d2e2e3de0cc9874e699ff2c56c4",
|
|
8
8
|
"repository": "matt0x6F/personalassistant",
|
|
9
|
-
"runId":
|
|
9
|
+
"runId": 44818784882,
|
|
10
10
|
"workflow": ".github/workflows/moonlet-linux-bundle.yml"
|
|
11
11
|
},
|
|
12
12
|
"schema": 1,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
|
|
1
|
+
234dc36473f16d2e2e3de0cc9874e699ff2c56c4
|
|
@@ -836,7 +836,7 @@ if [ -f "$mail" ] && [ ! -L "$mail" ]; then
|
|
|
836
836
|
mv -f "$mail.new" "$mail"
|
|
837
837
|
fi
|
|
838
838
|
sudo -u ${He(s)} mkdir -p ${He(`${o}/journal`)}
|
|
839
|
-
[ -e ${He(`${o}/open-loops.md`)} ] || [ -e ${He(`${o}/open-loops.archived.md`)} ] || sudo -u ${He(s)} sh -c ${He(`printf '# Open loops\\n\\n## Index\\n\\n## Done\\n' > ${o}/open-loops.md`)}`}),v=>v.code!==255);if(w.code!==0)throw new Error(`installing the Moonlet conversation's directory: ${w.stderr.trim()}`);await g(),Ze(e).assertLegacySync();let b=await XQ(e,r.id);if(b&&await JQ(e,b))return Ze(e).assertLegacySync(),await e.sdk.threads.update({threadId:b,title:en(c.identity)}).catch(()=>{}),b;b&&(await e.sdk.threads.unpin({threadId:b}).catch(()=>{}),e.log.warn(`the Moonlet conversation ${b} isn't one Moonlet started, so its quiet turns and Moonlet's messages can't apply there; starting Moonlet's own`)),Ze(e).assertLegacySync();let k=await e.sdk.threads.spawn({projectId:n,title:en(c.identity),prompt:l?VQ(en(c.identity),Gt(c.identity),l,r.name):GQ(en(c.identity),Gt(c.identity)),environment:{type:"host",hostId:r.id,workspace:{type:"unmanaged",path:vc}},...qn(io,!0),model:c.models.orbit,pinned:!0});return await Jx(e,k.id),e.log.info(`started the Moonlet conversation ${k.id} on ${r.name}`),k.id}i(F2,"ensureFront");import{z as $s}from"zod";import{createHash as Ree}from"node:crypto";var Yx=new Map([["orbit",new Set(["route spawn","route tell","schedule add","schedule list","schedule cancel","prefs show","userland show","prefs propose","changes propose","changes list","changes show","changes withdraw","changes undo","status","work list","work show","work retry","work drop","work first","threads list","threads start","threads archive","thread outcome","thread reply","relay","messages send","messages list","messages read","messages mark-read","messages reply","say","wakes","loops show","loops next","tasks reconciliation","tasks reconcile","records ready","records show","records find","records list","records change","records comments"])]]),Nt="ORB",Xx=/^ORB-[1-9][0-9]{0,8}$/,tee=/^[a-z]+(-[a-z]+)*$/,H2=32,vk={list:{on:"project",values:["--status","--priority","--label","--search","--sort","--limit"],switches:["--active","--json"],required:[]},show:{on:"key",values:[],switches:["--json"],required:[]},create:{on:"project",values:["--title","--description","--priority","--label","--due","--parent"],switches:["--json"],required:["--title"]},update:{on:"key",values:["--status","--priority","--title","--description","--due","--add-label","--remove-label","--parent"],switches:["--no-due","--json"],required:[]},attach:{on:"key",values:[],switches:["--json"],required:[]},detach:{on:"key",values:[],switches:["--json"],required:[]},comment:{on:"key",values:["--body"],switches:["--json"],required:["--body"]},"label list":{on:"project",values:[],switches:["--json"],required:[]},"label create":{on:"project",values:["--name"],switches:["--json"],required:["--name"]}};function Zx(e){if(e[0]==="show"&&e.some(l=>l==="--compact"||l==="--comments")){let l=e[1];if(l&&Xx.test(l)&&e[2]==="--compact"&&(e.length===3||e.length===5&&e[3]==="--comments"&&/^(?:[1-9]|1[0-9]|20)$/.test(e[4])))return;ye("Use bb tasks show ORB-<n> --compact [--comments 1..20].")}let t=e[0]==="label"?2:1,r=e.length>=t?e.slice(0,t).join(" "):void 0,n=e.slice(t),o=r!==void 0&&Object.hasOwn(vk,r)?vk[r]:void 0;o||ye(`of bb tasks, station runs only ${Object.keys(vk).join(", ")}, in the ${Nt} project`);let s,a=0,c=new Set;for(let l=0;l<n.length;l++){let d=n[l];if(!d.startsWith("-")){(o.on!=="key"||s!==void 0)&&ye(`bb tasks ${r} takes no argument ${JSON.stringify(d)}`),Xx.test(d)||ye(`bb tasks ${r} works only on ${Nt}-<n> tasks, not ${JSON.stringify(d)}`),s=d;continue}if(o.on==="project"&&d==="--project"){n[++l]!==Nt&&ye(`bb tasks ${r} works only in the ${Nt} project`),a+=1;continue}if(o.switches.includes(d))continue;o.values.includes(d)||ye(`bb tasks ${r}: ${d} isn't open to station`);let u=n[++l];(u===void 0||u.startsWith("-"))&&ye(`bb tasks ${r}: ${d} takes one value, not starting with -`),d==="--parent"&&!Xx.test(u)&&ye(`bb tasks ${r}: --parent is a ${Nt}-<n> task, not ${JSON.stringify(u)}`),d==="--name"&&c.has(d)&&ye(`bb tasks ${r}: one --name`),d==="--name"&&!(tee.test(u)&&u.length<=H2)&&ye(`bb tasks ${r}: --name is plain lowercase words, at most ${H2} characters, not ${JSON.stringify(u)}`),c.add(d)}o.on==="key"&&s===void 0&&ye(`bb tasks ${r} names its task, ${Nt}-<n>`),o.on==="project"&&a!==1&&ye(`bb tasks ${r} takes --project ${Nt}, once`);for(let l of o.required)c.has(l)||ye(`bb tasks ${r} needs ${l}`)}i(Zx,"checkTaskArgv");var bk={"agent-board":[["show","<thread>"],["show","<thread>","--json"]],"host-monitor":[["snapshot"],["snapshot","--pretty"]]},ree=/^thr_[a-z0-9]+$/;function Qx(e){let t=bk[e]??[],r=t.map(n=>`\`${e} ${n.join(" ")}\``).join(", ");return n=>{let o=i(s=>s.length===n.length&&s.every((a,c)=>a==="<thread>"?ree.test(n[c]):a===n[c]),"fits");t.some(o)||ye(`of the ${e} plugin's CLI, station runs only ${r}`)}}i(Qx,"readOnlyArgv");function W2(e){e[0]==="work"&&(e[1]==="list"&&(e.length===2||e.length===3&&e[2]==="--all")||["show","retry","drop","first"].includes(e[1]??"")&&e.length===3&&eO.test(e[2])||ye("Station work commands are list [--all], or show|retry|drop|first with one work key; no files, author or station override."))}i(W2,"checkWorkArgv");var tO="send_operator_inbox_message",rO="The operator inbox is retired. Send questions to the Orbit assistant in your report or a message to the Orbit thread; it asks the owner once, batched, in chat and Waiting for you.",nO=new Map;var Mm="memory",iO=new Set(["catalog","list","search","get","history"]),oO=new Set(["add","update","forget"]),nee=/^mem_[a-z0-9_-]{1,64}$/,iee=/was not found in the current scope$/;function sO(e,t){return["get",e,"--scope",t,"--json"]}i(sO,"memoryLookupArgv");function aO(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("the memory lookup answered in an unknown shape");let{exitCode:t,stdout:r}=e;if(typeof r!="string")throw new Error("the memory lookup printed nothing");let n=JSON.parse(r);if(t!==0){let s=n.error;if(n.ok===!1&&s?.code==="command_failed"&&typeof s.message=="string"&&iee.test(s.message))return null;throw new Error("the memory lookup failed")}let o=n.memory;if(n.ok!==!0||typeof o?.id!="string"||o.scope!=="global"&&o.scope!=="project"||o.projectId!==null&&typeof o.projectId!="string")throw new Error("the memory lookup answered in an unknown shape");return{id:o.id,scope:o.scope,projectId:o.projectId}}i(aO,"memoryRecordFrom");function oee(e){return(!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&ye("a plugin command's argv must be words"),e}i(oee,"words");function see(e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];n==="--scope"?(e[r+1]!=="project"&&ye("station saves memories with --scope project, in its own project; global memories are the owner's"),t+=1):n.startsWith("--scope=")&&(n!=="--scope=project"&&ye("station saves memories with --scope project, in its own project; global memories are the owner's"),t+=1)}t!==1&&ye("bb memory add from station takes --scope project, once")}i(see,"onlyProjectScope");async function cO(e,t){let r=oee(e.argv);(typeof e.threadId!="string"||!ui.test(e.threadId))&&ye("a memory command from station names its thread"),await Ho(e.threadId,t);let n=r[0]??"";if(iO.has(n))return;oO.has(n)||ye(`of bb memory, station runs only ${[...iO,...oO].join(", ")}`),r.includes("--")&&ye("bb memory from station takes no -- separator"),typeof e.projectId!="string"&&ye("station saves and changes memories only in its own project, which the command names");let o=e.projectId;if(fp(o,t),n==="add")return see(r);let s=r[1];(s===void 0||!nee.test(s))&&ye(`bb memory ${n} from station names the memory by its id, mem_\u2026, right after the command`),t.memoryRecord||ye("changing a memory from station needs the gate's memory lookup"),await t.memoryRecord(s,"global",o)!==null&&ye(`${s} names a global memory, which is the owner's; station changes only its own project's memories`);let a=await t.memoryRecord(s,"project",o);(a===null||a.id!==s||a.scope!=="project"||a.projectId!==o)&&ye(`memory ${s} isn't in this project; station changes only its own project's memories`)}i(cO,"checkMemoryCommand");function aee(e){let{protected:t,...r}=e.station;return{...e,station:r}}i(aee,"own");function Bm(e){return(!e||typeof e!="object"||Array.isArray(e))&&ye("a protected request needs an object"),e}i(Bm,"bodyObject");function lO(e){let t=e.protected;(!t||!["front","canary"].includes(t.role)||t.threadId!==null&&!/^thr_[a-z0-9]+$/.test(t.threadId))&&ye("protected conversation selection unavailable"),e.sharedProjectIds?.size&&ye("a private project cannot have shared sources");let r=new Set([e.hostId]);(!/^host_[a-z0-9]+$/.test(e.hostId)||t.jobs.length>20)&&ye("protected job destinations unavailable");for(let n of t.jobs)(!/^host_[a-z0-9]+$/.test(n.hostId)||r.has(n.hostId)||"protected"in n)&&ye("protected job destinations unavailable"),r.add(n.hostId),[...n.projectIds,...n.sharedProjectIds??[]].some(o=>e.projectIds.has(o))&&ye("private project is also a job destination");return t.jobs}i(lO,"profileStations");async function z2(e,t){let r=lO(t.station),n=t.station.protected,o=aee(t),s=dO(e.path),{method:a,path:c,body:l}=e;if(a==="GET"&&["/health","/install/version","/install/bb-app.tgz","/install.sh"].includes(c))return{gateAuth:!1};if(s[0]==="internal"){let d=new Set(["/internal/hosts/enroll","/internal/session/open","/internal/session/events","/internal/session/interactive-request","/internal/session/interactive-request/interrupt","/internal/session/tool-call"]),u=/^\/internal\/plugins\/(provider-claude-code|provider-codex)\/host\/[a-f0-9]{64}$/.test(c),f=/^\/internal\/skills\/tree\/[a-zA-Z0-9_.-]+$/.test(c),p=c==="/internal/ws"||c==="/internal/session/project-attachment-content"||u||f;if(a==="POST"&&d.has(c)||a==="GET"&&p||ye("internal route is not part of the protected runtime"),a==="POST"){let h=Bm(l);h.hostId!==void 0&&h.hostId!==t.station.hostId&&ye("another daemon identity")}if(c==="/internal/session/project-attachment-content"){let h=new URLSearchParams(e.search);(h.getAll("threadId").length!==1||!n.threadId||h.get("threadId")!==n.threadId||h.getAll("projectId").length!==1||!t.station.projectIds.has(h.get("projectId")))&&ye("another conversation's attachment")}if(c==="/internal/session/tool-call"){let h=Bm(l);(!n.threadId||h.threadId!==n.threadId)&&ye("only the selected protected conversation calls tools"),t.agentTools.has(h.tool)&&ye("the protected workspace is fixed by the server")}return ho(e,o)}if((s[0]!=="api"||s[1]!=="v1")&&ye("not part of the protected conversation API"),s[2]==="threads"&&s.length===3&&a==="POST"){let d=Bm(l),u=Bm(d.environment),f=r.find(h=>h.hostId===u.hostId);(!f||u.type!=="host")&&ye("work needs an explicit existing job machine"),(!n.threadId||d.parentThreadId!==n.threadId)&&ye("work needs the selected conversation as parent"),d.lifecycleOwnerThreadId!==void 0&&d.lifecycleOwnerThreadId!==n.threadId&&ye("another lifecycle owner"),d.senderThreadId!==void 0&&d.senderThreadId!==n.threadId&&ye("only the selected conversation sends work");let p={...d};return delete p.parentThreadId,delete p.lifecycleOwnerThreadId,delete p.senderThreadId,ho({...e,body:p},{...t,station:f})}if(s[2]==="threads"&&s[3]&&ui.test(s[3])){let d=s[3];if(d===n.threadId)return a!=="GET"&&ye("the protected conversation is controlled by the server"),ho(e,o);let u=await t.threadHost(d),f=r.find(p=>p.hostId===u);return f||ye("thread is outside the protected conversation's job destinations"),ho(e,{...t,station:f})}if(s[2]==="plugins"&&s[4]==="cli"&&s.length===5&&a==="POST")return(!n.threadId||Bm(l).threadId!==n.threadId)&&ye("a protected plugin command names the selected conversation"),ho(e,o);if(a==="GET"&&s.length===3&&["threads","threads/running","projects","environments","queued-messages"].includes(s[2]))return ho(e,o);if(a==="GET"&&c==="/api/v1/threads/running")return ho(e,o);if(a==="GET"&&s[2]==="projects"&&s[3]){let d=r.find(u=>u.projectIds.has(s[3]));if(d)return ho(e,{...t,station:d})}if((a==="GET"||a==="POST"&&s.length===5&&s[4]==="cleanup")&&s[2]==="environments"&&s[3]){let d=await t.environmentHost(s[3]),u=r.find(f=>f.hostId===d);if(u)return ho(e,{...t,station:u})}if(a==="GET"&&uO.has(s.slice(2).join("/")))return ho(e,o);ye("route is not open to the protected conversation")}i(z2,"protectedDecision");async function kk(e,t,r){if("protected"in r.station)return cee(e,t,r);Array.isArray(t)||ye(`bb answered ${e} with something other than a list`);let n=i(s=>s!==null&&typeof s=="object"?s:{},"record"),o=i(s=>{let a=n(s),c=n(a.environment);return(a.environmentHostId??c.hostId)===r.station.hostId},"onStation");switch(e){case"threads":return t.filter(o);case"threads/running":case"environments":return t.filter(s=>n(s).hostId===r.station.hostId);case"projects":return t.filter(s=>r.station.projectIds.has(n(s).id)).map(s=>{let a=n(s);return Array.isArray(a.threads)?{...a,threads:a.threads.filter(o)}:a});case"queued-messages":{let s=[];for(let a of t){let c=n(a).threadId;typeof c=="string"&&ui.test(c)&&await r.threadHost(c)===r.station.hostId&&s.push(a)}return s}}}i(kk,"filterList");async function cee(e,t,r){let n=lO(r.station),o=r.station.protected,{protected:s,...a}=r.station,c=i(u=>u!==null&&typeof u=="object"?u:{},"record"),l=[];for(let u of[a,...n]){let f=await kk(e,t,{...r,station:u}),p=u.hostId===a.hostId;for(let h of f){let y=c(h);p&&["threads","threads/running","queued-messages"].includes(e)&&(y.threadId??y.id)!==o.threadId||p&&e==="environments"||(e==="projects"&&Array.isArray(y.threads)&&p?l.push({...y,threads:y.threads.filter(m=>c(m).id===o.threadId)}):l.push(h))}}let d=new Set;return l.filter(u=>{let f=c(u).id;return typeof f!="string"?!0:d.has(f)?!1:(d.add(f),!0)})}i(cee,"protectedList");var ui=/^([a-z]+)_[a-z0-9]+$/,Le=class extends Error{static{i(this,"Deny")}};function ye(e){throw new Le(e)}i(ye,"deny");function dO(e){e.startsWith("/")||ye("not an origin-form path"),/^[A-Za-z0-9\-._~!$&'()*+,;=:@%/]+$/.test(e)||ye("characters outside a URL path");let t=e.slice(1).split("/"),r=!1;return t.forEach((n,o)=>{(n===""||n==="."||n===".."||/%(2e|2f|5c)/i.test(n))&&ye(`unroutable path segment ${JSON.stringify(n)}`),!r&&n.includes("%")&&ye(`escaped route segment ${JSON.stringify(n)}`),o>=2&&(n==="files"||n==="host-files")&&(r=!0)}),t}i(dO,"segments");function lee(e){let t=new Map;for(let[r,n]of new URLSearchParams(e))t.has(r)&&ye(`duplicate query parameter ${r}`),t.set(r,n);return t}i(lee,"queryOf");var uO=new Set(["hosts","thread-sections","plugins","plugins/contributions","system/config","system/version","system/execution-options","system/providers","system/providers/state","system/providers/catalog","system/machine-providers","system/environment-providers"]),dee=new Set(["threads","threads/running","projects","environments","queued-messages"]),uee=new Set(["projectId","providerId","origin","lifecycleOwnerThreadId","visibility","title","input","model","serviceTier","reasoningLevel","permissionMode","executionInputSources","environment","parentThreadId","sectionId","pinned","sourceThreadId","sourceSeqEnd","startedOnBehalfOf","originKind","sendAt","senderThreadId","parentNotifications"]),pee=new Set(["sourceThreadId","sourceSeqEnd","input","agentContextSeed","title","permissionMode","visibility","environment","origin","lifecycleOwnerThreadId"]),fee=new Set(["cols","rows","start","target","title"]),hee=new Set(["hostId","path","rootPath","content","contentEncoding","createParents","expectedSha256","mode","query","limit","includeHidden","excludeNames","includeFiles","includeDirectories","recursive","sourcePath","destinationPath"]),mee=new Set(["read","write","list","paths","mkdir","move","remove"]),gee=new Set(["argv","cwd","threadId","projectId"]);function Is(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&ye(`${t} needs a JSON object`),e}i(Is,"objectBody");function Os(e,t,r){for(let n of Object.keys(e))t.has(n)||ye(`${r}: unknown field ${n}`)}i(Os,"onlyFields");async function Um(e,t){return"protected"in t.station?z2(e,t):ho(e,t)}i(Um,"decide");async function ho(e,t){let{method:r,path:n,search:o="",body:s}=e,a=dO(n);if(a[0]==="internal"){let f=a.slice(1).join("/");return f==="hosts/enroll-key"&&ye("enrollment keys are minted on the server's machine only"),f.startsWith("server-move")&&ye("server moves are the server machine's business"),f==="session/tool-call"&&await wee(s,t),{gateAuth:!1}}if(r==="GET"&&(n==="/health"||n==="/install.sh"||n==="/install/version"||n==="/install/bb-app.tgz"))return{gateAuth:!1};a[0]==="ws"&&a[1]==="terminals"&&a.length===3&&ye("terminal sockets bypass station credential isolation; use local station tools"),(a[0]!=="api"||a[1]!=="v1")&&ye("not part of bb's API");let l=r==="POST"&&a[2]==="plugins"&&a[4]==="cli"&&a.length===5&&t.pluginCommands?.has(a[3])&&s&&typeof s=="object"&&!Array.isArray(s)?{...s,argv:[]}:s,d=r==="POST"&&a.length===3&&a[2]==="threads";await bee(l,t,d);let u=await yee(r,a.slice(2),lee(o),s,t);return u?{gateAuth:!0,filter:u}:{gateAuth:!0}}i(ho,"regularDecision");async function yee(e,t,r,n,o){let[s,a,...c]=t,l=c.join("/");if(e==="GET"&&(s==="hosts"&&c[0]==="files"||s==="threads"&&(c[0]==="host-files"||c[0]==="thread-storage"&&c[1]==="files"&&c.length>2)||s==="environments"&&c[0]==="files"||s==="projects"&&(c[0]==="files"&&c.length>1||c[0]==="hosts"&&c[2]==="files"))&&ye("raw daemon file reads bypass station credential isolation; use local station tools or the bounded job reader"),s==="environments"&&["status","diff","paths","actions","revisions"].includes(c[0]??"")&&ye("daemon repository operations can execute repository-controlled programs; use local sandboxed Git"),s==="threads"&&c[0]==="interactions"&&c.length>=3&&["respond","resolve","cancel"].includes(c[2])&&ye("only the user answers interactions"),s==="threads"&&a&&ui.test(a)&&(e==="POST"&&l==="archive-all"||e==="DELETE"&&l===""))return await Ho(a,o),G2({thread:a},o);if(s==="environments"&&a&&ui.test(a)&&(e==="POST"&&(l==="archive-threads"||l==="cleanup")||e==="DELETE"&&l===""))return await hp(a,o),G2({environment:a},o);if(s==="threads"&&a&&ui.test(a))return Ho(a,o);if(s==="environments"&&a&&ui.test(a))return hp(a,o);if(s==="terminals"&&a&&ui.test(a)){await V2(a,o),e==="POST"&&["input","restart"].includes(l)&&ye("host terminal execution bypasses station credential isolation; use local station tools");return}if(s==="hosts"&&a){if(a!==o.station.hostId&&ye("another machine"),e==="GET"||e==="POST"&&l==="paths/exist")return;ye("machine management")}if(s==="projects"&&a){if(fp(a,o),c[0]==="hosts"&&c[1]!==o.station.hostId&&ye("another machine"),e==="GET"&&l!=="machine-environment"&&l!=="prompt-history")return;e==="POST"&&(l==="attachments"||l==="attachments/copy")&&ye("daemon attachment file input bypasses station credential isolation"),ye("changing the project")}let d=t.join("/");if(!(e==="GET"&&uO.has(d))){if(e==="GET"&&dee.has(d))return d;if(e==="GET"&&d==="terminals"){if(r.get("hostId")===o.station.hostId)return;let u=r.get("threadId");if(u!==void 0)return Ho(u,o);let f=r.get("environmentId");if(f!==void 0)return hp(f,o);ye("terminals on another machine")}if(e==="POST"&&d==="threads")return Eee(n,o);if(e==="POST"&&d==="threads/fork"){let u=Is(n,"a fork");Os(u,pee,"a fork"),u.sourceThreadId===void 0&&ye("a fork needs its source"),await Ho(u.sourceThreadId,o),u.origin==="plugin"&&ye("plugin-origin threads"),u.environment!==void 0&&await K2(u.environment,o);let f=await o.threadProvider(qm(u.sourceThreadId,"thread"));(f===null||!_k.includes(f))&&ye(`a fork of a thread on ${f??"an unknown provider"}: station's threads run on ${_k.join(" or ")}`),X2(f,u.permissionMode,!0);return}if(!(e==="POST"&&d==="threads/resolve-mentions")){if(e==="POST"&&d==="terminals"){let u=Is(n,"a terminal");Os(u,fee,"a terminal"),await See(u.target,o),ye("host terminal execution bypasses station credential isolation; use local station tools")}if(e==="POST"&&s==="files"&&t.length===2&&mee.has(a)){let u=Is(n,"a file operation");Os(u,hee,"a file operation"),u.hostId!==o.station.hostId&&ye("files on another machine (no hostId means the server's)"),ye("host file operations bypass station credential isolation; use local station tools or the bounded job reader")}if(e==="POST"&&s==="plugins"&&t.length===3&&c[0]==="cli"){let u=Is(n,"a plugin command");if(Os(u,gee,"a plugin command"),a===Mm)return cO(u,o);if(o.pluginClis.has(a))return;let f=o.pluginArgv?.get(a);if(f){let m=u.argv;return(!Array.isArray(m)||!m.every(g=>typeof g=="string"))&&ye("a plugin command's argv must be words"),f(m)}let p=o.pluginCommands?.get(a);p||ye(`the ${a} plugin's CLI isn't allowed on station`),(typeof u.threadId!="string"||!u.threadId)&&ye("a plugin command from station names its thread");let h=u.argv;(!Array.isArray(h)||!h.every(m=>typeof m=="string"))&&ye("a plugin command's argv must be words");let y=h;a==="orbit"&&(y[0]==="userland"&&(y.length!==4||y[1]!=="show"||y[2]!=="guidance/context-core"||y[3]!=="--json")&&ye("Station context guidance reads the active guidance/context-core artifact as JSON; no versions or changes."),W2(y)),!p.has(y.slice(0,2).join(" "))&&!p.has(y[0]??"")&&ye(`only ${[...p].map(m=>`\`${a} ${m}\``).join(", ")} of the ${a} plugin's CLI are open to station`);return}ye(`${e} /${d} isn't open to station`)}}}i(yee,"apiRoute");async function wee(e,t){let r=e??{},n=r.tool;if(typeof n!="string"&&ye(`agent tool ${String(n)} isn't allowed on station`),n===tO&&ye(rO),t.agentTools.has(n)){await Ho(r.threadId,t);return}let o=t.stationTools?.get(n);if(o)return typeof r.threadId!="string"&&ye(`${n} is called by one of station's threads`),await Ho(r.threadId,t),o(r.arguments);ye(`agent tool ${n} isn't allowed on station`)}i(wee,"toolCall");var vee=new Set(["type","kind","mode"]);async function bee(e,t,r=!1){let n=[],o,s=i((a,c,l)=>{if(c>64&&ye("a body nested too deeply"),typeof a=="string"){if(l!==void 0&&vee.has(l))return;r&&c===1&&l==="projectId"?o=a:ui.test(a)&&n.push(a)}else if(Array.isArray(a))for(let d of a)s(d,c+1);else if(a!==null&&typeof a=="object")for(let[d,u]of Object.entries(a))(d==="pluginSubmission"||d==="pluginMetadata"||d==="originPluginId")&&ye(`plugin data (${d})`),s(u,c+1,d)},"walk");s(e,0),o!==void 0&&fp(o,t,!0);for(let a of new Set(n)){let c=ui.exec(a)[1];c==="thr"?await Ho(a,t):c==="env"?await hp(a,t):c==="term"?await V2(a,t):c==="host"&&a!==t.station.hostId?ye(`machine ${a} isn't station`):c==="proj"?fp(a,t):c==="src"&&ye("project sources")}}i(bee,"references");function qm(e,t){return(typeof e!="string"||!ui.test(e))&&ye(`bad ${t} id`),e}i(qm,"checkedId");async function G2(e,t){t.archive||ye("archiving from station needs the unpushed work check");try{await t.archive(e)}catch(r){if(r instanceof Le)throw r;ye(r.message)}}i(G2,"checkArchive");async function Ho(e,t){let r=qm(e,"thread");await t.threadHost(r)!==t.station.hostId&&ye(`thread ${r} isn't on station`)}i(Ho,"ownThread");async function hp(e,t){let r=qm(e,"environment");await t.environmentHost(r)!==t.station.hostId&&ye(`environment ${r} isn't on station`)}i(hp,"ownEnvironment");async function V2(e,t){let r=qm(e,"terminal");await t.terminalHost(r)!==t.station.hostId&&ye(`terminal ${r} isn't on station`)}i(V2,"ownTerminal");function fp(e,t,r=!1){let n=qm(e,"project");t.station.projectIds.has(n)||r&&t.station.sharedProjectIds?.has(n)||ye(`project ${n} isn't station's`)}i(fp,"ownProject");var pO="orbit-job-folder",eO=/^[a-z][a-z0-9-]*:[a-z0-9][a-z0-9_./:#-]{0,254}$/i,kee=/^ORB-[1-9][0-9]{0,8}$/;async function K2(e,t,r=!1){let n=Is(e,"an environment");switch(n.type){case"provider":{if(!r)break;Os(n,new Set(["type","environmentProviderId","machine","inputs"]),"an environment"),n.environmentProviderId!==pO&&ye(`environment provider ${String(n.environmentProviderId)} isn't open to station`);let o=Is(n.machine,"a machine");if(Os(o,new Set(["type","hostId"]),"a machine"),(o.type!=="existing"||o.hostId!==t.station.hostId)&&ye("a work folder on another machine"),n.inputs!==void 0){let s=Is(n.inputs,"the inputs");Object.keys(s).some(a=>!["key","adopt","class","loop"].includes(a))&&ye("a work folder's inputs are the plugin's, except the work key, its class and its loop"),s.class!==void 0&&!["promised","repair","background"].includes(s.class)&&ye("a start's class is promised, repair or background"),s.loop!==void 0&&(typeof s.loop!="string"||!kee.test(s.loop))&&ye("a start's loop is an ORB task, like ORB-269"),s.key!==void 0&&(typeof s.key!="string"||!eO.test(s.key))&&ye("a work key is like orb-269:fix-1"),s.adopt!==void 0&&(typeof s.adopt!="string"||!/^\/./.test(s.adopt)||s.adopt.split("/").some(a=>a==="."||a===".."))&&ye("a checkout is an absolute path without parent steps")}return}case"host":Os(n,new Set(["type","hostId","workspace"]),"an environment"),n.hostId!==t.station.hostId&&ye("a thread on another machine (no hostId means the server's)");return;case"reuse":return Os(n,new Set(["type","environmentId"]),"an environment"),hp(n.environmentId,t);case"project-default":Os(n,new Set(["type"]),"an environment");return}ye(`environment type ${String(n.type)} isn't open to station`)}i(K2,"placement");var J2="claude-code",_k=[J2,"codex"];function X2(e,t,r){e!=="codex"||t===cc||ye(`a Codex thread with permission mode ${t===void 0?r?"left out (the fork would keep its source's, which may be from an earlier release setting)":"left out (bb would take auto)":String(t)}: station's Codex threads start with ${cc}, as in bb thread spawn --provider codex --permission-mode ${cc} (the station kernel enforces access; the release setting controls Codex approval questions)`)}i(X2,"stationPermission");function _ee(e){e===void 0&&ye(`a thread that names no provider (bb would take the project's remembered one): station's threads name one, as in bb thread spawn --provider ${J2}`),(typeof e!="string"||!_k.includes(e))&&ye(`a thread on ${String(e)}: station's threads run on ${_k.join(" or ")}`)}i(_ee,"stationProvider");async function Eee(e,t){let r=Is(e,"a thread");Os(r,uee,"a thread"),r.senderThreadId!==void 0&&await Ho(r.senderThreadId,t),_ee(r.providerId),X2(r.providerId,r.permissionMode,!1),fp(r.projectId,t,!0),r.origin==="plugin"&&ye("plugin-origin threads"),!t.station.projectIds.has(r.projectId)&&Is(r.environment,"an environment").type==="project-default"&&ye("a thread in a project with sources elsewhere is placed on station explicitly"),await K2(r.environment,t,!0)}i(Eee,"createThread");async function See(e,t){let r=Is(e,"a terminal target");switch(r.kind){case"thread":return Ho(r.threadId,t);case"environment":return hp(r.environmentId,t);case"host_path":r.hostId!==t.station.hostId&&ye("a terminal on another machine");return;default:ye("unknown terminal target")}}i(See,"terminalTarget");import{z as Nn}from"zod";import{open as Tee,rename as Aee,unlink as xee}from"node:fs/promises";import{randomUUID as Oee}from"node:crypto";import{resolve as fO}from"node:path";import{pathToFileURL as Iee}from"node:url";var Y2=new Set(["report.md","evidence.md","job.log"]);function hO(e){if(!Array.isArray(e))throw new Error("Declare outputs as a JSON list.");let t=[],r=0;for(let n of e){if(typeof n!="string"||Buffer.byteLength(n,"utf8")>4096||/[\u0000-\u001f\u007f\ud800-\udfff\\]/u.test(n)||n.split("/").some(o=>o===""||o==="."||o===".."))throw new Error("Output names must be relative file paths.");if(!Y2.has(n)&&!n.startsWith("results/")&&!n.startsWith("logs/"))throw new Error("Extra files belong under results/ or logs/.");if(!t.includes(n)){if(t.some(o=>o.startsWith(n+"/")||n.startsWith(o+"/")))throw new Error("Output names cannot contain one another.");if(!Y2.has(n)&&++r>32)throw new Error("Declare at most 32 extra output files.");t.push(n)}}return t}i(hO,"outputNames");async function $ee(e,t){let r=hO(e),n=fO(t,".orbit-outputs-"+Oee()),o=fO(t,".orbit-outputs.json"),s=await Tee(n,"wx",384);try{await s.writeFile(JSON.stringify(r)+`
|
|
839
|
+
[ -e ${He(`${o}/open-loops.md`)} ] || [ -e ${He(`${o}/open-loops.archived.md`)} ] || sudo -u ${He(s)} sh -c ${He(`printf '# Open loops\\n\\n## Index\\n\\n## Done\\n' > ${o}/open-loops.md`)}`}),v=>v.code!==255);if(w.code!==0)throw new Error(`installing the Moonlet conversation's directory: ${w.stderr.trim()}`);await g(),Ze(e).assertLegacySync();let b=await XQ(e,r.id);if(b&&await JQ(e,b))return Ze(e).assertLegacySync(),await e.sdk.threads.update({threadId:b,title:en(c.identity)}).catch(()=>{}),b;b&&(await e.sdk.threads.unpin({threadId:b}).catch(()=>{}),e.log.warn(`the Moonlet conversation ${b} isn't one Moonlet started, so its quiet turns and Moonlet's messages can't apply there; starting Moonlet's own`)),Ze(e).assertLegacySync();let k=await e.sdk.threads.spawn({projectId:n,title:en(c.identity),prompt:l?VQ(en(c.identity),Gt(c.identity),l,r.name):GQ(en(c.identity),Gt(c.identity)),environment:{type:"host",hostId:r.id,workspace:{type:"unmanaged",path:vc}},...qn(io,!0),model:c.models.orbit,pinned:!0});return await Jx(e,k.id),e.log.info(`started the Moonlet conversation ${k.id} on ${r.name}`),k.id}i(F2,"ensureFront");import{z as $s}from"zod";import{createHash as Ree}from"node:crypto";var Yx=new Map([["orbit",new Set(["route spawn","route tell","schedule add","schedule list","schedule cancel","prefs show","userland kinds","userland list","userland show","userland history","userland draft","userland trial","userland activate","userland rollback","userland retire","userland disable","userland enable","userland fill","prefs propose","changes propose","changes list","changes show","changes withdraw","changes undo","status","work list","work show","work retry","work drop","work first","threads list","threads start","threads archive","thread outcome","thread reply","relay","messages send","messages list","messages read","messages mark-read","messages reply","say","wakes","loops show","loops next","tasks reconciliation","tasks reconcile","records ready","records show","records find","records list","records change","records comments"])]]),Nt="ORB",Xx=/^ORB-[1-9][0-9]{0,8}$/,tee=/^[a-z]+(-[a-z]+)*$/,H2=32,vk={list:{on:"project",values:["--status","--priority","--label","--search","--sort","--limit"],switches:["--active","--json"],required:[]},show:{on:"key",values:[],switches:["--json"],required:[]},create:{on:"project",values:["--title","--description","--priority","--label","--due","--parent"],switches:["--json"],required:["--title"]},update:{on:"key",values:["--status","--priority","--title","--description","--due","--add-label","--remove-label","--parent"],switches:["--no-due","--json"],required:[]},attach:{on:"key",values:[],switches:["--json"],required:[]},detach:{on:"key",values:[],switches:["--json"],required:[]},comment:{on:"key",values:["--body"],switches:["--json"],required:["--body"]},"label list":{on:"project",values:[],switches:["--json"],required:[]},"label create":{on:"project",values:["--name"],switches:["--json"],required:["--name"]}};function Zx(e){if(e[0]==="show"&&e.some(l=>l==="--compact"||l==="--comments")){let l=e[1];if(l&&Xx.test(l)&&e[2]==="--compact"&&(e.length===3||e.length===5&&e[3]==="--comments"&&/^(?:[1-9]|1[0-9]|20)$/.test(e[4])))return;ye("Use bb tasks show ORB-<n> --compact [--comments 1..20].")}let t=e[0]==="label"?2:1,r=e.length>=t?e.slice(0,t).join(" "):void 0,n=e.slice(t),o=r!==void 0&&Object.hasOwn(vk,r)?vk[r]:void 0;o||ye(`of bb tasks, station runs only ${Object.keys(vk).join(", ")}, in the ${Nt} project`);let s,a=0,c=new Set;for(let l=0;l<n.length;l++){let d=n[l];if(!d.startsWith("-")){(o.on!=="key"||s!==void 0)&&ye(`bb tasks ${r} takes no argument ${JSON.stringify(d)}`),Xx.test(d)||ye(`bb tasks ${r} works only on ${Nt}-<n> tasks, not ${JSON.stringify(d)}`),s=d;continue}if(o.on==="project"&&d==="--project"){n[++l]!==Nt&&ye(`bb tasks ${r} works only in the ${Nt} project`),a+=1;continue}if(o.switches.includes(d))continue;o.values.includes(d)||ye(`bb tasks ${r}: ${d} isn't open to station`);let u=n[++l];(u===void 0||u.startsWith("-"))&&ye(`bb tasks ${r}: ${d} takes one value, not starting with -`),d==="--parent"&&!Xx.test(u)&&ye(`bb tasks ${r}: --parent is a ${Nt}-<n> task, not ${JSON.stringify(u)}`),d==="--name"&&c.has(d)&&ye(`bb tasks ${r}: one --name`),d==="--name"&&!(tee.test(u)&&u.length<=H2)&&ye(`bb tasks ${r}: --name is plain lowercase words, at most ${H2} characters, not ${JSON.stringify(u)}`),c.add(d)}o.on==="key"&&s===void 0&&ye(`bb tasks ${r} names its task, ${Nt}-<n>`),o.on==="project"&&a!==1&&ye(`bb tasks ${r} takes --project ${Nt}, once`);for(let l of o.required)c.has(l)||ye(`bb tasks ${r} needs ${l}`)}i(Zx,"checkTaskArgv");var bk={"agent-board":[["show","<thread>"],["show","<thread>","--json"]],"host-monitor":[["snapshot"],["snapshot","--pretty"]]},ree=/^thr_[a-z0-9]+$/;function Qx(e){let t=bk[e]??[],r=t.map(n=>`\`${e} ${n.join(" ")}\``).join(", ");return n=>{let o=i(s=>s.length===n.length&&s.every((a,c)=>a==="<thread>"?ree.test(n[c]):a===n[c]),"fits");t.some(o)||ye(`of the ${e} plugin's CLI, station runs only ${r}`)}}i(Qx,"readOnlyArgv");function W2(e){e[0]==="work"&&(e[1]==="list"&&(e.length===2||e.length===3&&e[2]==="--all")||["show","retry","drop","first"].includes(e[1]??"")&&e.length===3&&eO.test(e[2])||ye("Station work commands are list [--all], or show|retry|drop|first with one work key; no files, author or station override."))}i(W2,"checkWorkArgv");var tO="send_operator_inbox_message",rO="The operator inbox is retired. Send questions to the Orbit assistant in your report or a message to the Orbit thread; it asks the owner once, batched, in chat and Waiting for you.",nO=new Map;var Mm="memory",iO=new Set(["catalog","list","search","get","history"]),oO=new Set(["add","update","forget"]),nee=/^mem_[a-z0-9_-]{1,64}$/,iee=/was not found in the current scope$/;function sO(e,t){return["get",e,"--scope",t,"--json"]}i(sO,"memoryLookupArgv");function aO(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new Error("the memory lookup answered in an unknown shape");let{exitCode:t,stdout:r}=e;if(typeof r!="string")throw new Error("the memory lookup printed nothing");let n=JSON.parse(r);if(t!==0){let s=n.error;if(n.ok===!1&&s?.code==="command_failed"&&typeof s.message=="string"&&iee.test(s.message))return null;throw new Error("the memory lookup failed")}let o=n.memory;if(n.ok!==!0||typeof o?.id!="string"||o.scope!=="global"&&o.scope!=="project"||o.projectId!==null&&typeof o.projectId!="string")throw new Error("the memory lookup answered in an unknown shape");return{id:o.id,scope:o.scope,projectId:o.projectId}}i(aO,"memoryRecordFrom");function oee(e){return(!Array.isArray(e)||!e.every(t=>typeof t=="string"))&&ye("a plugin command's argv must be words"),e}i(oee,"words");function see(e){let t=0;for(let r=0;r<e.length;r++){let n=e[r];n==="--scope"?(e[r+1]!=="project"&&ye("station saves memories with --scope project, in its own project; global memories are the owner's"),t+=1):n.startsWith("--scope=")&&(n!=="--scope=project"&&ye("station saves memories with --scope project, in its own project; global memories are the owner's"),t+=1)}t!==1&&ye("bb memory add from station takes --scope project, once")}i(see,"onlyProjectScope");async function cO(e,t){let r=oee(e.argv);(typeof e.threadId!="string"||!ui.test(e.threadId))&&ye("a memory command from station names its thread"),await Ho(e.threadId,t);let n=r[0]??"";if(iO.has(n))return;oO.has(n)||ye(`of bb memory, station runs only ${[...iO,...oO].join(", ")}`),r.includes("--")&&ye("bb memory from station takes no -- separator"),typeof e.projectId!="string"&&ye("station saves and changes memories only in its own project, which the command names");let o=e.projectId;if(fp(o,t),n==="add")return see(r);let s=r[1];(s===void 0||!nee.test(s))&&ye(`bb memory ${n} from station names the memory by its id, mem_\u2026, right after the command`),t.memoryRecord||ye("changing a memory from station needs the gate's memory lookup"),await t.memoryRecord(s,"global",o)!==null&&ye(`${s} names a global memory, which is the owner's; station changes only its own project's memories`);let a=await t.memoryRecord(s,"project",o);(a===null||a.id!==s||a.scope!=="project"||a.projectId!==o)&&ye(`memory ${s} isn't in this project; station changes only its own project's memories`)}i(cO,"checkMemoryCommand");function aee(e){let{protected:t,...r}=e.station;return{...e,station:r}}i(aee,"own");function Bm(e){return(!e||typeof e!="object"||Array.isArray(e))&&ye("a protected request needs an object"),e}i(Bm,"bodyObject");function lO(e){let t=e.protected;(!t||!["front","canary"].includes(t.role)||t.threadId!==null&&!/^thr_[a-z0-9]+$/.test(t.threadId))&&ye("protected conversation selection unavailable"),e.sharedProjectIds?.size&&ye("a private project cannot have shared sources");let r=new Set([e.hostId]);(!/^host_[a-z0-9]+$/.test(e.hostId)||t.jobs.length>20)&&ye("protected job destinations unavailable");for(let n of t.jobs)(!/^host_[a-z0-9]+$/.test(n.hostId)||r.has(n.hostId)||"protected"in n)&&ye("protected job destinations unavailable"),r.add(n.hostId),[...n.projectIds,...n.sharedProjectIds??[]].some(o=>e.projectIds.has(o))&&ye("private project is also a job destination");return t.jobs}i(lO,"profileStations");async function z2(e,t){let r=lO(t.station),n=t.station.protected,o=aee(t),s=dO(e.path),{method:a,path:c,body:l}=e;if(a==="GET"&&["/health","/install/version","/install/bb-app.tgz","/install.sh"].includes(c))return{gateAuth:!1};if(s[0]==="internal"){let d=new Set(["/internal/hosts/enroll","/internal/session/open","/internal/session/events","/internal/session/interactive-request","/internal/session/interactive-request/interrupt","/internal/session/tool-call"]),u=/^\/internal\/plugins\/(provider-claude-code|provider-codex)\/host\/[a-f0-9]{64}$/.test(c),f=/^\/internal\/skills\/tree\/[a-zA-Z0-9_.-]+$/.test(c),p=c==="/internal/ws"||c==="/internal/session/project-attachment-content"||u||f;if(a==="POST"&&d.has(c)||a==="GET"&&p||ye("internal route is not part of the protected runtime"),a==="POST"){let h=Bm(l);h.hostId!==void 0&&h.hostId!==t.station.hostId&&ye("another daemon identity")}if(c==="/internal/session/project-attachment-content"){let h=new URLSearchParams(e.search);(h.getAll("threadId").length!==1||!n.threadId||h.get("threadId")!==n.threadId||h.getAll("projectId").length!==1||!t.station.projectIds.has(h.get("projectId")))&&ye("another conversation's attachment")}if(c==="/internal/session/tool-call"){let h=Bm(l);(!n.threadId||h.threadId!==n.threadId)&&ye("only the selected protected conversation calls tools"),t.agentTools.has(h.tool)&&ye("the protected workspace is fixed by the server")}return ho(e,o)}if((s[0]!=="api"||s[1]!=="v1")&&ye("not part of the protected conversation API"),s[2]==="threads"&&s.length===3&&a==="POST"){let d=Bm(l),u=Bm(d.environment),f=r.find(h=>h.hostId===u.hostId);(!f||u.type!=="host")&&ye("work needs an explicit existing job machine"),(!n.threadId||d.parentThreadId!==n.threadId)&&ye("work needs the selected conversation as parent"),d.lifecycleOwnerThreadId!==void 0&&d.lifecycleOwnerThreadId!==n.threadId&&ye("another lifecycle owner"),d.senderThreadId!==void 0&&d.senderThreadId!==n.threadId&&ye("only the selected conversation sends work");let p={...d};return delete p.parentThreadId,delete p.lifecycleOwnerThreadId,delete p.senderThreadId,ho({...e,body:p},{...t,station:f})}if(s[2]==="threads"&&s[3]&&ui.test(s[3])){let d=s[3];if(d===n.threadId)return a!=="GET"&&ye("the protected conversation is controlled by the server"),ho(e,o);let u=await t.threadHost(d),f=r.find(p=>p.hostId===u);return f||ye("thread is outside the protected conversation's job destinations"),ho(e,{...t,station:f})}if(s[2]==="plugins"&&s[4]==="cli"&&s.length===5&&a==="POST")return(!n.threadId||Bm(l).threadId!==n.threadId)&&ye("a protected plugin command names the selected conversation"),ho(e,o);if(a==="GET"&&s.length===3&&["threads","threads/running","projects","environments","queued-messages"].includes(s[2]))return ho(e,o);if(a==="GET"&&c==="/api/v1/threads/running")return ho(e,o);if(a==="GET"&&s[2]==="projects"&&s[3]){let d=r.find(u=>u.projectIds.has(s[3]));if(d)return ho(e,{...t,station:d})}if((a==="GET"||a==="POST"&&s.length===5&&s[4]==="cleanup")&&s[2]==="environments"&&s[3]){let d=await t.environmentHost(s[3]),u=r.find(f=>f.hostId===d);if(u)return ho(e,{...t,station:u})}if(a==="GET"&&uO.has(s.slice(2).join("/")))return ho(e,o);ye("route is not open to the protected conversation")}i(z2,"protectedDecision");async function kk(e,t,r){if("protected"in r.station)return cee(e,t,r);Array.isArray(t)||ye(`bb answered ${e} with something other than a list`);let n=i(s=>s!==null&&typeof s=="object"?s:{},"record"),o=i(s=>{let a=n(s),c=n(a.environment);return(a.environmentHostId??c.hostId)===r.station.hostId},"onStation");switch(e){case"threads":return t.filter(o);case"threads/running":case"environments":return t.filter(s=>n(s).hostId===r.station.hostId);case"projects":return t.filter(s=>r.station.projectIds.has(n(s).id)).map(s=>{let a=n(s);return Array.isArray(a.threads)?{...a,threads:a.threads.filter(o)}:a});case"queued-messages":{let s=[];for(let a of t){let c=n(a).threadId;typeof c=="string"&&ui.test(c)&&await r.threadHost(c)===r.station.hostId&&s.push(a)}return s}}}i(kk,"filterList");async function cee(e,t,r){let n=lO(r.station),o=r.station.protected,{protected:s,...a}=r.station,c=i(u=>u!==null&&typeof u=="object"?u:{},"record"),l=[];for(let u of[a,...n]){let f=await kk(e,t,{...r,station:u}),p=u.hostId===a.hostId;for(let h of f){let y=c(h);p&&["threads","threads/running","queued-messages"].includes(e)&&(y.threadId??y.id)!==o.threadId||p&&e==="environments"||(e==="projects"&&Array.isArray(y.threads)&&p?l.push({...y,threads:y.threads.filter(m=>c(m).id===o.threadId)}):l.push(h))}}let d=new Set;return l.filter(u=>{let f=c(u).id;return typeof f!="string"?!0:d.has(f)?!1:(d.add(f),!0)})}i(cee,"protectedList");var ui=/^([a-z]+)_[a-z0-9]+$/,Le=class extends Error{static{i(this,"Deny")}};function ye(e){throw new Le(e)}i(ye,"deny");function dO(e){e.startsWith("/")||ye("not an origin-form path"),/^[A-Za-z0-9\-._~!$&'()*+,;=:@%/]+$/.test(e)||ye("characters outside a URL path");let t=e.slice(1).split("/"),r=!1;return t.forEach((n,o)=>{(n===""||n==="."||n===".."||/%(2e|2f|5c)/i.test(n))&&ye(`unroutable path segment ${JSON.stringify(n)}`),!r&&n.includes("%")&&ye(`escaped route segment ${JSON.stringify(n)}`),o>=2&&(n==="files"||n==="host-files")&&(r=!0)}),t}i(dO,"segments");function lee(e){let t=new Map;for(let[r,n]of new URLSearchParams(e))t.has(r)&&ye(`duplicate query parameter ${r}`),t.set(r,n);return t}i(lee,"queryOf");var uO=new Set(["hosts","thread-sections","plugins","plugins/contributions","system/config","system/version","system/execution-options","system/providers","system/providers/state","system/providers/catalog","system/machine-providers","system/environment-providers"]),dee=new Set(["threads","threads/running","projects","environments","queued-messages"]),uee=new Set(["projectId","providerId","origin","lifecycleOwnerThreadId","visibility","title","input","model","serviceTier","reasoningLevel","permissionMode","executionInputSources","environment","parentThreadId","sectionId","pinned","sourceThreadId","sourceSeqEnd","startedOnBehalfOf","originKind","sendAt","senderThreadId","parentNotifications"]),pee=new Set(["sourceThreadId","sourceSeqEnd","input","agentContextSeed","title","permissionMode","visibility","environment","origin","lifecycleOwnerThreadId"]),fee=new Set(["cols","rows","start","target","title"]),hee=new Set(["hostId","path","rootPath","content","contentEncoding","createParents","expectedSha256","mode","query","limit","includeHidden","excludeNames","includeFiles","includeDirectories","recursive","sourcePath","destinationPath"]),mee=new Set(["read","write","list","paths","mkdir","move","remove"]),gee=new Set(["argv","cwd","threadId","projectId"]);function Is(e,t){return(e===null||typeof e!="object"||Array.isArray(e))&&ye(`${t} needs a JSON object`),e}i(Is,"objectBody");function Os(e,t,r){for(let n of Object.keys(e))t.has(n)||ye(`${r}: unknown field ${n}`)}i(Os,"onlyFields");async function Um(e,t){return"protected"in t.station?z2(e,t):ho(e,t)}i(Um,"decide");async function ho(e,t){let{method:r,path:n,search:o="",body:s}=e,a=dO(n);if(a[0]==="internal"){let f=a.slice(1).join("/");return f==="hosts/enroll-key"&&ye("enrollment keys are minted on the server's machine only"),f.startsWith("server-move")&&ye("server moves are the server machine's business"),f==="session/tool-call"&&await wee(s,t),{gateAuth:!1}}if(r==="GET"&&(n==="/health"||n==="/install.sh"||n==="/install/version"||n==="/install/bb-app.tgz"))return{gateAuth:!1};a[0]==="ws"&&a[1]==="terminals"&&a.length===3&&ye("terminal sockets bypass station credential isolation; use local station tools"),(a[0]!=="api"||a[1]!=="v1")&&ye("not part of bb's API");let l=r==="POST"&&a[2]==="plugins"&&a[4]==="cli"&&a.length===5&&t.pluginCommands?.has(a[3])&&s&&typeof s=="object"&&!Array.isArray(s)?{...s,argv:[]}:s,d=r==="POST"&&a.length===3&&a[2]==="threads";await bee(l,t,d);let u=await yee(r,a.slice(2),lee(o),s,t);return u?{gateAuth:!0,filter:u}:{gateAuth:!0}}i(ho,"regularDecision");async function yee(e,t,r,n,o){let[s,a,...c]=t,l=c.join("/");if(e==="GET"&&(s==="hosts"&&c[0]==="files"||s==="threads"&&(c[0]==="host-files"||c[0]==="thread-storage"&&c[1]==="files"&&c.length>2)||s==="environments"&&c[0]==="files"||s==="projects"&&(c[0]==="files"&&c.length>1||c[0]==="hosts"&&c[2]==="files"))&&ye("raw daemon file reads bypass station credential isolation; use local station tools or the bounded job reader"),s==="environments"&&["status","diff","paths","actions","revisions"].includes(c[0]??"")&&ye("daemon repository operations can execute repository-controlled programs; use local sandboxed Git"),s==="threads"&&c[0]==="interactions"&&c.length>=3&&["respond","resolve","cancel"].includes(c[2])&&ye("only the user answers interactions"),s==="threads"&&a&&ui.test(a)&&(e==="POST"&&l==="archive-all"||e==="DELETE"&&l===""))return await Ho(a,o),G2({thread:a},o);if(s==="environments"&&a&&ui.test(a)&&(e==="POST"&&(l==="archive-threads"||l==="cleanup")||e==="DELETE"&&l===""))return await hp(a,o),G2({environment:a},o);if(s==="threads"&&a&&ui.test(a))return Ho(a,o);if(s==="environments"&&a&&ui.test(a))return hp(a,o);if(s==="terminals"&&a&&ui.test(a)){await V2(a,o),e==="POST"&&["input","restart"].includes(l)&&ye("host terminal execution bypasses station credential isolation; use local station tools");return}if(s==="hosts"&&a){if(a!==o.station.hostId&&ye("another machine"),e==="GET"||e==="POST"&&l==="paths/exist")return;ye("machine management")}if(s==="projects"&&a){if(fp(a,o),c[0]==="hosts"&&c[1]!==o.station.hostId&&ye("another machine"),e==="GET"&&l!=="machine-environment"&&l!=="prompt-history")return;e==="POST"&&(l==="attachments"||l==="attachments/copy")&&ye("daemon attachment file input bypasses station credential isolation"),ye("changing the project")}let d=t.join("/");if(!(e==="GET"&&uO.has(d))){if(e==="GET"&&dee.has(d))return d;if(e==="GET"&&d==="terminals"){if(r.get("hostId")===o.station.hostId)return;let u=r.get("threadId");if(u!==void 0)return Ho(u,o);let f=r.get("environmentId");if(f!==void 0)return hp(f,o);ye("terminals on another machine")}if(e==="POST"&&d==="threads")return Eee(n,o);if(e==="POST"&&d==="threads/fork"){let u=Is(n,"a fork");Os(u,pee,"a fork"),u.sourceThreadId===void 0&&ye("a fork needs its source"),await Ho(u.sourceThreadId,o),u.origin==="plugin"&&ye("plugin-origin threads"),u.environment!==void 0&&await K2(u.environment,o);let f=await o.threadProvider(qm(u.sourceThreadId,"thread"));(f===null||!_k.includes(f))&&ye(`a fork of a thread on ${f??"an unknown provider"}: station's threads run on ${_k.join(" or ")}`),X2(f,u.permissionMode,!0);return}if(!(e==="POST"&&d==="threads/resolve-mentions")){if(e==="POST"&&d==="terminals"){let u=Is(n,"a terminal");Os(u,fee,"a terminal"),await See(u.target,o),ye("host terminal execution bypasses station credential isolation; use local station tools")}if(e==="POST"&&s==="files"&&t.length===2&&mee.has(a)){let u=Is(n,"a file operation");Os(u,hee,"a file operation"),u.hostId!==o.station.hostId&&ye("files on another machine (no hostId means the server's)"),ye("host file operations bypass station credential isolation; use local station tools or the bounded job reader")}if(e==="POST"&&s==="plugins"&&t.length===3&&c[0]==="cli"){let u=Is(n,"a plugin command");if(Os(u,gee,"a plugin command"),a===Mm)return cO(u,o);if(o.pluginClis.has(a))return;let f=o.pluginArgv?.get(a);if(f){let m=u.argv;return(!Array.isArray(m)||!m.every(g=>typeof g=="string"))&&ye("a plugin command's argv must be words"),f(m)}let p=o.pluginCommands?.get(a);p||ye(`the ${a} plugin's CLI isn't allowed on station`),(typeof u.threadId!="string"||!u.threadId)&&ye("a plugin command from station names its thread");let h=u.argv;(!Array.isArray(h)||!h.every(m=>typeof m=="string"))&&ye("a plugin command's argv must be words");let y=h;a==="orbit"&&(y[0]==="userland"&&(y[1]==="kind"||y[1]==="purge")&&ye("Switching a whole userland kind and purging an artifact are the owner's, in Settings or with bb outside a station."),W2(y)),!p.has(y.slice(0,2).join(" "))&&!p.has(y[0]??"")&&ye(`only ${[...p].map(m=>`\`${a} ${m}\``).join(", ")} of the ${a} plugin's CLI are open to station`);return}ye(`${e} /${d} isn't open to station`)}}}i(yee,"apiRoute");async function wee(e,t){let r=e??{},n=r.tool;if(typeof n!="string"&&ye(`agent tool ${String(n)} isn't allowed on station`),n===tO&&ye(rO),t.agentTools.has(n)){await Ho(r.threadId,t);return}let o=t.stationTools?.get(n);if(o)return typeof r.threadId!="string"&&ye(`${n} is called by one of station's threads`),await Ho(r.threadId,t),o(r.arguments);ye(`agent tool ${n} isn't allowed on station`)}i(wee,"toolCall");var vee=new Set(["type","kind","mode"]);async function bee(e,t,r=!1){let n=[],o,s=i((a,c,l)=>{if(c>64&&ye("a body nested too deeply"),typeof a=="string"){if(l!==void 0&&vee.has(l))return;r&&c===1&&l==="projectId"?o=a:ui.test(a)&&n.push(a)}else if(Array.isArray(a))for(let d of a)s(d,c+1);else if(a!==null&&typeof a=="object")for(let[d,u]of Object.entries(a))(d==="pluginSubmission"||d==="pluginMetadata"||d==="originPluginId")&&ye(`plugin data (${d})`),s(u,c+1,d)},"walk");s(e,0),o!==void 0&&fp(o,t,!0);for(let a of new Set(n)){let c=ui.exec(a)[1];c==="thr"?await Ho(a,t):c==="env"?await hp(a,t):c==="term"?await V2(a,t):c==="host"&&a!==t.station.hostId?ye(`machine ${a} isn't station`):c==="proj"?fp(a,t):c==="src"&&ye("project sources")}}i(bee,"references");function qm(e,t){return(typeof e!="string"||!ui.test(e))&&ye(`bad ${t} id`),e}i(qm,"checkedId");async function G2(e,t){t.archive||ye("archiving from station needs the unpushed work check");try{await t.archive(e)}catch(r){if(r instanceof Le)throw r;ye(r.message)}}i(G2,"checkArchive");async function Ho(e,t){let r=qm(e,"thread");await t.threadHost(r)!==t.station.hostId&&ye(`thread ${r} isn't on station`)}i(Ho,"ownThread");async function hp(e,t){let r=qm(e,"environment");await t.environmentHost(r)!==t.station.hostId&&ye(`environment ${r} isn't on station`)}i(hp,"ownEnvironment");async function V2(e,t){let r=qm(e,"terminal");await t.terminalHost(r)!==t.station.hostId&&ye(`terminal ${r} isn't on station`)}i(V2,"ownTerminal");function fp(e,t,r=!1){let n=qm(e,"project");t.station.projectIds.has(n)||r&&t.station.sharedProjectIds?.has(n)||ye(`project ${n} isn't station's`)}i(fp,"ownProject");var pO="orbit-job-folder",eO=/^[a-z][a-z0-9-]*:[a-z0-9][a-z0-9_./:#-]{0,254}$/i,kee=/^ORB-[1-9][0-9]{0,8}$/;async function K2(e,t,r=!1){let n=Is(e,"an environment");switch(n.type){case"provider":{if(!r)break;Os(n,new Set(["type","environmentProviderId","machine","inputs"]),"an environment"),n.environmentProviderId!==pO&&ye(`environment provider ${String(n.environmentProviderId)} isn't open to station`);let o=Is(n.machine,"a machine");if(Os(o,new Set(["type","hostId"]),"a machine"),(o.type!=="existing"||o.hostId!==t.station.hostId)&&ye("a work folder on another machine"),n.inputs!==void 0){let s=Is(n.inputs,"the inputs");Object.keys(s).some(a=>!["key","adopt","class","loop"].includes(a))&&ye("a work folder's inputs are the plugin's, except the work key, its class and its loop"),s.class!==void 0&&!["promised","repair","background"].includes(s.class)&&ye("a start's class is promised, repair or background"),s.loop!==void 0&&(typeof s.loop!="string"||!kee.test(s.loop))&&ye("a start's loop is an ORB task, like ORB-269"),s.key!==void 0&&(typeof s.key!="string"||!eO.test(s.key))&&ye("a work key is like orb-269:fix-1"),s.adopt!==void 0&&(typeof s.adopt!="string"||!/^\/./.test(s.adopt)||s.adopt.split("/").some(a=>a==="."||a===".."))&&ye("a checkout is an absolute path without parent steps")}return}case"host":Os(n,new Set(["type","hostId","workspace"]),"an environment"),n.hostId!==t.station.hostId&&ye("a thread on another machine (no hostId means the server's)");return;case"reuse":return Os(n,new Set(["type","environmentId"]),"an environment"),hp(n.environmentId,t);case"project-default":Os(n,new Set(["type"]),"an environment");return}ye(`environment type ${String(n.type)} isn't open to station`)}i(K2,"placement");var J2="claude-code",_k=[J2,"codex"];function X2(e,t,r){e!=="codex"||t===cc||ye(`a Codex thread with permission mode ${t===void 0?r?"left out (the fork would keep its source's, which may be from an earlier release setting)":"left out (bb would take auto)":String(t)}: station's Codex threads start with ${cc}, as in bb thread spawn --provider codex --permission-mode ${cc} (the station kernel enforces access; the release setting controls Codex approval questions)`)}i(X2,"stationPermission");function _ee(e){e===void 0&&ye(`a thread that names no provider (bb would take the project's remembered one): station's threads name one, as in bb thread spawn --provider ${J2}`),(typeof e!="string"||!_k.includes(e))&&ye(`a thread on ${String(e)}: station's threads run on ${_k.join(" or ")}`)}i(_ee,"stationProvider");async function Eee(e,t){let r=Is(e,"a thread");Os(r,uee,"a thread"),r.senderThreadId!==void 0&&await Ho(r.senderThreadId,t),_ee(r.providerId),X2(r.providerId,r.permissionMode,!1),fp(r.projectId,t,!0),r.origin==="plugin"&&ye("plugin-origin threads"),!t.station.projectIds.has(r.projectId)&&Is(r.environment,"an environment").type==="project-default"&&ye("a thread in a project with sources elsewhere is placed on station explicitly"),await K2(r.environment,t,!0)}i(Eee,"createThread");async function See(e,t){let r=Is(e,"a terminal target");switch(r.kind){case"thread":return Ho(r.threadId,t);case"environment":return hp(r.environmentId,t);case"host_path":r.hostId!==t.station.hostId&&ye("a terminal on another machine");return;default:ye("unknown terminal target")}}i(See,"terminalTarget");import{z as Nn}from"zod";import{open as Tee,rename as Aee,unlink as xee}from"node:fs/promises";import{randomUUID as Oee}from"node:crypto";import{resolve as fO}from"node:path";import{pathToFileURL as Iee}from"node:url";var Y2=new Set(["report.md","evidence.md","job.log"]);function hO(e){if(!Array.isArray(e))throw new Error("Declare outputs as a JSON list.");let t=[],r=0;for(let n of e){if(typeof n!="string"||Buffer.byteLength(n,"utf8")>4096||/[\u0000-\u001f\u007f\ud800-\udfff\\]/u.test(n)||n.split("/").some(o=>o===""||o==="."||o===".."))throw new Error("Output names must be relative file paths.");if(!Y2.has(n)&&!n.startsWith("results/")&&!n.startsWith("logs/"))throw new Error("Extra files belong under results/ or logs/.");if(!t.includes(n)){if(t.some(o=>o.startsWith(n+"/")||n.startsWith(o+"/")))throw new Error("Output names cannot contain one another.");if(!Y2.has(n)&&++r>32)throw new Error("Declare at most 32 extra output files.");t.push(n)}}return t}i(hO,"outputNames");async function $ee(e,t){let r=hO(e),n=fO(t,".orbit-outputs-"+Oee()),o=fO(t,".orbit-outputs.json"),s=await Tee(n,"wx",384);try{await s.writeFile(JSON.stringify(r)+`
|
|
840
840
|
`),await s.sync(),await s.close(),await Aee(n,o)}finally{await s.close(),await xee(n).catch(a=>{if(a.code!=="ENOENT")throw a})}return r}i($ee,"declareOutputs");if(process.argv[1]&&import.meta.url===Iee(fO(process.argv[1])).href)try{if(process.argv.length!==3)throw new Error("Usage: node declare-outputs.mjs JSON_LIST (writes in the current folder)");await $ee(JSON.parse(process.argv[2]),process.cwd())}catch(e){console.error(e.message),process.exitCode=1}var Jr=pO,Z2=i(e=>Ree("sha256").update(e).digest("hex").slice(0,32),"jobId"),Pee=Nn.array(Nn.string()).superRefine((e,t)=>{try{hO(e)}catch(r){t.addIssue({code:"custom",message:r instanceof Error?r.message:"Invalid output names."})}}).default(["report.md","evidence.md","job.log"]),Nee=Nn.string().regex(/^\/./).refine(e=>!e.split("/").some(t=>t==="."||t===".."),"Checkout paths cannot contain parent steps."),gO=Nn.object({outputs:Pee,key:Nn.string().regex(vm).optional(),adopt:Nee.optional()}).strict(),Cee=new Set(["queued","admitted","running"]);function Lee(e,t){return t.aborted?Promise.reject(t.reason):new Promise((r,n)=>{let o=i(()=>n(t.reason),"stop");t.addEventListener("abort",o,{once:!0}),e.then(s=>{t.removeEventListener("abort",o),r(s)})})}i(Lee,"settled");function mO(e,t){return t.aborted?Promise.reject(t.reason):new Promise((r,n)=>{let o=setTimeout(()=>{t.removeEventListener("abort",s),r()},e),s=i(()=>{clearTimeout(o),n(t.reason)},"stop");t.addEventListener("abort",s,{once:!0})})}i(mO,"nap");var bc=class extends Error{static{i(this,"CapacityFull")}},Q2=Nn.object({checkouts:Nn.array(Nn.object({path:Nn.string(),branches:Nn.array(Nn.object({branch:Nn.string(),commits:Nn.number().int().positive()}).strict()),detached:Nn.number().int().nonnegative(),uncommitted:Nn.number().int().nonnegative(),untracked:Nn.number().int().nonnegative(),stashes:Nn.number().int().nonnegative()}).strict())}).strict(),eU=i(e=>e?/\/job-([a-f0-9]{32})$/.exec(e)?.[1]??null:null,"jobFolderId");function tU(e,t,r){let{items:n,admission:o}=r,s=new Map;function a(d,u,f,p){let h=d.key??`thread:${u.id.toLowerCase()}`,y=n.get(h);if(y){if(y.thread===null&&y.attempt>1&&typeof u.createdAt=="number"){let g=n.history(h).find(w=>w.attempt===y.attempt)?.at;if(g!==void 0&&u.createdAt<g)throw new Error(`@thread:${u.id} is from an earlier attempt of ${h}; it doesn't take attempt ${y.attempt}'s place.`)}}else{if(d.key)throw new Error(`The start's work item ${h} is missing; start it again.`);n.claim({key:h,host:f,mode:d.adopt?"checkout":"folder",class:"asked",loop:null,source:"station"})}let m=n.bind(h,u.id);return n.bindPath(p,h),m}i(a,"itemFor");async function c(d,u,f,p,h,y,m){let g=!1;try{for(;;){let w=await o.admit(d,p,h,()=>{g=!0},m),b=o.generation();n.recordJob(u,w.job),g||p.step(f);try{return await y(w.job),o.answered(d),g&&p.step(f),w.job}catch(k){if(!(k instanceof bc))throw o.answered(d),k;g=!0,await o.refused(d,k.message,p,h,b)}}}finally{o.done(d)}}i(c,"admitted"),e.experimental_environments.register({id:Jr,displayName:"Moonlet work folder",description:"A temporary work folder. Declared results are saved before bb removes it.",icon:"Folder",requires:{},inputs:gO,policy:{retireGraceMs:3e5,pathKeys:"per-attempt",experimental_cleanupFailedBeforeRun:!0,internal_DO_NOT_USE_removeChecksWorkspaceUse:!0},async availability({host:d}){try{return await t.location(d.id),{status:"available"}}catch{return{status:"unavailable",message:"This machine cannot create Moonlet work folders."}}},async validate({host:d}){return await t.location(d.id),{action:"accept"}},async create({host:d,project:u,thread:f,pathKey:p,inputs:h,experimental_claimPath:y,signal:m,report:g}){let w=a(h,f,d.id,p);if(h.adopt){let E=h.adopt,C=i(R=>(n.get(w.key)?.state==="queued"&&(n.move(w.key,"sharing",R),o.wake()),{status:"created",path:E,ownsPath:!1,resource:{key:w.key}}),"share"),N=`${d.id}\0${u.id}\0${E}`,I=i(async()=>(await e.sdk.environments.list({hostId:d.id,path:E,limit:5})).find(R=>R.projectId===u.id&&(R.status==="ready"||R.status==="provisioning")),"here"),P=!1,_=null,O=i(()=>{},"resolveEntry"),S=i(()=>{_&&s.get(N)===_&&s.delete(N),O(!1),_=null},"letGo");for(;;){let R=s.get(N),U=R&&R.key!==w.key?n.get(R.key):null;if(R&&U&&Cee.has(U.state)){if(P||g.step(`Waiting for ${U.key}, which is taking this checkout's slot`),P=!0,!await Lee(R.reserved,m))continue;let V=await I(),z=V?.lifecycle?.phase==="teardown"||V?.lifecycle?.phase==="destroyed";if(V?.environmentProviderId===Jr&&V.status==="ready"&&!z)return C(`shares the checkout ${E} with ${U.key}, and its slot`);await mO(2e3,m);continue}let j;_={key:w.key,pathKey:p,reserved:new Promise(V=>j=V)},O=j,s.set(N,_);let F=await I().catch(V=>{throw S(),V});if(F&&S(),F&&(F.lifecycle?.phase==="teardown"||F.lifecycle?.phase==="destroyed")){P||g.step(`Waiting for the environment at ${E} to be removed`),P=!0,await mO(5e3,m);continue}if(F?.environmentProviderId===Jr&&F.status==="provisioning"){P||g.step(`Waiting for the environment being made at ${E}`),P=!0,await mO(5e3,m);continue}if(F)return C(F.environmentProviderId===Jr?`shares the environment already at ${E}, and its slot`:`runs in the environment already at ${E}, which the queue doesn't track (no slot)`);break}try{await c(w.key,p,"Taking a station slot",g,m,R=>t.reserve(d.id,R,f.id,m)),O(!0)}catch(R){throw S(),R}return{status:"created",path:E,ownsPath:!1,resource:{key:w.key}}}let b=await t.location(d.id),k=h.key===void 0?Z2(p):void 0,v=await c(w.key,p,"Creating the work folder",g,m,async E=>{if(!await y(`${b}/job-${E}`))throw new Error("The work folder could not be claimed.");await t.create(d.id,E,f.id,h.outputs,m)},k);return{status:"created",path:`${b}/job-${v}`,ownsPath:!0,resource:{key:w.key}}},async remove({hostId:d,path:u,pathKey:f,signal:p,report:h}){if(d===null)return{status:"removed"};let y=n.envOf(f);if(!y){let g=Z2(f),w=`${await t.location(d)}/job-${g}`;if(u!==null&&u!==w)throw new Error("The work folder path does not match its creation key.");return h.step("Saving declared results and removing the work folder"),await t.remove(d,g,p),{status:"removed"}}if(y.job!==null)if(y.mode==="checkout")h.step("Releasing the station slot"),await t.release(d,y.job,p);else{let g=`${await t.location(d)}/job-${y.job}`;if(u!==null&&u!==g)throw new Error("The work folder path does not match its work item.");h.step("Saving declared results and removing the work folder"),await t.remove(d,y.job,p)}for(let[g,w]of s)w.pathKey===f&&s.delete(g);let m=n.get(y.key);return m&&await r.removed(m,y.attempt),o.wake(),{status:"removed"}}});async function l(d){if(d.status!=="error"||d.environmentId===null)return;let u=await e.sdk.environments.get({environmentId:d.environmentId});!u.managed||u.environmentProviderId!==Jr||u.lifecycle.phase!=="active"||(await e.sdk.threads.events.list({threadId:d.id,types:["turn/started","thread/identity"],limit:"1"})).length>0||await e.sdk.environments.experimental_cleanup({environmentId:u.id})}i(l,"cleanup"),e.events.on("thread.failed",({thread:d})=>l(d).catch(u=>e.log.warn(`Work folder cleanup for @thread:${d.id}: ${String(u)}`)))}i(tU,"setupJobWorkspaces");var mp=$s.object({free:$s.number().int().nonnegative(),floor:$s.number().int().nonnegative(),inodes:$s.number().int().nonnegative().nullable(),inodeFloor:$s.number().int().nonnegative(),low:$s.boolean(),bytes:$s.number().int().nonnegative().nullable(),files:$s.number().int().nonnegative().nullable(),complete:$s.boolean().nullable()}).strict(),Ul=class extends Error{static{i(this,"JobMeasurementError")}stage;constructor(t,r){super(`Work folder measurement failed during ${t}.`,{cause:r}),this.stage=t}};function yO(e){if(e instanceof Ul)return`${e.stage}: ${yO(e.cause)}`;if(e instanceof $s.ZodError)return`ZodError: ${e.issues.slice(0,10).map(n=>`${n.path.length===1&&typeof n.path[0]=="string"&&Object.hasOwn(mp.shape,n.path[0])?n.path[0]:"response"}=${n.code}`).join(", ")}`;let t=[["manager-disconnected",/managing machine.*isn't connected/],["manager-unavailable",/no connected machine manages/],["timeout",/timed? out|timeout/i],["permission-denied",/permission denied/i],["disk-full",/no space left on device/i],["connection-refused",/connection refused/i]],r=[e instanceof SyntaxError?"SyntaxError":e instanceof Error?"Error":"unknown error"];if(e instanceof Error){let n=t.find(([,o])=>o.test(e.message))?.[0];n&&r.push(`reason=${n}`)}return e&&typeof e=="object"&&("exitCode"in e&&Number.isSafeInteger(e.exitCode)&&r.push(`exitCode=${e.exitCode}`),"code"in e&&typeof e.code=="string"&&["ENOENT","EACCES","EPERM","ENOSPC","ETIMEDOUT","ECONNRESET","ECONNREFUSED","EPIPE","EIO"].includes(e.code)&&r.push(`code=${e.code}`)),r.join(" ")}i(yO,"measurementDiagnostic");var Dee=i(e=>e.usage!==null,"measured"),wO=i((e,t)=>(t?e.usage?.files:e.usage?.bytes)??0,"size"),rU=i((e,t)=>e.usage===null||e.usage.complete===!1?Number.POSITIVE_INFINITY:wO(e,t),"rank"),jee=i(e=>e.free<e.floor,"bytesLow"),Ek=i(e=>!jee(e)&&e.inodes!==null&&e.inodes<e.inodeFloor,"filesOnly"),nU=new Set(["starting","active","stopping"]),vO=i(e=>(e/1e9).toFixed(1).replace(/\.0$/,""),"gb"),bO=i(e=>e.toLocaleString("en-US"),"count"),iU=i(e=>Ek(e)?`below ${bO(e.inodeFloor)} free file entries`:`below ${vO(e.floor)} GB free`,"shortage"),Mee=i(e=>Ek(e)?`${bO(e.inodes??0)} left`:`${vO(e.free)} GB left`,"left");function oU(e,t,r){let n=new AbortController;e.onDispose(()=>n.abort());let o=!1;function s(y,m,g,w){e.log.warn(`Work folder measurement failed: environment=${y.id} host=${y.hostId} folder=${m} phase=${g}; ${yO(w)}`)}i(s,"measurementFailed");async function a(y,m){e.log.warn(m),await e.storage.kv.get(y)!==m&&(await r(m),await e.storage.kv.set(y,m))}i(a,"flagOnce");async function c(y){let m=[];for(let g=0;;g+=100){let w=await e.sdk.threads.list({environmentId:y.id,archived:!1,includeHidden:!0,offset:g,limit:100});for(let b of w){let k=await e.sdk.threads.get({threadId:b.id});k&&k.environmentId===y.id&&!k.archivedAt&&m.push(k)}if(w.length<100)return m}}i(c,"threadsOf");async function l(y){let m=await e.sdk.environments.get({environmentId:y.id});return m.path===y.path&&m.hostId===y.hostId&&m.environmentProviderId===Jr&&m.lifecycle.phase==="active"}i(l,"stillActive");async function d(y){for(let{env:m,id:g}of y)try{return mp.parse(await t.measure(m.hostId,g,n.signal,{size:!1}))}catch(w){s(m,g,"fresh",w)}return null}i(d,"freshReading");async function u(y,m){await e.storage.kv.delete(`work-storage-low:${y}`);for(let{env:g,usage:w}of m){await e.storage.kv.delete(`work-storage-warning:${g.id}`),await e.storage.kv.delete(`work-storage-stopped:${g.id}`),await e.storage.kv.delete(`work-storage-cleaned:${g.id}`);let b=`work-storage-check:${g.id}`;if(w!==null){await e.storage.kv.delete(b);continue}let k=(await c(g)).slice(0,10).map(v=>`@thread:${v.id}`);await a(b,`${k.join(", ")} The station disk's free space could not be checked for this work folder. Its work keeps running; the check repeats every minute, and if the disk is low this folder is stopped first.`.trim())}}i(u,"settle");async function f(y,m){let g=`work-storage-cleaned:${y.id}`;if(await e.storage.kv.get(g)===!0)return!0;try{return await t.saveAndClean(y.hostId,m,n.signal),await e.storage.kv.set(g,!0),!0}catch(w){return e.log.warn(`Saving and cleaning stopped work failed: environment=${y.id}; ${yO(w)}`),!1}}i(f,"saveAndClean");async function p(y,m){let g=[];for(let C of m){if(C.usage===null||C.usage.low){g.push(C);continue}let N=null;try{N=mp.parse(await t.measure(C.env.hostId,C.id,n.signal))}catch(I){s(C.env,C.id,"size",I)}g.push({...C,usage:N})}let w=g.filter(Dee),b=w.find(C=>C.usage.low)??w[0];if(!b)return;let k=b.usage,v=i((C,N)=>[...C].sort((I,P)=>rU(P,N)-rU(I,N)||wO(P,N)-wO(I,N)),"largestFirst"),E=new Set;for(;;){let C=g.filter(A=>!E.has(A.env.id));if(C.length===0||n.signal.aborted)break;let N=await d([...v(C,Ek(k)),...w.filter(A=>E.has(A.env.id))]);if(N&&!N.low){await u(y,g);return}N&&(k=N);let I=Ek(k),P=v(C,I)[0];if(!P)break;let{env:_,id:O,usage:S}=P;if(E.add(_.id),!await l(_))continue;let R=`work-storage-warning:${_.id}`,U=`work-storage-stopped:${_.id}`,j=await c(_);if(!j.some(A=>nU.has(A.status))&&await e.storage.kv.get(U)!==void 0)try{await t.stopFolder(_.hostId,O,n.signal),await f(_,O);continue}catch{await e.storage.kv.delete(U)}if(!await l(_))continue;let V=j.slice(0,10).map(A=>`@thread:${A.id}`),z=!0,te=!1;try{for(let A of j){let x=await e.sdk.threads.get({threadId:A.id});if(!x||x.environmentId!==_.id||x.archivedAt)continue;await e.sdk.threads.stop({threadId:A.id});let D=await e.sdk.threads.get({threadId:A.id});if(D&&nU.has(D.status))throw new Error("Work has not confirmed that it stopped.")}await t.stopFolder(_.hostId,O,n.signal),await e.storage.kv.set(U,!0),await e.storage.kv.delete(`work-storage-cleaned:${_.id}`),te=await f(_,O)}catch{z=!1}let oe=I?S?.files:S?.bytes,J=i(A=>I?`${bO(A)} files`:`${vO(A)} GB`,"sizeText"),L=S?.complete===!0&&oe!==null&&oe!==void 0?`This was the largest work folder (${J(oe)}), so`:`This work folder's size could not be fully measured${oe?` (at least ${J(oe)})`:""}, so it counts as the largest and`,T=`${V.join(", ")} Station disk ${iU(k)} (${Mee(k)}). ${L} ${z?"its work was stopped":"its work was asked to stop, but stopping could not be confirmed"}; other work keeps running. `+(te?"A recovery copy of its source is declared as a result, and its install and build output has been removed. Its source and earlier results are kept.":z?"Its source and remaining output are kept. Saving and cleanup will be tried again.":"Its source and output are kept until stopping is confirmed."),M=await e.storage.kv.get(R);if(!z&&typeof M=="string"&&M.includes("could not be confirmed")){e.log.warn(T.trim());return}await a(R,T.trim());return}await a(`work-storage-low:${y}`,`Station disk ${iU(k)}, and the work in every work folder is already stopped. The folders are kept. Archive handled work to free disk space.`)}i(p,"relieve");async function h(){if(!(o||n.signal.aborted)){o=!0;try{let y=await e.sdk.environments.list({environmentProviderId:Jr,status:"ready",limit:100}),m=new Map;for(let g of y){if(n.signal.aborted)return;if(!g.managed||g.environmentProviderId!==Jr||g.lifecycle.phase!=="active"||!g.path)continue;let w=/\/job-([a-f0-9]{32})$/.exec(g.path)?.[1];if(!w)throw new Error("A managed work folder has an invalid path.");let b=null;try{b=mp.parse(await t.measure(g.hostId,w,n.signal))}catch(k){s(g,w,"tick",k),b=null}m.set(g.hostId,[...m.get(g.hostId)??[],{env:g,id:w,usage:b}])}for(let[g,w]of m){if(n.signal.aborted)return;if(w.some(b=>b.usage?.low)){await p(g,w);continue}await u(g,w)}}finally{o=!1}}}return i(h,"tick"),rt(e,"managed-work-storage","* * * * *",h),{tick:h}}i(oU,"setupJobWatchdog");import{createHash as Yde}from"node:crypto";import{readFileSync as Zde}from"node:fs";import{join as Qde}from"node:path";import{z as Bee}from"zod";var cU=Bee.string().refine(e=>e===""||/^(?:[1-8][0-9]|90)$/.test(e),{message:"Moonlet chat compaction must be empty or a whole percentage from 10 to 90."}),lU={type:"string",label:"Moonlet chat safety-net compaction (%)",description:"Moonlet compacts its chat at natural breaks: after ten quiet minutes once the chat holds 150,000 tokens, and at the first quiet moment of a new day once it holds 60,000. This percentage is only the far safety net for one very long turn. Defaults to 60, about 600,000 tokens with a one-million-token window. Empty uses Claude Code's usual point. Enter a whole percentage from 10 to 90. Applies at the next main chat session start.",default:"60",experimental_schema:cU};function dU(e,t,r){if(!t||t!==r)return[];let n=cU.parse(e);return n===""?[]:[{name:"CLAUDE_AUTOCOMPACT_PCT_OVERRIDE",value:n,reason:"Moonlet main chat safety-net compaction"}]}i(dU,"mainChatCompactionEnv");var Uee=10*6e4,qee=15e4,Fee=6e4,Hee=60*6e4,sU="main-chat-compaction:last";function aU(e,t){return new Intl.DateTimeFormat("en-CA",{timeZone:t,year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date(e))}i(aU,"localDay");function Wee(e){return e.quietMs<Uee||e.turnsSinceCompaction===0||e.lastCompactedAt!==null&&e.now-e.lastCompactedAt<Hee?null:e.usedTokens>=qee?"boundary":(e.lastCompactedAt===null||aU(e.lastCompactedAt,e.zone)!==aU(e.now,e.zone))&&e.usedTokens>=Fee?"new-day":null}i(Wee,"boundaryDecision");function uU(e,t){let r=t.now??Date.now,n=null,o=null,s=!1;e.events.on("thread.idle",({thread:c})=>{n?.thread!==c.id&&(n={thread:c.id,at:r()})}),e.events.on("thread.active",({thread:c})=>{n?.thread===c.id&&(n=null),t.mainThread().then(l=>{c.id===l&&(s?s=!1:o!==null&&o++)})});async function a(){let c=await t.mainThread();if(!c)return null;if((await e.sdk.threads.get({threadId:c})).status!=="idle")return n=null,null;n?.thread!==c&&(n={thread:c,at:r()});let d=(await e.sdk.threads.context({threadId:c})).usage;if(!d)return null;let u=await e.storage.kv.get(sU),f=Wee({usedTokens:d.usedTokens,quietMs:r()-n.at,now:r(),lastCompactedAt:typeof u=="number"?u:null,turnsSinceCompaction:o,zone:await t.zone()});return f?(s=!0,await e.sdk.threads.compact({threadId:c}),o=0,await e.storage.kv.set(sU,r()),e.log.info(`Moonlet chat compacted at a ${f==="boundary"?"quiet break":"new day"} with ${d.usedTokens} tokens in context.`),f):null}return i(a,"tick"),rt(e,"main-chat-compaction","* * * * *",a),{tick:a}}i(uU,"setupBoundaryCompaction");Ts();import{existsSync as Ude}from"node:fs";import{homedir as qde}from"node:os";import{join as Fde}from"node:path";sc();br();var zee="tag:orbit",Gee="2596A99EAAB33821893C0A79458CA832957F5868";function pU(e){return e==="linux"?"/usr/bin/tailscale":"/opt/homebrew/bin/tailscale"}i(pU,"tailscale");var Vee=`if ! command -v tailscale >/dev/null; then
|
|
841
841
|
. /etc/os-release
|
|
842
842
|
case "$ID" in ubuntu|debian) ;; *) echo "the Tailscale integration supports Debian and Ubuntu, not $ID" >&2; exit 1 ;; esac
|