@astrofoundry/pi-astro 0.40.1 β†’ 0.40.3

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/agents/media.md CHANGED
@@ -19,6 +19,6 @@ Rules:
19
19
  - Movies go to `add-movies`, series to `add-series`; batch independent IDs in one call.
20
20
  - Success needs an explicit `added` or `already_exists` in `results`; `already_exists` means it was already there, not newly added. Report every ID of a batch.
21
21
  - Pause or resume downloads only when the task asks for it, then report the returned state. Adding never implies a queue change.
22
- - Keep replies short: canonical title and year, outcome, and the SABnzbd state an add returned.
22
+ - Keep replies short: canonical title and year, and the outcome. When an add returned `sabnzbd_paused: true`, end with "Downloads are paused."; say nothing about the queue otherwise. Outside failures, name no tool or service (SABnzbd, Radarr, Sonarr, trendarr, TMDB, OMDb): say downloads, library, search.
23
23
  - Library settings, quality profiles, Radarr and Sonarr configuration, and deletions are operator tasks; say so and stop.
24
24
  - Delegate through `subagent` only to another specialist (`astro.arcane` for the media containers on the Arcane VM) and only for that specialist's own area.
@@ -97,6 +97,8 @@ export interface StackEntry {
97
97
  state: StackState;
98
98
  /** What the last update did, or why it failed. */
99
99
  detail?: string;
100
+ /** The thread of an Upgrade carefully click; the `stack-update` astro.arcane runs there sets the state. */
101
+ thread?: string;
100
102
  }
101
103
 
102
104
  /** One posted message of a report and the stacks it shows, so a click redraws exactly that message. */
@@ -34,7 +34,7 @@ import {
34
34
  writePostedArcane,
35
35
  } from "./daily-report.ts";
36
36
  import { GatewayClient } from "./gateway.ts";
37
- import { type CommandOption, IS_COMPONENTS_V2, KeyedQueue, MEDIA, MEDIA_COMMANDS, type MediaKind, type Outcome, addOutcome, applyOutcome, commandArgs, hasActiveButton, listMessage, mediaAccess, mediaPointer, parseAddButton, parseAddReport, parseMediaList, parseQueueState, queueLine } from "./media.ts";
37
+ import { type CommandOption, IS_COMPONENTS_V2, KeyedQueue, MEDIA, MEDIA_COMMANDS, type MediaKind, type Outcome, PAUSED_TEXT, RESUME_ID, addOutcome, addedWhilePaused, applyOutcome, commandArgs, hasActiveButton, listMessage, mediaAccess, mediaPointer, parseAddButton, parseAddReport, parseMediaList, parseQueueState, queueLine, resumedText, unpauseRow } from "./media.ts";
38
38
  import { cancelledApprovalText, interruptedTaskText, readOpenWork, type OpenWork, type StopReason, writeOpenWork } from "./open-work.ts";
39
39
  import { DISMISSED, type Picks, parseNoButton, parsePicks, picksArgs, picksFailureText, picksMessage, readPicksState, withDismissed, withSuggested, writePicksState } from "./media-picks.ts";
40
40
  import { FRIDAY, isDue, MONDAY, readReportState, writeReportState, zonedWeekday } from "./reports.ts";
@@ -76,7 +76,7 @@ import { type Quote, type QuotedMessage, withQuotes } from "./quote.ts";
76
76
  import { DiscordRest, type MessageComponent } from "./rest.ts";
77
77
  import { ArcaneWatch } from "./arcane-watch-monitor.ts";
78
78
  import { parseSnapshot } from "./arcane-watch.ts";
79
- import { type Applied, autoFailureText, foremanTask, stackProblems, SUPERVISE_DELAY_MS, SUPERVISE_LIMIT_MS } from "./supervise.ts";
79
+ import { type Applied, autoFailureText, foremanTask, stackProblems, stackUpdateAnswer, SUPERVISE_DELAY_MS, SUPERVISE_LIMIT_MS } from "./supervise.ts";
80
80
  import { stackPlan, toolPlan } from "./update-policy.ts";
81
81
  import { type AreaStatus, arcaneSummary, backupStatus, dnsStatus, edgeStatus, identityStatus, inferenceStatus, mediaStatus, networkStatus, problemText, proxmoxStatus, type ReportLine, type Route, summaryText, toolsSummary } from "./daily-run.ts";
82
82
  import { type InvestigationRequest, SecurityMonitor } from "./security-monitor.ts";
@@ -1095,6 +1095,7 @@ class Bridge {
1095
1095
  try {
1096
1096
  const posted = await this.rest.createMessage(report.channelId, { content: `🧭 Careful upgrade of **${entry.stack}**, requested by <@${userId}>.`, replyTo: messageId });
1097
1097
  const thread = await this.rest.startThread(report.channelId, posted.id, `Upgrade of ${entry.stack}`.slice(0, 100));
1098
+ this.rememberCarefulThread(report, entry.stack, thread.id);
1098
1099
  const starter = await this.rest.createMessage(thread.id, { content: 'The arcane specialist reads the release notes and posts a plan here. Nothing changes until you write "go".' });
1099
1100
  void this.investigateIn("arcane", { threadId: thread.id, starterId: starter.id, userId, task: carefulTask(entry) });
1100
1101
  } catch (err) {
@@ -1103,6 +1104,33 @@ class Bridge {
1103
1104
  }
1104
1105
  }
1105
1106
 
1107
+ private rememberCarefulThread(report: ArcaneReport, stack: string, threadId: string): void {
1108
+ const current = readPostedArcane();
1109
+ const target = current && current.date === report.date ? current : report;
1110
+ const entry = target.stacks.find((s) => s.stack === stack);
1111
+ if (entry) entry.thread = threadId;
1112
+ if (target === current) writePostedArcane(target);
1113
+ }
1114
+
1115
+ /**
1116
+ * After an arcane task in a careful-upgrade thread: the report line takes the
1117
+ * outcome of the `stack-update` the specialist ran there, and an update is
1118
+ * checked again like one an owner started with Update.
1119
+ */
1120
+ private async carefulOutcome(threadId: string, messages: RunResult["messages"]): Promise<void> {
1121
+ const report = readPostedArcane();
1122
+ const entry = report?.stacks.find((s) => s.thread === threadId && s.state === "planning");
1123
+ if (!report || !entry) return;
1124
+ const ran = stackUpdateAnswer(messages, entry.stack);
1125
+ if (!ran) return;
1126
+ const outcome = stackOutcome(ran.answer);
1127
+ await this.markArcane(report, entry.stack, outcome.state, outcome.detail);
1128
+ log(`arcane: careful ${entry.stack} ${outcome.detail}`);
1129
+ if (outcome.state !== "updated") return;
1130
+ const applied: Applied = { stack: entry.stack, finishedAt: ran.at, detail: outcome.detail, ...(outcome.commit ? { commit: outcome.commit } : {}) };
1131
+ void this.superviseArcane(report, [applied]).catch((err) => log(`arcane: supervising ${entry.stack} failed: ${err instanceof Error ? err.message : String(err)}`));
1132
+ }
1133
+
1106
1134
  /**
1107
1135
  * Sets one stack's state in the posted report and redraws its message
1108
1136
  * through the bot's own route, which outlives the interaction token. A run
@@ -1412,12 +1440,45 @@ class Bridge {
1412
1440
  await this.rest.editOriginal(app, interaction.token, { components: next });
1413
1441
  this.rememberMediaMessage(message.id, next);
1414
1442
  log(`media add ${target.imdbId} for ${userId}: ${outcome.label}`);
1415
- if (outcome.note) await this.rest.followUp(app, interaction.token, { content: outcome.note, flags: EPHEMERAL });
1443
+ if (outcome.note) await this.rest.followUp(app, interaction.token, { content: outcome.note, flags: EPHEMERAL, ...(outcome.paused ? { components: unpauseRow() } : {}) });
1416
1444
  })
1417
1445
  .catch((err) => log(`media add ${target.imdbId} failed: ${err instanceof Error ? err.message : String(err)}`))
1418
1446
  .finally(() => this.untrackMedia(interaction));
1419
1447
  }
1420
1448
 
1449
+ /** Unpause under a media answer or an Add note: the queue resumes, and the message says who resumed it. */
1450
+ private async onResumeButton(interaction: Interaction): Promise<void> {
1451
+ const message = interaction.message;
1452
+ if (!message) return;
1453
+ const userId = interaction.member?.user?.id ?? interaction.user?.id ?? "";
1454
+ if (this.stopping) {
1455
+ await this.rest.ephemeralReply(interaction.id, interaction.token, "The bridge is restarting; try again in a minute.");
1456
+ return;
1457
+ }
1458
+ if (!(await this.mediaAllowed(interaction, userId))) return;
1459
+ await this.rest.deferUpdate(interaction.id, interaction.token);
1460
+ const app = this.config.applicationId;
1461
+ await this.mediaClicks
1462
+ .run(message.id, async () => {
1463
+ if (!hasActiveButton(message.components ?? [], RESUME_ID)) return;
1464
+ let paused: boolean | null = null;
1465
+ let reason = "";
1466
+ try {
1467
+ paused = parseQueueState(JSON.parse(await this.runEntry(MEDIA, `discord-${userId}`, ["sabnzbd", "resume"], MEDIA_TIMEOUT_MS)));
1468
+ } catch (err) {
1469
+ reason = (err instanceof Error ? err.message : String(err)).split("\n")[0].slice(0, 300);
1470
+ }
1471
+ if (paused === false) {
1472
+ await this.rest.editOriginal(app, interaction.token, { content: resumedText(userId), components: [] });
1473
+ log(`media: downloads resumed by ${userId}`);
1474
+ return;
1475
+ }
1476
+ log(`media: resume for ${userId} failed: ${reason || "the queue still reports paused"}`);
1477
+ await this.rest.followUp(app, interaction.token, { content: `Downloads are still paused: ${reason || "the queue did not resume"}.`, flags: EPHEMERAL });
1478
+ })
1479
+ .catch((err) => log(`media: resume failed: ${err instanceof Error ? err.message : String(err)}`));
1480
+ }
1481
+
1421
1482
  /** Not interested on a weekly pick: the title never comes back, unlike an ignored one, and only that button changes. */
1422
1483
  private async onDismissButton(interaction: Interaction, customId: string): Promise<void> {
1423
1484
  const target = parseNoButton(customId);
@@ -1520,6 +1581,7 @@ class Bridge {
1520
1581
  let output: string;
1521
1582
  let attachment: string | undefined;
1522
1583
  let seen = 0;
1584
+ let messages: RunResult["messages"] = [];
1523
1585
  try {
1524
1586
  const result = await runAgent({
1525
1587
  agent: { ...agent, timeoutMinutes: agent.timeoutMinutes ?? TASK_TIMEOUT_MINUTES },
@@ -1542,6 +1604,7 @@ class Bridge {
1542
1604
  },
1543
1605
  });
1544
1606
  failed = isFailed(result);
1607
+ messages = result.messages;
1545
1608
  if (failed) {
1546
1609
  const reply = failureReply(result);
1547
1610
  output = reply.text;
@@ -1567,6 +1630,11 @@ class Bridge {
1567
1630
  const answers = await this.deliver(task, placeholder, `${failed ? "❌" : "βœ…"} **${task.specialist}**\n${output}`, attachment);
1568
1631
  this.conversations = recordAnswer(this.conversations, task.conversation.key, answers, Date.now());
1569
1632
  saveState(this.conversations);
1633
+ if (task.specialist === "arcane") await this.carefulOutcome(task.channelId, messages).catch((err) => log(`arcane: careful outcome failed: ${err instanceof Error ? err.message : String(err)}`));
1634
+ if (task.specialist === MEDIA && addedWhilePaused(messages)) {
1635
+ const last = answers[answers.length - 1];
1636
+ await this.rest.createMessage(task.channelId, { content: PAUSED_TEXT, components: unpauseRow(), ...(last ? { replyTo: last } : {}) }).catch((err) => log(`media: paused notice failed: ${err instanceof Error ? err.message : String(err)}`));
1637
+ }
1570
1638
  return failed;
1571
1639
  }
1572
1640
 
@@ -1625,6 +1693,10 @@ class Bridge {
1625
1693
  }
1626
1694
  if (interaction.type !== 3) return;
1627
1695
  const customId = interaction.data?.custom_id ?? "";
1696
+ if (customId === RESUME_ID) {
1697
+ await this.onResumeButton(interaction);
1698
+ return;
1699
+ }
1628
1700
  if (customId.startsWith("media:no:")) {
1629
1701
  await this.onDismissButton(interaction, customId);
1630
1702
  return;
@@ -1,3 +1,4 @@
1
+ import type { Message } from "@earendil-works/pi-ai";
1
2
  import { describe, expect, it, vi } from "vitest";
2
3
  import { helpText } from "./commands.ts";
3
4
  import { validateConfig } from "./config.ts";
@@ -22,6 +23,11 @@ import {
22
23
  parseMediaList,
23
24
  parseQueueState,
24
25
  queueLine,
26
+ PAUSED_TEXT,
27
+ RESUME_ID,
28
+ addedWhilePaused,
29
+ resumedText,
30
+ unpauseRow,
25
31
  } from "./media.ts";
26
32
  import { DiscordRest, type MessageComponent } from "./rest.ts";
27
33
 
@@ -130,7 +136,8 @@ describe("media add buttons", () => {
130
136
  it("turns each add result into a button state and a private note", () => {
131
137
  const report = (status: string, paused: boolean | null = false, detail: string | null = null) => ({ results: [{ imdb_id: "tt1", title: "Hope", status, detail }], sabnzbd_paused: paused });
132
138
  expect(addOutcome(report("added"), "movie", "tt1")).toEqual({ label: "Added", style: 3, disabled: true });
133
- expect(addOutcome(report("added", true), "movie", "tt1").note).toMatch(/downloads are paused/);
139
+ expect(addOutcome(report("added", true), "movie", "tt1")).toMatchObject({ note: "Added **Hope**; the search started. ⏸️ Downloads are paused.", paused: true });
140
+ expect(addOutcome(report("added", false), "movie", "tt1").paused).toBeUndefined();
134
141
  expect(addOutcome(report("already_exists"), "movie", "tt1")).toEqual({ label: "In library", style: 2, disabled: true });
135
142
  expect(addOutcome(report("not_found"), "series", "tt1")).toMatchObject({ label: "Not found", disabled: true, note: expect.stringMatching(/Sonarr/) });
136
143
  expect(addOutcome(report("error", false, "quality profile missing"), "movie", "tt1")).toMatchObject({ label: "Retry", disabled: false, note: "Not added: quality profile missing." });
@@ -242,3 +249,24 @@ describe("media rest calls", () => {
242
249
  expect((JSON.parse(calls[4].init.body as string) as { name: string }[]).map((c) => c.name)).toEqual(["trending", "search", "downloads"]);
243
250
  });
244
251
  });
252
+
253
+ describe("paused downloads", () => {
254
+ const call = (id: string, args: string[], name = "media") => ({ role: "assistant", content: [{ type: "toolCall", id, name, arguments: { args } }] });
255
+ const result = (id: string, value: unknown, isError = false) => ({ role: "toolResult", toolCallId: id, toolName: "media", content: [{ type: "text", text: JSON.stringify(value) }], isError, timestamp: 1 });
256
+ const added = (paused: boolean | null) => ({ results: [{ imdb_id: "tt1", title: "X", status: "added", detail: null }], sabnzbd_paused: paused, warnings: [] });
257
+
258
+ it("asks to unpause only when an add left the queue paused", () => {
259
+ expect(addedWhilePaused([call("a", ["search", "x"]), result("a", { movies: [], series: [] }), call("b", ["add-movies", "tt1"]), result("b", added(true))] as unknown as Message[])).toBe(true);
260
+ expect(addedWhilePaused([call("b", ["add-movies", "tt1"]), result("b", added(true)), call("c", ["sabnzbd", "resume"]), result("c", { sabnzbd_paused: false })] as unknown as Message[])).toBe(false);
261
+ expect(addedWhilePaused([call("b", ["add-series", "tt1"]), result("b", added(false))] as unknown as Message[])).toBe(false);
262
+ expect(addedWhilePaused([call("c", ["sabnzbd", "status"]), result("c", { sabnzbd_paused: true })] as unknown as Message[])).toBe(false);
263
+ expect(addedWhilePaused([call("b", ["add-movies", "tt1"]), result("b", "failed", true)] as unknown as Message[])).toBe(false);
264
+ expect(addedWhilePaused([call("b", ["add-movies", "tt1"], "arcane"), result("b", added(true))] as unknown as Message[])).toBe(false);
265
+ });
266
+
267
+ it("offers one Unpause button and names who resumed", () => {
268
+ expect(unpauseRow()).toEqual([{ type: 1, components: [{ type: 2, style: 1, label: "Unpause", custom_id: RESUME_ID }] }]);
269
+ expect(PAUSED_TEXT).toBe("⏸️ Downloads are paused");
270
+ expect(resumedText("178096425509453824")).toBe("▢️ Downloads resumed by <@178096425509453824>");
271
+ });
272
+ });
@@ -1,3 +1,4 @@
1
+ import type { Message } from "@earendil-works/pi-ai";
1
2
  import { type ChannelSettings, type DiscordConfig, canUse, channelSpecialists } from "./config.ts";
2
3
  import type { MessageComponent } from "./rest.ts";
3
4
 
@@ -228,6 +229,8 @@ export interface Outcome {
228
229
  disabled: boolean;
229
230
  /** Shown only to the user who clicked. */
230
231
  note?: string;
232
+ /** The add left downloads paused; the note carries an Unpause button. */
233
+ paused?: boolean;
231
234
  }
232
235
 
233
236
  /** What the clicked button turns into after the add, from the wrapper's answer or its failure text. */
@@ -236,7 +239,7 @@ export function addOutcome(report: AddReport | null, kind: MediaKind, imdbId: st
236
239
  const result = report.results.find((r) => r.imdb_id === imdbId);
237
240
  const name = result?.title ? `**${escapeDiscord(result.title)}**` : imdbId;
238
241
  if (result?.status === "added") {
239
- return { label: "Added", style: SUCCESS, disabled: true, ...(report.sabnzbd_paused === true ? { note: `Added ${name}; the search started, but downloads are paused. \`/downloads resume\` starts them.` } : {}) };
242
+ return { label: "Added", style: SUCCESS, disabled: true, ...(report.sabnzbd_paused === true ? { note: `Added ${name}; the search started. ${PAUSED_TEXT}.`, paused: true } : {}) };
240
243
  }
241
244
  if (result?.status === "already_exists") return { label: "In library", style: SECONDARY, disabled: true };
242
245
  if (result?.status === "not_found") return { label: "Not found", style: DANGER, disabled: true, note: `${name} was not found ${kind === "movie" ? "in Radarr" : "on TMDB or in Sonarr"}; nothing was added.` };
@@ -269,6 +272,49 @@ export function applyOutcome(components: readonly MessageComponent[], customId:
269
272
  }));
270
273
  }
271
274
 
275
+ export const PAUSED_TEXT = "⏸️ Downloads are paused";
276
+ export const RESUME_ID = "media:resume";
277
+
278
+ export function unpauseRow(): MessageComponent[] {
279
+ return [{ type: 1, components: [{ type: 2, style: PRIMARY, label: "Unpause", custom_id: RESUME_ID }] }];
280
+ }
281
+
282
+ export function resumedText(userId: string): string {
283
+ return `▢️ Downloads resumed by <@${userId}>`;
284
+ }
285
+
286
+ function mediaArgs(args: unknown): string[] {
287
+ const list = (args as { args?: unknown } | null)?.args;
288
+ return Array.isArray(list) ? list.filter((a): a is string => typeof a === "string") : [];
289
+ }
290
+
291
+ /**
292
+ * Whether a media task added something and the queue was still paused at its
293
+ * end: the pause state each add or queue call reported, the last one winning.
294
+ */
295
+ export function addedWhilePaused(messages: readonly Message[]): boolean {
296
+ const calls = new Map<string, string>();
297
+ for (const m of messages) {
298
+ if (m.role !== "assistant") continue;
299
+ for (const part of m.content) if (part.type === "toolCall" && part.name === MEDIA) calls.set(part.id, mediaArgs(part.arguments)[0] ?? "");
300
+ }
301
+ let added = false;
302
+ let paused: boolean | null = null;
303
+ for (const m of messages) {
304
+ if (m.role !== "toolResult" || m.isError) continue;
305
+ const command = calls.get(m.toolCallId);
306
+ if (command !== "add-movies" && command !== "add-series" && command !== "sabnzbd") continue;
307
+ try {
308
+ const state = parseQueueState(JSON.parse(m.content.map((c) => (c.type === "text" ? c.text : "")).join("")));
309
+ if (command !== "sabnzbd") added = true;
310
+ if (state !== null) paused = state;
311
+ } catch {
312
+ continue;
313
+ }
314
+ }
315
+ return added && paused === true;
316
+ }
317
+
272
318
  export type MediaAccess = "ok" | "channel" | "user";
273
319
 
274
320
  /** Media commands answer where the media specialist is present and for owners or users listed under `access.media`. */
@@ -1,6 +1,7 @@
1
+ import type { Message } from "@earendil-works/pi-ai";
1
2
  import { describe, expect, it } from "vitest";
2
3
  import type { WatchedContainer } from "../../specialists/lib/container-watch.ts";
3
- import { autoFailureText, foremanTask, stackProblems } from "./supervise.ts";
4
+ import { autoFailureText, foremanTask, stackProblems, stackUpdateAnswer } from "./supervise.ts";
4
5
 
5
6
  const MIN = 60_000;
6
7
 
@@ -32,3 +33,29 @@ describe("supervision", () => {
32
33
  expect(task).toContain("Change nothing.");
33
34
  });
34
35
  });
36
+
37
+ describe("careful upgrades", () => {
38
+ const call = (id: string, args: string[], name = "arcane") => ({ role: "assistant", content: [{ type: "text", text: "running" }, { type: "toolCall", id, name, arguments: { args } }] });
39
+ const result = (id: string, text: string, isError = false, timestamp = 1000) => ({ role: "toolResult", toolCallId: id, toolName: "arcane", content: [{ type: "text", text }], isError, timestamp });
40
+
41
+ it("takes the answer of the last stack-update of that stack in the run", () => {
42
+ const messages = [
43
+ call("a", ["containers", "get", "uptime-kuma"]),
44
+ result("a", '{"status":"updated"}'),
45
+ call("b", ["stack-update", "uptime-kuma", "--confirm"]),
46
+ result("b", "arcane: the operator denied the approval request", true),
47
+ call("c", ["stack-update", "uptime-kuma", "--confirm"]),
48
+ result("c", '{"status":"updated","stack":"uptime-kuma","services":[{"service":"uptime-kuma","to":"2.5.7"}]}', false, 2000),
49
+ call("d", ["stack-update", "mealie"]),
50
+ result("d", '{"status":"failed"}'),
51
+ ] as unknown as Message[];
52
+ expect(stackUpdateAnswer(messages, "uptime-kuma")).toEqual({ answer: { status: "updated", stack: "uptime-kuma", services: [{ service: "uptime-kuma", to: "2.5.7" }] }, at: 2000 });
53
+ });
54
+
55
+ it("leaves the line alone when the run only planned, was denied, or answered no JSON", () => {
56
+ expect(stackUpdateAnswer([call("a", ["release-notes", "uptime-kuma/uptime-kuma"]), result("a", "{}")] as unknown as Message[], "uptime-kuma")).toBeNull();
57
+ expect(stackUpdateAnswer([call("b", ["stack-update", "uptime-kuma"]), result("b", "denied", true)] as unknown as Message[], "uptime-kuma")).toBeNull();
58
+ expect(stackUpdateAnswer([call("c", ["stack-update", "uptime-kuma"]), result("c", "(no output)")] as unknown as Message[], "uptime-kuma")).toBeNull();
59
+ expect(stackUpdateAnswer([call("d", ["stack-update", "uptime-kuma"], "edge"), result("d", '{"status":"updated"}')] as unknown as Message[], "uptime-kuma")).toBeNull();
60
+ });
61
+ });
@@ -1,3 +1,4 @@
1
+ import type { Message } from "@earendil-works/pi-ai";
1
2
  import type { WatchedContainer } from "../../specialists/lib/container-watch.ts";
2
3
  import { healthProblem } from "./arcane-watch.ts";
3
4
  import { escapeDiscord } from "./media.ts";
@@ -59,3 +60,32 @@ export function foremanTask(applied: Applied, problems: readonly string[], rollb
59
60
  "Change nothing. Answer with the cause, the evidence, the state now, and your recommendation.",
60
61
  ].join("\n");
61
62
  }
63
+
64
+ function isStackUpdate(args: unknown, stack: string): boolean {
65
+ const list = (args as { args?: unknown } | null)?.args;
66
+ return Array.isArray(list) && list[0] === "stack-update" && list[1] === stack;
67
+ }
68
+
69
+ /**
70
+ * The answer of the last `stack-update <stack>` the arcane specialist ran in
71
+ * one task, with the time it ended; null when it ran none or the call failed
72
+ * (a denied approval, a wrapper error), which leaves the report line as it was.
73
+ */
74
+ export function stackUpdateAnswer(messages: readonly Message[], stack: string): { answer: Record<string, unknown>; at: number } | null {
75
+ const calls = new Set<string>();
76
+ for (const m of messages) {
77
+ if (m.role !== "assistant") continue;
78
+ for (const part of m.content) if (part.type === "toolCall" && part.name === "arcane" && isStackUpdate(part.arguments, stack)) calls.add(part.id);
79
+ }
80
+ let found: { answer: Record<string, unknown>; at: number } | null = null;
81
+ for (const m of messages) {
82
+ if (m.role !== "toolResult" || m.isError || !calls.has(m.toolCallId)) continue;
83
+ try {
84
+ const value: unknown = JSON.parse(m.content.map((c) => (c.type === "text" ? c.text : "")).join(""));
85
+ if (typeof value === "object" && value !== null && !Array.isArray(value)) found = { answer: value as Record<string, unknown>, at: m.timestamp };
86
+ } catch {
87
+ continue;
88
+ }
89
+ }
90
+ return found;
91
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.1",
3
+ "version": "0.40.3",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -54,7 +54,7 @@ Leave out the rating part when it is null. Add nothing else. When the user then
54
54
 
55
55
  ## Replies
56
56
 
57
- Short and factual. Example: `Added **Dune: Part Three (2026)**. Search started. SABnzbd is not paused.` For a batch, one line per title. For an existing title: `**Title (Year)** is already in the library.` For failures, what was not added and why.
57
+ Short and factual. Example: `Added **Dune: Part Three (2026)**. Search started.` For a batch, one line per title. When the add returned `sabnzbd_paused: true`, end with `Downloads are paused.` and nothing on how to resume: in Discord the bridge posts an Unpause button under the answer. Say nothing about the queue when it is not paused. Outside failures, name no tool or service (SABnzbd, Radarr, Sonarr, trendarr, TMDB, OMDb): say downloads, library, search. For an existing title: `**Title (Year)** is already in the library.` For failures, what was not added and why.
58
58
 
59
59
  ## When to stop and report
60
60
 
@@ -141,7 +141,7 @@ Check: `sudo -n -u specialist -H /usr/local/bin/specialist-cli arcane --caller t
141
141
  The `astro-discord` extension gives Discord users access to the specialists from a channel. It runs in a headless Pi host on Cortex (LaunchAgent `com.astrofoundry.astro-discord`, user `cortex`), never in interactive sessions.
142
142
 
143
143
  - Channels are configured one by one (`channels.<id>`): `trigger` is `always` (every message that names a specialist counts) or `mention` (only messages that start with `@Cortex` or reply to the bot); `specialists` is `*` or a list. A channel with one specialist needs no prefix: every message there is a task for it. In a channel with several, `dns list the zones` names the specialist; an addressed message without a name gets a reply asking for one. Threads inherit their parent channel's entry; unlisted channels are ignored. The bot replies at once with "<specialist> is working on your task" and shows the typing indicator until the answer replaces that reply. Reactions on your message: ⏳ running, πŸ”’ waiting for an owner's approval, βœ… done, ❌ failed. `help` shows the specialists you may use in that channel and the commands (`status` lists running tasks; owners in the admin channel also see the `config` commands). Each channel and specialist has one conversation: a reply to the bot's answer, or another task for that specialist within 30 minutes, continues it with everything the specialist saw before; otherwise a new one starts, and a task beginning with `new` forces that. Replied-to and forwarded messages (text, embeds, attachment names) travel with the task, so "check this" on a forwarded alert works. Image attachments on the message or on what it quotes (up to 4, 8 MiB each) are downloaded and passed to the specialist, which sees them; other file types are named only. Sessions live under `~/.config/astro-discord/sessions/<specialist>/` and are deleted after 7 days. Long answers arrive as a `.md` attachment. When the bridge restarts, open approval requests are marked cancelled and running tasks interrupted in Discord; ask again. Scheduled reports are a list in the config, one entry per report: `"reports": [{ "report": "arcane", "channelId": "<id>", "time": "06:00", "timeZone": "Europe/Madrid" }, { "report": "tools", "channelId": "<admin channel id>", "time": "06:00", "timeZone": "Europe/Madrid" }]` (the earlier single `dailyReport` key is refused; move it into the list). The Arcane report posts an "Arcane Daily Report:" message every morning from a fresh `update-report`: one section per stack with updates, each service as current to target version with the kind of change, a release-notes verdict on every major version, and an Update button per stack that only owners can press (it runs `arcane stack-update <stack>`; the button turns into the outcome and the reason arrives as a note only the clicker sees). Stacks held in `update-holds.json` at the root of the arcane GitOps repository (`{ "supabase": "coordinated release: review first" }`) show the reason and get no button. Replying to the report asks the arcane specialist with the report as context. The tools report posts "Cortex Tools Report:": every tool on Cortex with a newer version (Homebrew packages installed on request and casks, Pi, pi-astro, and through `specialist-install` the wrappers, arcane-cli at the Arcane server's version, trendarr, and the specialist Node at the latest LTS), a release-notes verdict from `astro.release-reviewer` for the tools the specialists build on, an Update button per line, and one Upgrade everything for Homebrew. Only owners can press them; nothing is installed otherwise. After an update that needs it, the bridge, herdr, or Astrogate restarts as soon as nothing runs on it; after a day of waiting, a Restart now button appears. The bridge calls `sudo -n /usr/local/sbin/specialist-install` through the sudoers rule from step 4.
144
- - Media: where the `media` specialist is present (`config channel <#channel> always media`), `/trending [type] [min_rating] [count]`, `/search <title> [type]`, and `/downloads <status|pause|resume|unpause>` run the wrapper without a model. Lists arrive as two messages, Movies and Series, each title with a button beside it: **Add** adds it at once and turns into Added, In library, or Not found (Retry after a failure); a greyed-out In library or No IMDb ID button needs nothing. Notes such as "downloads are paused" go only to the user who clicked. Owners and `access.media` users may use them; anyone else gets a refusal only they see, and in a channel without `media` the bot names the channels that have it. Plain messages in the channel still go to the agent, for requests by name ("add the new Dune"). A `media-weekly` report entry posts the weekly picks there every Friday at its time: three movies and three series from `recommend`, each with the library titles that led to it, an Add button, and a Not interested button; the owners are tagged when there is something new. A pick nobody acts on stays out for six months; Not interested keeps it out for good (`media-picks.json`). At startup the bridge sets the three commands as the application's global commands (servers only).
144
+ - Media: where the `media` specialist is present (`config channel <#channel> always media`), `/trending [type] [min_rating] [count]`, `/search <title> [type]`, and `/downloads <status|pause|resume|unpause>` run the wrapper without a model. Lists arrive as two messages, Movies and Series, each title with a button beside it: **Add** adds it at once and turns into Added, In library, or Not found (Retry after a failure); a greyed-out In library or No IMDb ID button needs nothing. Notes go only to the user who clicked; when downloads are paused, the note has an **Unpause** button. When the media specialist adds a title by name and downloads stay paused, the bridge posts "⏸️ Downloads are paused" with Unpause under its answer; a click resumes the queue and the message names who resumed it. Owners and `access.media` users may use them; anyone else gets a refusal only they see, and in a channel without `media` the bot names the channels that have it. Plain messages in the channel still go to the agent, for requests by name ("add the new Dune"). A `media-weekly` report entry posts the weekly picks there every Friday at its time: three movies and three series from `recommend`, each with the library titles that led to it, an Add button, and a Not interested button; the owners are tagged when there is something new. A pick nobody acts on stays out for six months; Not interested keeps it out for good (`media-picks.json`). At startup the bridge sets the three commands as the application's global commands (servers only).
145
145
  - Arcane manager: when the morning Arcane Daily Report shows a newer manager release, the `arcane` section carries an **Upgrade Arcane to vX** button. Only an owner's click on the newest report runs `arcane manager-upgrade <version>` through the entry point (one at a time, counted as open work so no bridge restart interrupts it); the button turns into the outcome, a reply gives the result, and a successful upgrade installs the matching `arcane-cli` with `specialist-install`.
146
146
  - Access: `owners` may use every specialist and decide approvals; `access.<specialist>` lists extra users for that specialist; everyone else gets no reply. Owners change the configuration from the admin channel (`adminChannelId`) without a shell: `config show`, `config channel <#channel> <always|mention> <*|dns,edge>`, `config channel <#channel> remove`, `config access <specialist> add|remove <@user>`; the bot writes `~/.config/astro-discord/config.json` on Cortex, which is also editable by hand and re-read on every message. Deny the bot's role View Channel on channels it must never read; that is the boundary the map cannot provide.
147
147
  - Approvals: a risky call (anything with `--confirm`, plus writes such as record or zone deletes, Zitadel changes, Pomerium deploys, service restarts, and on Arcane destructive actions: `down`, deletes, prunes, image, volume, or network removal, `system upgrade`, `gitops delete`, plus `manager-upgrade`, `manager-rollback`, `host db-restore`, and the Radarr host-config reads; `stack-update` asks only across a major version, through its `--confirm`; an owner's Update click on the report needs no approval; help lookups never ask) pauses the specialist and posts Approve/Deny buttons; only owners' clicks count; no decision within `approvalTimeoutMinutes` denies it. The specialist then reports the denial. Ambiguous tasks get a question back instead of an action.