@join-pantheon/cli 0.33.10-rc.1 → 0.33.11-rc.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.
@@ -35,6 +35,20 @@ export function toastButtons(notice, key) {
35
35
  const out = [];
36
36
  const add = (content, uri) => { if (uri)
37
37
  out.push({ content, uri }); };
38
+ if (notice.review) {
39
+ add("Review", notice.review.what === "changes" ? buildUri("changes", {}, key) : buildUri("board", {}, key));
40
+ return out;
41
+ }
42
+ if (notice.change) {
43
+ add("Approve", buildUri("change", { id: notice.change.id, answer: "approve" }, key));
44
+ add("Keep as is", buildUri("change", { id: notice.change.id, answer: "keep" }, key));
45
+ return out;
46
+ }
47
+ if (notice.run) {
48
+ add("Take over", buildUri("work", { ref: notice.run.ref, do: "takeover", space }, key));
49
+ add("Stop", buildUri("work", { ref: notice.run.ref, do: "stop", space }, key));
50
+ return out;
51
+ }
38
52
  if (notice.kind === "decision" && d.decision) {
39
53
  add("Done", buildUri("done", { decision: d.decision, act: d.act, space }, key));
40
54
  add("Explain", buildUri("explain", { decision: d.decision, act: d.act, space }, key));
@@ -99,6 +113,9 @@ export function powershellPath(env = process.env) {
99
113
  export function powershellArgs(script, mode) {
100
114
  return ["-NoProfile", "-NonInteractive", "-Command", `${CLM_GUARD}; & ([scriptblock]::Create([IO.File]::ReadAllText(${psQuote(script)}))) -Mode ${mode}`];
101
115
  }
116
+ export function toastExpiresMinutes(notice) {
117
+ return notice.run ? 10 : undefined;
118
+ }
102
119
  export function balloonText(notice) {
103
120
  const title = toastText(notice.heading, BALLOON_CAPS.title) || "Pantheon";
104
121
  const text = toastText([notice.context, notice.body].filter(Boolean).join(" — "), BALLOON_CAPS.text) || toastText(notice.who, BALLOON_CAPS.text) || "Open Pantheon";
@@ -106,13 +123,15 @@ export function balloonText(notice) {
106
123
  }
107
124
  const aboutOf = (notice) => `${notice.kind}${notice.details?.decision ? ` ${notice.details.decision}` : notice.details?.act ? ` ${notice.details.act}` : ""}`;
108
125
  export function queuedNotice(notice, key, aumids, now = Date.now()) {
109
- return { v: 2, at: now, about: aboutOf(notice), toast: toastFields(notice, key), tag: toastTag(notice), aumids, balloon: balloonText(notice) };
126
+ const expires = toastExpiresMinutes(notice);
127
+ return { v: 2, at: now, about: aboutOf(notice), toast: toastFields(notice, key), tag: toastTag(notice), aumids, balloon: balloonText(notice), ...(expires ? { expires } : {}) };
110
128
  }
111
129
  export function toastCall(notice, key, aumids, env = process.env, script = windowsNoticeScriptPath()) {
112
130
  return {
113
131
  file: powershellPath(env),
114
132
  args: powershellArgs(script, "toast"),
115
- env: { PANTHEON_TOAST_XML: b64(toastXml(notice, key)), PANTHEON_TOAST_TAG: toastTag(notice), PANTHEON_TOAST_AUMIDS: aumids.join(";") },
133
+ env: { PANTHEON_TOAST_XML: b64(toastXml(notice, key)), PANTHEON_TOAST_TAG: toastTag(notice), PANTHEON_TOAST_AUMIDS: aumids.join(";"),
134
+ ...(toastExpiresMinutes(notice) ? { PANTHEON_TOAST_EXPIRES: String(toastExpiresMinutes(notice)) } : {}) },
116
135
  };
117
136
  }
118
137
  export function balloonCall(notice, icon, env = process.env, script = windowsNoticeScriptPath()) {
package/dist/notifier.js CHANGED
@@ -2,7 +2,7 @@ import { showWindowsNotice } from "./notice-windows.js";
2
2
  import { showLinuxNotice } from "./notice-linux.js";
3
3
  import { spawn } from "node:child_process";
4
4
  import { helperStale, installHelper } from "./helpers-build.js";
5
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
6
6
  import { homedir, platform } from "node:os";
7
7
  import { dirname, join, resolve } from "node:path";
8
8
  import { fileURLToPath } from "node:url";
@@ -11,6 +11,7 @@ import { CONFIG_DIR } from "./config.js";
11
11
  import { loadProfile } from "./profile.js";
12
12
  import { APP_TOOLS, composeDecision, composeDelivery, composePassedOver, composeWakeAsk, neverAlerts, passedOverNotice, TOOL_LABELS } from "./notice.js";
13
13
  import { loadPolicy } from "./worker-policy.js";
14
+ import { withoutAgentMarkers } from "./setup-changes.js";
14
15
  import { wakeAlerted } from "./continued.js";
15
16
  import { cliOnPath, detectAvailable } from "./agents.js";
16
17
  import { whichPantheon } from "./service.js";
@@ -117,7 +118,20 @@ export function preferredTool(profile, tools, home = CONFIG_DIR) {
117
118
  catch { }
118
119
  return profile.agent.primary_surface;
119
120
  }
121
+ export const NO_ALERTS_ENV = "PANTHEON_NO_DESKTOP_ALERTS";
122
+ export function desktopAlertsOff(env = process.env) {
123
+ const v = env[NO_ALERTS_ENV];
124
+ return !!v && v !== "0" && v.toLowerCase() !== "false";
125
+ }
120
126
  export function sendDesktopNotification(notice, home = CONFIG_DIR) {
127
+ if (desktopAlertsOff()) {
128
+ try {
129
+ mkdirSync(join(home, "logs"), { recursive: true });
130
+ appendFileSync(join(home, "logs", "alerts.log"), `${new Date().toISOString()} alerts off (${NO_ALERTS_ENV}) — not shown: ${notice.heading.replace(/[\u0000-\u001f]/g, " ").slice(0, 120)}\n`, { mode: 0o600 });
131
+ }
132
+ catch { }
133
+ return false;
134
+ }
121
135
  if (platform() === "win32")
122
136
  return showWindowsNotice(notice, home);
123
137
  if (platform() === "linux")
@@ -128,7 +142,7 @@ export function sendDesktopNotification(notice, home = CONFIG_DIR) {
128
142
  if (!existsSync(binary))
129
143
  return false;
130
144
  try {
131
- const child = spawn(binary, ["post", "--json", JSON.stringify({ ...notice, bin_dir: join(home, "bin"), pantheon: whichPantheon() ?? "pantheon" })], { detached: true, stdio: "ignore" });
145
+ const child = spawn(binary, ["post", "--json", JSON.stringify({ ...notice, bin_dir: join(home, "bin"), pantheon: whichPantheon() ?? "pantheon" })], { detached: true, stdio: "ignore", env: withoutAgentMarkers(process.env) });
132
146
  child.unref();
133
147
  return true;
134
148
  }
package/dist/pending.js CHANGED
@@ -8,6 +8,9 @@ import { expectsSigs, joinedSigning, loadPins, markMemberSigns, markSigs, member
8
8
  import { copiesAmong, noteNonce } from "./nonces.js";
9
9
  import { trusted, verifyAct } from "./verify-act.js";
10
10
  import { signedRead, relayClockSkew, learnRelayClock } from "./reads.js";
11
+ import { currentMode } from "./worker-policy.js";
12
+ import { loadRunStops } from "./run-control.js";
13
+ import { declinedLine, loadDeclined, personsOwnThread } from "./declined.js";
11
14
  const cursorPath = (home) => join(home ?? CONFIG_DIR, "cursors.json");
12
15
  function readCursors(file) {
13
16
  try {
@@ -99,7 +102,72 @@ export async function pending(opts) {
99
102
  .filter((o) => o.owner === cfg.member);
100
103
  const workerOnline = !!obligationsBody?.worker_online;
101
104
  const heldNow = Date.now();
102
- const heldForWorker = (o) => workerOnline && heldNow - o.created_at < LIMITS.workerFallbackMs;
105
+ let autopilot = false;
106
+ try {
107
+ autopilot = (opts.mode ?? currentMode(opts.home)) === "autopilot";
108
+ }
109
+ catch {
110
+ autopilot = false;
111
+ }
112
+ let taken = new Set();
113
+ try {
114
+ taken = new Set(loadRunStops(opts.home).filter((x) => x.how === "takeover").map((x) => x.ref));
115
+ }
116
+ catch { }
117
+ const actsEarly = (historyBody?.acts ?? []);
118
+ const actById = async (id) => actsEarly.find((a) => a.id === id) ?? (await getJson(cfg, "/act", { id }, LIMITS.pendingTimeoutMs))?.act ?? null;
119
+ const personRefs = new Set();
120
+ let declined = {};
121
+ let workerReady = true;
122
+ let workerCapped = false;
123
+ if (autopilot) {
124
+ try {
125
+ declined = loadDeclined(opts.home);
126
+ }
127
+ catch {
128
+ declined = {};
129
+ }
130
+ const roster = obligationsBody?.roster;
131
+ const me = Array.isArray(roster) ? roster.find((m) => m.id === cfg.member) : undefined;
132
+ if (me?.worker?.state === "unavailable")
133
+ workerReady = false;
134
+ if (me?.worker?.state === "holding" && me.worker.reason === "capped")
135
+ workerCapped = true;
136
+ const openers = new Map();
137
+ const openerOf = async (goal) => {
138
+ if (!goal)
139
+ return null;
140
+ if (openers.has(goal))
141
+ return openers.get(goal);
142
+ let o = null;
143
+ const acts = (await getJson(cfg, "/history", { goal }, LIMITS.pendingTimeoutMs))?.acts ?? [];
144
+ const opening = acts.find((a) => !!a.meta?.goal_members);
145
+ if (opening)
146
+ o = { by: opening.from, run: (opening.meta.goal_sig?.role) === "run" };
147
+ openers.set(goal, o);
148
+ return o;
149
+ };
150
+ for (const o of outstanding.filter((x) => !taken.has(x.ref))) {
151
+ const r = await actById(o.ref);
152
+ const before = r?.ref ? await actById(r.ref) : null;
153
+ if (personsOwnThread(cfg.member, before, await openerOf(r?.goal ?? o.goal)))
154
+ personRefs.add(o.ref);
155
+ }
156
+ }
157
+ const autopilotHolds = (ref) => autopilot && !taken.has(ref) && !personRefs.has(ref) && workerOnline && workerReady && !workerCapped && !declined[ref];
158
+ const whyNot = (ref) => {
159
+ if (!autopilot || personRefs.has(ref))
160
+ return null;
161
+ const d = declined[ref];
162
+ if (d)
163
+ return declinedLine(d.reason, d.line);
164
+ if (workerCapped)
165
+ return "Your worker has used its runs for now — it's yours, or it'll take it once its cap frees a run";
166
+ return null;
167
+ };
168
+ const heldForWorker = (o) => !taken.has(o.ref) && (autopilot && !personRefs.has(o.ref)
169
+ ? autopilotHolds(o.ref)
170
+ : !autopilot && workerOnline && heldNow - o.created_at < LIMITS.workerFallbackMs);
103
171
  const surfaced = outstanding.filter((o) => !heldForWorker(o));
104
172
  const left_for_worker = outstanding.length - surfaced.length;
105
173
  const alreadySeen = new Set(known?.seen ?? []);
@@ -167,7 +235,8 @@ export async function pending(opts) {
167
235
  const obligations = [];
168
236
  for (const o of candidates) {
169
237
  if (!checkSigs) {
170
- obligations.push(o);
238
+ const w = whyNot(o.ref);
239
+ obligations.push(w ? { ...o, body: `${w}. ${o.body}` } : o);
171
240
  continue;
172
241
  }
173
242
  let r = all.find((a) => a.id === o.ref) ?? null;
@@ -191,15 +260,23 @@ export async function pending(opts) {
191
260
  : false;
192
261
  if (!fits)
193
262
  continue;
194
- obligations.push({ ...o, body: `${r.from} ${r.act === "ASK" ? "asked" : "sent"}: ${r.body.split("\n").find((l) => l.trim()) ?? ""}`.slice(0, 200) });
263
+ const w = whyNot(o.ref);
264
+ const why = w ? `${w}. ` : "";
265
+ obligations.push({ ...o, body: `${why}${`${r.from} ${r.act === "ASK" ? "asked" : "sent"}: ${r.body.split("\n").find((l) => l.trim()) ?? ""}`.slice(0, 200)}` });
195
266
  }
196
267
  const mine = all.filter((r) => r.from === cfg.member);
268
+ const owedRefs = obligationsBody === null ? null
269
+ : new Set((obligationsBody?.obligations ?? []).filter((o) => o.owner === cfg.member).map((o) => o.ref));
270
+ const isRequestFor = (r) => owedRefs
271
+ ? owedRefs.has(r.id)
272
+ : (r.act === "ASK" || r.act === "PROPOSE" || r.act === "OBJECT") && !!r.to?.includes(cfg.member);
197
273
  const acts = all
198
274
  .filter((r) => r.from !== cfg.member)
199
275
  .filter((r) => r.act !== "JOIN" && r.act !== "LEAVE")
200
276
  .filter((r) => !r.to || r.to.length === 0 || r.to.includes(cfg.member))
201
277
  .filter((r) => !mine.some((m) => m.seq > r.seq && (m.ref === r.id || (!!r.goal && m.goal === r.goal))))
202
- .filter((r) => !checkSigs || verified(r));
278
+ .filter((r) => !checkSigs || verified(r))
279
+ .filter((r) => !isRequestFor(r) || !autopilotHolds(r.id));
203
280
  let copies = new Set();
204
281
  try {
205
282
  copies = copiesAmong(teamPinId(cfg), acts.filter((r) => !!r.sig && trusted(trustIn(r))).map((r) => ({ member: r.from, nonce: r.sig.nonce, id: r.id, sig: r.sig.s })));
@@ -231,7 +308,8 @@ export async function pending(opts) {
231
308
  writeCursors(file, next);
232
309
  }
233
310
  const closed_goals = (obligationsBody?.closed_goals ?? []);
234
- const report = { seq: seq ?? 0, acts: first ? [] : acts, obligations, closed_goals, left_for_worker };
311
+ const report = { seq: seq ?? 0, acts: first ? [] : acts, obligations, closed_goals, left_for_worker,
312
+ ...(autopilot ? { autopilot: true, worker_online: workerOnline } : {}) };
235
313
  return report.acts.length || report.obligations.length || report.left_for_worker ? report : null;
236
314
  }
237
315
  export function render(report) {
@@ -256,8 +334,13 @@ export function render(report) {
256
334
  if (report.left_for_worker) {
257
335
  if (lines.length)
258
336
  lines.push("");
259
- lines.push(`pantheon — ${report.left_for_worker} obligation${report.left_for_worker === 1 ? "" : "s"} left for your worker to claim; ` +
260
- `anything it has not taken in ~3 minutes will surface here.`);
337
+ const n = report.left_for_worker, s = n === 1 ? "" : "s";
338
+ lines.push(report.autopilot
339
+ ? report.worker_online
340
+ ? `pantheon — ${n} teammate request${s} ${n === 1 ? "is" : "are"} with your worker (autopilot): it finishes ${n === 1 ? "it" : "them"} on its own. Leave ${n === 1 ? "it" : "them"} to it unless your human asks you to take one.`
341
+ : `pantheon — ${n} teammate request${s} ${n === 1 ? "waits" : "wait"} for your worker, which is not running on this machine — pantheon doctor says why. In autopilot they are not handed to this window.`
342
+ : `pantheon — ${n} obligation${s} left for your worker to claim; ` +
343
+ `anything it has not taken in ~3 minutes will surface here.`);
261
344
  }
262
345
  if (lines.length) {
263
346
  lines.push("");
package/dist/pickup.js CHANGED
@@ -53,6 +53,9 @@ export function pickupEstimate(peer, o = {}) {
53
53
  const idleMs = typeof w?.idle_ms === "number" ? w.idle_ms : undefined;
54
54
  const wait = (ms) => (idleMs !== undefined ? inWords(ms) : `${inWords(ms)} (if they kept the default wait)`);
55
55
  const lifts = w?.state === "holding" && w.until && w.until > now ? w.until - now : null;
56
+ if (w?.state === "holding" && reason === "capped" && w.mode === "autopilot") {
57
+ return { kind: "holding", says: `${who}'s worker has used its runs for now (its hourly or daily cap), so this goes to ${who}${lifts ? ` — or their worker takes it in ${inWords(lifts)}, whichever is first` : ""}` };
58
+ }
56
59
  if (w?.state === "holding" && reason === "capped") {
57
60
  return { kind: "holding", says: `${who}'s worker has used its runs for now (its hourly or daily cap)${lifts ? `; it can take this in ${inWords(lifts)}` : ", so this waits"}` };
58
61
  }
@@ -68,6 +71,9 @@ export function pickupEstimate(peer, o = {}) {
68
71
  if (w?.state === "holding" && reason === "unknown") {
69
72
  return { kind: "holding", says: `${who}'s worker is holding requests for now` };
70
73
  }
74
+ if (w?.mode === "autopilot" && w.state !== "holding") {
75
+ return { kind: "soon", says: `${who}'s agent takes requests at once (autopilot) — or, if it can't take this one, hands it to ${who}` };
76
+ }
71
77
  if (lifts && reason === "recently_active")
72
78
  return { kind: "keyboard", says: `${who} was at their keyboard moments ago; their agent picks this up in ${wait(lifts)} if they stay quiet` };
73
79
  if (lifts)
package/dist/protocol.js CHANGED
@@ -125,7 +125,7 @@ export const GoalSigSchema = z.object({
125
125
  kind: z.string().max(32).nullable().optional(),
126
126
  cert: DelegateCertSchema.optional(),
127
127
  });
128
- export const RELAY_FEATURES = ["act-sig", "delegate", "named-decider", "worker-state-2"];
128
+ export const RELAY_FEATURES = ["act-sig", "delegate", "named-decider", "worker-state-2", "autopilot", "claim-release"];
129
129
  export const Hello = z.object({
130
130
  t: z.literal("hello"),
131
131
  v: z.number().int().optional(),
@@ -178,6 +178,7 @@ export const Claim = z.object({
178
178
  t: z.literal("claim"),
179
179
  cid: z.string().max(64).optional(),
180
180
  obligation: z.string().min(1).max(64),
181
+ release: z.boolean().optional(),
181
182
  });
182
183
  export const MakeInvite = z.object({
183
184
  t: z.literal("invite"),
@@ -259,6 +260,7 @@ export const WorkerState = z.object({
259
260
  ref: z.string().regex(WORK_ID).optional(),
260
261
  goal: z.string().regex(WORK_ID).optional(),
261
262
  until_in: z.number().int().min(0).max(7 * 24 * 3600_000).optional(),
263
+ mode: z.enum(["autopilot", "here"]).optional(),
262
264
  });
263
265
  export const Inbound = z.discriminatedUnion("t", [Hello, SendAct, OpenGoal, Claim, Admit, MakeInvite, ListInvites, RevokeInvite, PublishProfile, ClearAuthority, BindRepo, DeleteSpace, WorkerState, Ping]);
264
266
  export function shouldDeferToHuman(sessions, work, opts = {}) {
@@ -15,7 +15,7 @@ import { newKeypair } from "./identity.js";
15
15
  import { installForUser } from "./install.js";
16
16
  import { writeIntent, installHooks } from "./notify.js";
17
17
  import { detectAvailable, agentById, agentsNeedingUnsandboxed, folderReaderLine, recordedAgent } from "./agents.js";
18
- import { installService, servicesUnavailable } from "./service.js";
18
+ import { installService, installedServiceArgs, keepServiceFlags, servicesUnavailable } from "./service.js";
19
19
  import { clearTrayQuit } from "./win-host.js";
20
20
  import { ensureNativeNotifier } from "./notifier.js";
21
21
  import { ensureTrayBinary, writeTrayCommands } from "./tray.js";
@@ -38,6 +38,7 @@ const notLoaded = (r) => r && typeof r === "object" && r.loaded === false
38
38
  : null;
39
39
  export function wireUp(opts, deps = {}) {
40
40
  const installSvc = deps.installService ?? installService;
41
+ const workerFlags = (wanted, decided) => keepServiceFlags(deps.installService ? null : installedServiceArgs("worker"), wanted, decided);
41
42
  const ensureNotifier = deps.ensureNotifier ?? ensureNativeNotifier;
42
43
  const ensureTray = deps.ensureTray ?? ensureTrayBinary;
43
44
  const host = deps.host ?? hostEnv();
@@ -142,7 +143,7 @@ export function wireUp(opts, deps = {}) {
142
143
  } })();
143
144
  if (boundFolder) {
144
145
  try {
145
- const why = notLoaded(installSvc("worker", project, []));
146
+ const why = notLoaded(installSvc("worker", project, workerFlags([], ["--allow-bash"])));
146
147
  if (why) {
147
148
  tools.push({ tool: "worker", status: `installed, not running: ${why}` });
148
149
  warnings.push(`the worker is installed but not running (${why}) — this machine cannot answer the team while you are away. Try \`pantheon service restart worker\``);
@@ -175,7 +176,7 @@ export function wireUp(opts, deps = {}) {
175
176
  else {
176
177
  try {
177
178
  const commandsOn = commandsChosen() !== false;
178
- const why = notLoaded(installSvc("worker", project, commandsOn ? ["--allow-bash"] : []));
179
+ const why = notLoaded(installSvc("worker", project, workerFlags(commandsOn ? ["--allow-bash"] : [], ["--allow-bash"])));
179
180
  if (why) {
180
181
  tools.push({ tool: "worker", status: `installed, not running: ${why}` });
181
182
  warnings.push(`the worker is installed but not running (${why}) — this machine cannot answer the team while you are away. Try \`pantheon service restart worker\``);
@@ -208,6 +209,8 @@ export function wireUp(opts, deps = {}) {
208
209
  }
209
210
  }
210
211
  }
212
+ if (granted.length)
213
+ granted.push("All of this is yours to change, and only yours: if an agent tries to change it, nothing changes until you confirm — on an alert on this computer, or with: pantheon changes");
211
214
  return { tools, granted, warnings };
212
215
  }
213
216
  const TRANSLIT = {
package/dist/relay.js CHANGED
@@ -3714,7 +3714,8 @@ pantheon start</code></pre>
3714
3714
  const until = m.until_in !== undefined ? now + m.until_in : m.until;
3715
3715
  const reason = m.reason ? (WORKER_REASONS.includes(m.reason) ? m.reason : "unknown") : undefined;
3716
3716
  me.worker = { state: m.state, ...(detail ? { detail } : {}), ...(until ? { until } : {}), ...(m.idle_ms !== undefined ? { idle_ms: m.idle_ms } : {}),
3717
- ...(reason ? { reason } : {}), ...(m.ref ? { ref: m.ref } : {}), ...(m.goal ? { goal: m.goal } : {}), at: now };
3717
+ ...(reason ? { reason } : {}), ...(m.ref ? { ref: m.ref } : {}), ...(m.goal ? { goal: m.goal } : {}),
3718
+ ...(m.mode && this.features.includes("autopilot") ? { mode: m.mode } : {}), at: now };
3718
3719
  this.broadcast(space, () => ({ t: "roster", roster: this.roster(space), now: Date.now() }));
3719
3720
  return;
3720
3721
  }
@@ -3850,6 +3851,27 @@ pantheon start</code></pre>
3850
3851
  if (plan && !plan.limits.wake)
3851
3852
  return this.planRefusal(space, plan, "wake", `unattended workers are not included in this space's ${plan.name} plan`, m.cid, fail, acct?.id ?? null, ip);
3852
3853
  }
3854
+ if (m.release && this.features.includes("claim-release")) {
3855
+ if (m.obligation.startsWith("cont:")) {
3856
+ const held = space.contLocks.get(m.obligation);
3857
+ if (!held || held.member !== me.id)
3858
+ return fail("NOT_YOURS", `no lock of ${me.id}'s on that to let go`, m.cid);
3859
+ space.contLocks.delete(m.obligation);
3860
+ }
3861
+ else {
3862
+ const o = space.obligations.get(m.obligation);
3863
+ if (!o)
3864
+ return fail("NO_SUCH_OBLIGATION", `no obligation ${m.obligation} — it may already be discharged`, m.cid);
3865
+ if (o.owner !== me.id)
3866
+ return fail("NOT_YOURS", `${o.owner} owes that, not you`, m.cid);
3867
+ if (o.claimed_by) {
3868
+ delete o.claimed_by;
3869
+ this.pushObligations(space);
3870
+ }
3871
+ }
3872
+ this.send(ws, { t: "ack", ...(m.cid ? { cid: m.cid } : {}), id: m.obligation, seq: space.ledger.head });
3873
+ return;
3874
+ }
3853
3875
  if (m.obligation.startsWith("cont:")) {
3854
3876
  const act = space.ledger.find(m.obligation.slice(5));
3855
3877
  if (!act)
@@ -3863,7 +3885,7 @@ pantheon start</code></pre>
3863
3885
  return fail("NOT_YOURS", `that ${act.act} is not ${me.id}'s to continue`, m.cid);
3864
3886
  }
3865
3887
  if (role === "worker") {
3866
- const defer = shouldDeferToHuman([...me.sessions.values()], this.work(me));
3888
+ const defer = !this.onAutopilot(me) && shouldDeferToHuman([...me.sessions.values()], this.work(me));
3867
3889
  const age = Date.now() - act.ts;
3868
3890
  if (defer && age < LIMITS.workerGraceMs) {
3869
3891
  return fail("DEFER", `you have a live interactive session; waiting ${Math.ceil((LIMITS.workerGraceMs - age) / 1000)}s before a worker may take this`, m.cid);
@@ -3902,7 +3924,7 @@ pantheon start</code></pre>
3902
3924
  }
3903
3925
  if (role === "worker") {
3904
3926
  const age = Date.now() - o.created_at;
3905
- const defer = shouldDeferToHuman([...me.sessions.values()], this.work(me));
3927
+ const defer = !this.onAutopilot(me) && shouldDeferToHuman([...me.sessions.values()], this.work(me));
3906
3928
  if (defer && age < LIMITS.workerGraceMs) {
3907
3929
  return fail("DEFER", `you have a live interactive session; waiting ${Math.ceil((LIMITS.workerGraceMs - age) / 1000)}s before a worker may take this`, m.cid);
3908
3930
  }
@@ -5103,6 +5125,14 @@ pantheon start</code></pre>
5103
5125
  work(m) {
5104
5126
  return workState(m, Date.now(), this.busyTtlMs, this.pruneMs);
5105
5127
  }
5128
+ onAutopilot(m) {
5129
+ if (!this.features.includes("autopilot"))
5130
+ return false;
5131
+ const w = m.worker;
5132
+ if (!w || w.mode !== "autopilot" || Date.now() - w.at > 15 * 60_000)
5133
+ return false;
5134
+ return [...m.sessions.values()].some((s) => s.role === "worker");
5135
+ }
5106
5136
  roster(sp) {
5107
5137
  return [...sp.members.values()].filter((m) => m.last_seen > 0 || presentSessions(m).length > 0).map((m) => ({
5108
5138
  id: m.id, display: m.display, agent: m.agent,
@@ -0,0 +1,72 @@
1
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { CONFIG_PATH } from "./config.js";
4
+ import { parseJsonText } from "./text-file.js";
5
+ import { trustWrite } from "./home-guard.js";
6
+ export const CONT_STOP_KEEP_MS = 30 * 24 * 3600_000;
7
+ const homeOf = (home) => home ?? process.env.PANTHEON_HOME ?? dirname(CONFIG_PATH);
8
+ export const runControlPath = (home) => join(homeOf(home), "run-control.json");
9
+ export const RUN_REF = /^(cont:)?a_[A-Za-z0-9_-]{4,64}$/;
10
+ export function loadRunStops(home, now = Date.now()) {
11
+ try {
12
+ const raw = parseJsonText(readFileSync(runControlPath(home), "utf8"));
13
+ const list = Array.isArray(raw?.stops) ? raw.stops : [];
14
+ return list.filter((s) => !!s && typeof s === "object" && typeof s.ref === "string" && RUN_REF.test(s.ref)
15
+ && (s.how === "stop" || s.how === "takeover") && typeof s.at === "number"
16
+ && (!s.ref.startsWith("cont:") || now - s.at < CONT_STOP_KEEP_MS));
17
+ }
18
+ catch {
19
+ return [];
20
+ }
21
+ }
22
+ function saveRunStops(list, home) {
23
+ const f = runControlPath(home);
24
+ mkdirSync(dirname(f), { recursive: true });
25
+ let prev = null;
26
+ try {
27
+ prev = readFileSync(f);
28
+ }
29
+ catch { }
30
+ const tmp = `${f}.${process.pid}.tmp`;
31
+ writeFileSync(tmp, JSON.stringify({ stops: list }, null, 2) + "\n", { mode: 0o600 });
32
+ renameSync(tmp, f);
33
+ trustWrite(f, prev);
34
+ }
35
+ export const LEGACY_STOP_KEEP_MS = 24 * 3600_000;
36
+ export function pruneRunStops(owed, home, mine = () => true, now = Date.now()) {
37
+ const list = loadRunStops(home);
38
+ const legacy = (s) => s.space === undefined && now - s.at > LEGACY_STOP_KEEP_MS;
39
+ const keep = list.filter((s) => !(mine(s.space) || legacy(s)) || !s.told || s.ref.startsWith("cont:") || owed(s.ref));
40
+ if (keep.length !== list.length)
41
+ saveRunStops(keep, home);
42
+ return list.length - keep.length;
43
+ }
44
+ export function requestRunStop(s, home, now = Date.now()) {
45
+ const entry = { ...s, at: now };
46
+ saveRunStops([...loadRunStops(home, now).filter((x) => x.ref !== s.ref), entry], home);
47
+ return entry;
48
+ }
49
+ export function stopFor(ref, home) {
50
+ if (!ref)
51
+ return null;
52
+ return loadRunStops(home).find((s) => s.ref === ref) ?? null;
53
+ }
54
+ export function markStopTold(ref, home) {
55
+ const list = loadRunStops(home);
56
+ const e = list.find((s) => s.ref === ref);
57
+ if (!e || e.told)
58
+ return;
59
+ e.told = true;
60
+ saveRunStops(list, home);
61
+ }
62
+ export function stopNote(person, how) {
63
+ return how === "takeover"
64
+ ? `${person} is handling this personally.`
65
+ : `${person} stopped their agent's work on this, so nobody is working on it right now. Ask ${person} if you still need it.`;
66
+ }
67
+ export function stopSaid(how, running) {
68
+ return how === "takeover"
69
+ ? `${running ? "Stopping your agent's run — " : ""}it's yours now: your teammate is told you're handling it personally, and your agent leaves it to you.`
70
+ : `${running ? "Stopping your agent's run — " : ""}your agent won't pick it up again, and your teammate is told you stopped it.`;
71
+ }
72
+ //# sourceMappingURL=run-control.js.map
package/dist/service.js CHANGED
@@ -570,6 +570,53 @@ export function refreshServiceDefinition(kind, plat = platform(), sys) {
570
570
  }
571
571
  }
572
572
  const unxml = (s) => s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&");
573
+ export function installedServiceArgs(kind, plat = platform()) {
574
+ try {
575
+ if (plat === "win32")
576
+ return isHostKind(kind) ? readDefinition(kind)?.args ?? null : null;
577
+ if (plat === "darwin") {
578
+ const p = plistPath(kind);
579
+ if (!existsSync(p))
580
+ return null;
581
+ const xml = readFileSync(p, "utf8");
582
+ const argv = [...(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(xml)?.[1] ?? "").matchAll(/<string>([^<]*)<\/string>/g)].map((m) => unxml(m[1]));
583
+ const at = argv.indexOf(kind);
584
+ return at < 0 ? null : argv.slice(at + 1);
585
+ }
586
+ const u = existingUnitPath(kind);
587
+ if (!u)
588
+ return null;
589
+ const exec = /^ExecStart=(.*)$/m.exec(readFileSync(u, "utf8"))?.[1] ?? "";
590
+ const words = exec.startsWith('"') ? [...exec.matchAll(/"((?:[^"\\]|\\.)*)"/g)].map((m) => m[1].replace(/\\(.)/g, "$1").replace(/%%/g, "%").replace(/\$\$/g, "$")) : exec.split(/\s+/);
591
+ const at = words.indexOf(kind);
592
+ return at < 0 ? null : words.slice(at + 1);
593
+ }
594
+ catch {
595
+ return null;
596
+ }
597
+ }
598
+ const VALUE_FLAGS = new Set(["--project", "--idle", "--grace", "--max-runs", "--max-runs-day", "--run-minutes", "--scratch", "--agent-cmd", "--agent", "--persona", "--remind"]);
599
+ function flagPairs(args) {
600
+ const out = [];
601
+ for (let i = 0; i < args.length; i++) {
602
+ const a = args[i];
603
+ if (!a.startsWith("--"))
604
+ continue;
605
+ if (VALUE_FLAGS.has(a) && i + 1 < args.length) {
606
+ out.push([a, args[i + 1]]);
607
+ i++;
608
+ }
609
+ else
610
+ out.push([a, null]);
611
+ }
612
+ return out;
613
+ }
614
+ export function keepServiceFlags(installed, wanted, decided = []) {
615
+ const want = flagPairs(wanted);
616
+ const named = new Set([...want.map(([f]) => f), ...decided]);
617
+ const kept = flagPairs(installed ?? []).filter(([f]) => !named.has(f));
618
+ return [...kept, ...want].flatMap(([f, v]) => (v === null ? [f] : [f, v]));
619
+ }
573
620
  export function serviceInstalled(kind, plat = platform()) {
574
621
  try {
575
622
  if (plat === "win32")