@join-pantheon/cli 0.37.3 → 0.38.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/worker.js CHANGED
@@ -20,7 +20,9 @@ import { AGENTS, headlessSpawn, materializeSpawnFiles, chooseAgent, agentById, d
20
20
  import { activeOutages, detectOutage, earliest, isSignOut, outagePredicate, whenAgain, SIGNIN_REFUSED } from "./agent-outage.js";
21
21
  import { agentSpawn, CmdLineUnsafe } from "./which.js";
22
22
  import { VERSION } from "./version.js";
23
- import { applyAnswer, ASK_EXPIRY_MS, policyUnreadable, CAPABILITY_ARGS, CARRY_REASON, carryOverWakers, dropLedgerGrants, hasWakeOnce, isApprovedWaker, mayAskWake, takeWakeOnce, OLD_RELAY_WAKE, relayKnowsAdmitters, loadPolicy, mayAsk, needsSelfUpgrade, parseGrantAnswer, recordAsk, savePolicy, useGrant, WOKEN_RUN_ENV, takeTeamFlagOnYes, unsandboxedAllowed, policyPath, isNewer, RUN_MINUTES, effectiveRunMinutes, effectiveIdleSeconds, readinessRecheckPath, policyHome, describeRunMinutes, parseRunMinutes, currentMode, wakeSettled, } from "./worker-policy.js";
23
+ import { composeUpgradeFailed, fetchRelayPkg, recordRelayPkg, upgradeFailedOnce } from "./version-health.js";
24
+ import { noteServiceConnected } from "./crash-loop.js";
25
+ import { applyAnswer, ASK_EXPIRY_MS, policyUnreadable, CAPABILITY_ARGS, CARRY_REASON, carryOverWakers, dropLedgerGrants, hasWakeOnce, isApprovedWaker, mayAskWake, takeWakeOnce, OLD_RELAY_WAKE, relayKnowsAdmitters, loadPolicy, mayAsk, needsSelfUpgrade, parseGrantAnswer, recordAsk, savePolicy, useGrant, WOKEN_RUN_ENV, takeTeamFlagOnYes, unsandboxedAllowed, policyPath, isNewer, RUN_MINUTES, effectiveRunMinutes, effectiveIdleSeconds, readinessRecheckPath, policyHome, describeRunMinutes, parseRunMinutes, currentMode, wakeSettled, effectiveRunModel, describeRunModel, effectiveGoalRuns, claudeRouting, } from "./worker-policy.js";
24
26
  import { readinessAlerts } from "./readiness-alert.js";
25
27
  import { clearDeclined, markDeclined, personsOwnThread, pruneDeclined } from "./declined.js";
26
28
  import { loadRunStops, markStopTold, pruneRunStops, requestRunStop, stopFor, stopNote } from "./run-control.js";
@@ -28,7 +30,7 @@ import { runtimeNodeVersion } from "./managed.js";
28
30
  import { removalWords, removedLine, removedNotice, takeTold } from "./removed.js";
29
31
  import { agentHookStates, repairHook, repairNote } from "./notify.js";
30
32
  import { fence, assess } from "./untrusted.js";
31
- import { allowed, closeStartedRun, finishRun, recordRun, startRun } from "./spend.js";
33
+ import { allowed, closeStartedRun, finishRun, goalAllowed, recordRun, startRun } from "./spend.js";
32
34
  import { handledIn, liveReadAt, loadContinued, markContinued, storedIn, storedKey, unmarkContinued, wakeAlertedKey, WORKER_MARK } from "./continued.js";
33
35
  import { decisionAlertsOn, loadProfile, profileForTeam, reservedDecisionsNote, saveProfile, wakeMode } from "./profile.js";
34
36
  import { clip } from "./brief.js";
@@ -939,7 +941,7 @@ DO THIS
939
941
  There is no human in this session. Do not ask for approval; you will not get an answer.
940
942
  Keep going until you have replied, then finish.`;
941
943
  }
942
- export function buildContinuationBrief(act, trigger, branch, persona, canPush = false) {
944
+ export function buildContinuationBrief(act, trigger, branch, persona, canPush = false, more = []) {
943
945
  const placed = branch
944
946
  ? `in an isolated git worktree on branch ${branch}`
945
947
  : `in a scratch directory (your human's workspace is not a git repo, so nothing can be DELIVERED from here)`;
@@ -966,7 +968,7 @@ WHY YOU WERE WOKEN
966
968
  This ${kind} (id ${id}) is addressed to your side and creates no formal obligation —
967
969
  nothing else on this machine will act on it. The continuation lock is already held for this
968
970
  run: do NOT call pantheon_claim.
969
- ${persona ? personaBrief(persona) : ""}
971
+ ${persona ? personaBrief(persona) : ""}${moreRepliesBrief(more)}
970
972
  DO THIS
971
973
  1. pantheon_status, then pantheon_history${inGoal("for")} — if the thread shows your side
972
974
  already responded after this ${kind}, STOP and send nothing; it was handled live.
@@ -980,6 +982,19 @@ DO THIS
980
982
  There is no human in this session. Do not ask for approval; you will not get an answer.
981
983
  Act, reply if a reply is owed, then finish.`;
982
984
  }
985
+ export function moreRepliesBrief(more) {
986
+ if (!more.length)
987
+ return "";
988
+ const blocks = more.map((m) => `${fence("your peer", actLine(m))}\n${riskNote(assess(actLine(m)), "what arrived")}`.trimEnd());
989
+ return `
990
+ ALSO ARRIVED FOR YOU — ${more.length} more ${more.length === 1 ? "reply" : "replies"} with the ball in your court, each already
991
+ locked for this run (do NOT call pantheon_claim for ${more.length === 1 ? "it" : "them"}). Handle each in its OWN goal, after the
992
+ one above, the same way: use the answer; pantheon_send CLOSE in that goal if it settles it, otherwise the
993
+ one act that moves it forward. If one needs code work, do it only if it belongs on this branch; otherwise
994
+ reply in its goal and leave the code for a run of its own. One you leave untouched gets a run of its own.
995
+ ${blocks.join("\n\n")}
996
+ `;
997
+ }
983
998
  export function autopilotBrief(who) {
984
999
  return `
985
1000
 
@@ -1470,6 +1485,9 @@ const HELD_BACKOFF_MS = 60_000;
1470
1485
  const HELD_BACKOFF_MAX_MS = 30 * 60_000;
1471
1486
  export const EXIT_GRACE_MS = 3_000;
1472
1487
  const CONTINUATION_HORIZON_MS = 24 * 60 * 60_000;
1488
+ export const GATHER_MAX_MS = 10 * 60_000;
1489
+ export const SWEEP_SPAN_MS = 3 * 60_000;
1490
+ export const FOLD_MAX = 5;
1473
1491
  const HELD_CONTINUATIONS_MAX = 20;
1474
1492
  export function answerWindow(askSeq, hint, fullScanDue) {
1475
1493
  if (askSeq !== null)
@@ -2925,7 +2943,8 @@ export class Worker {
2925
2943
  act: "NOTE", goal: o.goal, ref: o.ref, to: [member], after_seq: Math.max(client.readSeq, client.seq),
2926
2944
  summary: `${this.cfg.member} has been asked to let you start work on their machine — this waits for that`,
2927
2945
  body: `${this.cfg.member}'s machine takes unattended requests only from people ${this.cfg.member} approved there. ${this.cfg.member} has just been asked about you; once they say yes, this runs on its own. Nothing was run yet.`,
2928
- }).catch(() => { });
2946
+ meta: { declined: "wake_ask" },
2947
+ }).then(() => this.markFor("declined-told", o.id), () => { });
2929
2948
  }
2930
2949
  catch (e) {
2931
2950
  this.opts.log(`! could not ask whether ${member} may wake this machine: ${e.message}`);
@@ -3132,6 +3151,7 @@ export class Worker {
3132
3151
  try {
3133
3152
  await this.recoverGuard();
3134
3153
  await client.connect();
3154
+ noteServiceConnected();
3135
3155
  this.client = client;
3136
3156
  await (this.opts.alertsOnly ? this.sayKeyChanges(client) : this.opts.housekeeping ? this.keepHouse(client) : this.serve(client));
3137
3157
  }
@@ -3382,8 +3402,6 @@ export class Worker {
3382
3402
  : /cannot tell who sent it/.test(refusedWake.why) ? "it could not be told who sent it"
3383
3403
  : `${asker} isn't approved to start work on this computer`;
3384
3404
  this.decline(o.ref, why);
3385
- if (this.mode() === "autopilot" && !refusedWake.transient)
3386
- await this.tellAskerDeclined(client, o, reqAct, refusedWake.askable ? `it waits for ${this.cfg.member} to approve you` : "this machine doesn't start work for you on its own");
3387
3405
  if (!this.skipLogged.has(`wake:${o.id}`)) {
3388
3406
  this.skipLogged.add(`wake:${o.id}`);
3389
3407
  this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: ${refusedWake.why} — it waits for a live session`);
@@ -3402,6 +3420,19 @@ export class Worker {
3402
3420
  this.tickHold = { reason: "awaiting_wake_approval", detail: "asking its person whether this teammate may start work here" };
3403
3421
  }
3404
3422
  }
3423
+ if (!refusedWake.transient) {
3424
+ const asking = !!refusedWake.askable && (() => {
3425
+ try {
3426
+ const pol = loadPolicy(this.opts.home);
3427
+ const ts = [this.cfg.spaceId, this.cfg.space].filter((t) => !!t);
3428
+ return Object.values(pol.wakeAsks ?? {}).some((a) => ts.includes(a.team) && a.member === refusedWake.askable);
3429
+ }
3430
+ catch {
3431
+ return false;
3432
+ }
3433
+ })();
3434
+ await this.tellAskerDeclined(client, o, reqAct, asking ? `it waits for ${this.cfg.member} to approve you` : "this machine doesn't start work for you on its own", asking ? "wake_ask" : /^this machine is set not to be woken/.test(refusedWake.why) ? "wake_off" : /^the team does not let/.test(refusedWake.why) ? "team_wake" : "wake");
3435
+ }
3405
3436
  continue;
3406
3437
  }
3407
3438
  if (presentNow && await this.personThread(client, reqAct)) {
@@ -3415,14 +3446,20 @@ export class Worker {
3415
3446
  const sel = this.selectPersona(client, o, reqAct?.from);
3416
3447
  if (sel.skip) {
3417
3448
  this.decline(o.ref, "no playbook here covers it");
3418
- if (this.mode() === "autopilot")
3419
- await this.tellAskerDeclined(client, o, reqAct, "none of its playbooks covers it");
3449
+ await this.tellAskerDeclined(client, o, reqAct, "none of its playbooks covers it", "playbook");
3420
3450
  if (!this.skipLogged.has(o.id)) {
3421
3451
  this.skipLogged.add(o.id);
3422
3452
  this.opts.log(`- not taking ${owedLabel(o.kind)} ${o.id}: ${sel.skip}`);
3423
3453
  }
3424
3454
  continue;
3425
3455
  }
3456
+ const gc = this.escalationAnswer(client, o) ? null : this.goalCapped(o.goal);
3457
+ if (gc) {
3458
+ this.decline(o.ref, `its goal has had ${gc.n} runs here today`, `Your worker has done ${gc.n} runs on this goal today — it's yours, or it'll take it after ${whenWords(gc.freeAt)}`);
3459
+ await this.sayGoalCapped(client, o.goal, gc, null);
3460
+ await this.tellAskerDeclined(client, o, reqAct, `it has done ${gc.n} runs on this goal today; it can take it after ${whenWords(gc.freeAt)}`, "goal_cap");
3461
+ continue;
3462
+ }
3426
3463
  return { i, o, act: reqAct, persona: sel.persona };
3427
3464
  }
3428
3465
  return null;
@@ -3475,6 +3512,11 @@ export class Worker {
3475
3512
  body: `${act.act} from ${act.from}: ${act.body.split("\n")[0]?.slice(0, 120) ?? ""}`,
3476
3513
  }, held, false);
3477
3514
  }
3515
+ else if (this.goalCapped(pick.continuation.goal)) {
3516
+ const act = pick.continuation, gc = this.goalCapped(act.goal);
3517
+ this.requeueContinuation(act, Math.max(5_000, gc.freeAt - Date.now()));
3518
+ await this.sayGoalCapped(client, act.goal, gc, act.from);
3519
+ }
3478
3520
  else
3479
3521
  ({ continuation, persona } = pick);
3480
3522
  }
@@ -3515,11 +3557,7 @@ export class Worker {
3515
3557
  continue;
3516
3558
  }
3517
3559
  if (continuation && me?.work && !me.work.busy && me.work.idle_since !== null && this.liveThread(client, continuation)) {
3518
- const asked = continuation.ref ? client.seenAct(continuation.ref)?.session : undefined;
3519
- const open = new Set(me.sessions.map((s) => s.id));
3520
- const shown = asked && open.has(asked) ? (this.opts.home !== undefined ? [this.opts.home, undefined] : [undefined])
3521
- .flatMap((h) => liveReadAt(this.contKeys(), continuation.id, h)).filter((m) => m.session === asked) : [];
3522
- if (shown.some((m) => me.work.idle_since >= m.at)) {
3560
+ if (this.shownToAsker(client, me, continuation)) {
3523
3561
  this.markDone(continuation.id);
3524
3562
  this.forgetQueued(continuation.id);
3525
3563
  this.opts.log(`- not continuing from ${continuation.act} ${continuation.id}: the window that asked was shown it, and its turn ended after that`);
@@ -3542,6 +3580,8 @@ export class Worker {
3542
3580
  maxRunsPerDay: this.opts.maxRunsPerDay,
3543
3581
  });
3544
3582
  const slot = this.takeSlot();
3583
+ let folded = [];
3584
+ let foldedSince = 0;
3545
3585
  if ("held" in slot) {
3546
3586
  this.writeState("watching", `waiting: ${slot.held}`);
3547
3587
  this.tickHold = slot.held === PERSON_ANSWERING
@@ -3570,7 +3610,7 @@ export class Worker {
3570
3610
  held.push({ o: next.o, act: next.act });
3571
3611
  for (const h of held) {
3572
3612
  this.decline(h.o.ref, `it has done its ${gate.cap.n} runs ${gate.cap.per === "hour" ? "this hour" : "today"}`, line);
3573
- await this.tellAskerDeclined(client, h.o, h.act ?? await this.fetchActById(h.o.ref), `it has used its runs for now${when ? `; it can take it after ${when}` : ""}`);
3613
+ await this.tellAskerDeclined(client, h.o, h.act ?? await this.fetchActById(h.o.ref), `it has used its runs for now${when ? `; it can take it after ${when}` : ""}`, "capped");
3574
3614
  }
3575
3615
  }
3576
3616
  if (continuation)
@@ -3601,6 +3641,10 @@ export class Worker {
3601
3641
  this.opts.log(`- not continuing from ${continuation.id}: the worker is stopping`);
3602
3642
  break;
3603
3643
  }
3644
+ folded = await this.foldContinuations(client, continuation, persona, me, !!me && shouldDeferToHuman(me.sessions, me.work, {
3645
+ idleMs: this.idleMs(), busyTtlMs, busySince: this.busyObservedSince, hooksInstalled,
3646
+ }));
3647
+ foldedSince = client.relayNow();
3604
3648
  }
3605
3649
  if (this.readiness && !this.readiness.ok)
3606
3650
  this.checkReadiness(true);
@@ -3610,7 +3654,7 @@ export class Worker {
3610
3654
  try {
3611
3655
  job = candidate
3612
3656
  ? await this.handle(client, candidate, persona, policy, candidateAct)
3613
- : await this.handleContinuation(client, continuation, persona, policy);
3657
+ : await this.handleContinuation(client, continuation, persona, policy, folded);
3614
3658
  }
3615
3659
  catch (e) {
3616
3660
  const msg = e?.message?.split("\n")[0] ?? String(e);
@@ -3736,6 +3780,8 @@ export class Worker {
3736
3780
  }
3737
3781
  }
3738
3782
  this.endAttempt();
3783
+ if (folded.length)
3784
+ this.settleFolded(client, folded, foldedSince);
3739
3785
  this.giveSlot(slot.token);
3740
3786
  if (continuation)
3741
3787
  client.forgetClaim(`cont:${continuation.id}`);
@@ -4039,19 +4085,19 @@ export class Worker {
4039
4085
  const decided = await this.decisionFor(client, o);
4040
4086
  return this.runJob(client, o, persona, policy, (branch, canPush) => buildBrief(o, trigger, branch, persona, canPush, decided), true, needs, trigger, act);
4041
4087
  }
4042
- async handleContinuation(client, act, persona, policy) {
4088
+ async handleContinuation(client, act, persona, policy, more = []) {
4043
4089
  this.markDone(act.id);
4044
4090
  const o = {
4045
4091
  id: `cont:${act.id}`, kind: "CONTINUE", owner: this.cfg.member,
4046
4092
  ref: act.id, goal: act.goal, created_at: act.ts,
4047
4093
  body: `${act.act} from ${act.from}: ${act.body.split("\n")[0]?.slice(0, 120) ?? ""}`,
4048
4094
  };
4049
- this.opts.log(`> continuing from ${act.act} ${act.id} by ${act.from}${persona ? ` — persona "${persona.name}"` : ""}`);
4095
+ this.opts.log(`> continuing from ${act.act} ${act.id} by ${act.from}${persona ? ` — persona "${persona.name}"` : ""}${more.length ? ` — with ${more.length} more ${more.length === 1 ? "reply" : "replies"} in the same run: ${more.map((m) => `${m.act} ${m.id} by ${m.from}`).join(", ")}` : ""}`);
4050
4096
  this.lastHold = "";
4051
4097
  this.report("running", `${act.act} ${act.id}`, undefined, { ref: act.id, ...(act.goal ? { goal: act.goal } : {}) });
4052
4098
  const trigger = actLine(act);
4053
4099
  const needs = workNeedsCommands("CONTINUE", trigger, act.act);
4054
- return this.runJob(client, o, persona, policy, (branch, canPush) => buildContinuationBrief(act, trigger, branch, persona, canPush), false, needs, trigger, act);
4100
+ return this.runJob(client, o, persona, policy, (branch, canPush) => buildContinuationBrief(act, trigger, branch, persona, canPush, more), false, needs || more.some((m) => workNeedsCommands("CONTINUE", actLine(m), m.act)), trigger, act);
4055
4101
  }
4056
4102
  spentOnce = {};
4057
4103
  policyBytes() { try {
@@ -4178,6 +4224,7 @@ export class Worker {
4178
4224
  cause: "repo_not_here", says,
4179
4225
  fix: route.kind === "missing" ? `Clone ${name} and run pantheon repo find (or pantheon use ${this.cfg.space} --here inside it); the request waits until then.` : `Bind a repo or folder: pantheon use ${this.cfg.space} --here`,
4180
4226
  peer: {
4227
+ code: route.kind === "missing" ? "not_here" : "no_folder",
4181
4228
  summary: route.kind === "missing" ? `${name} is not on ${this.cfg.member}'s machine — this waits for ${this.cfg.member}` : `nothing on ${this.cfg.member}'s machine is bound to this team yet`,
4182
4229
  body: route.kind === "missing"
4183
4230
  ? `${this.cfg.member}'s machine does not have ${name}, so its worker cannot look at it — and it will not answer from another repo's code.\nThis is still owed and waits for ${this.cfg.member}; a teammate who works on ${name} can take it meanwhile. Nothing was run.`
@@ -4264,6 +4311,20 @@ export class Worker {
4264
4311
  this.lastFeaturesSaid = said;
4265
4312
  }
4266
4313
  }
4314
+ const routing = agentId === "claude-code" ? claudeRouting(process.env, this.opts.home ?? homedir()) : null;
4315
+ const runModel = (() => { try {
4316
+ return effectiveRunModel(agentId, loadPolicy(this.opts.home), routing);
4317
+ }
4318
+ catch {
4319
+ return effectiveRunModel(agentId, null, routing);
4320
+ } })();
4321
+ {
4322
+ const said = `${agentId ?? "agent"}: ${describeRunModel(runModel)}`;
4323
+ if (said !== this.lastModelSaid) {
4324
+ this.opts.log(` model ${said}${runModel.from === "default" ? " — pantheon policy set model <name|own> to change it" : ""}`);
4325
+ this.lastModelSaid = said;
4326
+ }
4327
+ }
4267
4328
  const codexReadOnly = place.kind === "folder" && agentId === "codex" && !this.opts.agentCmd;
4268
4329
  const byCli = !!this.opts.agentCmd && !!this.opts.agentCmdFromCli;
4269
4330
  const noCommandsHere = features?.unknown ? "unknown"
@@ -4454,6 +4515,7 @@ export class Worker {
4454
4515
  const plan = headlessSpawn({
4455
4516
  backend, binary, prompt: brief, worktree, cfg: runCfg, branch, allowBash, runHome,
4456
4517
  ...(claudeToken ? { claudeToken } : {}),
4518
+ ...(runModel.model ? { model: runModel.model } : {}),
4457
4519
  ...(attached.length ? { readOnlyDirs: attached.map((a) => a.path) } : {}),
4458
4520
  ...(baseSha ? { base: baseSha } : {}), ...(tipSha ? { commandsRev: tipSha } : {}), goal,
4459
4521
  ...(features ? { claude: { features, pantheonHome: this.stateDir(), home: personHome, userSettings: join(personHome, ".claude", "settings.json"), ...(() => { const c = adoptedCommon(worktree); return c ? { gitCommon: c } : {}; })() } } : {}),
@@ -4831,6 +4893,7 @@ export class Worker {
4831
4893
  }
4832
4894
  }
4833
4895
  lastFeaturesSaid = "";
4896
+ lastModelSaid = "";
4834
4897
  notesSaid = new Set();
4835
4898
  restoreHomeAfterRun(before, o) {
4836
4899
  let changes = [];
@@ -5250,6 +5313,7 @@ export class Worker {
5250
5313
  `${this.cfg.member} will pick this up in their next session on this machine.`,
5251
5314
  `It is still owed. Nothing was run.`,
5252
5315
  ].join("\n"),
5316
+ meta: { declined: d.peer?.code ?? (d.cause === "not_signed_in" ? "signed_out" : "unavailable") },
5253
5317
  });
5254
5318
  markContinued(space, key, this.opts.home);
5255
5319
  this.opts.log(d.cause === "agent_unavailable" ? `* told ${peer ?? "the teammate"} that ${o.id} waits: ${d.says}`
@@ -5373,6 +5437,10 @@ export class Worker {
5373
5437
  this.decline(candidate.ref, "its run failed twice on this computer");
5374
5438
  if (failures >= 2 && diagnosis)
5375
5439
  await this.reportStuck(client, candidate, diagnosis, attempts);
5440
+ if (failures >= 2) {
5441
+ const commands = diagnosis?.cause === "no_commands" || diagnosis?.cause === "no_sandbox_commands";
5442
+ await this.tellAskerDeclined(client, candidate, client.seenAct(candidate.ref) ?? await this.fetchActById(candidate.ref), commands ? `it needs ${this.cfg.member}'s OK to run commands for it` : "it tried and couldn't finish it", commands ? "commands" : "failed");
5443
+ }
5376
5444
  }
5377
5445
  async noteOnDecision(client, o, d, decision, blocked = []) {
5378
5446
  const key = `stuck-note:${decision}`;
@@ -5845,10 +5913,119 @@ export class Worker {
5845
5913
  }
5846
5914
  continue;
5847
5915
  }
5916
+ if (this.gathering(client, r)) {
5917
+ this.contQueue.push({ act: r, notBefore: now + Math.min(15_000, this.opts.gatherMs ?? GATHER_MAX_MS) });
5918
+ if (!this.skipLogged.has(`gather:${r.id}`)) {
5919
+ this.skipLogged.add(`gather:${r.id}`);
5920
+ this.opts.log(`- waiting with ${r.act} ${r.id}: other teammates asked at the same time have not answered yet — up to ${Math.round((this.opts.gatherMs ?? GATHER_MAX_MS) / 60_000)} min, so their answers share one run`);
5921
+ }
5922
+ continue;
5923
+ }
5848
5924
  return { continuation: r, ...(sel.persona ? { persona: sel.persona } : {}) };
5849
5925
  }
5850
5926
  return undefined;
5851
5927
  }
5928
+ shownToAsker(client, me, r) {
5929
+ if (!me?.work || me.work.busy || me.work.idle_since === null || !this.liveThread(client, r))
5930
+ return false;
5931
+ const asked = r.ref ? client.seenAct(r.ref)?.session : undefined;
5932
+ const open = new Set(me.sessions.map((s) => s.id));
5933
+ const shown = asked && open.has(asked) ? (this.opts.home !== undefined ? [this.opts.home, undefined] : [undefined])
5934
+ .flatMap((h) => liveReadAt(this.contKeys(), r.id, h)).filter((m) => m.session === asked) : [];
5935
+ return shown.some((m) => me.work.idle_since >= m.at);
5936
+ }
5937
+ gatherSince = new Map();
5938
+ myAsk(client, r) {
5939
+ if (r.act !== "ANSWER" || !r.ref)
5940
+ return null;
5941
+ const ask = client.seenAct(r.ref);
5942
+ return ask && ask.act === "ASK" && ask.from === this.cfg.member ? ask : null;
5943
+ }
5944
+ sameSweep(a, b) {
5945
+ return a.id === b.id || Math.abs(a.ts - b.ts) <= SWEEP_SPAN_MS;
5946
+ }
5947
+ gathering(client, r) {
5948
+ const ask = this.myAsk(client, r);
5949
+ if (!ask)
5950
+ return false;
5951
+ const max = this.opts.gatherMs ?? GATHER_MAX_MS;
5952
+ const since = this.gatherSince.get(r.id) ?? Date.now();
5953
+ if (!this.gatherSince.has(r.id)) {
5954
+ this.gatherSince.set(r.id, since);
5955
+ if (this.gatherSince.size > 500)
5956
+ this.gatherSince.delete(this.gatherSince.keys().next().value);
5957
+ }
5958
+ if (Date.now() - since >= max)
5959
+ return false;
5960
+ return client.obligations.some((o) => {
5961
+ if (o.kind !== "ANSWER" || o.owner === this.cfg.member || o.owner.startsWith("human:"))
5962
+ return false;
5963
+ const other = client.seenAct(o.ref);
5964
+ return !!other && other.act === "ASK" && other.from === this.cfg.member && this.sameSweep(ask, other);
5965
+ });
5966
+ }
5967
+ async foldContinuations(client, primary, persona, me, personPresent) {
5968
+ const ask = this.myAsk(client, primary);
5969
+ const fits = (r) => {
5970
+ if (r.id === primary.id || r.act !== "ANSWER")
5971
+ return false;
5972
+ if (primary.goal && r.goal === primary.goal)
5973
+ return true;
5974
+ const other = ask ? this.myAsk(client, r) : null;
5975
+ return !!ask && !!other && this.sameSweep(ask, other);
5976
+ };
5977
+ const out = [];
5978
+ for (const c of [...this.contQueue]) {
5979
+ if (out.length >= FOLD_MAX)
5980
+ break;
5981
+ const r = c.act;
5982
+ if (!fits(r) || this.contDone.has(r.id))
5983
+ continue;
5984
+ const g = r.goal ? client.goals.get(r.goal) : undefined;
5985
+ if (g?.state === "CLOSED" || stopFor(`cont:${r.id}`, this.opts.home))
5986
+ continue;
5987
+ if (settledReply(r, client.mineSince(r.ts, r.goal), (id) => client.seenAct(id), this.cfg.member))
5988
+ continue;
5989
+ if (this.shownToAsker(client, me, r))
5990
+ continue;
5991
+ if (personPresent && !this.workerThread(client, r))
5992
+ continue;
5993
+ if (this.goalCapped(r.goal))
5994
+ continue;
5995
+ const sel = this.selectPersona(client, { id: `cont:${r.id}`, kind: "CONTINUE", owner: this.cfg.member, ref: r.id, goal: r.goal, created_at: r.ts, body: r.body.slice(0, 120) }, r.from);
5996
+ if (sel.skip || sel.persona?.name !== persona?.name)
5997
+ continue;
5998
+ if (await this.requestTrust(client, null, r))
5999
+ continue;
6000
+ if (await this.wakeRefusal(client, r.id, { from: r.from, role: r.role }))
6001
+ continue;
6002
+ if (this.heldForSandbox(sel.persona?.agent ?? this.opts.agent))
6003
+ continue;
6004
+ try {
6005
+ await client.claim(`cont:${r.id}`);
6006
+ }
6007
+ catch {
6008
+ continue;
6009
+ }
6010
+ this.contQueue = this.contQueue.filter((x) => x.act.id !== r.id);
6011
+ out.push(r);
6012
+ }
6013
+ return out;
6014
+ }
6015
+ settleFolded(client, folded, since) {
6016
+ for (const r of folded) {
6017
+ client.forgetClaim(`cont:${r.id}`);
6018
+ const acted = client.mineSince(since).some((a) => a.ref === r.id || (!!r.goal && a.goal === r.goal));
6019
+ if (acted) {
6020
+ this.markDone(r.id);
6021
+ this.forgetQueued(r.id);
6022
+ continue;
6023
+ }
6024
+ this.opts.log(`- ${r.act} ${r.id} rode along but nothing was sent about it — it gets a run of its own`);
6025
+ void client.releaseClaim(`cont:${r.id}`).catch(() => false);
6026
+ this.requeueContinuation(r, 0);
6027
+ }
6028
+ }
5852
6029
  lastHealthCheck = 0;
5853
6030
  async maintain(client, arrived) {
5854
6031
  const home = this.opts.home;
@@ -5892,6 +6069,7 @@ export class Worker {
5892
6069
  return;
5893
6070
  this.lastHealthCheck = Date.now();
5894
6071
  const relayPkg = await (this.opts.selfUpgrade?.check ?? (() => this.fetchRelayPkg()))();
6072
+ recordRelayPkg(this.cfg.relay, relayPkg, home ? { home } : {});
5895
6073
  const policy = loadPolicy(home);
5896
6074
  const lastAttempt = policy.attempts.self_upgrade ?? null;
5897
6075
  if (!needsSelfUpgrade(VERSION, relayPkg, lastAttempt))
@@ -5921,8 +6099,11 @@ export class Worker {
5921
6099
  this.opts.log(`! self-upgrade failed: ${e.message}`);
5922
6100
  }
5923
6101
  if (result.needsPerson) {
5924
- if (grantBefore)
6102
+ if (grantBefore) {
5925
6103
  policy.grants.self_upgrade = grantBefore;
6104
+ if (policy.usedOnce)
6105
+ delete policy.usedOnce.self_upgrade;
6106
+ }
5926
6107
  delete policy.attempts.self_upgrade;
5927
6108
  policy.upgradeHeld = { version: relayPkg ?? result.to, node: nodeNow(), at: Date.now(), why: result.needsPerson };
5928
6109
  savePolicy(policy, home);
@@ -5954,6 +6135,20 @@ export class Worker {
5954
6135
  }
5955
6136
  else if (!result.ok) {
5956
6137
  this.opts.log("! self-upgrade did not complete — will not retry for an hour; run `pantheon upgrade` by hand to see why");
6138
+ const pkg = relayPkg ?? result.to;
6139
+ const canAlert = !!this.opts.notify && decisionAlertsOn() && (() => { try {
6140
+ return !this.opts.canAlert || this.opts.canAlert();
6141
+ }
6142
+ catch {
6143
+ return false;
6144
+ } })();
6145
+ if (upgradeFailedOnce(pkg, { ...(home ? { home } : {}), canAlert })) {
6146
+ try {
6147
+ this.opts.notify?.({ ...composeUpgradeFailed(VERSION, pkg), context: this.cfg.space });
6148
+ }
6149
+ catch { }
6150
+ }
6151
+ this.writeState("needs you", `could not update pantheon ${VERSION} -> ${pkg}: run pantheon upgrade to see why`);
5957
6152
  }
5958
6153
  return;
5959
6154
  }
@@ -6256,17 +6451,7 @@ export class Worker {
6256
6451
  return null;
6257
6452
  }
6258
6453
  }
6259
- async fetchRelayPkg() {
6260
- try {
6261
- const base = this.cfg.relay.replace(/^ws/, "http").replace(/\/+$/, "");
6262
- const res = await fetch(`${base}/health`, { signal: AbortSignal.timeout(3000) });
6263
- const j = await res.json();
6264
- return typeof j.pkg === "string" ? j.pkg : null;
6265
- }
6266
- catch {
6267
- return null;
6268
- }
6269
- }
6454
+ async fetchRelayPkg() { return fetchRelayPkg(this.cfg.relay); }
6270
6455
  cursorFile() { return join(this.opts.home ?? process.env.PANTHEON_HOME ?? join(homedir(), ".pantheon"), "worker-cursor.json"); }
6271
6456
  cursorSaid = 0;
6272
6457
  readCursor() {
@@ -6363,22 +6548,74 @@ export class Worker {
6363
6548
  }, Math.max(PICKUP_COALESCE_MS, b.shownAt + PICKUP_MIN_GAP_MS - now));
6364
6549
  b.timer.unref?.();
6365
6550
  }
6366
- async tellAskerDeclined(client, o, act, why) {
6551
+ goalCapped(goal) {
6552
+ if (!goal)
6553
+ return null;
6554
+ let cap = effectiveGoalRuns(null).runs;
6555
+ try {
6556
+ cap = effectiveGoalRuns(loadPolicy(this.opts.home)).runs;
6557
+ }
6558
+ catch { }
6559
+ const g = goalAllowed(goal, cap, this.opts.home);
6560
+ return g.ok ? null : { n: g.n, cap, freeAt: g.freeAt };
6561
+ }
6562
+ async sayGoalCapped(client, goal, gc, peer) {
6563
+ const key = `goal-cap-said:${goal}:${Math.floor(Date.now() / 86_400_000)}`;
6564
+ this.loadContinued();
6565
+ if (this.contDone.has(key) || this.continuedHas(key))
6566
+ return;
6567
+ this.markDone(key);
6568
+ const title = client.goals.get(goal)?.title ?? "one goal";
6569
+ const when = whenWords(gc.freeAt);
6570
+ this.opts.log(`! goal ${goal}: ${gc.n} runs in the last 24 hours, its limit is ${gc.cap} — what arrives in it waits for you until ${when} (pantheon policy set goal-runs <n> to change the limit)`);
6571
+ try {
6572
+ this.opts.notify?.({
6573
+ kind: "worker", who: "Your worker", heading: "Paused one goal for today", context: title,
6574
+ body: `Your worker has done ${gc.n} runs on this goal in a day, so it stops there until ${when}: two agents may be answering each other. What arrives in it waits for you — nothing is lost.`,
6575
+ ttl: 0, sound: false,
6576
+ });
6577
+ }
6578
+ catch { }
6579
+ if (!peer || peer === this.cfg.member)
6580
+ return;
6581
+ try {
6582
+ await client.send({
6583
+ act: "NOTE", goal, after_seq: Math.max(client.readSeq, client.seq), to: [peer],
6584
+ summary: `${this.cfg.member}'s agent has paused this goal for today — it's with ${this.cfg.member}`,
6585
+ body: `${this.cfg.member}'s agent has done ${gc.n} runs on this goal in a day, so it won't start another on its own until ${when} — it's with ${this.cfg.member} until then. Nothing is lost: what you sent is still there. If it can't wait, remind ${this.cfg.member}.`,
6586
+ meta: { declined: "goal_cap" },
6587
+ });
6588
+ this.opts.log(`* told ${peer} that goal ${goal} waits for ${this.cfg.member} until ${when}`);
6589
+ }
6590
+ catch (e) {
6591
+ this.opts.log(`! could not tell ${peer} that goal ${goal} is paused: ${e.message.split("\n")[0]}`);
6592
+ }
6593
+ }
6594
+ async tellAskerDeclined(client, o, act, why, code) {
6367
6595
  const peer = act?.from ?? client.recentFrom(o.ref);
6368
6596
  if (!peer || peer === this.cfg.member)
6369
6597
  return;
6370
- const key = `declined-told:${o.id}`;
6371
- const space = this.spaceKey();
6372
- if (this.contDone.has(key) || loadContinued(space, this.opts.home).has(key))
6598
+ if (client.relayNow() - o.created_at > 24 * 3_600_000)
6373
6599
  return;
6600
+ this.learnRequests([o]);
6601
+ this.loadContinued();
6602
+ const key = `declined-told:${this.oKey(o.id)}`;
6603
+ if (this.marked("declined-told", o.id))
6604
+ return;
6605
+ const told = (prefix) => this.marked(prefix, o.id) || this.continuedHas(`${prefix}:${this.oKey(o.id)}`) || this.continuedHas(`${prefix}:${o.id}`);
6606
+ if (told("declined-told") || told("refused")) {
6607
+ this.contDone.add(key);
6608
+ return;
6609
+ }
6374
6610
  this.contDone.add(key);
6375
6611
  try {
6376
6612
  await client.send({
6377
6613
  act: "NOTE", goal: o.goal, ref: o.ref, after_seq: Math.max(client.readSeq, client.seq), to: [peer],
6378
6614
  summary: `${this.cfg.member}'s agent won't take this on its own — it's with ${this.cfg.member}`,
6379
- body: `${this.cfg.member}'s agent won't take this one on its own (${why}), so it's with ${this.cfg.member} now. It is still owed.`,
6615
+ body: `${this.cfg.member}'s agent won't take this one on its own (${why}), so it's with ${this.cfg.member} now. It is still owed. If it can't wait, remind ${this.cfg.member} or ask someone else.`,
6616
+ meta: { declined: code },
6380
6617
  });
6381
- markContinued(space, key, this.opts.home);
6618
+ this.markDone(key);
6382
6619
  this.opts.log(`* told ${peer} that ${o.id} is with ${this.cfg.member}: ${why}`);
6383
6620
  }
6384
6621
  catch (e) {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "format": 1,
3
- "built_at": "2026-11-05T07:13:40.757Z",
3
+ "built_at": "2026-11-13T10:46:28.280Z",
4
4
  "swiftc": "Apple Swift version 6.4.2 (swiftlang-6.4.2.1.9 clang-2100.4.1.1)",
5
5
  "helpers": {
6
6
  "pantheon-tray": {
@@ -17,7 +17,7 @@
17
17
  "pantheon-hud": {
18
18
  "source": "main.swift",
19
19
  "source_sha256": "4976c00b5d4bd0d8c509d2d284d9c6e2d70a1b3db952de5f11108dfff4951a82",
20
- "sha256": "4f41cf800c322ef947945ca7905bbae5faaa9d344594428dbdb09bb4ab20d734",
20
+ "sha256": "6b81963a5d075d034224d5e9181038194e362af14d281ad98d74c2bb9fe1dd6f",
21
21
  "archs": [
22
22
  "arm64",
23
23
  "x86_64"
Binary file
@@ -1,15 +1,16 @@
1
1
  {
2
2
  "name": "@join-pantheon/cli",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "@join-pantheon/cli",
9
- "version": "0.37.3",
9
+ "version": "0.38.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@modelcontextprotocol/sdk": "^1.32.1",
13
+ "mmdb-lib": "3.0.3",
13
14
  "undici": "^7.29.1",
14
15
  "ws": "^8.18.0",
15
16
  "zod": "^3.23.8"
@@ -777,6 +778,16 @@
777
778
  "url": "https://opencollective.com/express"
778
779
  }
779
780
  },
781
+ "node_modules/mmdb-lib": {
782
+ "version": "3.0.3",
783
+ "resolved": "https://registry.npmjs.org/mmdb-lib/-/mmdb-lib-3.0.3.tgz",
784
+ "integrity": "sha512-xQPoBXcNjjHiOvOraFBKtA++uNWF6aCVHL9dRKFXEov8eI3QJwtgiw3qApsonFT5SpoqsEVISUTg3HIDs2DiXw==",
785
+ "license": "MIT",
786
+ "engines": {
787
+ "node": ">=10",
788
+ "npm": ">=6"
789
+ }
790
+ },
780
791
  "node_modules/ms": {
781
792
  "version": "2.1.3",
782
793
  "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@join-pantheon/cli",
3
- "version": "0.37.3",
3
+ "version": "0.38.1",
4
4
  "description": "Let your coding agent collaborate directly with your teammates' agents — ask, agree an interface, and deliver, without a human relaying messages.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -26,6 +26,7 @@
26
26
  },
27
27
  "dependencies": {
28
28
  "@modelcontextprotocol/sdk": "^1.32.1",
29
+ "mmdb-lib": "3.0.3",
29
30
  "undici": "^7.29.1",
30
31
  "ws": "^8.18.0",
31
32
  "zod": "^3.23.8"