@astrofoundry/pi-astro 0.40.1 → 0.40.2

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.
@@ -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. */
@@ -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
@@ -1520,6 +1548,7 @@ class Bridge {
1520
1548
  let output: string;
1521
1549
  let attachment: string | undefined;
1522
1550
  let seen = 0;
1551
+ let messages: RunResult["messages"] = [];
1523
1552
  try {
1524
1553
  const result = await runAgent({
1525
1554
  agent: { ...agent, timeoutMinutes: agent.timeoutMinutes ?? TASK_TIMEOUT_MINUTES },
@@ -1542,6 +1571,7 @@ class Bridge {
1542
1571
  },
1543
1572
  });
1544
1573
  failed = isFailed(result);
1574
+ messages = result.messages;
1545
1575
  if (failed) {
1546
1576
  const reply = failureReply(result);
1547
1577
  output = reply.text;
@@ -1567,6 +1597,7 @@ class Bridge {
1567
1597
  const answers = await this.deliver(task, placeholder, `${failed ? "❌" : "✅"} **${task.specialist}**\n${output}`, attachment);
1568
1598
  this.conversations = recordAnswer(this.conversations, task.conversation.key, answers, Date.now());
1569
1599
  saveState(this.conversations);
1600
+ if (task.specialist === "arcane") await this.carefulOutcome(task.channelId, messages).catch((err) => log(`arcane: careful outcome failed: ${err instanceof Error ? err.message : String(err)}`));
1570
1601
  return failed;
1571
1602
  }
1572
1603
 
@@ -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.2",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"