@astrofoundry/pi-astro 0.40.57 → 0.40.58

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.
@@ -50,7 +50,12 @@ function runCommand(specialist: string, text: string): Command {
50
50
  /** Prompt paragraph appended for tasks that arrive from a chat channel. */
51
51
  export const CHANNEL_RULES = `## Channel rules
52
52
 
53
- This task arrived from a Discord channel and your answer is posted there. Answer in plain text under 1500 characters when possible, facts first, no headings. When the task is ambiguous (which guest, which record, which host), do not act: ask one precise question and stop. Risky calls may wait for an operator's approval; if the tool reports a denial or a missing answer, report it and stop.`;
53
+ This task arrived from a Discord channel and your answer is posted there. Answer in plain text under 1500 characters when possible, facts first, no headings. When the task is ambiguous (which guest, which record, which host), do not act: ask one precise question and stop. Risky calls may wait for an operator's approval; if the tool reports a denial or a missing answer, report it and stop. When you need something from the owner (a go, a decision, an action, or a blocker you cannot remove), your first line starts with **Needs you:** and says what you need in one sentence; the bridge then tags them.`;
54
+
55
+ /** A reply whose first line asks the owner for something; the bridge tags the requester on it. */
56
+ export function needsYou(output: string): boolean {
57
+ return /^\s*\**Needs you:/i.test(output);
58
+ }
54
59
 
55
60
  export function helpText(allowed: readonly string[], present: readonly string[], isOwner: boolean, trigger: Trigger, canConfig: boolean): string {
56
61
  if (allowed.length === 0) return present.length === 0 ? "No specialist is present in this channel." : "You may not use the specialists present in this channel.";
@@ -198,6 +198,7 @@ describe("Arcane report plans", () => {
198
198
  const task = carefulTask(pdf);
199
199
  expect(task).toContain("- stirling-pdf: 2.14.3 → 3.0.0 (major version); release notes: check, the config key changed");
200
200
  expect(task).toContain("Wait in this thread for the owner's \"go\"; then apply the image change with `stack-update stirling-pdf --confirm`");
201
+ expect(task).toContain("Its first line is `**Needs you:**`");
201
202
  expect(carefulTask(entry(report(), "arcane"))).toContain("`manager-upgrade 2.17.0`");
202
203
  });
203
204
 
@@ -246,7 +246,7 @@ export function carefulTask(s: StackEntry): string {
246
246
  "Pending:",
247
247
  ...lines,
248
248
  `1. Read what changes: \`release-notes ${s.stack}/<service>\` for each line, \`git show ${s.stack}/compose.yaml\`, and the stack's README in the GitOps checkout.`,
249
- "2. Post a short plan: what changes, what must happen first (a `host db-dump <stack>` when the stack's database is one the tool covers), the order, how you will check it, and how to roll back.",
249
+ "2. Post the plan. Its first line is `**Needs you:**` and what you need in one sentence: the go, or the blocker and what the owner must do or decide. Then at most five numbered one-line steps: what changes, what must happen first (a `host db-dump <stack>` when the stack's database is one the tool covers), the order, how you will check it, and how to roll back.",
250
250
  `3. Change nothing yet. Wait in this thread for the owner's "go"; then apply the image change with ${apply} and the other steps of your plan, and report each result.`,
251
251
  ].join("\n");
252
252
  }
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
5
  import { ApprovalServer, type Ticket } from "./approvals.ts";
6
6
  import { chunkMessage, fenceState } from "./chunk.ts";
7
7
  import { applyAdminCommand, describeConfig } from "./admin.ts";
8
- import { helpText, needsPrefixText, parseCommand } from "./commands.ts";
8
+ import { helpText, needsPrefixText, needsYou, parseCommand } from "./commands.ts";
9
9
  import { allowedSpecialists, canUse, channelSpecialists, loadConfig, loadToken, validateConfig } from "./config.ts";
10
10
  import { GatewayClient, INTENTS, initialState, reduce } from "./gateway.ts";
11
11
  import type { RunResult } from "../astro-subagents/child.ts";
@@ -89,6 +89,12 @@ describe("chunk", () => {
89
89
  });
90
90
 
91
91
  describe("commands", () => {
92
+ it("tags the requester only when the reply's first line asks the owner for something", () => {
93
+ expect(needsYou("**Needs you:** the go for the queue drain.\n1. Pull the image.")).toBe(true);
94
+ expect(needsYou("Needs you: a decision on the backup.")).toBe(true);
95
+ expect(needsYou("All three services run.\n**Needs you:** nothing")).toBe(false);
96
+ });
97
+
92
98
  const many = { botUserId: ID, specialists: ["dns", "edge"], trigger: "always" as const, repliedToBot: false };
93
99
  const one = { ...many, specialists: ["arcane"] };
94
100
  it("parses prefixed tasks, mentions, help, status, and config", () => {
@@ -306,6 +312,9 @@ describe("rest", () => {
306
312
  expect(calls[4].url).toBe("https://discord.com/api/v10/channels/m9");
307
313
  expect(calls[4].init.method).toBe("PATCH");
308
314
  expect(JSON.parse(calls[4].init.body as string)).toEqual({ archived: true });
315
+ await rest.createThread("c1", "2026-11-06: Weekly media picks");
316
+ expect(calls[5].url).toBe("https://discord.com/api/v10/channels/c1/threads");
317
+ expect(JSON.parse(calls[5].init.body as string)).toEqual({ name: "2026-11-06: Weekly media picks", auto_archive_duration: 10080, type: 11 });
309
318
  });
310
319
  });
311
320
 
@@ -10,7 +10,7 @@ import { pruneSessions, sessionDirFor } from "../astro-subagents/sessions.ts";
10
10
  import { ApprovalServer, type Ticket } from "./approvals.ts";
11
11
  import { chunkMessage } from "./chunk.ts";
12
12
  import { applyAdminCommand } from "./admin.ts";
13
- import { CHANNEL_RULES, helpText, needsPrefixText, parseCommand } from "./commands.ts";
13
+ import { CHANNEL_RULES, helpText, needsPrefixText, needsYou, parseCommand } from "./commands.ts";
14
14
  import { ACTIVATION_ENV, type ChannelSettings, type DiscordConfig, MORNING_REPORTS, type ReportName, type ReportSchedule, allowedSpecialists, canUse, channelSpecialists, isOwner, loadConfig, loadToken, reportSchedule, saveConfig } from "./config.ts";
15
15
  import { type ConversationState, type ResolvedConversation, forgetStale, loadState, newConversationId, recordAnswer, resolveConversation, saveState, sessionsRoot, startConversation } from "./conversations.ts";
16
16
  import { describeImages, downloadImages, type ImageAttachment, imageAttachments } from "./attachments.ts";
@@ -36,7 +36,7 @@ import {
36
36
  import { GatewayClient } from "./gateway.ts";
37
37
  import { type CommandOption, IS_COMPONENTS_V2, KeyedQueue, MEDIA, MEDIA_COMMANDS, type MediaKind, type Outcome, PAUSED_TEXT, RESUME_ID, addOutcome, addedWhilePaused, applyOutcome, commandArgs, escapeDiscord, 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
- import { DISMISSED, type Picks, parseNoButton, parsePicks, picksArgs, picksFailureText, picksMessage, readPicksState, withDismissed, withSuggested, writePicksState } from "./media-picks.ts";
39
+ import { DISMISSED, type Picks, parseNoButton, parsePicks, picksArgs, picksFailureText, picksMessage, picksThreadName, readPicksState, withDismissed, withSuggested, writePicksState } from "./media-picks.ts";
40
40
  import { FRIDAY, isDue, MONDAY, readReportState, writeReportState, zonedWeekday } from "./reports.ts";
41
41
  import { ACTIVITY_COMMAND, type Activity, addRestarts, astrogateActivity, herdrActivity, needsPrompt, type PendingRestart, readRestarts, restartCommand, SERVICE_LABEL, SERVICE_ORDER, writeRestarts } from "./restarts.ts";
42
42
  import {
@@ -576,13 +576,14 @@ class Bridge {
576
576
  if (this.stopping) return;
577
577
  const label = new Intl.DateTimeFormat("en-GB", { timeZone: schedule.timeZone, weekday: "short", day: "numeric", month: "short" }).format(new Date());
578
578
  writeReportState("media-weekly", { date, status: "sending" });
579
+ const thread = await this.rest.createThread(schedule.channelId, picksThreadName(date));
579
580
  if (!picks) {
580
- const posted = await this.rest.createMessage(schedule.channelId, { content: picksFailureText(label) });
581
+ const posted = await this.rest.createMessage(thread.id, { content: picksFailureText(label) });
581
582
  writeReportState("media-weekly", { date, status: "failed", messageId: posted.id });
582
583
  return;
583
584
  }
584
585
  const tagged = picks.movies.length + picks.series.length > 0;
585
- const posted = await this.rest.createComponentsMessage(schedule.channelId, picksMessage(picks, label, this.config.owners), tagged ? this.config.owners : undefined);
586
+ const posted = await this.rest.createComponentsMessage(thread.id, picksMessage(picks, label, this.config.owners), tagged ? this.config.owners : undefined);
586
587
  writePicksState(withSuggested(readPicksState(), picks, date));
587
588
  writeReportState("media-weekly", { date, status: "sent", messageId: posted.id });
588
589
  log(`media picks ${date}: ${picks.movies.length} movie(s), ${picks.series.length} series`);
@@ -1882,8 +1883,8 @@ class Bridge {
1882
1883
  }
1883
1884
  await this.rest.removeOwnReaction(task.channelId, task.messageId, REACTION.running).catch(() => undefined);
1884
1885
  await this.rest.addReaction(task.channelId, task.messageId, failed ? REACTION.failed : REACTION.done).catch(() => undefined);
1885
- // In a request's thread the requester is tagged on every reply, questions or answer; an edited message never notifies, so it is posted new.
1886
- const notify = task.threaded ? task.userId : undefined;
1886
+ // In a request's thread the requester is tagged on every reply, elsewhere when the reply needs them; an edited message never notifies, so it is posted new.
1887
+ const notify = task.threaded || (!failed && needsYou(output)) ? task.userId : undefined;
1887
1888
  const reply = `${notify ? `<@${notify}> ` : ""}${failed ? "❌" : "✅"} **${task.specialist}**\n${output}`;
1888
1889
  const answers = await this.deliver(task, placeholder, reply, attachment, notify);
1889
1890
  const last = answers[answers.length - 1];
@@ -4,7 +4,7 @@ import { join } from "node:path";
4
4
  import { afterEach, beforeEach, describe, expect, it } from "vitest";
5
5
  import { validateReports } from "./config.ts";
6
6
  import { applyOutcome, countComponents, hasActiveButton } from "./media.ts";
7
- import { DISMISSED, type Pick, parseNoButton, parsePicks, pickText, picksArgs, picksMessage, readPicksState, withDismissed, withSuggested, writePicksState } from "./media-picks.ts";
7
+ import { DISMISSED, type Pick, parseNoButton, parsePicks, pickText, picksArgs, picksMessage, picksThreadName, readPicksState, withDismissed, withSuggested, writePicksState } from "./media-picks.ts";
8
8
  import { FRIDAY, isDue } from "./reports.ts";
9
9
 
10
10
  const OWNER = "178096425509453824";
@@ -14,6 +14,10 @@ function pick(over: Partial<Pick>): Pick {
14
14
  }
15
15
 
16
16
  describe("weekly picks", () => {
17
+ it("names each week's thread by its local date", () => {
18
+ expect(picksThreadName("2026-11-06")).toBe("2026-11-06: Weekly media picks");
19
+ });
20
+
17
21
  it("keeps only well-formed picks with an IMDb id, three per kind", () => {
18
22
  const raw = { movies: [pick({}), { title: "No id", imdb_id: null, matches: 1, because: [] }, pick({ imdb_id: "tt1" }), pick({ imdb_id: "tt2" }), pick({ imdb_id: "tt3" })], series: [], warnings: ["Sonarr slow", 3] };
19
23
  const picks = parsePicks(raw);
@@ -108,6 +108,11 @@ function withWarnings(components: MessageComponent[], warnings: readonly string[
108
108
  return components;
109
109
  }
110
110
 
111
+ /** Each week's picks get their own thread, named by the local date so the weeks stay apart. */
112
+ export function picksThreadName(date: string): string {
113
+ return `${date}: Weekly media picks`;
114
+ }
115
+
111
116
  export function picksFailureText(date: string): string {
112
117
  return `**🍿 Weekly picks** · ${date} · the recommendation check failed, so there are no picks this week. The bridge log on Cortex has the reason.`;
113
118
  }
@@ -1,4 +1,6 @@
1
1
  export const API = "https://discord.com/api/v10";
2
+ /** Channel type of a public thread; Start Thread without Message makes a private one when the type is left out. */
3
+ const PUBLIC_THREAD = 11;
2
4
 
3
5
  export interface MessageComponent {
4
6
  type: number;
@@ -113,6 +115,11 @@ export class DiscordRest {
113
115
  return (await this.call("POST", `/channels/${channelId}/messages/${messageId}/threads`, JSON.stringify({ name: name.slice(0, 100), auto_archive_duration: 10080 }), "application/json")).json() as Promise<{ id: string }>;
114
116
  }
115
117
 
118
+ /** A public thread with no message in the channel under it, such as a week's media picks. */
119
+ async createThread(channelId: string, name: string): Promise<{ id: string }> {
120
+ return (await this.call("POST", `/channels/${channelId}/threads`, JSON.stringify({ name: name.slice(0, 100), auto_archive_duration: 10080, type: PUBLIC_THREAD }), "application/json")).json() as Promise<{ id: string }>;
121
+ }
122
+
116
123
  /** Renames a thread the bot started. */
117
124
  async renameThread(threadId: string, name: string): Promise<void> {
118
125
  await this.call("PATCH", `/channels/${threadId}`, JSON.stringify({ name: name.slice(0, 100) }), "application/json");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.57",
3
+ "version": "0.40.58",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"