@halcyonlabs/app 0.47.0-halcyon.518 → 0.47.0-halcyon.520

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 CHANGED
@@ -524,8 +524,8 @@ declare const environmentSchema: z$1.ZodObject<{
524
524
  retireAt: z$1.ZodNullable<z$1.ZodNumber>;
525
525
  teardown: z$1.ZodNullable<z$1.ZodObject<{
526
526
  status: z$1.ZodEnum<{
527
- running: "running";
528
527
  failed: "failed";
528
+ running: "running";
529
529
  removed: "removed";
530
530
  }>;
531
531
  attempt: z$1.ZodNumber;
@@ -620,8 +620,8 @@ declare const hostSchema: z$1.ZodObject<{
620
620
  pendingLog: z$1.ZodString;
621
621
  teardown: z$1.ZodNullable<z$1.ZodObject<{
622
622
  status: z$1.ZodEnum<{
623
- running: "running";
624
623
  failed: "failed";
624
+ running: "running";
625
625
  removed: "removed";
626
626
  }>;
627
627
  attempt: z$1.ZodNumber;
@@ -732,8 +732,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
732
732
  providerThreadId: z$1.ZodString;
733
733
  objective: z$1.ZodString;
734
734
  status: z$1.ZodEnum<{
735
- paused: "paused";
736
735
  active: "active";
736
+ paused: "paused";
737
737
  budgetLimited: "budgetLimited";
738
738
  complete: "complete";
739
739
  }>;
@@ -1304,9 +1304,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
1304
1304
  step: z$1.ZodString;
1305
1305
  status: z$1.ZodOptional<z$1.ZodEnum<{
1306
1306
  pending: "pending";
1307
+ active: "active";
1307
1308
  completed: "completed";
1308
1309
  failed: "failed";
1309
- active: "active";
1310
1310
  }>>;
1311
1311
  }, z$1.core.$strip>>;
1312
1312
  explanation: z$1.ZodOptional<z$1.ZodString>;
@@ -1385,10 +1385,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
1385
1385
  }>;
1386
1386
  taskStatus: z$1.ZodEnum<{
1387
1387
  pending: "pending";
1388
- running: "running";
1389
- paused: "paused";
1390
1388
  completed: "completed";
1391
1389
  failed: "failed";
1390
+ paused: "paused";
1391
+ running: "running";
1392
1392
  killed: "killed";
1393
1393
  stopped: "stopped";
1394
1394
  }>;
@@ -1405,8 +1405,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
1405
1405
  index: z$1.ZodNumber;
1406
1406
  label: z$1.ZodString;
1407
1407
  state: z$1.ZodEnum<{
1408
- running: "running";
1409
1408
  failed: "failed";
1409
+ running: "running";
1410
1410
  queued: "queued";
1411
1411
  done: "done";
1412
1412
  skipped: "skipped";
@@ -2076,9 +2076,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2076
2076
  step: z$1.ZodString;
2077
2077
  status: z$1.ZodOptional<z$1.ZodEnum<{
2078
2078
  pending: "pending";
2079
+ active: "active";
2079
2080
  completed: "completed";
2080
2081
  failed: "failed";
2081
- active: "active";
2082
2082
  }>>;
2083
2083
  }, z$1.core.$strip>>;
2084
2084
  explanation: z$1.ZodOptional<z$1.ZodString>;
@@ -2157,10 +2157,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2157
2157
  }>;
2158
2158
  taskStatus: z$1.ZodEnum<{
2159
2159
  pending: "pending";
2160
- running: "running";
2161
- paused: "paused";
2162
2160
  completed: "completed";
2163
2161
  failed: "failed";
2162
+ paused: "paused";
2163
+ running: "running";
2164
2164
  killed: "killed";
2165
2165
  stopped: "stopped";
2166
2166
  }>;
@@ -2177,8 +2177,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2177
2177
  index: z$1.ZodNumber;
2178
2178
  label: z$1.ZodString;
2179
2179
  state: z$1.ZodEnum<{
2180
- running: "running";
2181
2180
  failed: "failed";
2181
+ running: "running";
2182
2182
  queued: "queued";
2183
2183
  done: "done";
2184
2184
  skipped: "skipped";
@@ -2389,10 +2389,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2389
2389
  }>;
2390
2390
  taskStatus: z$1.ZodEnum<{
2391
2391
  pending: "pending";
2392
- running: "running";
2393
- paused: "paused";
2394
2392
  completed: "completed";
2395
2393
  failed: "failed";
2394
+ paused: "paused";
2395
+ running: "running";
2396
2396
  killed: "killed";
2397
2397
  stopped: "stopped";
2398
2398
  }>;
@@ -2409,8 +2409,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2409
2409
  index: z$1.ZodNumber;
2410
2410
  label: z$1.ZodString;
2411
2411
  state: z$1.ZodEnum<{
2412
- running: "running";
2413
2412
  failed: "failed";
2413
+ running: "running";
2414
2414
  queued: "queued";
2415
2415
  done: "done";
2416
2416
  skipped: "skipped";
@@ -2488,10 +2488,10 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2488
2488
  }>;
2489
2489
  taskStatus: z$1.ZodEnum<{
2490
2490
  pending: "pending";
2491
- running: "running";
2492
- paused: "paused";
2493
2491
  completed: "completed";
2494
2492
  failed: "failed";
2493
+ paused: "paused";
2494
+ running: "running";
2495
2495
  killed: "killed";
2496
2496
  stopped: "stopped";
2497
2497
  }>;
@@ -2508,8 +2508,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2508
2508
  index: z$1.ZodNumber;
2509
2509
  label: z$1.ZodString;
2510
2510
  state: z$1.ZodEnum<{
2511
- running: "running";
2512
2511
  failed: "failed";
2512
+ running: "running";
2513
2513
  queued: "queued";
2514
2514
  done: "done";
2515
2515
  skipped: "skipped";
@@ -2704,9 +2704,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2704
2704
  step: z$1.ZodString;
2705
2705
  status: z$1.ZodOptional<z$1.ZodEnum<{
2706
2706
  pending: "pending";
2707
+ active: "active";
2707
2708
  completed: "completed";
2708
2709
  failed: "failed";
2709
- active: "active";
2710
2710
  }>>;
2711
2711
  }, z$1.core.$strip>>;
2712
2712
  explanation: z$1.ZodOptional<z$1.ZodString>;
@@ -2715,8 +2715,8 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
2715
2715
  threadId: z$1.ZodString;
2716
2716
  providerThreadId: z$1.ZodString;
2717
2717
  state: z$1.ZodEnum<{
2718
- running: "running";
2719
2718
  idle: "idle";
2719
+ running: "running";
2720
2720
  }>;
2721
2721
  }, z$1.core.$strip>, z$1.ZodObject<{
2722
2722
  type: z$1.ZodLiteral<"turn/diff/updated">;
@@ -3578,9 +3578,9 @@ declare const threadEventSchema: z$1.ZodUnion<readonly [z$1.ZodIntersection<z$1.
3578
3578
  threadId: z$1.ZodString;
3579
3579
  provisioningId: z$1.ZodString;
3580
3580
  status: z$1.ZodEnum<{
3581
+ active: "active";
3581
3582
  completed: "completed";
3582
3583
  failed: "failed";
3583
- active: "active";
3584
3584
  cancelled: "cancelled";
3585
3585
  }>;
3586
3586
  environmentId: z$1.ZodNullable<z$1.ZodString>;
@@ -6131,8 +6131,8 @@ declare const hostDaemonCommandRegistry: {
6131
6131
  skillFilePath: z$1.ZodString;
6132
6132
  }, z$1.core.$strict>], "kind">>;
6133
6133
  instructionMode: z$1.ZodEnum<{
6134
- replace: "replace";
6135
6134
  append: "append";
6135
+ replace: "replace";
6136
6136
  }>;
6137
6137
  type: z$1.ZodLiteral<"thread.rewind.prepare">;
6138
6138
  leaseId: z$1.ZodString;
@@ -6280,8 +6280,8 @@ declare const hostDaemonCommandRegistry: {
6280
6280
  skillFilePath: z$1.ZodString;
6281
6281
  }, z$1.core.$strict>], "kind">>;
6282
6282
  instructionMode: z$1.ZodEnum<{
6283
- replace: "replace";
6284
6283
  append: "append";
6284
+ replace: "replace";
6285
6285
  }>;
6286
6286
  type: z$1.ZodLiteral<"thread.start">;
6287
6287
  requestId: z$1.ZodString;
@@ -6744,8 +6744,8 @@ declare const hostDaemonCommandRegistry: {
6744
6744
  envPassthrough: z$1.ZodArray<z$1.ZodString>;
6745
6745
  }, z$1.core.$strict>;
6746
6746
  instructionMode: z$1.ZodEnum<{
6747
- replace: "replace";
6748
6747
  append: "append";
6748
+ replace: "replace";
6749
6749
  }>;
6750
6750
  projectId: z$1.ZodString;
6751
6751
  providerId: z$1.ZodString;
@@ -6960,8 +6960,8 @@ declare const hostDaemonCommandRegistry: {
6960
6960
  envPassthrough: z$1.ZodArray<z$1.ZodString>;
6961
6961
  }, z$1.core.$strict>;
6962
6962
  instructionMode: z$1.ZodEnum<{
6963
- replace: "replace";
6964
6963
  append: "append";
6964
+ replace: "replace";
6965
6965
  }>;
6966
6966
  projectId: z$1.ZodString;
6967
6967
  providerId: z$1.ZodString;
@@ -8185,9 +8185,9 @@ declare const hostDaemonCommandRegistry: {
8185
8185
  executablePath: z$1.ZodNullable<z$1.ZodString>;
8186
8186
  installed: z$1.ZodBoolean;
8187
8187
  installSource: z$1.ZodEnum<{
8188
+ external: "external";
8188
8189
  notInstalled: "notInstalled";
8189
8190
  npmGlobal: "npmGlobal";
8190
- external: "external";
8191
8191
  }>;
8192
8192
  currentVersion: z$1.ZodNullable<z$1.ZodString>;
8193
8193
  latestVersion: z$1.ZodNullable<z$1.ZodString>;
@@ -8736,9 +8736,9 @@ declare const providerCliStatusResponseSchema: z$1.ZodRecord<z$1.ZodString, z$1.
8736
8736
  executablePath: z$1.ZodNullable<z$1.ZodString>;
8737
8737
  installed: z$1.ZodBoolean;
8738
8738
  installSource: z$1.ZodEnum<{
8739
+ external: "external";
8739
8740
  notInstalled: "notInstalled";
8740
8741
  npmGlobal: "npmGlobal";
8741
- external: "external";
8742
8742
  }>;
8743
8743
  currentVersion: z$1.ZodNullable<z$1.ZodString>;
8744
8744
  latestVersion: z$1.ZodNullable<z$1.ZodString>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@halcyonlabs/app",
3
- "version": "0.47.0-halcyon.518",
3
+ "version": "0.47.0-halcyon.520",
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": "Report the last station delivery stage in status (#539)"
108
+ "summary": "fix(moonlet): retain the pending task cutover reason (#550)"
109
109
  },
110
110
  "license": "SEE LICENSE IN LICENSE"
111
111
  }
@@ -1,12 +1,12 @@
1
1
  {
2
- "commit": "3872726cf58a1cc1a2f13a42aae1011b936dd160",
2
+ "commit": "69a64586e70a3d7c19063f20637ab7e13b41fde2",
3
3
  "file": "orbit-deploy",
4
4
  "platform": "linux-x64",
5
5
  "provenance": {
6
- "artifactId": 15056104870,
7
- "artifactName": "linux-bundle-3872726cf58a1cc1a2f13a42aae1011b936dd160",
6
+ "artifactId": 15059335165,
7
+ "artifactName": "linux-bundle-69a64586e70a3d7c19063f20637ab7e13b41fde2",
8
8
  "repository": "matt0x6F/personalassistant",
9
- "runId": 45683592470,
9
+ "runId": 45684310125,
10
10
  "workflow": ".github/workflows/moonlet-linux-bundle.yml"
11
11
  },
12
12
  "schema": 1,
@@ -1 +1 @@
1
- 3872726cf58a1cc1a2f13a42aae1011b936dd160
1
+ 69a64586e70a3d7c19063f20637ab7e13b41fde2
@@ -1 +1 @@
1
- {"repository":"matt0x6F/personalassistant","revision":"3872726cf58a1cc1a2f13a42aae1011b936dd160"}
1
+ {"repository":"matt0x6F/personalassistant","revision":"69a64586e70a3d7c19063f20637ab7e13b41fde2"}
@@ -1800,7 +1800,7 @@ else:
1800
1800
  print('task-index-retired')
1801
1801
  ORBIT_RETIRE_INDEX`}i(I7,"retireLoopIndex");var $7="loop-index-retired",N7="loop-index-cutover-imported",Hke="loop-index-archive",Wke="personal-loop-aliases",zke=["personal-loops-migrated","personal-loops-high-water","personal-loops-changes"],Gke="personal-task-change:",P7="personal-loops-failure-day",C7=2e4,L7=/^thr_[A-Za-z0-9_-]+$/,Vke=/\bsch_[a-f0-9]{10}\b/g,Kke={owner:"owner",assistant:"assistant",others:"waiting"},Xke=pM.record(pM.string(),pM.string().regex($g)).catch({}),Yke=i(e=>({kind:"conversation",ref:e,label:null}),"conversation"),Jke=i(e=>({kind:"schedule",ref:e,label:null}),"schedule");function Zke(e){let t=[],r=0;for(;r!==null;){let n=e.list({status:"open",limit:500,offset:r});t.push(...n.tasks),r=n.next}return t.sort((n,o)=>o.createdAt-n.createdAt||n.key.localeCompare(o.key))}i(Zke,"openTasks");function Qke(e,t){return e.when?.form==="due"&&e.when.time===null?e.when.date:e.dueAt===null?null:`${tn(e.dueAt,t)} ${ls(e.dueAt,t)} ${t}`}i(Qke,"nextCheck");function e_e(e){return e.move==="others"?`waiting on ${e.waitingOn??"someone else"}`:e.move==="owner"?"the owner's move":"the assistant's move"}i(e_e,"stateWords");function t_e(e,t,r,n){let o=t.aliases(e.id),s=o.find(l=>$g.test(l))??o.map(l=>r[l]).find(l=>l!==void 0)??e.key,a=t.links(e.id),c=Qke(e,n);return{id:s,title:e.title,task:e.key,text:[s===e.key?e.title:`${s} ${e.title}`,e.description,e.doneWhen?`Done when: ${e.doneWhen}`:"",`Status: ${e_e(e)}`,`Next check: ${c??"none"}`].filter(Boolean).join(`
1802
1802
  `),threads:a.filter(l=>l.kind==="conversation"&&L7.test(l.ref)).map(l=>l.ref),status:"open",move:e.move,waitingOn:e.waitingOn,nextCheck:c,checks:[...new Set([...e.schedule?[e.schedule]:[],...a.filter(l=>l.kind==="schedule").map(l=>l.ref)])],changedAt:e.updatedAt}}i(t_e,"entry");function r_e(e,t){return["# Open tasks","",`Generated from Moonlet tasks (read only). ${e.length} open. Read a task for its full meaning and history.`,`Next personal task: ${t}`,"",...e.map(r=>[`- ${r.task}`,Kke[r.move],r.title.replace(/\s+/g," "),...r.id!==r.task?[r.id]:[],...r.waitingOn?[`on ${r.waitingOn}`]:[],`next check: ${r.nextCheck??"none"}`].join(" \xB7 "))].join(`
1803
- `)}i(r_e,"indexText");function n_e(e,t,r,n){let o=!1;for(let s of LY(t)){let a=s.task?e.find(s.task):null;if(s.task&&!a)throw new Error(`Personal tasks: the open-loops file names ${s.task}, which isn't among the tasks; the file stays until that task is.`);let c=a??e.find(s.id),l=[...s.threads.filter(f=>L7.test(f)).map(Yke),...[...new Set([...s.text.matchAll(Vke)].map(f=>f[0]))].map(Jke)],d=FR(s.text,n);if(!c){let f=`Carried over from ${s.id} in the open-loops file`;e.adopt({aliases:[s.id],project:Ri,task:{project:Ri,title:(s.title.trim()||s.id).slice(0,300),description:i_e(s.text),origin:"assistant",why:f,links:l.slice(0,50),...d?{kind:"followup",when:d}:{}},status:"open",reason:null,createdAt:r,updatedAt:r,closedAt:null,journal:[{at:r,actor:"system",what:"created",body:f,ref:"open-loops-import"}]}),o=!0;continue}d&&c.when===null&&c.status==="open"&&(e.update(c.id,{when:d,why:`Its next check was in the open-loops file under ${s.id}`},"system"),o=!0);let u=new Set(e.links(c.id).map(f=>`${f.kind}:${f.ref}`));for(let f of l)u.has(`${f.kind}:${f.ref}`)||(e.link(c.id,f),o=!0)}return o}i(n_e,"carryOver");function D7(e,t,r,n){async function o(d){if(n)try{let u=new Date().toISOString().slice(0,10);await e.storage.kv.get(P7)!==u&&(await n(d),await e.storage.kv.set(P7,u))}catch(u){e.log.warn(`Personal task index notice: ${String(u)}`)}}i(o,"dailyNotice");async function s(d,u){try{return await u()}catch(f){throw await o(`${d} ${f instanceof Error?f.message:String(f)}`),f}}i(s,"reported");function a(){let d=Gt(e).store.nextKey(Ri);return{key:d.key,highWater:d.number-1}}i(a,"personalNext");async function c(){if(await e.storage.kv.get($7)===!0)return!0;if(!r)return!1;let d=Gt(e);if(!await d.orbMoved())return!1;let u=await t(!0),f=Fke("sha256").update(u).digest("hex");await e.storage.kv.get(N7)!==f&&(n_e(d.store,u,Date.now(),d.zone())&&e.realtime.publish("tasks",{changed:!0}),await e.storage.kv.set(N7,f));let h=await r.ready();return h!==null?(await o(`The personal task index is available; archive retirement is waiting. ${h}`),!1):(await e.storage.kv.set(Hke,x7(u)),await r.retire(f),await e.storage.kv.set($7,!0),!0)}i(c,"retireIndex"),(async()=>{for(let d of[...zke,...await e.storage.kv.list(Gke)])await e.storage.kv.delete(d)})().catch(d=>e.log.warn(`Personal tasks: old index records weren't removed: ${d instanceof Error?d.message:String(d)}`));let l=null;return{snapshot(){return s("The personal task index could not be built.",async()=>{let d=Gt(e);await d.fresh();let u=Xke.parse(await e.storage.kv.get(Wke)),f=Zke(d.store).map(p=>t_e(p,d.store,u,d.zone())),h=a();return{complete:!0,loops:f,highWater:h.highWater,markdown:r_e(f,h.key)}})},async next(){return a().key},async taskForCheck(d){return Gt(e).store.forSchedule(d)?.key??null},retireIndex(){return l??=s("The open-loops file couldn't be retired yet.",c).finally(()=>{l=null}),l}}}i(D7,"setupPersonalLoops");function i_e(e){let t=Buffer.from(e);if(t.length<=C7)return e;let r=`
1803
+ `)}i(r_e,"indexText");function n_e(e,t,r,n){let o=!1;for(let s of LY(t)){let a=s.task?e.find(s.task):null;if(s.task&&!a)throw new Error(`Personal tasks: the open-loops file names ${s.task}, which isn't among the tasks; the file stays until that task is.`);let c=a??e.find(s.id),l=[...s.threads.filter(f=>L7.test(f)).map(Yke),...[...new Set([...s.text.matchAll(Vke)].map(f=>f[0]))].map(Jke)],d=FR(s.text,n);if(!c){let f=`Carried over from ${s.id} in the open-loops file`;e.adopt({aliases:[s.id],project:Ri,task:{project:Ri,title:(s.title.trim()||s.id).slice(0,300),description:i_e(s.text),origin:"assistant",why:f,links:l.slice(0,50),...d?{kind:"followup",when:d}:{}},status:"open",reason:null,createdAt:r,updatedAt:r,closedAt:null,journal:[{at:r,actor:"system",what:"created",body:f,ref:"open-loops-import"}]}),o=!0;continue}d&&c.when===null&&c.status==="open"&&(e.update(c.id,{when:d,why:`Its next check was in the open-loops file under ${s.id}`},"system"),o=!0);let u=new Set(e.links(c.id).map(f=>`${f.kind}:${f.ref}`));for(let f of l)u.has(`${f.kind}:${f.ref}`)||(e.link(c.id,f),o=!0)}return o}i(n_e,"carryOver");function D7(e,t,r,n){async function o(d){if(n)try{let u=new Date().toISOString().slice(0,10);await e.storage.kv.get(P7)!==u&&(await n(d),await e.storage.kv.set(P7,u))}catch(u){e.log.warn(`Personal task index notice: ${String(u)}`)}}i(o,"dailyNotice");async function s(d,u){try{return await u()}catch(f){throw await o(`${d} ${f instanceof Error?f.message:String(f)}`),f}}i(s,"reported");function a(){let d=Gt(e).store.nextKey(Ri);return{key:d.key,highWater:d.number-1}}i(a,"personalNext");async function c(){if(await e.storage.kv.get($7)===!0)return null;if(!r)return"The archive retirement service is not ready.";let d=Gt(e);if(!await d.orbMoved())return"The old task board has not finished moving; the archive stays in place.";let u=await t(!0),f=Fke("sha256").update(u).digest("hex");await e.storage.kv.get(N7)!==f&&(n_e(d.store,u,Date.now(),d.zone())&&e.realtime.publish("tasks",{changed:!0}),await e.storage.kv.set(N7,f));let h=await r.ready();return h!==null?(await o(`The personal task index is available; archive retirement is waiting. ${h}`),h):(await e.storage.kv.set(Hke,x7(u)),await r.retire(f),await e.storage.kv.set($7,!0),null)}i(c,"retireIndex"),(async()=>{for(let d of[...zke,...await e.storage.kv.list(Gke)])await e.storage.kv.delete(d)})().catch(d=>e.log.warn(`Personal tasks: old index records weren't removed: ${d instanceof Error?d.message:String(d)}`));let l=null;return{snapshot(){return s("The personal task index could not be built.",async()=>{let d=Gt(e);await d.fresh();let u=Xke.parse(await e.storage.kv.get(Wke)),f=Zke(d.store).map(p=>t_e(p,d.store,u,d.zone())),h=a();return{complete:!0,loops:f,highWater:h.highWater,markdown:r_e(f,h.key)}})},async next(){return a().key},async taskForCheck(d){return Gt(e).store.forSchedule(d)?.key??null},retireIndex(){return l??=s("The open-loops file couldn't be retired yet.",c).finally(()=>{l=null}),l}}}i(D7,"setupPersonalLoops");function i_e(e){let t=Buffer.from(e);if(t.length<=C7)return e;let r=`
1804
1804
  [Archived entry shortened; full text remains in the legacy archive.]`,n=C7-Buffer.byteLength(r);for(;n>0&&((t[n]??0)&192)===128;)n--;return t.subarray(0,n).toString("utf8")+r}i(i_e,"cappedArchiveEntry");import{readFile as o_e}from"node:fs/promises";import{join as s_e}from"node:path";var fM="context-core",Ux=`guidance/${fM}`,j7="plugins/orbit/front/context-core.md";async function M7(e,t,r=()=>o_e(s_e(Bn(),"assets/orbit-guidance/starter",j7))){if(!("state"in e.show(Ux)))return;let o=Sg("Context core guidance copied from the existing hook",[{path:j7,bytes:await r()}]),s=Ag(e,t,fM,o);if(s.state!=="trial")throw new Error("The context core guidance could not be copied");let a=e.fill(t,Ux,{},s.n);if(a.state!=="ok")throw new Error(a.reason);if(a.text!==JSON.stringify(o.files))throw new Error("The context core guidance changed during its first read");let c=e.trial(t,Ux,{outcome:"pass",note:"The complete guidance read matches the captured source"});if(c.state!=="ok")throw new Error(c.reason);let l=e.activate(t,Ux,s.n);if(l.state!=="ok")throw new Error(l.reason);let d=nc(e,fM);if("state"in d||JSON.stringify(d.files)!==JSON.stringify(o.files))throw new Error("The context core guidance could not be read back unchanged")}i(M7,"prepareContextCoreGuidance");import{createHash as a_e}from"node:crypto";import{readFile as c_e}from"node:fs/promises";import{join as l_e}from"node:path";import{z as ia}from"zod";var cd="guidance/task-index",Fc=["plugins/orbit/front/CLAUDE.md","plugins/orbit/back/CLAUDE.md","orbit/docs/handoff-to-new-conversation.md"],B7=ia.object({path:ia.enum(["plugins/orbit/front/CLAUDE.md","plugins/orbit/back/CLAUDE.md","orbit/docs/handoff-to-new-conversation.md"]),before:ia.string().min(1),previous:ia.string().min(1).optional(),after:ia.string().min(1)}).strict(),U7=i(e=>new Set(e.map(t=>`${t.path}:${t.before}`)).size===e.length&&e.every(t=>t.before!==t.after&&(t.previous===void 0||t.previous!==t.before&&t.previous!==t.after)),"distinct"),d_e=ia.object({version:ia.literal(1),changes:ia.array(B7)}).strict().refine(e=>e.changes.length===4&&Fc.every(t=>e.changes.filter(r=>r.path===t).length===(t===Fc[0]?2:1))&&U7(e.changes)),u_e=ia.object({version:ia.literal(1),changes:ia.array(B7).min(1)}).strict().refine(e=>Fc.every(t=>e.changes.some(r=>r.path===t))&&U7(e.changes)),qx=[{file:"assets/orbit-guidance/migrations/task-index.json",patched:"task-index-guidance-patched",why:"Use the generated task index and preserve all unrelated guide wording",schema:d_e},{file:"assets/orbit-guidance/migrations/moonlet-tasks.json",patched:"moonlet-tasks-guidance-patched",why:"Keep tasks only in Moonlet's own task list and preserve all unrelated guide wording",schema:u_e}],o3e=[...Fc,...qx.map(e=>e.file)],q7=i(e=>e.previous===void 0?[e.before]:[e.before,e.previous],"versions");function hM(e,t,r){let n=e.slice(t+1).flatMap((o,s)=>o.filter(a=>a.path===r.path&&q7(a).includes(r.after)).map(a=>({k:t+1+s,next:a})));return[r.after,...n.flatMap(({k:o,next:s})=>hM(e,o,s))]}i(hM,"finals");function p_e(e){return e.replace(/^plugins\/orbit\//,"plugins/moonlet/").replace(/^orbit\//,"moonlet/")}i(p_e,"guideSourcePath");async function F7(e,t,r){if(!await e.storage.kv.get("task-index-owned-guidance"))return;let n=await e.storage.kv.get("task-index-guide-requested");n!==void 0&&n.version===t||await e.storage.kv.set("task-index-guide-requested",{version:t,generation:r()})}i(F7,"requestTaskIndexGuides");function H7(e,t,r,n=o=>c_e(l_e(Bn(),p_e(o)),"utf8")){let o=null,s="";async function a(){return Promise.all(qx.map(async f=>f.schema.parse(JSON.parse(await n(f.file))).changes))}i(a,"chain");async function c(){for(let f of qx)if(!await e.storage.kv.get(f.patched))return!0;return!1}i(c,"pending");function l(f,h){let p=t.show(cd,h);if(!("state"in p)&&p.artifact.active===h){let w=nc(t,"task-index");if("state"in w)throw new Error(w.reason);return}let g=t.fill(f,cd,{},h);if(g.state!=="ok")throw new Error(g.reason);let m=t.trial(f,cd,{outcome:"pass",note:"Read the complete guidance candidate through the production reader contract"});if(m.state!=="ok")throw new Error(m.reason);let y=t.activate(f,cd,h);if(y.state!=="ok")throw new Error(y.reason)}i(l,"accept");async function d(){let f=await r();if(!f)return!1;let h={role:"orbit-thread",thread:f},p=await a(),g=await e.storage.kv.get("task-index-owned-guidance");if(g&&!await c()){let E=nc(t,"task-index");if("state"in E||Fc.some(v=>!E.files.some(I=>I.path===v)))throw new Error("The effective guide set is unavailable");return!0}let m=t.show(cd);if("state"in m){let E=await Promise.all(Fc.map(async I=>({path:I,bytes:Buffer.from(await n(I))}))),v=Ag(t,h,"task-index",Sg("Effective guide capture before task index cutover",E));if(v.state!=="trial")throw new Error("The existing guide set could not be captured");l(h,v.n),m=t.show(cd)}if("state"in m)throw new Error(m.reason);let y=gd(m.body);if(!y.ok)throw new Error("The owned guide set could not be read");let w=y.body;for(let E of Fc)if(!w.files.some(v=>v.path===E))throw new Error("The complete guide set is required for task index cutover");if(!g){for(let E of w.files)if(Fc.includes(E.path)&&E.text!==await n(E.path))throw new Error("The captured guide differs from its effective source");l(h,m.version.n),await e.storage.kv.set("task-index-owned-guidance",!0)}let k=m.version.n;for(let[E,v]of qx.entries()){if(await e.storage.kv.get(v.patched))continue;let I=!1;for(let $ of p[E]){let _=w.files.find(S=>S.path===$.path),R=q7($);if(hM(p,E,$).some(S=>_.text.includes(S))&&R.every(S=>!_.text.includes(S)))continue;let b=R.filter(S=>_.text.split(S).length===2);if(b.length!==1)throw new Error("Local guide wording needs to be preserved before this cutover");_.text=_.text.replace(b[0],()=>$.after),I=!0}if(I){let $=t.draft(h,cd,JSON.stringify(w),v.why);if($.state!=="trial")throw new Error($.reason);k=$.n}l(h,k);let T=nc(t,"task-index");if("state"in T||JSON.stringify(T.files)!==JSON.stringify(w.files))throw new Error("The new guide did not survive its complete readback");await e.storage.kv.set(v.patched,!0)}return!0}i(d,"prepare");let u={async text(f,h){if(!await e.storage.kv.get("task-index-owned-guidance"))return h();let p=nc(t,"task-index");if("state"in p)throw new Error(p.reason);let g=p.files.find(m=>m.path===f);if(!g)throw new Error("The effective guide set is incomplete");return g.text},async delivery(f,h,p,g){if(!await e.storage.kv.get("task-index-owned-guidance"))return async()=>{};let m=t.show(cd);if("state"in m)throw new Error(m.reason);let y=nc(t,"task-index"),w=gd(m.body);if("state"in y||!w.ok)throw new Error("The complete effective guide is unavailable");let k=w.body.baseline.find(S=>S.path===f),E=y.files.find(S=>S.path===f);if(!k||!E)throw new Error("The complete effective guide is required");let v=`task-index-guide-delivery:${h}:${f}`,I=await e.storage.kv.get(v),T=i(S=>a_e("sha256").update(S).digest("hex"),"hash"),$=await g(),_=p(E.text),R=[p(k.text),_],b=`
1805
1805
  `+cl.assistantLimits;if(!I&&Fc.slice(0,2).includes(f))for(let S of[...R])S.endsWith(b)&&R.push(S.slice(0,-b.length));if($!==null&&!R.includes($)&&(!I||T($)!==I))throw new Error("Local guide changes were preserved; this delivery needs their meaning clarified");return async()=>{await e.storage.kv.set(v,T(_))}},async delivered(f,h){let p=await a();return p.flatMap((g,m)=>g.filter(y=>y.path===f&&hM(p,m,y).length===1)).every(g=>{let m=0;for(let y of g.after.split(/\{\{[^}]+\}\}/).filter(w=>w.trim().length>12)){let w=h.indexOf(y,m);if(w<0)return!1;m=w+y.length}return!0})},prepare(){return o||(o=d().finally(()=>{o=null})),o},async upgrade(){if(!await e.storage.kv.get("task-index-owned-guidance"))return!1;if(!await c())return!0;try{let f=await u.prepare();return s="",f}catch(f){let h=f instanceof Error?f.message:String(f);return h!==s&&e.log.warn(`Owned guide update is held: ${h}`),s=h,!1}}};return cF(e,u),u}i(H7,"setupTaskIndexGuidance");async function W7(e){let t="guide set preparation";try{if(!e.guides||!await e.guides.prepare())return`${t}: the complete guide set is not ready`;if(t="front CLAUDE.md guide delivery",!e.deliver)return`${t}: the delivery queue is not ready`;let r=await e.deliver();if(r!==null)return`${t}: ${r}`;let n=await e.readNotes(`${zt}/CLAUDE.md`);if(n.text===null)return`${t}: the installed guide could not be read (exit ${n.code})`;if(!await e.guides.delivered("plugins/orbit/front/CLAUDE.md",n.text))return`${t}: the installed guide does not contain the task index changes`;t="handoff note";let o=await e.readNotes(`${zt}/handoff.md`);if(o.code!==4){if(o.text===null)return`${t}: the installed note could not be read (exit ${o.code})`;if(!await e.guides.delivered("orbit/docs/handoff-to-new-conversation.md",o.text))return`${t}: the installed note does not contain the task index changes`}if(t="background guide",await e.backgroundOn()){let s=await e.readStation(`${Co}/CLAUDE.md`);if(s.text===null)return`${t}: the installed guide could not be read (exit ${s.code})`;if(!await e.guides.delivered("plugins/orbit/back/CLAUDE.md",s.text))return`${t}: the installed guide does not contain the task index changes`}return null}catch(r){return`${t}: ${r instanceof Error?r.message:String(r)}`}}i(W7,"taskIndexRetirementReady");kr();fa();var f_e="station-manager";function z7(e,t,r,n=()=>{},o=()=>({revision:Gp(),source:Jk()})){let s=new Map,a=e.hosts.experimental_client({contract:px}),c=i(T=>`station-manager:${T}`,"pinKey"),l=e.hosts.internal_DO_NOT_USE_machineRecords,d=i(async T=>l?.list().find($=>$.kind==="station"&&$.name===T)?.managedFrom??e.storage.kv.get(c(T)),"readPin"),u=i(async(T,$)=>{l?l.setManager(T,$):await e.storage.kv.set(c(T),$)},"writePin"),f=i(async T=>{let $=T.driver==="libvirt"&&T.server?n(T.server):void 0;return $?{config:T,server:(await CU(Bn(),T.server,$)).station}:{config:T}},"target");async function h(T){let $=(await e.sdk.hosts.list()).find(_=>_.id===T);return!!$&&$.status==="connected"&&$.machineProviderId!==t&&$.machineProviderId!==St}i(h,"eligible");async function p(T,$){let _=await a.call("station.ready",null,{hostId:T,timeoutMs:3e4}).catch(()=>null);if(!_?.hasKey)return e.log.warn(`stations: ${$.name}: server management probe on ${T}: ${_?"administrator key unavailable":"readiness call unavailable"}`),null;let R=await a.call("station.vm",await f($),{hostId:T,timeoutMs:6e4}).catch(()=>null);return R||e.log.warn(`stations: ${$.name}: server management probe on ${T}: VM lookup unavailable`),R}i(p,"probe");async function g(T){let $=await d(T.name),_=null;try{_=(await e.sdk.system.config()).primaryHostId}catch{}if(T.driver==="libvirt"){if(!_||!await h(_))throw new Error(`${T.name}: server management machine isn't connected`);let A=await p(_,T);if(!A)throw new Error(`${T.name}: server management needs its administrator key and VM connection; the server log records which check failed`);return _!==$&&await u(T.name,_),{hostId:_,vm:A}}if(_&&_!==$&&await h(_)){let A=await p(_,T);if(A)return await u(T.name,_),{hostId:_,vm:A}}if($){if(!await h($))throw new Error(`${T.name}'s managing machine (${$}) isn't connected`);let A=await a.call("station.vm",await f(T),{hostId:$,timeoutMs:6e4});return{hostId:$,vm:A}}let R=(await e.sdk.hosts.list()).filter(A=>A.status==="connected"&&A.machineProviderId!==t&&A.machineProviderId!==St),b=[];for(let A of R){let q=await p(A.id,T);q&&b.push({id:A.id,name:A.name,vm:q})}if(b.length===0)throw new Error(`no connected machine manages ${T.name} (one with Moonlet's station key whose hypervisor has its VM)`);let S=b.length===1?b[0].id:await m(T.name,b),P=b.find(A=>A.id===S);if(!P)throw new Error(`${S} can't manage ${T.name}`);return await u(T.name,P.id),e.log.info(`stations: ${T.name} is managed from ${P.name} (${P.id})`),{hostId:P.id,vm:P.vm}}i(g,"manager");function m(T,$){let _=s.get(T);if(_)return _;let R=(async()=>{let b=$.map(q=>`${q.name} (${q.id})`).join(", "),S=`Choose with: bb orbit station manager ${T} <machine>`,P=await r();if(!P)throw new Error(`several machines can manage ${T}: ${b}. ${S}`);let A={station:T,machines:$.map(({id:q,name:j})=>({id:q,name:j}))};for(;;){let q=await Ql(e,{threadId:P,rendererId:f_e,title:`Which machine manages ${T}?`,payload:A,timeoutMs:36e5,presentation:{label:{pending:`Waiting for a choice: ${T}`,completed:`Chosen: ${T}`}}});if(q.outcome==="waiting")throw new Error(`${q.reason}. ${S}`);if(q.outcome==="cancelled"&&q.reason==="timeout")continue;let j=q.outcome==="submitted"?q.value?.hostId:void 0;if(typeof j!="string")throw new Error(`no machine chosen for ${T}. ${S}`);return j}})().finally(()=>s.delete(T));return s.set(T,R),R}i(m,"choose");async function y(T,$){if(!await h($))throw new Error(`${$} isn't a connected machine that may manage stations`);if(!await p($,T))throw new Error(`${$} can't manage ${T.name}: it needs Moonlet's station key and the station's VM`);await u(T.name,$)}i(y,"setManager");async function w(T){return(await g(T).catch(()=>{}))?.vm??void 0}i(w,"vm");async function k(T,$=0){let{hostId:_}=await g(T),R=$;return{name:T.name,os:T.os,async exec(b){let S=await a.call("station.exec",{...await f(T),as:b.as,script:b.script,...R?{waitSeconds:R}:{}},{hostId:_,timeoutMs:(R+1800)*1e3});return R=0,S},async run({argv:b,stdin:S,timeoutMs:P,signal:A,onOutput:q}){let{code:j,output:C}=await a.call("station.run",{...await f(T),argv:b,stdin:S,timeoutMs:P},{hostId:_,timeoutMs:P+6e4,...A?{signal:A}:{}});return C&&q(C),j}}}i(k,"connect");async function E(T,$){let{hostId:_}=await g(T);return a.call("station.tunnel",{...await f(T),up:$},{hostId:_,timeoutMs:6e4})}i(E,"tunnel");async function v(T){let $=await d(T.name);if(!$||!await h($))throw new Error(`${T.name}'s managing machine isn't connected`);return a.call("station.tunnel",{...await f(T),up:!1},{hostId:$,timeoutMs:6e4})}i(v,"endTunnel");async function I(T,$,_,R,b=!1,S){let{revision:P,source:A}=o(),q=b&&P?A:null;if(b&&P&&(!q||q.revision!==P))throw new Error("Automatic station delivery has no matching app source record.");b&&S?.stage(T.name,"manager");let j;try{j=(await g(T)).hostId}catch(U){throw b&&S?.fail(T.name,"manager"),U}let C={...await f(T),policy:$,dryRun:_,...R?{owner:R}:{}};if(b&&S?.stage(T.name,"installer"),q)try{let U=await a.call("station.applyPolicyManaged",{...C,source:q},{hostId:j,timeoutMs:18e5});return U.code===0?S?.stage(T.name,"installed"):S?.fail(T.name,"installer"),U}catch(U){throw S?.fail(T.name,"installer"),U}return a.call(b?"station.applyPolicyDrained":"station.applyPolicy",{...C,...P?{revision:P}:{}},{hostId:j,timeoutMs:30*6e4})}return i(I,"applyPolicy"),{vm:w,connect:k,setManager:y,applyPolicy:I,tunnel:E,endTunnel:v}}i(z7,"stationAccess");function mM(e){return e.own?`Orbit on ${e.name}`:"Orbit"}i(mM,"projectName");var gM=[{id:"memory",name:"Memory",why:"bb memory: where the Moonlet conversation keeps facts (people, accounts, what the owner likes; design.md, Continuity)",store:{entry:"memory",marketplace:"bb-official"}},{id:"agent-board",name:"Agent Board",why:"the conversation tree's board the Moonlet conversation reads (bb agent-board show)",repo:"agent-board"},{id:"host-monitor",name:"Host Monitor",why:"each machine's resource snapshot (bb host-monitor snapshot)",pin:{url:"https://github.com/MateoCerquetella/bb-plugins.git",tag:"host-monitor/v0.1.6",commit:"f9836254c0286296d36f2b2af4c03cd7160823b8",subdirectory:"plugins/host-monitor",reviewed:"bb-community/host-monitor"}},{id:"library",name:"Library",why:"each station's library: browse, upload, delete (plugins/library)",repo:"library"}];function h_e(e){return{source:`git:${e.url}@${e.tag}`,...e.subdirectory?{subdirectory:e.subdirectory}:{}}}i(h_e,"pinSource");function m_e(e){return e.startsWith("builtin:")?{kind:"builtin"}:e.startsWith("path:")?{kind:"path",path:e.slice(5)}:e.startsWith("git:")?{kind:"git",source:e.slice(4).replace(/#.*$/,"")}:{kind:"other",source:e}}i(m_e,"parseOrbitSource");function g_e(e,t){if(e.kind==="builtin")return{source:`builtin:${t}`};if(e.kind==="path"){let r=/^(.*)\/plugins\/(?:moonlet|orbit)\/?$/.exec(e.path);return r?{source:`${r[1]}/plugins/${t}`}:null}return e.kind==="git"?{source:e.source,subdirectory:`plugins/${t}`}:null}i(g_e,"repoInstall");function y_e(e,t){if(!e)return t;if(e.kind==="npm")return`${e.package}@${e.resolvedVersion??e.range??e.tag??"latest"}${e.unresolvedReason?` (unresolved: ${e.unresolvedReason})`:""}`;let r=e.resolvedTag??e.resolvedCommit?.slice(0,12)??e.ref??e.range??"HEAD";return`${e.url}@${r}${e.subdir?`#${e.subdir}`:""}${e.unresolvedReason?` (unresolved: ${e.unresolvedReason})`:""}`}i(y_e,"resolvedText");function V7(e){let t=new Map(e.map(r=>[r.id,r]));return{missing:gM.filter(r=>!t.has(r.id)),disabled:gM.filter(r=>t.get(r.id)?.enabled===!1)}}i(V7,"companionsMissing");function Fx(e){let{missing:t,disabled:r}=V7(e),n=[];return t.length&&n.push(`missing: ${t.map(o=>o.id).join(", ")}`),r.length&&n.push(`disabled: ${r.map(o=>o.id).join(", ")}`),n.length?`Companion plugins ${n.join("; ")} (bb orbit setup shows what it would install)`:null}i(Fx,"companionsLine");async function K7(e,t=!1){let r=[],n=!0,o=0,s=t?await e.record():{installed:[],enabled:[]},a=await e.installed(),c=a.find(f=>f.id==="orbit"),l=c?m_e(c.source):null,{missing:d,disabled:u}=V7(a);for(let f of d)try{let h,p;if("store"in f){let g=await e.planStore(f.store.entry,f.store.marketplace);if(p=`bb's store (${f.store.marketplace}/${f.store.entry}: ${g.displayName}, ${g.resolved})`,!g.compatible)throw new Error(`bb's store says ${g.displayName} isn't compatible: ${g.reason??"no reason given"}`);h=i(()=>e.installStore(f.store.entry,f.store.marketplace,g.confirmed),"install")}else if("pin"in f){let g=h_e(f.pin);p=`${g.source}${g.subdirectory?`#${g.subdirectory}`:""} (commit ${f.pin.commit.slice(0,12)}, as reviewed in ${f.pin.reviewed})`,h=i(()=>e.installSource(g.source,g.subdirectory),"install")}else{let g=l&&g_e(l,f.repo);if(!g)throw new Error(`Orbit's own source (${c?.source??"unknown"}) says nothing about where plugins/${f.repo} is; bb plugin install <path to it>`);p=l?.kind==="builtin"?`the app (${g.source}, built in like Moonlet)`:`this repo (plugins/${f.repo}), ${g.source}${g.subdirectory?`#${g.subdirectory}`:""}`,h=i(()=>e.installSource(g.source,g.subdirectory),"install")}if(!t){r.push(`${f.id}: would install from ${p}: ${f.why}`),o++;continue}await h(),s.installed=[...new Set([...s.installed,f.id])],r.push(`${f.id}: installed from ${p}`)}catch(h){n=!1,r.push(`${f.id}: failed: ${h.message}`)}for(let f of u){if(!t){r.push(`${f.id}: would enable`),o++;continue}try{await e.enable(f.id),s.enabled=[...new Set([...s.enabled,f.id])],r.push(`${f.id}: enabled`)}catch(h){n=!1,r.push(`${f.id}: enabling failed: ${h.message}`)}}for(let f of gM)!d.includes(f)&&!u.includes(f)&&r.push(`${f.id}: installed`);return t&&await e.saveRecord(s),!t&&o&&r.push("Nothing was changed. To do the above: bb orbit setup --yes. To take it back later: bb orbit setup undo."),{lines:r,ok:n}}i(K7,"setupCompanions");async function X7(e,t=!1){let r=await e.record(),n=new Set((await e.installed()).map(d=>d.id)),o=r.installed.filter(d=>n.has(d)),s=r.enabled.filter(d=>n.has(d)&&!o.includes(d)),a=[],c=!0;if(!o.length&&!s.length)return{lines:["Setup hasn't installed or enabled anything that's still there: nothing to undo."],ok:c};let l={installed:[],enabled:[]};for(let d of o)t?await e.remove(d).then(()=>a.push(`${d}: removed`),u=>{c=!1,l.installed.push(d),a.push(`${d}: removing failed: ${u.message}`)}):a.push(`${d}: would remove (setup installed it; bb deletes its settings and schedules too)`);for(let d of s)t?await e.disable(d).then(()=>a.push(`${d}: disabled`),u=>{c=!1,l.enabled.push(d),a.push(`${d}: disabling failed: ${u.message}`)}):a.push(`${d}: would disable (setup enabled it)`);return t?await e.saveRecord(l):a.push("Nothing was changed. To do the above: bb orbit setup undo --yes."),{lines:a,ok:c}}i(X7,"undoSetup");var G7="companions-setup";function yM(e){return{installed:i(async()=>(await e.sdk.plugins.list()).plugins.map(t=>({id:t.id,source:t.source,enabled:t.enabled})),"installed"),planStore:i(async(t,r)=>{let n=await e.sdk.plugins.catalog.installPlan({entryId:t,marketplace:r}),o=n.kind==="marketplace"?n.resolvedSource:void 0;return{displayName:n.displayName,compatible:n.compatible,reason:n.incompatibleReason,resolved:y_e(o,n.source),...o?{confirmed:o}:{}}},"planStore"),installStore:i(async(t,r,n)=>{await e.sdk.plugins.catalog.install({entryId:t,marketplace:r,...n?{confirmedSource:n}:{}})},"installStore"),installSource:i(async(t,r)=>{await e.sdk.plugins.install(r?{source:t,subdirectory:r}:{source:t})},"installSource"),enable:i(async t=>{await e.sdk.plugins.enable({pluginId:t})},"enable"),disable:i(async t=>{await e.sdk.plugins.disable({pluginId:t})},"disable"),remove:i(async t=>{await e.sdk.plugins.remove({pluginId:t})},"remove"),record:i(async()=>await e.storage.kv.get(G7)??{installed:[],enabled:[]},"record"),saveRecord:i(async t=>{await e.storage.kv.set(G7,t)},"saveRecord")}}i(yM,"bbSetupDeps");function Y7(e,t=1e3){let r=setTimeout(()=>{let n=i(o=>e.log.warn(`companion plugins: couldn't list bb's plugins: ${o.message}`),"failed");try{e.sdk.plugins.list().then(o=>{let s=Fx(o.plugins);s&&e.log.warn(s)}).catch(n)}catch(o){n(o)}},t);e.onDispose(()=>clearTimeout(r))}i(Y7,"companionsAtLoad");var w_e=i(e=>/: failed: /.test(e),"failed");function J7(e,t,r,n={firstMs:1e3,everyMs:1e4}){let o=!1;e.onDispose(()=>{o=!0}),(async()=>{let s=[];for(let a=0;a<12;a++){if(await new Promise(c=>setTimeout(c,a===0?n.firstMs:n.everyMs)),o)return;if(s=await t(),s.length>0&&!s.every(w_e))return s.forEach(c=>e.log.info(`sync: ${c}`));if(s.length===0&&(await r()).length===0)return}if(s.length>0)return s.forEach(a=>e.log.warn(`sync: ${a} (still failing after two minutes; run \`bb orbit station sync\`)`));e.log.warn("sync: no station connected within two minutes; run `bb orbit station sync` once it is")})().catch(s=>{o||e.log.warn(`sync failed: ${s.message}`)})}i(J7,"syncAtLoad");import{defineRpcContract as A_e}from"@get-bb/plugin-sdk";import{z as ld}from"zod";kr();var Z7=".orbit-events-activation",v_e="/usr/local/orbit/bin/orbit-cap",b_e="/usr/local/orbit/bin/orbit-events",k_e="/run/orbit-deploy/deploy.sock",wM="/usr/local/orbit/etc/deploy-runner.toml",Wx="Settings \u2192 your moonlet \u2192 Event service",__e="event service: it can't be offered from the protected conversation, because the switch question has to come from work on the station. Ask Orbit to have work on the station request `orbit-cap deploy activate events`; the question then appears in that work's conversation";function bM(e){let t=`${e}/${Z7}`;return`set -u
1806
1806
  f=${Ue(t)}
@@ -1823,7 +1823,7 @@ rm -f "$f.pid" "$f.out" "$f.code"
1823
1823
  BB_THREAD_ID=${Ue(t)} setsid -f sh -c 'echo $$ > "$1.pid"; ${v_e} deploy ${r?"activate":"undo"} events > "$1.out" 2>&1; echo $? > "$1.code"' sh "$f" < /dev/null > /dev/null 2>&1
1824
1824
  for _ in $(seq 50); do [ -s "$f.pid" ] && break; sleep 0.1; done
1825
1825
  [ -s "$f.pid" ] && echo asked`}i(E_e,"askScript");function vM(e){return(e.trim().split(`
1826
- `).map(t=>t.replace(/^orbit-cap: /,"").trim()).filter(Boolean).pop()??"no reason given").slice(0,300)}i(vM,"lastLine");function T_e(e){return[!e.installed&&"the event service's program (orbit station policy installs it)",!e.options&&"its settings for the station runner (orbit station policy saves them)",!e.runner&&"the station runner's socket (activation.md, Switching the station runner on)"].filter(t=>!!t)}i(T_e,"missing");function _M(e,t,r){let{now:n,ownerAsked:o}=r,s=e??{state:r.fresh?"due":"untouched",at:n},a=null;if(s.state==="asked"){let d=t.request,u=s.target??!0;if(d?.code===null&&d.running)return{record:s,ask:!1,report:o?"event service: a switch question is already waiting":null};d?.code===0&&t.active===u?(s={state:u?"on":"stopped",at:n},a=`event service: switched ${u?"on":"off"} after your approval`):d?d.code===77?s={state:"declined",at:n,reason:vM(d.output)}:s={state:"failed",at:n,reason:d.code===null?"the request ended before an answer":vM(d.output)}:s={state:"failed",at:n,reason:"the request's record on the station is gone"},s.state==="declined"&&(a=`event service: not switched ${u?"on":"off"} (${s.reason}). It stays ${t.active?"on":"off"}, and you won't be asked again unless you ask: ${Wx}.`),s.state==="failed"&&(a=`event service: switching didn't complete and it stays ${t.active?"on":"off"} (${s.reason}). To try again: ${Wx}.`)}else t.active&&s.state!=="on"?(s={state:"on",at:n},a=e?"event service: on":null):!t.active&&s.state==="on"&&(s={state:"stopped",at:n},a=`event service: off now. Orbit won't switch it on or ask again; to be asked: ${Wx}.`);let c=!1,l=r.target??!0;if(o&&t.active===l)a=`event service: already ${l?"on":"off"}`;else if((o||s.state==="due")&&!r.canAsk)o&&(a=__e);else if(o||s.state==="due"&&!t.active){let d=l?T_e(t):t.runner?[]:["the station runner's socket"];d.length?(o&&(a=`event service: you'll be asked once the station has ${d.join(", ")}`),o||(s={state:"due",at:s.at})):(c=!0,s={state:"asked",target:l,at:n},a=`event service: asked you in your Moonlet window whether to switch it ${l?"on":"off"}`)}return{record:s,ask:c,report:a}}i(_M,"decide");var Hx=new Map;function pg(e){return EM(e.dataDir,()=>S_e(e))}i(pg,"reconcileEvents");function EM(e,t){let r=(Hx.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Hx.set(e,r),r.finally(()=>{Hx.get(e)===r&&Hx.delete(e)}).catch(()=>{}),r}i(EM,"withEventsLock");async function S_e(e){let t=await e.station.exec({as:"orbit",script:bM(e.dataDir)}),r=t.code===0?kM(t.stdout):null;if(!r)return"event service: its state on the station couldn't be read, so nothing was changed or asked";let n=e.ownerTarget!==void 0,o=_M(await e.load(),r,{fresh:e.fresh,ownerAsked:n,target:e.ownerTarget,canAsk:e.canAsk,now:e.now()});if(!o.ask)return await e.save(o.record),o.report;let s=typeof e.front=="string"?e.front:await e.front();try{await e.save({...o.record,thread:s})}catch(c){return`event service: the question couldn't be recorded, so it wasn't asked (${c.message})`}let a=await e.station.exec({as:"orbit",script:E_e(e.dataDir,s,o.record.target)}).catch(c=>({code:1,stdout:"",stderr:c.message}));if(a.code!==0||a.stdout.trim()!=="asked"){let c=vM(a.stderr||a.stdout);return await e.save({state:"failed",at:e.now(),reason:`the question couldn't be requested: ${c}`}),`event service: the question couldn't be requested (${c}), so its state is unchanged. To try again: ${Wx}.`}return o.report}i(S_e,"reconcileNow");var Q7=ld.object({active:ld.boolean(),pending:ld.boolean(),thread:ld.string().nullable(),message:ld.string().nullable()}),eZ=A_e({"events.state":{input:ld.null(),output:Q7},"events.switch":{input:ld.object({active:ld.boolean()}).strict(),output:Q7}});async function tZ(e){await e.get("events-switch-migrated")||(await e.delete("events-offer-owner-ask"),await e.set("events-switch-migrated",!0))}i(tZ,"migrateEventService");function rZ(e){async function t(){let n=await e.target();return EM(n.dataDir,async()=>{let o=await n.station.exec({as:"orbit",script:bM(n.dataDir)}),s=o.code===0?kM(o.stdout):null;if(!s)throw new Error("The event service's state couldn't be read. Reconnect the station and try again.");let a=_M(await n.load(),s,{fresh:!1,ownerAsked:!1,canAsk:!1,now:n.now()});return await n.save(a.record),{active:s.active,pending:a.record.state==="asked",thread:a.record.state==="asked"?a.record.thread??null:null,message:a.record.reason??a.report}})}i(t,"state");async function r(n){let o=await e.target(),s=await pg({...o,front:o.questionThread,ownerTarget:n});return{...await t(),message:s}}return i(r,"switchTo"),{state:t,switchTo:r}}i(rZ,"eventService");import{PluginCliError as nZ}from"@get-bb/plugin-sdk";async function iZ(e,t){let r=await e.sdk.threads.internal_DO_NOT_USE_visibleReplyEvidence({threadId:t,body:{}});if(r.status!=="visible")throw new nZ("No current visible reply can satisfy this reminder. Review the conversation and send any answer that is due.");let n=await e.sdk.threads.internal_DO_NOT_USE_visibleReplyEvidence({threadId:t,body:{revision:r.revision}});if(n.status!=="visible"||n.revision!==r.revision||n.messageSeq!==r.messageSeq)throw new nZ("Visible reply evidence changed. Review the current conversation and send any answer that is due.");return n.messageSeq}i(iZ,"acknowledgeVisibleMessage");import{cliCommand as sZ,defineRpcContract as C_e}from"@get-bb/plugin-sdk";import{z as Hc}from"zod";import{createHash as x_e}from"node:crypto";import{z as Qi}from"zod";var O_e=Qi.string().regex(wn),R_e=Qi.object({version:Qi.literal(1),phase:Qi.enum(["snapshot","tasks","history","index","complete"]),pending:Qi.array(O_e),checked:Qi.number().int().nonnegative(),waiting:Qi.string().nullable()}),$k="task-reconciliation-v1",I_e="meaning-needed",$_e=/^(?:review:|worker:|ci:|prompt:|approve:|unread:|rule:|schedule:|output-clean:|archive-output:|fixture-expiry:|retention:work)/i,N_e=/https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]{0,8}\b/g;function P_e(e,t){if(e.project.id===Ri)return!1;let r=[...e.description.matchAll(/^Work start: ([^\n]+)$/gm)].at(-1)?.[1];if(r)return t.some(s=>s.key===r&&s.key.startsWith("review:")&&s.class==="background")&&!t.some(s=>!s.key.startsWith("review:")&&!s.key.startsWith("event:"));let n=/^Key: ([^\n]+)(?:\n|$)/.exec(e.description)?.[1];if(!n)return!1;let o=/^Labels: ([^\n]*)$/m.exec(e.description)?.[1]?.split(",").map(s=>s.trim())??[];return[...e.labels,...o].includes("event-service")||$_e.test(n)}i(P_e,"systemRecord");function oZ(e,t){let r=Ce(e),n=t.tasks??(()=>Gt(e)),o=null,s=VR(e,n),a=i(()=>e.realtime.publish("tasks",{changed:!0}),"changed");async function c(){let h=await e.storage.kv.get($k);return h==null?null:R_e.parse(h)}i(c,"status");function l(h,p){let g=n().store;g.update(h.id,{addLabels:[I_e]},"system"),g.note(h.id,"system",`Needs your decision: ${p}`,"note",`meaning-needed:${x_e("sha256").update(p).digest("hex").slice(0,32)}`),a()}i(l,"hold");async function d(){let h=n(),p=await h.moveOrb();if(!await h.orbMoved())throw new Error(p?.failed.length?`The old task board is partly moved; ${p.failed.length} tasks are still to come over`:"The old task board hasn't moved into Moonlet's tasks yet");let g=new Set;for(let m of Qi.array(Qi.object({orb:Qi.string()})).parse(r.prepare("SELECT orb FROM task_orb_mirror ORDER BY orb").all())){let y=h.store.find(m.orb);y&&g.add(y.key)}return[...g]}i(d,"snapshot");async function u(h){let p=n().store,g=p.find(h);if(!g||g.status==="dropped")return;let m=fk(p,g),y=Qi.array(Qi.object({key:Qi.string(),class:Qi.string()})).parse(r.prepare(`SELECT key, class FROM work_items WHERE loop IN (${m.map(()=>"?").join(",")})`).all(...m));if(P_e(g,y))return;let w=p.links(g.id).filter(b=>b.kind==="conversation"&&/^thr_[a-z0-9]+$/.test(b.ref)).map(b=>b.ref),k=await t.workers(m,g.description,w),E=!1;for(let b of k){let S=await e.sdk.threads.get({threadId:b}),P=await e.sdk.threads.timeline({threadId:b,summaryOnly:"true",segmentLimit:"1"});E||=["active","starting","pending"].includes(S.status)||!!P.goal&&P.goal.status!=="complete"||P.activeWorkflows.length>0||P.activeBackgroundCommands.length>0||!!P.pendingTodos?.items.some(A=>A.status!=="completed"),E||=(await e.sdk.threads.interactions.list({threadId:b})).some(A=>A.status==="pending")}let v=y.length>0;if(g.status==="done"&&!E&&!v)return;v||await e.storage.kv.set(bj(g.key),!0);for(let b of k)await s.attach({loop:g.key,thread:b});let I=hx(g.description);if(I&&!t.repos().includes(new URL(I).pathname.split("/").slice(1,3).join("/"))){l(g,"the named repository is not available for independent completion evidence");return}let T=[...g.description.matchAll(N_e)].map(b=>b[0]);if((!I||T.some(b=>b!==I))&&(T.length>0||kj(g)==="in_review")&&!E&&!v){l(g,"the completion condition needs a decision; a pull request reference alone does not finish this promise");return}let _=i(b=>JSON.stringify([b.title,b.description,b.doneWhen,b.priority,b.status]),"meaning");if(I&&T.every(b=>b===I)&&!p.list({parent:g.id,status:"open",limit:1}).tasks.length){if(_(p.get(g.id))!==_(g))return;p.links(g.id).some(b=>b.kind==="pull_request"&&b.ref===I)||(p.link(g.id,{kind:"pull_request",ref:I,label:null}),a())}await t.update(g.key);let R=p.get(g.id);if(R.status!=="done"&&(R.description!==g.description||R.title!==g.title||R.priority!==g.priority||R.doneWhen!==g.doneWhen))throw new Error("Task meaning changed during reconciliation; its current condition will be read again")}i(u,"reconcile");async function f(){let h=await c();if(h?.phase!=="complete"){h||(h={version:1,phase:"snapshot",pending:[],checked:0,waiting:null},await e.storage.kv.set($k,h)),h.waiting=null;try{if(h.phase==="snapshot"&&(h.pending=await d(),h.phase="tasks",await e.storage.kv.set($k,h)),h.phase==="tasks"){let p=h.pending.slice(0,12),g=null;for(let m of p){try{await u(m),h.pending=h.pending.filter(y=>y!==m),h.checked++}catch(y){h.pending=[...h.pending.filter(w=>w!==m),m],h.waiting=y instanceof Error?y.message:String(y),g=y}await e.storage.kv.set($k,h)}if(g)throw g;h.pending.length||(h.phase="history")}if(h.phase==="history"){let p=await t.historyStep();p.waiting?h.waiting=p.waiting:h.phase="index"}h.phase==="index"&&(await t.index()?h.phase="complete":h.waiting="The task index works; its guide delivery and file retirement are still waiting.")}catch(p){throw h.waiting=p instanceof Error?p.message:String(p),p}finally{await e.storage.kv.set($k,h)}}}return i(f,"pass"),{status:c,tick(){return o??=f().finally(()=>{o=null}),o}}}i(oZ,"taskReconciliation");var aZ=Hc.object({version:Hc.literal(1),phase:Hc.enum(["snapshot","tasks","history","index","complete"]),pending:Hc.array(Hc.string()),checked:Hc.number(),waiting:Hc.string().nullable()}).nullable(),L_e=C_e({"tasks.reconciliation":{input:Hc.null(),output:aZ},"tasks.reconcile":{input:Hc.null(),output:aZ}}),TM=new WeakMap;function cZ(e,t){let r=oZ(e,t);return TM.set(e,r),e.rpc.register(L_e,{"tasks.reconciliation":i(()=>r.status(),"tasks.reconciliation"),"tasks.reconcile":i(async()=>(await r.tick(),r.status()),"tasks.reconcile")}),ot(e,"task-reconciliation","* * * * *",r.tick),r.tick().catch(n=>e.log.warn(`Task reconciliation: ${String(n)}`)),r}i(cZ,"setupTaskReconciliation");function lZ(e,t){return{"tasks reconciliation":sZ({summary:"Read the automatic board reconciliation progress",async run(r,n){await t(n.threadId);let o=TM.get(e);if(!o)throw new Error("Task reconciliation is not ready");return{exitCode:0,stdout:JSON.stringify(await o.status())}}}),"tasks reconcile":sZ({summary:"Retry the automatic board reconciliation without changing task meaning",async run(r,n){await t(n.threadId);let o=TM.get(e);if(!o)throw new Error("Task reconciliation is not ready");return await o.tick(),{exitCode:0,stdout:JSON.stringify(await o.status())}}})}}i(lZ,"taskReconciliationCommands");import{cliCommand as fg,PluginCliError as dZ}from"@get-bb/plugin-sdk";var uZ={name:"id",description:"System record identity, including a historical ORB alias",required:!0},hg={type:"boolean",description:"Emit JSON"},mg=i(e=>({exitCode:0,stdout:JSON.stringify(e)}),"output");function pZ(e){return{"records ready":fg({summary:"Prepare durable system records without changing task history",options:{json:hg},async run(){return await Qs(e).ready(),mg({ready:!0,version:1})}}),"records show":fg({summary:"Read one work record, notice or watch",positionals:[uZ],options:{json:hg},async run(t){let r=await Qs(e).query({action:"get",id:t.positionals.id});if(!r.records.length&&!t.options.json)throw new dZ("System record not found");return mg(r)}}),"records find":fg({summary:"Find a system record by its exact event key",options:{key:{type:"string",required:!0,description:"Exact event key"},json:hg},async run(t){return mg(await Qs(e).query({action:"find",key:t.options.key}))}}),"records list":fg({summary:"List work, notices and watches with bounded pages",options:{all:{type:"boolean",description:"Include resolved work and notice history"},label:{type:"string",description:"Filter by label"},parent:{type:"string",description:"Parent record or task identity"},after:{type:"integer",min:0,max:Number.MAX_SAFE_INTEGER,default:0,description:"Continue after this sequence"},limit:{type:"integer",min:1,max:200,default:100,description:"Maximum records in a page"},json:hg},async run(t){return mg(await Qs(e).query({action:"list",active:!t.options.all,label:t.options.label??"",parent:t.options.parent??null,after:t.options.after,limit:t.options.limit}))}}),"records change":fg({summary:"Record system work, notice or watch state",options:{data:{type:"string",required:!0,description:"JSON create, update or comment operation; never changes a task's meaning"},json:hg},async run(t,r){let n;try{n=JSON.parse(t.options.data)}catch{throw new dZ("Record data must be JSON")}let o=g_["records.change"].input.parse(n);return mg(await Qs(e).change(o,r.threadId?`conversation:${r.threadId}`:"cli:records"))}}),"records comments":fg({summary:"Read system record comments",positionals:[uZ],options:{after:{type:"integer",min:0,max:Number.MAX_SAFE_INTEGER,default:0,description:"Continue after this comment sequence"},limit:{type:"integer",min:1,max:200,default:100,description:"Maximum comments"},json:hg},async run(t){let r=Qs(e);return await r.ready(),mg(r.store.comments(t.positionals.id,t.options.after,t.options.limit))}})}}i(pZ,"eventRecordCommands");import{PluginCliError as D_e}from"@get-bb/plugin-sdk";function fZ(e){async function t(n,o){return n===o||!!await e.orbitConversationOf(n)}i(t,"moonletConversation");async function r(n){let o=await e.backThread().catch(()=>null),s=await e.parentOf(n);for(let a=0;s&&a<16;a++){if(await t(s,o))return!0;s=await e.parentOf(s)}return!1}return i(r,"startedByMoonlet"),async n=>{if(!n)return await e.requireUser(n),"owner";if(await t(n,await e.backThread().catch(()=>null))||await e.onStation(n)||await e.onListedMachine(n)&&await r(n))return"assistant";if(await e.requireUser(n).then(()=>!0,()=>!1))return"owner";throw new D_e("Tasks are read and changed by the owner, the Moonlet conversation, and work on its stations or the owner's machines.")}}i(fZ,"taskCaller");import{cliCommand as Xn,PluginCliError as qp}from"@get-bb/plugin-sdk";import{z as mZ}from"zod";var Yn={type:"boolean",description:"Print JSON"},Wc={name:"task",description:"A task key (ME-3, MOON-1308), an old key (ORB-12, L-0042) or its id",required:!0},zx=["todo","followup","scheduled"],SM=["owner","assistant","others"],hZ=["urgent","high","medium","low","none"],j_e=["owner","assistant"],M_e={urgent:"!!",high:"! ",medium:" ",low:"\xB7 ",none:" "},B_e=mZ.enum(["chat","mail","message","calendar","conversation","cli"]),U_e={owner:"your move",assistant:"assistant\u2019s move",others:"waiting"};function Gx(e){let t=e.whenText?` \xB7 ${e.whenText}`:"",r=e.move==="others"&&e.waitingOn?` on ${e.waitingOn}`:"",n=e.status==="open"?`${U_e[e.move]}${r}`:e.status,o=e.origin==="assistant"?" \xB7 added by the assistant":"";return`${e.key.padEnd(10)} ${M_e[e.priority]} ${e.title}${t} \xB7 ${n}${o}`}i(Gx,"line");var Nk=i((e,t)=>t.length?[`${e} (${t.length})`,...t.map(r=>` ${Gx(r)}`)]:[],"section");async function dd(e){try{return await e()}catch(t){throw t instanceof rn?new qp(t.message):t instanceof mZ.ZodError?new qp(t.issues.map(r=>`${r.path.join(".")||"input"}: ${r.message}`).join("; ")):t}}i(dd,"run");var Qa=i((e,t,r)=>({exitCode:0,stdout:r?JSON.stringify(e):Array.isArray(t)?t.join(`
1826
+ `).map(t=>t.replace(/^orbit-cap: /,"").trim()).filter(Boolean).pop()??"no reason given").slice(0,300)}i(vM,"lastLine");function T_e(e){return[!e.installed&&"the event service's program (orbit station policy installs it)",!e.options&&"its settings for the station runner (orbit station policy saves them)",!e.runner&&"the station runner's socket (activation.md, Switching the station runner on)"].filter(t=>!!t)}i(T_e,"missing");function _M(e,t,r){let{now:n,ownerAsked:o}=r,s=e??{state:r.fresh?"due":"untouched",at:n},a=null;if(s.state==="asked"){let d=t.request,u=s.target??!0;if(d?.code===null&&d.running)return{record:s,ask:!1,report:o?"event service: a switch question is already waiting":null};d?.code===0&&t.active===u?(s={state:u?"on":"stopped",at:n},a=`event service: switched ${u?"on":"off"} after your approval`):d?d.code===77?s={state:"declined",at:n,reason:vM(d.output)}:s={state:"failed",at:n,reason:d.code===null?"the request ended before an answer":vM(d.output)}:s={state:"failed",at:n,reason:"the request's record on the station is gone"},s.state==="declined"&&(a=`event service: not switched ${u?"on":"off"} (${s.reason}). It stays ${t.active?"on":"off"}, and you won't be asked again unless you ask: ${Wx}.`),s.state==="failed"&&(a=`event service: switching didn't complete and it stays ${t.active?"on":"off"} (${s.reason}). To try again: ${Wx}.`)}else t.active&&s.state!=="on"?(s={state:"on",at:n},a=e?"event service: on":null):!t.active&&s.state==="on"&&(s={state:"stopped",at:n},a=`event service: off now. Orbit won't switch it on or ask again; to be asked: ${Wx}.`);let c=!1,l=r.target??!0;if(o&&t.active===l)a=`event service: already ${l?"on":"off"}`;else if((o||s.state==="due")&&!r.canAsk)o&&(a=__e);else if(o||s.state==="due"&&!t.active){let d=l?T_e(t):t.runner?[]:["the station runner's socket"];d.length?(o&&(a=`event service: you'll be asked once the station has ${d.join(", ")}`),o||(s={state:"due",at:s.at})):(c=!0,s={state:"asked",target:l,at:n},a=`event service: asked you in your Moonlet window whether to switch it ${l?"on":"off"}`)}return{record:s,ask:c,report:a}}i(_M,"decide");var Hx=new Map;function pg(e){return EM(e.dataDir,()=>S_e(e))}i(pg,"reconcileEvents");function EM(e,t){let r=(Hx.get(e)??Promise.resolve()).catch(()=>{}).then(t);return Hx.set(e,r),r.finally(()=>{Hx.get(e)===r&&Hx.delete(e)}).catch(()=>{}),r}i(EM,"withEventsLock");async function S_e(e){let t=await e.station.exec({as:"orbit",script:bM(e.dataDir)}),r=t.code===0?kM(t.stdout):null;if(!r)return"event service: its state on the station couldn't be read, so nothing was changed or asked";let n=e.ownerTarget!==void 0,o=_M(await e.load(),r,{fresh:e.fresh,ownerAsked:n,target:e.ownerTarget,canAsk:e.canAsk,now:e.now()});if(!o.ask)return await e.save(o.record),o.report;let s=typeof e.front=="string"?e.front:await e.front();try{await e.save({...o.record,thread:s})}catch(c){return`event service: the question couldn't be recorded, so it wasn't asked (${c.message})`}let a=await e.station.exec({as:"orbit",script:E_e(e.dataDir,s,o.record.target)}).catch(c=>({code:1,stdout:"",stderr:c.message}));if(a.code!==0||a.stdout.trim()!=="asked"){let c=vM(a.stderr||a.stdout);return await e.save({state:"failed",at:e.now(),reason:`the question couldn't be requested: ${c}`}),`event service: the question couldn't be requested (${c}), so its state is unchanged. To try again: ${Wx}.`}return o.report}i(S_e,"reconcileNow");var Q7=ld.object({active:ld.boolean(),pending:ld.boolean(),thread:ld.string().nullable(),message:ld.string().nullable()}),eZ=A_e({"events.state":{input:ld.null(),output:Q7},"events.switch":{input:ld.object({active:ld.boolean()}).strict(),output:Q7}});async function tZ(e){await e.get("events-switch-migrated")||(await e.delete("events-offer-owner-ask"),await e.set("events-switch-migrated",!0))}i(tZ,"migrateEventService");function rZ(e){async function t(){let n=await e.target();return EM(n.dataDir,async()=>{let o=await n.station.exec({as:"orbit",script:bM(n.dataDir)}),s=o.code===0?kM(o.stdout):null;if(!s)throw new Error("The event service's state couldn't be read. Reconnect the station and try again.");let a=_M(await n.load(),s,{fresh:!1,ownerAsked:!1,canAsk:!1,now:n.now()});return await n.save(a.record),{active:s.active,pending:a.record.state==="asked",thread:a.record.state==="asked"?a.record.thread??null:null,message:a.record.reason??a.report}})}i(t,"state");async function r(n){let o=await e.target(),s=await pg({...o,front:o.questionThread,ownerTarget:n});return{...await t(),message:s}}return i(r,"switchTo"),{state:t,switchTo:r}}i(rZ,"eventService");import{PluginCliError as nZ}from"@get-bb/plugin-sdk";async function iZ(e,t){let r=await e.sdk.threads.internal_DO_NOT_USE_visibleReplyEvidence({threadId:t,body:{}});if(r.status!=="visible")throw new nZ("No current visible reply can satisfy this reminder. Review the conversation and send any answer that is due.");let n=await e.sdk.threads.internal_DO_NOT_USE_visibleReplyEvidence({threadId:t,body:{revision:r.revision}});if(n.status!=="visible"||n.revision!==r.revision||n.messageSeq!==r.messageSeq)throw new nZ("Visible reply evidence changed. Review the current conversation and send any answer that is due.");return n.messageSeq}i(iZ,"acknowledgeVisibleMessage");import{cliCommand as sZ,defineRpcContract as C_e}from"@get-bb/plugin-sdk";import{z as Hc}from"zod";import{createHash as x_e}from"node:crypto";import{z as Qi}from"zod";var O_e=Qi.string().regex(wn),R_e=Qi.object({version:Qi.literal(1),phase:Qi.enum(["snapshot","tasks","history","index","complete"]),pending:Qi.array(O_e),checked:Qi.number().int().nonnegative(),waiting:Qi.string().nullable()}),$k="task-reconciliation-v1",I_e="meaning-needed",$_e=/^(?:review:|worker:|ci:|prompt:|approve:|unread:|rule:|schedule:|output-clean:|archive-output:|fixture-expiry:|retention:work)/i,N_e=/https:\/\/github\.com\/[A-Za-z0-9][A-Za-z0-9-]*\/[A-Za-z0-9_.-]+\/pull\/[1-9][0-9]{0,8}\b/g;function P_e(e,t){if(e.project.id===Ri)return!1;let r=[...e.description.matchAll(/^Work start: ([^\n]+)$/gm)].at(-1)?.[1];if(r)return t.some(s=>s.key===r&&s.key.startsWith("review:")&&s.class==="background")&&!t.some(s=>!s.key.startsWith("review:")&&!s.key.startsWith("event:"));let n=/^Key: ([^\n]+)(?:\n|$)/.exec(e.description)?.[1];if(!n)return!1;let o=/^Labels: ([^\n]*)$/m.exec(e.description)?.[1]?.split(",").map(s=>s.trim())??[];return[...e.labels,...o].includes("event-service")||$_e.test(n)}i(P_e,"systemRecord");function oZ(e,t){let r=Ce(e),n=t.tasks??(()=>Gt(e)),o=null,s=VR(e,n),a=i(()=>e.realtime.publish("tasks",{changed:!0}),"changed");async function c(){let h=await e.storage.kv.get($k);return h==null?null:R_e.parse(h)}i(c,"status");function l(h,p){let g=n().store;g.update(h.id,{addLabels:[I_e]},"system"),g.note(h.id,"system",`Needs your decision: ${p}`,"note",`meaning-needed:${x_e("sha256").update(p).digest("hex").slice(0,32)}`),a()}i(l,"hold");async function d(){let h=n(),p=await h.moveOrb();if(!await h.orbMoved())throw new Error(p?.failed.length?`The old task board is partly moved; ${p.failed.length} tasks are still to come over`:"The old task board hasn't moved into Moonlet's tasks yet");let g=new Set;for(let m of Qi.array(Qi.object({orb:Qi.string()})).parse(r.prepare("SELECT orb FROM task_orb_mirror ORDER BY orb").all())){let y=h.store.find(m.orb);y&&g.add(y.key)}return[...g]}i(d,"snapshot");async function u(h){let p=n().store,g=p.find(h);if(!g||g.status==="dropped")return;let m=fk(p,g),y=Qi.array(Qi.object({key:Qi.string(),class:Qi.string()})).parse(r.prepare(`SELECT key, class FROM work_items WHERE loop IN (${m.map(()=>"?").join(",")})`).all(...m));if(P_e(g,y))return;let w=p.links(g.id).filter(b=>b.kind==="conversation"&&/^thr_[a-z0-9]+$/.test(b.ref)).map(b=>b.ref),k=await t.workers(m,g.description,w),E=!1;for(let b of k){let S=await e.sdk.threads.get({threadId:b}),P=await e.sdk.threads.timeline({threadId:b,summaryOnly:"true",segmentLimit:"1"});E||=["active","starting","pending"].includes(S.status)||!!P.goal&&P.goal.status!=="complete"||P.activeWorkflows.length>0||P.activeBackgroundCommands.length>0||!!P.pendingTodos?.items.some(A=>A.status!=="completed"),E||=(await e.sdk.threads.interactions.list({threadId:b})).some(A=>A.status==="pending")}let v=y.length>0;if(g.status==="done"&&!E&&!v)return;v||await e.storage.kv.set(bj(g.key),!0);for(let b of k)await s.attach({loop:g.key,thread:b});let I=hx(g.description);if(I&&!t.repos().includes(new URL(I).pathname.split("/").slice(1,3).join("/"))){l(g,"the named repository is not available for independent completion evidence");return}let T=[...g.description.matchAll(N_e)].map(b=>b[0]);if((!I||T.some(b=>b!==I))&&(T.length>0||kj(g)==="in_review")&&!E&&!v){l(g,"the completion condition needs a decision; a pull request reference alone does not finish this promise");return}let _=i(b=>JSON.stringify([b.title,b.description,b.doneWhen,b.priority,b.status]),"meaning");if(I&&T.every(b=>b===I)&&!p.list({parent:g.id,status:"open",limit:1}).tasks.length){if(_(p.get(g.id))!==_(g))return;p.links(g.id).some(b=>b.kind==="pull_request"&&b.ref===I)||(p.link(g.id,{kind:"pull_request",ref:I,label:null}),a())}await t.update(g.key);let R=p.get(g.id);if(R.status!=="done"&&(R.description!==g.description||R.title!==g.title||R.priority!==g.priority||R.doneWhen!==g.doneWhen))throw new Error("Task meaning changed during reconciliation; its current condition will be read again")}i(u,"reconcile");async function f(){let h=await c();if(h?.phase!=="complete"){h||(h={version:1,phase:"snapshot",pending:[],checked:0,waiting:null},await e.storage.kv.set($k,h)),h.waiting=null;try{if(h.phase==="snapshot"&&(h.pending=await d(),h.phase="tasks",await e.storage.kv.set($k,h)),h.phase==="tasks"){let p=h.pending.slice(0,12),g=null;for(let m of p){try{await u(m),h.pending=h.pending.filter(y=>y!==m),h.checked++}catch(y){h.pending=[...h.pending.filter(w=>w!==m),m],h.waiting=y instanceof Error?y.message:String(y),g=y}await e.storage.kv.set($k,h)}if(g)throw g;h.pending.length||(h.phase="history")}if(h.phase==="history"){let p=await t.historyStep();p.waiting?h.waiting=p.waiting:h.phase="index"}h.phase==="index"&&(h.waiting=await t.index(),h.waiting===null&&(h.phase="complete"))}catch(p){throw h.waiting=p instanceof Error?p.message:String(p),p}finally{await e.storage.kv.set($k,h)}}}return i(f,"pass"),{status:c,tick(){return o??=f().finally(()=>{o=null}),o}}}i(oZ,"taskReconciliation");var aZ=Hc.object({version:Hc.literal(1),phase:Hc.enum(["snapshot","tasks","history","index","complete"]),pending:Hc.array(Hc.string()),checked:Hc.number(),waiting:Hc.string().nullable()}).nullable(),L_e=C_e({"tasks.reconciliation":{input:Hc.null(),output:aZ},"tasks.reconcile":{input:Hc.null(),output:aZ}}),TM=new WeakMap;function cZ(e,t){let r=oZ(e,t);return TM.set(e,r),e.rpc.register(L_e,{"tasks.reconciliation":i(()=>r.status(),"tasks.reconciliation"),"tasks.reconcile":i(async()=>(await r.tick(),r.status()),"tasks.reconcile")}),ot(e,"task-reconciliation","* * * * *",r.tick),r.tick().catch(n=>e.log.warn(`Task reconciliation: ${String(n)}`)),r}i(cZ,"setupTaskReconciliation");function lZ(e,t){return{"tasks reconciliation":sZ({summary:"Read the automatic board reconciliation progress",async run(r,n){await t(n.threadId);let o=TM.get(e);if(!o)throw new Error("Task reconciliation is not ready");return{exitCode:0,stdout:JSON.stringify(await o.status())}}}),"tasks reconcile":sZ({summary:"Retry the automatic board reconciliation without changing task meaning",async run(r,n){await t(n.threadId);let o=TM.get(e);if(!o)throw new Error("Task reconciliation is not ready");return await o.tick(),{exitCode:0,stdout:JSON.stringify(await o.status())}}})}}i(lZ,"taskReconciliationCommands");import{cliCommand as fg,PluginCliError as dZ}from"@get-bb/plugin-sdk";var uZ={name:"id",description:"System record identity, including a historical ORB alias",required:!0},hg={type:"boolean",description:"Emit JSON"},mg=i(e=>({exitCode:0,stdout:JSON.stringify(e)}),"output");function pZ(e){return{"records ready":fg({summary:"Prepare durable system records without changing task history",options:{json:hg},async run(){return await Qs(e).ready(),mg({ready:!0,version:1})}}),"records show":fg({summary:"Read one work record, notice or watch",positionals:[uZ],options:{json:hg},async run(t){let r=await Qs(e).query({action:"get",id:t.positionals.id});if(!r.records.length&&!t.options.json)throw new dZ("System record not found");return mg(r)}}),"records find":fg({summary:"Find a system record by its exact event key",options:{key:{type:"string",required:!0,description:"Exact event key"},json:hg},async run(t){return mg(await Qs(e).query({action:"find",key:t.options.key}))}}),"records list":fg({summary:"List work, notices and watches with bounded pages",options:{all:{type:"boolean",description:"Include resolved work and notice history"},label:{type:"string",description:"Filter by label"},parent:{type:"string",description:"Parent record or task identity"},after:{type:"integer",min:0,max:Number.MAX_SAFE_INTEGER,default:0,description:"Continue after this sequence"},limit:{type:"integer",min:1,max:200,default:100,description:"Maximum records in a page"},json:hg},async run(t){return mg(await Qs(e).query({action:"list",active:!t.options.all,label:t.options.label??"",parent:t.options.parent??null,after:t.options.after,limit:t.options.limit}))}}),"records change":fg({summary:"Record system work, notice or watch state",options:{data:{type:"string",required:!0,description:"JSON create, update or comment operation; never changes a task's meaning"},json:hg},async run(t,r){let n;try{n=JSON.parse(t.options.data)}catch{throw new dZ("Record data must be JSON")}let o=g_["records.change"].input.parse(n);return mg(await Qs(e).change(o,r.threadId?`conversation:${r.threadId}`:"cli:records"))}}),"records comments":fg({summary:"Read system record comments",positionals:[uZ],options:{after:{type:"integer",min:0,max:Number.MAX_SAFE_INTEGER,default:0,description:"Continue after this comment sequence"},limit:{type:"integer",min:1,max:200,default:100,description:"Maximum comments"},json:hg},async run(t){let r=Qs(e);return await r.ready(),mg(r.store.comments(t.positionals.id,t.options.after,t.options.limit))}})}}i(pZ,"eventRecordCommands");import{PluginCliError as D_e}from"@get-bb/plugin-sdk";function fZ(e){async function t(n,o){return n===o||!!await e.orbitConversationOf(n)}i(t,"moonletConversation");async function r(n){let o=await e.backThread().catch(()=>null),s=await e.parentOf(n);for(let a=0;s&&a<16;a++){if(await t(s,o))return!0;s=await e.parentOf(s)}return!1}return i(r,"startedByMoonlet"),async n=>{if(!n)return await e.requireUser(n),"owner";if(await t(n,await e.backThread().catch(()=>null))||await e.onStation(n)||await e.onListedMachine(n)&&await r(n))return"assistant";if(await e.requireUser(n).then(()=>!0,()=>!1))return"owner";throw new D_e("Tasks are read and changed by the owner, the Moonlet conversation, and work on its stations or the owner's machines.")}}i(fZ,"taskCaller");import{cliCommand as Xn,PluginCliError as qp}from"@get-bb/plugin-sdk";import{z as mZ}from"zod";var Yn={type:"boolean",description:"Print JSON"},Wc={name:"task",description:"A task key (ME-3, MOON-1308), an old key (ORB-12, L-0042) or its id",required:!0},zx=["todo","followup","scheduled"],SM=["owner","assistant","others"],hZ=["urgent","high","medium","low","none"],j_e=["owner","assistant"],M_e={urgent:"!!",high:"! ",medium:" ",low:"\xB7 ",none:" "},B_e=mZ.enum(["chat","mail","message","calendar","conversation","cli"]),U_e={owner:"your move",assistant:"assistant\u2019s move",others:"waiting"};function Gx(e){let t=e.whenText?` \xB7 ${e.whenText}`:"",r=e.move==="others"&&e.waitingOn?` on ${e.waitingOn}`:"",n=e.status==="open"?`${U_e[e.move]}${r}`:e.status,o=e.origin==="assistant"?" \xB7 added by the assistant":"";return`${e.key.padEnd(10)} ${M_e[e.priority]} ${e.title}${t} \xB7 ${n}${o}`}i(Gx,"line");var Nk=i((e,t)=>t.length?[`${e} (${t.length})`,...t.map(r=>` ${Gx(r)}`)]:[],"section");async function dd(e){try{return await e()}catch(t){throw t instanceof rn?new qp(t.message):t instanceof mZ.ZodError?new qp(t.issues.map(r=>`${r.path.join(".")||"input"}: ${r.message}`).join("; ")):t}}i(dd,"run");var Qa=i((e,t,r)=>({exitCode:0,stdout:r?JSON.stringify(e):Array.isArray(t)?t.join(`
1827
1827
  `):t}),"out"),q_e=768*1024,AM=200,xM=i(e=>({key:e.key,title:e.title,project:e.project.key,kind:e.kind,priority:e.priority,move:e.move,waitingOn:e.waitingOn,dueAt:e.dueAt,whenText:e.whenText}),"brief");function OM(e,t){let r=t==="newest"?[...e].reverse():e,n=[],o=0;for(let s of r){if(o+=Buffer.byteLength(JSON.stringify(s))+1,o>q_e&&n.length)break;n.push(s)}return t==="newest"?n.reverse():n}i(OM,"fitOutput");function gZ(e,t){let r=i(()=>Gt(e),"service");async function n(s,a){if(s===void 0)return;await r().fresh();let c=r().parse(s,a);if(!c.ok)throw new qp(c.error);return c.when}i(n,"when");async function o(s,a,c){let l=await t(a),d=await dd(()=>r().apply(s,l,l==="owner"?"owner":"assistant"));return Qa(d,Gx(d),c)}return i(o,"change"),{"tasks today":Xn({summary:"What needs the owner, what the assistant is on, what's waiting, and today's times",options:{project:{type:"string",description:"Only this project (key, name or id)"},json:Yn},async run(s,a){await t(a.threadId);let c=await dd(()=>r().today({project:s.options.project})),l=[{name:"yours",title:"Your move",more:"--move owner",tasks:c.yours},{name:"onIt",title:"Assistant\u2019s move",more:"--move assistant",tasks:c.onIt},{name:"waiting",title:"Waiting on others",more:"--move others --sort due",tasks:c.waiting},{name:"overdue",title:"Overdue",more:"--sort due",tasks:c.overdue}].map(p=>({...p,shown:p.tasks.slice(0,AM)})),d=c.schedule.slice(0,AM),u=d.map(p=>` ${yd(ls(p.at,c.zone)).padEnd(9)} ${p.task.key} ${p.task.title}`),f=i(p=>p.tasks.length>p.shown.length?[` ${p.tasks.length-p.shown.length} more: bb orbit tasks list ${p.more}`]:[],"more"),h=i(p=>l.find(g=>g.name===p),"sectionOf");return Qa({day:c.day,zone:c.zone,...Object.fromEntries(l.map(p=>[p.name,p.shown.map(xM)])),schedule:d.map(p=>({at:p.at,timed:p.timed,task:xM(p.task)})),more:{...Object.fromEntries(l.map(p=>[p.name,p.tasks.length-p.shown.length])),schedule:c.schedule.length-d.length}},[`Today, ${c.day}`,...Nk("Your move",h("yours").shown),...f(h("yours")),...Nk("Assistant\u2019s move",h("onIt").shown),...f(h("onIt")),...Nk("Waiting on others",h("waiting").shown),...f(h("waiting")),...u.length?["Today\u2019s times",...u]:[],...Nk("Overdue",h("overdue").shown),...f(h("overdue"))],s.options.json)}}),"tasks now":Xn({summary:"For the assistant at the start of a turn: its move, what's due within a day, and check-backs that have come",options:{json:Yn},async run(s,a){await t(a.threadId);let c=r();await c.fresh();let l=c.store.attention(),d=[{name:"mine",title:"Your move (the assistant\u2019s)",more:"--move assistant",tasks:l.mine},{name:"due",title:"Due within a day",more:"--sort due",tasks:l.due},{name:"checks",title:"Check-backs that have come",more:"--move others --sort due",tasks:l.checks},{name:"unwatched",title:"Waiting with nothing watching",more:"--move others",tasks:l.unwatched}].map(u=>({...u,shown:u.tasks.slice(0,AM).map(f=>c.decorate(f))}));return Qa({...Object.fromEntries(d.map(u=>[u.name,u.shown.map(xM)])),more:Object.fromEntries(d.map(u=>[u.name,u.tasks.length-u.shown.length]))},d.flatMap(u=>[...Nk(u.title,u.shown),...u.tasks.length>u.shown.length?[` ${u.tasks.length-u.shown.length} more: bb orbit tasks list ${u.more}`]:[]]).join(`
1828
1828
  `)||"Nothing is due and nothing is waiting on you.",s.options.json)}}),"tasks list":Xn({summary:"List tasks, ordered by priority then when",options:{project:{type:"string",description:"Project key, name or id"},origin:{type:"enum",values:j_e,description:"Who added it"},move:{type:"enum",values:SM,description:"Whose move it is"},kind:{type:"enum",values:zx,description:"Kind of task"},status:{type:"enum",values:["open","done","dropped","all"],default:"open",description:"Which tasks"},label:{type:"string",description:"Only tasks with this label"},search:{type:"string",description:"Words in the title or description"},sort:{type:"enum",values:["priority","due","closed"],default:"priority",description:"By priority then when, by when then priority, or most recently closed first"},offset:{type:"integer",min:0,max:1e6,default:0,description:"Skip this many"},limit:{type:"integer",min:1,max:500,default:100,description:"At most this many"},json:Yn},async run(s,a){await t(a.threadId);let c=r();await c.fresh();let l=s.options,d=await dd(async()=>c.store.list({project:l.project,origin:l.origin,move:l.move,kind:l.kind,status:l.status,label:l.label,search:l.search,sort:l.sort,offset:l.offset,limit:l.limit})),u=OM(d.tasks.map(h=>c.decorate(h)),"oldest"),f=u.length<d.tasks.length?l.offset+u.length:d.next;return Qa({tasks:u,next:f,total:d.total},u.length?[...u.map(Gx),...f!==null?[`${d.total-f} more: --offset ${f}`]:[]]:"No tasks match.",s.options.json)}}),"tasks show":Xn({summary:"One task with its steps, links, old keys and its newest journal lines",positionals:[Wc],options:{recent:{type:"integer",min:1,max:500,default:200,description:"How many of the newest journal lines to show"},json:Yn},async run(s,a){await t(a.threadId);let c=r();await c.fresh();let l=await dd(async()=>c.store.show(s.positionals.task,s.options.recent)),d=OM(l.journal,"newest"),u={...l,journal:d,earlier:d.length<l.journal.length?d[0]?.seq??l.earlier:l.earlier},f=c.decorate(u.task),h=c.zone();return Qa({...u,task:f},[Gx(f),`Project: ${f.project.name} (${f.project.key})${u.aliases.length?` \xB7 also ${u.aliases.join(", ")}`:""}`,...f.why?[`Why: ${f.why}`]:[],...f.doneWhen?[`Done when: ${f.doneWhen}`]:[],...f.description?["",f.description]:[],...u.steps.length?["","Steps",...u.steps.map(p=>` ${p.doneAt?"[x]":"[ ]"} ${p.position}. ${p.title}`)]:[],...u.links.length?["","Links",...u.links.map(p=>` ${p.kind}: ${p.ref}${p.label?` (${p.label})`:""}`)]:[],"","Journal",...u.earlier!==null?[` Earlier lines: bb orbit tasks journal --task ${f.key} --before ${u.earlier}`]:[],...u.journal.map(p=>` ${tn(p.at,h)} ${ls(p.at,h)} ${p.actor}: ${p.body}`)],s.options.json)}}),"tasks add":Xn({summary:"Add a task. The assistant says --why; a waiting task names --waiting-on",options:{title:{type:"string",required:!0,description:"What the task is"},project:{type:"string",default:"personal",description:"Project key, name or id (personal, internal, MOON, \u2026)"},description:{type:"string",description:"Background"},"done-when":{type:"string",description:"What finishing means"},kind:{type:"enum",values:zx,default:"todo",description:"to-do, follow-up or scheduled"},when:{type:"string",description:"In plain words: \u201Ctoday 5pm\u201D, \u201Cby friday\u201D, \u201Cevery weekday at 7:30\u201D, \u201Ccheck back fri 9am\u201D"},priority:{type:"enum",values:hZ,default:"medium",description:"Priority"},move:{type:"enum",values:SM,default:"assistant",description:"Whose move it is"},"waiting-on":{type:"string",description:"Who a waiting task waits on"},why:{type:"string",description:"Why the assistant added it, in one line"},source:{type:"string",description:"Where it came from, as kind:ref (mail:<id>, chat:<seq>, message:<id>)"},label:{type:"string",repeatable:!0,split:",",description:"Labels"},parent:{type:"string",description:"Parent task"},step:{type:"string",repeatable:!0,description:"A step, in order"},json:Yn},async run(s,a){let c=s.options,l=c.source?/^(chat|mail|message|calendar|conversation|cli):(.+)$/.exec(c.source):null;if(c.source&&!l)throw new qp("--source is kind:ref, with kind one of chat, mail, message, calendar, conversation, cli");let d=l?{kind:B_e.parse(l[1]),ref:l[2]??""}:null;return o({action:"create",task:{project:c.project,title:c.title,description:c.description??"",doneWhen:c["done-when"]??"",kind:c.kind,move:c.move,waitingOn:c["waiting-on"]??null,priority:c.priority,why:c.why??null,when:await n(c.when,c.kind)??null,source:d,labels:c.label??[],parent:c.parent??null,steps:c.step??[]}},a.threadId,c.json)}}),"tasks update":Xn({summary:"Change a task. Re-ranks and hand-overs are journaled with --why",positionals:[Wc],options:{title:{type:"string",description:"New title"},description:{type:"string",description:"New description"},"done-when":{type:"string",description:"What finishing means"},kind:{type:"enum",values:zx,description:"Kind"},when:{type:"string",description:"New when, in plain words"},"no-when":{type:"boolean",description:"Clear the when"},priority:{type:"enum",values:hZ,description:"Priority"},move:{type:"enum",values:SM,description:"Whose move it is"},"waiting-on":{type:"string",description:"Who it waits on"},label:{type:"string",repeatable:!0,split:",",description:"Add labels"},"remove-label":{type:"string",repeatable:!0,split:",",description:"Remove labels"},parent:{type:"string",description:"New parent"},"no-parent":{type:"boolean",description:"No longer a subtask"},why:{type:"string",description:"Why, for the journal"},json:Yn},async run(s,a){let c=s.options,l=r(),d=await dd(async()=>l.store.get(s.positionals.task));return o({action:"update",ref:d.id,patch:{title:c.title,description:c.description,doneWhen:c["done-when"],kind:c.kind,priority:c.priority,move:c.move,waitingOn:c["waiting-on"],when:c["no-when"]?null:await n(c.when,c.kind??d.kind),addLabels:c.label,removeLabels:c["remove-label"],parent:c["no-parent"]?null:c.parent,why:c.why}},a.threadId,c.json)}}),"tasks done":Xn({summary:"Mark a task done",positionals:[Wc],options:{note:{type:"string",description:"How it ended"},json:Yn},run:i((s,a)=>o({action:"done",ref:s.positionals.task,note:s.options.note??null},a.threadId,s.options.json),"run")}),"tasks drop":Xn({summary:"Drop a task, with the reason. The assistant can undo a drop for 7 days",positionals:[Wc],options:{reason:{type:"string",required:!0,description:"Why it no longer matters"},json:Yn},run:i((s,a)=>o({action:"drop",ref:s.positionals.task,reason:s.options.reason},a.threadId,s.options.json),"run")}),"tasks reopen":Xn({summary:"Reopen a done or dropped task",positionals:[Wc],options:{why:{type:"string",description:"Why"},json:Yn},run:i((s,a)=>o({action:"reopen",ref:s.positionals.task,why:s.options.why??null},a.threadId,s.options.json),"run")}),"tasks move":Xn({summary:"Move a task to another project; its old key keeps working",positionals:[Wc],options:{project:{type:"string",required:!0,description:"Destination project"},json:Yn},run:i((s,a)=>o({action:"move",ref:s.positionals.task,project:s.options.project},a.threadId,s.options.json),"run")}),"tasks note":Xn({summary:"Add a line to a task's journal",positionals:[Wc],options:{body:{type:"string",required:!0,stdin:!0,description:"What happened, or what to remember"},json:Yn},run:i((s,a)=>o({action:"note",ref:s.positionals.task,body:s.options.body},a.threadId,s.options.json),"run")}),"tasks step":Xn({summary:"Add a step, or mark one done or not done",positionals:[Wc],options:{add:{type:"string",description:"A new step's title"},check:{type:"integer",min:1,max:1e3,description:"Mark this step done"},uncheck:{type:"integer",min:1,max:1e3,description:"Mark this step not done"},json:Yn},async run(s,a){let c=s.options;if([c.add!==void 0,c.check!==void 0,c.uncheck!==void 0].filter(Boolean).length!==1)throw new qp("Give one of --add, --check or --uncheck");return c.add!==void 0?o({action:"addStep",ref:s.positionals.task,title:c.add},a.threadId,c.json):o({action:"checkStep",ref:s.positionals.task,position:c.check??c.uncheck??0,done:c.check!==void 0},a.threadId,c.json)}}),"tasks link":Xn({summary:"Link a conversation, page, pull request, mail, schedule or address to a task",positionals:[Wc],options:{kind:{type:"enum",values:["conversation","artifact","pull_request","mail","task","schedule","url"],required:!0,description:"What it is"},ref:{type:"string",required:!0,description:"Its id or address"},label:{type:"string",description:"A short label"},json:Yn},run:i((s,a)=>o({action:"link",ref:s.positionals.task,link:{kind:s.options.kind,ref:s.options.ref,label:s.options.label??null}},a.threadId,s.options.json),"run")}),"tasks journal":Xn({summary:"Read the journal: one task's, one project's or one day's",options:{task:{type:"string",description:"One task"},project:{type:"string",description:"One project"},actor:{type:"enum",values:["owner","assistant","system"],description:"Whose lines"},day:{type:"string",description:"One day, YYYY-MM-DD in the owner's zone"},after:{type:"integer",min:0,max:Number.MAX_SAFE_INTEGER,default:0,description:"Continue after this line"},before:{type:"integer",min:1,max:Number.MAX_SAFE_INTEGER,description:"Read back from this line: the newest lines before it"},limit:{type:"integer",min:1,max:500,default:200,description:"At most this many lines"},json:Yn},async run(s,a){await t(a.threadId);let c=r(),l=s.options,d=l.before!==void 0,u=await dd(()=>c.journalDay({task:l.task,project:l.project,actor:l.actor,day:l.day,after:l.after,before:l.before,newest:d,limit:l.limit})),f=OM(u.entries,d?"newest":"oldest"),h=f.length<u.entries.length,p={...u,entries:f,next:h?(d?f[0]?.seq:f.at(-1)?.seq)??u.next:u.next},g=c.zone();return Qa(p,[...p.notes.map(m=>`Note from ${m.actor}: ${m.body}`),...p.entries.map(m=>`${tn(m.at,g)} ${ls(m.at,g)} ${m.key} ${m.actor}: ${m.body}`),...p.next!==null?[`More: ${d?"--before":"--after"} ${p.next}`]:[]].join(`
1829
1829
  `)||"Nothing in the journal for that.",l.json)}}),"tasks day-note":Xn({summary:"Write a day's note: the owner's own, or the assistant's summary of the day",options:{body:{type:"string",required:!0,stdin:!0,description:"The note; an empty one clears it"},day:{type:"string",description:"The day, YYYY-MM-DD in the owner's zone (today if left out)"},json:Yn},async run(s,a){let c=await t(a.threadId),l=r();await l.fresh();let d=s.options.day??tn(Date.now(),l.zone());if(!/^\d{4}-\d{2}-\d{2}$/.test(d))throw new qp("--day is YYYY-MM-DD");return await dd(async()=>l.writeDayNote(d,c,s.options.body)),Qa({day:d,actor:c},`Saved the ${c==="owner"?"owner\u2019s":"assistant\u2019s"} note for ${d}.`,s.options.json)}}),"tasks projects":Xn({summary:"The projects tasks belong to, with their keys",options:{json:Yn},async run(s,a){await t(a.threadId);let c=r().store.projects();return Qa(c,c.map(l=>`${l.key.padEnd(8)} ${l.name} (${l.id})`),s.options.json)}}),"tasks when":Xn({summary:"Read a when in plain words, and show the next five times",positionals:[{name:"text",description:"For example \u201Cevery other friday at 4pm starting next week\u201D",required:!0}],options:{kind:{type:"enum",values:zx,default:"todo",description:"The task's kind, which decides what a bare time means"},json:Yn},async run(s,a){await t(a.threadId);let c=r();await c.fresh();let l=c.parse(s.positionals.text,s.options.kind);if(!l.ok)throw new qp(l.error);let d=c.zone();return Qa(l,[l.reading,...l.next.map(u=>` ${tn(u,d)} ${yd(ls(u,d))}`)],s.options.json)}}),"tasks move-orb":Xn({summary:"Move ORB's tasks into Moonlet, once; after that ORB is retired and never read again",options:{json:Yn},async run(s,a){await t(a.threadId);let c=await dd(()=>r().moveOrb()),l=i((u,f)=>f.length?`