@astrofoundry/pi-astro 0.40.74 → 0.40.75

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.
@@ -3,6 +3,20 @@ import { createServer, type Server } from "node:http";
3
3
 
4
4
  export type Decision = "approve" | "deny" | "timeout";
5
5
 
6
+ /** Longest command an approval message shows inline; Discord refuses messages above 2000 characters. */
7
+ export const APPROVAL_INLINE_CHARS = 1200;
8
+ const APPROVAL_PREVIEW_CHARS = 300;
9
+
10
+ /**
11
+ * How an approval shows the command: whole when it is short, otherwise its start in the message and the whole
12
+ * command as an attached text file, so the owner can still read everything he approves.
13
+ */
14
+ export function approvalCommand(args: readonly string[]): { inline: string; file?: { name: string; content: string } } {
15
+ const whole = args.join(" ");
16
+ if (whole.length <= APPROVAL_INLINE_CHARS) return { inline: whole };
17
+ return { inline: `${whole.slice(0, APPROVAL_PREVIEW_CHARS)}… (${whole.length} characters, the whole command is attached)`, file: { name: "command.txt", content: `${whole}\n` } };
18
+ }
19
+
6
20
  export interface Ticket {
7
21
  id: string;
8
22
  agent: string;
@@ -2,7 +2,7 @@ import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { ApprovalServer, type Ticket } from "./approvals.ts";
5
+ import { APPROVAL_INLINE_CHARS, ApprovalServer, approvalCommand, type Ticket } from "./approvals.ts";
6
6
  import { chunkMessage, fenceState } from "./chunk.ts";
7
7
  import { applyAdminCommand, describeConfig } from "./admin.ts";
8
8
  import { helpText, needsPrefixText, needsYou, parseCommand } from "./commands.ts";
@@ -70,6 +70,21 @@ describe("config", () => {
70
70
  });
71
71
  });
72
72
 
73
+ describe("approval command", () => {
74
+ it("shows a short command whole and a long one as a preview with the whole command attached", () => {
75
+ expect(approvalCommand(["restart", "--confirm"])).toEqual({ inline: "restart --confirm" });
76
+ const body = JSON.stringify({ alias: "Hallway lights", actions: "x".repeat(3000) });
77
+ const long = approvalCommand(["rest", "post", "/api/config/automation/config/1734267132664", body]);
78
+ const whole = `rest post /api/config/automation/config/1734267132664 ${body}`;
79
+ expect(long.inline.length).toBeLessThan(APPROVAL_INLINE_CHARS);
80
+ expect(long.inline.startsWith("rest post /api/config/automation/config/1734267132664")).toBe(true);
81
+ expect(long.inline).toContain(`(${whole.length} characters, the whole command is attached)`);
82
+ expect(long.file).toEqual({ name: "command.txt", content: `${whole}\n` });
83
+ // The message around the command stays far below Discord's 2000-character limit.
84
+ expect(`🔒 **home** wants to run \`${long.inline}\` for <@123456789012345678>. <@123456789012345678>: approve or deny within 30 min.`.length).toBeLessThan(2000);
85
+ });
86
+ });
87
+
73
88
  describe("chunk", () => {
74
89
  it("splits on paragraphs and keeps fences balanced", () => {
75
90
  const text = `${"a".repeat(1500)}\n\n${"b".repeat(1500)}`;
@@ -7,7 +7,7 @@ import { APPROVAL_TOKEN_ENV, APPROVAL_URL_ENV } from "../specialist-gate/index.t
7
7
  import { type AgentConfig, defaultDirs, discoverAgents, resolveSkills } from "../astro-subagents/agents.ts";
8
8
  import { AGENT_ENV, type ChildSession, type DispatchDefaults, type RunResult, childRemaining, currentDepth, finalOutput, isFailed, resultOutput, runAgent } from "../astro-subagents/child.ts";
9
9
  import { pruneSessions, sessionDirFor } from "../astro-subagents/sessions.ts";
10
- import { ApprovalServer, type Ticket } from "./approvals.ts";
10
+ import { ApprovalServer, approvalCommand, type Ticket } from "./approvals.ts";
11
11
  import { chunkMessage } from "./chunk.ts";
12
12
  import { applyAdminCommand } from "./admin.ts";
13
13
  import { CHANNEL_RULES, helpText, needsPrefixText, needsYou, parseCommand } from "./commands.ts";
@@ -275,7 +275,7 @@ class Bridge {
275
275
  this.config = config;
276
276
  this.conversations = loadState();
277
277
  this.rest = new DiscordRest(token);
278
- this.approvals = new ApprovalServer({ onTicket: (t) => void this.askApproval(t), onExpired: (t) => void this.expireApproval(t) }, config.approvalTimeoutMinutes * 60_000);
278
+ this.approvals = new ApprovalServer({ onTicket: (t) => void this.askApproval(t).catch((err) => this.approvalFailed(t, err)), onExpired: (t) => void this.expireApproval(t).catch((err) => log(`approval ${t.id} expiry: ${err instanceof Error ? err.message : String(err)}`)) }, config.approvalTimeoutMinutes * 60_000);
279
279
  this.security = new SecurityMonitor({
280
280
  rest: this.rest,
281
281
  runEntry: (service, caller, args, timeoutMs) => this.runEntry(service, caller, args, timeoutMs),
@@ -1946,12 +1946,14 @@ class Bridge {
1946
1946
  const owners = this.config.owners.map((id) => `<@${id}>`).join(" ");
1947
1947
  const liveView = (await this.settingsFor(task.channelId))?.settings.liveView;
1948
1948
  const site = liveView ? captchaSite(ticket.args) : null;
1949
+ const command = approvalCommand(ticket.args);
1949
1950
  const content =
1950
1951
  site && liveView
1951
1952
  ? `${captchaText(site, liveView, owners)} Within ${this.config.approvalTimeoutMinutes} min.`
1952
- : `🔒 **${short}** wants to run ${code(ticket.args.join(" "))} for <@${task.userId}>. ${owners}: approve or deny within ${this.config.approvalTimeoutMinutes} min.`;
1953
+ : `🔒 **${short}** wants to run ${code(command.inline)} for <@${task.userId}>. ${owners}: approve or deny within ${this.config.approvalTimeoutMinutes} min.`;
1953
1954
  const posted = await this.rest.createMessage(task.channelId, {
1954
1955
  content,
1956
+ ...(command.file && !site ? { file: command.file } : {}),
1955
1957
  replyTo: task.messageId,
1956
1958
  components: approvalButtons(ticket.id, false, site ? CAPTCHA_LABELS : undefined),
1957
1959
  mentionUsers: this.config.owners,
@@ -1960,12 +1962,20 @@ class Bridge {
1960
1962
  this.saveOpenWork();
1961
1963
  }
1962
1964
 
1965
+ /** A ticket that could not be shown is denied, so the specialist stops waiting; the bridge keeps running. */
1966
+ private approvalFailed(ticket: Ticket, err: unknown): void {
1967
+ log(`approval ${ticket.id} for ${ticket.agent} could not be posted; denying: ${err instanceof Error ? err.message : String(err)}`);
1968
+ this.approvals.decide(ticket.id, "deny", "bridge");
1969
+ const task = this.active.get(ticket.agent.replace(/^astro\./, ""));
1970
+ if (task) void this.rest.createMessage(task.channelId, { content: "⚠️ The approval request could not be posted, so the change was not run. Ask again.", replyTo: task.messageId }).catch(() => undefined);
1971
+ }
1972
+
1963
1973
  private async expireApproval(ticket: Ticket): Promise<void> {
1964
1974
  const posted = this.approvalMessages.get(ticket.id);
1965
1975
  if (!posted) return;
1966
1976
  this.approvalMessages.delete(ticket.id);
1967
1977
  this.saveOpenWork();
1968
- await this.rest.editMessage(posted.channelId, posted.messageId, `⌛ No decision within ${this.config.approvalTimeoutMinutes} min; ${code(ticket.args.join(" "))} was not run.`).catch(() => undefined);
1978
+ await this.rest.editMessage(posted.channelId, posted.messageId, `⌛ No decision within ${this.config.approvalTimeoutMinutes} min; ${code(approvalCommand(ticket.args).inline)} was not run.`).catch(() => undefined);
1969
1979
  await this.rest.removeOwnReaction(posted.userMessage.channelId, posted.userMessage.messageId, REACTION.waiting).catch(() => undefined);
1970
1980
  }
1971
1981
 
@@ -2033,7 +2043,7 @@ class Bridge {
2033
2043
  this.saveOpenWork();
2034
2044
  const site = captchaSite(ticket.args);
2035
2045
  const verdict = decision === "approve" ? `✅ Approved by <@${userId}>` : `⛔ Denied by <@${userId}>`;
2036
- await this.rest.updateInteractionMessage(interaction.id, interaction.token, site ? captchaVerdict(site, decision === "approve", userId) : `${verdict}: ${code(ticket.args.join(" "))}`);
2046
+ await this.rest.updateInteractionMessage(interaction.id, interaction.token, site ? captchaVerdict(site, decision === "approve", userId) : `${verdict}: ${code(approvalCommand(ticket.args).inline)}`);
2037
2047
  if (posted) await this.rest.removeOwnReaction(posted.userMessage.channelId, posted.userMessage.messageId, REACTION.waiting).catch(() => undefined);
2038
2048
  log(`approval ${ticket.id} ${decision} by ${userId}: ${ticket.args.join(" ")}`);
2039
2049
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.74",
3
+ "version": "0.40.75",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"