@astrofoundry/pi-astro 0.40.53 → 0.40.55

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.
@@ -17,7 +17,7 @@ Each task starts with `Session: t<id>. Today: <date>.` Use that session in every
17
17
 
18
18
  Work in this order:
19
19
 
20
- 1. **Title.** When the context says "New request", your reply always starts with the line `TITLE: [CATEGORY YYYY-MM-DD] <place>: <subject>`, also when it only asks questions. Example: `TITLE: [PRODUCT 2026-11-04] UAE: top 5 running shoes for men`. Categories: PRODUCT, FLIGHT, STAY, SERVICE, LOCAL, EVENT, INFO. Keep the number the user asked for. The bridge turns that line into the thread's name and removes it.
20
+ 1. **Title.** When the context says "New request", your reply always starts with the line `TITLE: [CATEGORY YYYY-MM-DD] <place>: <subject>`, also when it only asks questions. Example: `TITLE: [PRODUCT 2026-11-04] UAE: top 5 running shoes for men`. Categories: PRODUCT, FLIGHT, STAY, SERVICE, LOCAL, EVENT, INFO. Keep the number the user asked for. Put it at the top of your last message, the reply the user sees; the bridge turns it into the thread's name and removes it.
21
21
  2. **Defaults.** Run `defaults list` and apply GLOBAL and the category's defaults.
22
22
  3. **Questions.** If anything still open would change the answer (size, budget, dates, passengers, cabin, type of use), ask it as a numbered list of at most five short questions. Give each one your suggested answer in brackets. Then stop: do not search before the user answers. When nothing is open, state the defaults you applied in one line and research.
23
23
  4. **Research.** Follow the skill's sources and checks. Verify every fact you report on the page itself, in this sandbox, today.
@@ -74,7 +74,7 @@ import {
74
74
  } from "./tools-report.ts";
75
75
  import { type Quote, type QuotedMessage, withQuotes } from "./quote.ts";
76
76
  import { DiscordRest, type MessageComponent } from "./rest.ts";
77
- import { captchaText, provisionalName, REFRESH_ID, REFRESH_TASK, refreshRow, shapeAnswer, threadContext, threadDate } from "./research.ts";
77
+ import { captchaText, provisionalName, REFRESH_ID, REFRESH_TASK, refreshRow, shapeAnswer, threadContext, threadDate, titleFromTexts } from "./research.ts";
78
78
  import { ArcaneWatch } from "./arcane-watch-monitor.ts";
79
79
  import { parseSnapshot } from "./arcane-watch.ts";
80
80
  import { type Applied, autoFailureText, foremanTask, stackProblems, stackUpdateAnswer, SUPERVISE_DELAY_MS, SUPERVISE_LIMIT_MS } from "./supervise.ts";
@@ -1869,14 +1869,18 @@ class Bridge {
1869
1869
  let refreshable = false;
1870
1870
  if (task.threaded && !failed) {
1871
1871
  const shaped = shapeAnswer(output);
1872
- if (shaped.title) await this.rest.renameThread(task.channelId, shaped.title).catch((err) => log(`${task.specialist}: renaming thread ${task.channelId} failed: ${err instanceof Error ? err.message : String(err)}`));
1872
+ const texts = messages.flatMap((m) => (m.role === "assistant" ? m.content.flatMap((part) => (part.type === "text" ? [part.text] : [])) : []));
1873
+ const title = shaped.title ?? titleFromTexts(texts);
1874
+ if (title) await this.rest.renameThread(task.channelId, title).catch((err) => log(`${task.specialist}: renaming thread ${task.channelId} failed: ${err instanceof Error ? err.message : String(err)}`));
1873
1875
  output = shaped.text || "(no output)";
1874
1876
  refreshable = shaped.refreshable;
1875
1877
  }
1876
1878
  await this.rest.removeOwnReaction(task.channelId, task.messageId, REACTION.running).catch(() => undefined);
1877
1879
  await this.rest.addReaction(task.channelId, task.messageId, failed ? REACTION.failed : REACTION.done).catch(() => undefined);
1878
- const reply = `${failed ? "❌" : "✅"} **${task.specialist}**\n${output}`;
1879
- const answers = await this.deliver(task, placeholder, reply, attachment);
1880
+ // 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.
1881
+ const notify = task.threaded ? task.userId : undefined;
1882
+ const reply = `${notify ? `<@${notify}> ` : ""}${failed ? "❌" : "✅"} **${task.specialist}**\n${output}`;
1883
+ const answers = await this.deliver(task, placeholder, reply, attachment, notify);
1880
1884
  const last = answers[answers.length - 1];
1881
1885
  if (refreshable && last && attachment === undefined && reply.length <= ATTACHMENT_THRESHOLD) {
1882
1886
  const chunks = chunkMessage(reply);
@@ -1893,22 +1897,24 @@ class Bridge {
1893
1897
  }
1894
1898
 
1895
1899
  /** Turns the "working" placeholder into the answer: edit it in place when it fits, otherwise replace it with chunks or an attachment. Returns the answer message ids. */
1896
- private async deliver(task: ActiveTask, placeholder: string | undefined, text: string, attachment?: string): Promise<string[]> {
1900
+ private async deliver(task: ActiveTask, placeholder: string | undefined, text: string, attachment?: string, notify?: string): Promise<string[]> {
1901
+ const mentionUsers = notify ? [notify] : undefined;
1897
1902
  const oversized = attachment !== undefined || text.length > ATTACHMENT_THRESHOLD;
1898
1903
  if (oversized) {
1899
1904
  if (placeholder) await this.rest.deleteMessage(task.channelId, placeholder).catch(() => undefined);
1900
1905
  const file = attachment !== undefined ? { name: `astro-${task.specialist}-stderr-${Date.now()}.txt`, content: attachment } : { name: `astro-${task.specialist}-${Date.now()}.md`, content: text };
1901
1906
  const content = attachment !== undefined ? text.slice(0, 1900) : `${text.slice(0, 1200).trim()}\n… full answer attached (${text.length} characters).`;
1902
- const posted = await this.rest.createMessage(task.channelId, { content, replyTo: task.messageId, file });
1907
+ const posted = await this.rest.createMessage(task.channelId, { content, replyTo: task.messageId, file, mentionUsers });
1903
1908
  return [posted.id];
1904
1909
  }
1905
1910
  const chunks = chunkMessage(text);
1906
1911
  if (chunks.length === 0) chunks.push(text);
1907
1912
  const ids: string[] = [];
1908
- if (placeholder) {
1913
+ if (placeholder && notify) await this.rest.deleteMessage(task.channelId, placeholder).catch(() => undefined);
1914
+ if (placeholder && !notify) {
1909
1915
  await this.rest.editMessage(task.channelId, placeholder, chunks[0]).catch(() => undefined);
1910
1916
  ids.push(placeholder);
1911
- } else ids.push((await this.rest.createMessage(task.channelId, { content: chunks[0], replyTo: task.messageId })).id);
1917
+ } else ids.push((await this.rest.createMessage(task.channelId, { content: chunks[0], replyTo: task.messageId, mentionUsers })).id);
1912
1918
  for (let i = 1; i < chunks.length; i++) {
1913
1919
  ids.push((await this.rest.createMessage(task.channelId, { content: chunks[i] })).id);
1914
1920
  }
@@ -1,5 +1,5 @@
1
1
  import { describe, expect, it } from "vitest";
2
- import { captchaText, provisionalName, REFRESH_ID, refreshRow, shapeAnswer, threadContext, threadDate } from "./research.ts";
2
+ import { captchaText, provisionalName, REFRESH_ID, refreshRow, shapeAnswer, threadContext, threadDate, titleFromTexts } from "./research.ts";
3
3
  import { validateChannel } from "./config.ts";
4
4
 
5
5
  describe("research threads", () => {
@@ -10,6 +10,11 @@ describe("research threads", () => {
10
10
  expect(shapeAnswer("Read TITLE: inside a line\nREFRESH: yes, later")).toMatchObject({ title: null, refreshable: false });
11
11
  });
12
12
 
13
+ it("finds the title in an earlier text of the run", () => {
14
+ expect(titleFromTexts(["TITLE: [PRODUCT 2026-11-04] UAE: top 5 running shoes for men", "1. What size?"])).toBe("[PRODUCT 2026-11-04] UAE: top 5 running shoes for men");
15
+ expect(titleFromTexts(["Checking defaults", "1. What size?"])).toBeNull();
16
+ });
17
+
13
18
  it("names the thread from the request until the specialist titles it", () => {
14
19
  expect(provisionalName("<@1474400000000000000> give me top 5 running shoes for men in UAE", "2026-11-04")).toBe("[RESEARCH 2026-11-04] give me top 5 running shoes for men in UAE");
15
20
  expect(provisionalName("x".repeat(200), "2026-11-04")).toHaveLength(100);
@@ -39,6 +39,17 @@ export function shapeAnswer(output: string): ShapedAnswer {
39
39
  return { title, text: lines.join("\n").trim(), refreshable };
40
40
  }
41
41
 
42
+ /** The `TITLE:` line from any assistant text of the run, oldest first: the specialist may write it before its tool calls, and only the last text is the answer. */
43
+ export function titleFromTexts(texts: readonly string[]): string | null {
44
+ for (const text of texts) {
45
+ for (const line of text.split("\n")) {
46
+ const titled = TITLE.exec(line.trim());
47
+ if (titled) return titled[1];
48
+ }
49
+ }
50
+ return null;
51
+ }
52
+
42
53
  /** Requests come from Mira, so a thread carries Dubai's date. */
43
54
  const REQUEST_TIME_ZONE = "Asia/Dubai";
44
55
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrofoundry/pi-astro",
3
- "version": "0.40.53",
3
+ "version": "0.40.55",
4
4
  "description": "Personal pi customizations (extensions, subagents, skills, prompts, themes) for the pi coding agent.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -44,6 +44,15 @@ BROWSER_COMMANDS = {
44
44
  # Page titles and frames of the challenges a person has to solve in the live view.
45
45
  CAPTCHA_TITLES = re.compile(r"prove your humanity|just a moment|are you a robot|verify you are human|attention required|access denied", re.I)
46
46
  CAPTCHA_FRAMES = re.compile(r"recaptcha|hcaptcha|challenges\.cloudflare\.com|captcha-delivery|arkoselabs|funcaptcha|perimeterx", re.I)
47
+ # A challenge popup (reCAPTCHA's bframe, hCaptcha's challenge) is shown only when a person must act;
48
+ # the checkbox frames also sit invisibly on normal pages, such as Reddit's, so they count only on a near-empty page.
49
+ CHALLENGE_POPUP = re.compile(r"recaptcha/(api2|enterprise)/bframe|hcaptcha\.com/.*challenge|challenges\.cloudflare\.com", re.I)
50
+ VISIBLE_FRAMES = (
51
+ "JSON.stringify({title: document.title, text: document.body ? document.body.innerText.length : 0,"
52
+ " frames: [...document.querySelectorAll('iframe')].filter(f => { const r = f.getBoundingClientRect(), s = getComputedStyle(f);"
53
+ " return r.width > 30 && r.height > 30 && r.bottom > 0 && r.right > 0 && s.visibility !== 'hidden' && s.display !== 'none'"
54
+ " && Number(s.opacity) > 0.1; }).map(f => f.src)})"
55
+ )
47
56
 
48
57
 
49
58
  class Refused(Exception):
@@ -138,10 +147,17 @@ def op_captcha(request):
138
147
  found.append(page)
139
148
  session = request.get("session")
140
149
  if isinstance(session, str) and SESSION.fullmatch(session) and attached(session):
141
- frames = run([PLAYWRIGHT, f"-s={session}", "--raw", "eval",
142
- "[document.title, ...[...document.querySelectorAll('iframe')].map(f => f.src)].join(' ')"], 60)
143
- if CAPTCHA_TITLES.search(frames["stdout"]) or CAPTCHA_FRAMES.search(frames["stdout"]):
144
- found.append({"session": session, "evidence": frames["stdout"][:300]})
150
+ probe = run([PLAYWRIGHT, f"-s={session}", "--raw", "eval", VISIBLE_FRAMES], 60)
151
+ try:
152
+ state = json.loads(json.loads(probe["stdout"]))
153
+ except (ValueError, TypeError):
154
+ state = None
155
+ if isinstance(state, dict):
156
+ frames = [f for f in state.get("frames", []) if isinstance(f, str)]
157
+ popup = any(CHALLENGE_POPUP.search(f) for f in frames)
158
+ widget_only = any(CAPTCHA_FRAMES.search(f) for f in frames) and int(state.get("text") or 0) < 1500
159
+ if CAPTCHA_TITLES.search(str(state.get("title"))) or popup or widget_only:
160
+ found.append({"session": session, "title": str(state.get("title"))[:120], "frames": [f[:120] for f in frames if CAPTCHA_FRAMES.search(f)]})
145
161
  return {"captcha": bool(found), "pages": found}
146
162
 
147
163