Multiplayer agent harness for work.
Make reply and command parsers linear-time (#2570)
Regan Bell36b63795a3f7
diff --git a/plugins/web-ui/src/slack-text.ts b/plugins/web-ui/src/slack-text.tsindex cfd6aef7b..34cc13243 100644--- a/plugins/web-ui/src/slack-text.ts+++ b/plugins/web-ui/src/slack-text.ts@@ -66,8 +66,8 @@ export function slackWireToPlain(text: string): string {.join("");}-const REACTION_DIRECTIVE = /\[\[react:[^\]]*\]\]/gi;-const TRAILING_OPEN_REACTION = /\[\[react:[^\]]*$/i;+const REACTION_DIRECTIVE = /\[\[react:[^[\]]*\]\]/gi;+const TRAILING_OPEN_REACTION = /\[\[react:[^[\]]*$/i;const ANY_DIRECTIVE = /\[\[react:/i;const CODE_REGION = /```[\s\S]*?```|`[^`\n]*`/g;const CODE_PLACEHOLDER = /\u0000CODE(\d+)\u0000/g;diff --git a/src/api/routes/admin/slack-mirror.ts b/src/api/routes/admin/slack-mirror.tsindex 1d1d29230..60e514608 100644--- a/src/api/routes/admin/slack-mirror.ts+++ b/src/api/routes/admin/slack-mirror.ts@@ -2,6 +2,7 @@ import type { App } from "../../app.ts";import { sendJson } from "../../http.ts";import { audit, authorizeAdmin, orgScope } from "../shared.ts";import { type ApiCtx } from "../route.ts";+import { mentionedUserIds } from "../../../slack/mrkdwn.ts";const SLACK_MIRROR_PAGE_MAX = 400;const SLACK_MIRROR_PAGE_DEFAULT = 200;@@ -18,9 +19,8 @@ async function mirrorNames(deps: ApiCtx["deps"]) {author: (id?: string): string | undefined => (id ? byId.get(id) : undefined),mentions(text?: string, existing?: Record<string, string>): Record<string, string> | undefined {const out: Record<string, string> = { ...existing };- for (const m of (text ?? "").matchAll(/<@([A-Z0-9]+)(?:\|[^>]*)?>/g)) {- const id = m[1];- if (!id || out[id]) continue;+ for (const id of mentionedUserIds(text ?? "")) {+ if (out[id]) continue;const name = byId.get(id);if (name) out[id] = name;}diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex efb52f9ab..be08d9572 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -157,7 +157,8 @@ import {} from "../harness/replay.ts";import { errMessage, reportFailure, swallow, swallowAs } from "../util/errors.ts";import { isObj } from "../util/objects.ts";-import { absoluteAppLinks, headSlice, jsonbSafeStringify } from "../util/text.ts";+import { headSlice, jsonbSafeStringify } from "../util/text.ts";+import { absoluteAppLinks } from "../util/markdown.ts";import {isModelBudget,isNonRetryable,diff --git a/src/harness/goal.ts b/src/harness/goal.tsindex d17282331..300f9bb55 100644--- a/src/harness/goal.ts+++ b/src/harness/goal.ts@@ -28,6 +28,7 @@* semantics — keep working at least this much) and an optional token cap* (wind down when exhausted; never auto-complete).*/+import { outermostJsonObject } from "../util/text.ts";import { Type, type Static } from "typebox";import type { LlmCallUsage } from "../sessions/session-store.ts";import { createGrindMeter, type GrindBudget, type GrindMeter, grindState } from "./grind.ts";@@ -419,7 +420,7 @@ export async function governGoal(const reply = (await judge(GOAL_GOVERNOR_SYSTEM_PROMPT, prompt, signal)) ?? "";let parsed: { verdict?: unknown; reasons?: unknown } | undefined;try {- parsed = JSON.parse(reply.slice(reply.indexOf("{"), reply.lastIndexOf("}") + 1)) as typeof parsed;+ parsed = JSON.parse(outermostJsonObject(reply) ?? "") as typeof parsed;} catch {parsed = undefined;}diff --git a/src/loops/loop-fire.ts b/src/loops/loop-fire.tsindex 9c7eeb735..00aef86e2 100644--- a/src/loops/loop-fire.ts+++ b/src/loops/loop-fire.ts@@ -14,6 +14,7 @@ import type { Loop, LoopItem, LoopOutput, TurnRequest, TurnResult } from "../typimport { destinationVisible, runTrigger, type TriggerDeps, type TriggerOutcome } from "../triggers/run-trigger.ts";import { reachEnqueue } from "../reach/reach.ts";import { hashId } from "../util/crypto.ts";+import { fencedCodeBlocks, type FencedCodeBlock } from "../util/markdown.ts";import { errMessage } from "../util/errors.ts";import { userFacingFailureClause } from "../core/failure-copy.ts";import { isRunnable, type LoopStore } from "./loop-store.ts";@@ -175,13 +176,28 @@ function itemActionPrompt(loop: Loop, item: LoopItem, kind: string, args: Record].join("\n");}+function parsedBlock(blocks: FencedCodeBlock[]): { block: FencedCodeBlock; value: unknown } | undefined {+ for (let i = blocks.length - 1; i >= 0; i--) {+ try {+ return { block: blocks[i]!, value: JSON.parse(blocks[i]!.body) };+ } catch {+ continue;+ }+ }+ return undefined;+}+function splitProposalReply(reply: string): { text: string; proposal?: Record<string, unknown> } {- const parsed = fencedJson(reply);+ const hit = parsedBlock(fencedCodeBlocks(reply));+ const parsed = hit ? hit.value : bareJson(reply);const proposal =parsed && typeof parsed === "object" && !Array.isArray(parsed)? (parsed as Record<string, unknown>).proposal: undefined;- const text = reply.replace(/```(?:json)?\s*\n[\s\S]*?\n\s*```\s*$/, "").trim();+ const text =+ hit && proposal+ ? `${reply.slice(0, hit.block.start).trimEnd()}\n\n${reply.slice(hit.block.end).trimStart()}`.trim()+ : reply.trim();return {text: text || reply.trim(),...(proposal && typeof proposal === "object" && !Array.isArray(proposal)@@ -191,14 +207,10 @@ function splitProposalReply(reply: string): { text: string; proposal?: Record<st}function fencedJson(reply: string): unknown {- const fences = [...reply.matchAll(/```(?:json)?\s*\n([\s\S]*?)\n\s*```/g)];- for (let i = fences.length - 1; i >= 0; i--) {- try {- return JSON.parse(fences[i]![1]!);- } catch {- continue;- }- }+ return parsedBlock(fencedCodeBlocks(reply))?.value ?? bareJson(reply);+}++function bareJson(reply: string): unknown {const bare = reply.trim();if (bare.startsWith("[") || bare.startsWith("{")) {try {diff --git a/src/memory/bench.ts b/src/memory/bench.tsindex e5c4d046a..e266314e3 100644--- a/src/memory/bench.ts+++ b/src/memory/bench.ts@@ -1,4 +1,5 @@import type { ScopeId } from "../types.ts";+import { outermostJsonObject } from "../util/text.ts";import type { MemoryStrategy, MemoryStrategyKind } from "./strategy.ts";export interface BenchConversation {@@ -86,9 +87,9 @@ function clampScore(n: unknown): number {}export function parseJudgeVerdict(out: string): JudgeVerdict {- const match = /\{[\s\S]*\}/.exec(out);- if (!match) throw new Error(`judge output had no JSON object: ${out.slice(0, 200)}`);- const o = JSON.parse(match[0]) as Partial<JudgeVerdict>;+ const object = outermostJsonObject(out);+ if (!object) throw new Error(`judge output had no JSON object: ${out.slice(0, 200)}`);+ const o = JSON.parse(object) as Partial<JudgeVerdict>;return {signalToNoise: clampScore(o.signalToNoise),staleness: clampScore(o.staleness),diff --git a/src/memory/memory-service.ts b/src/memory/memory-service.tsindex d297a87b9..75a9fea86 100644--- a/src/memory/memory-service.ts+++ b/src/memory/memory-service.ts@@ -77,7 +77,7 @@ function cleanCapturedFacts(facts: string[]): string[] {.trim().replace(/^[-*]\s+/, "").replace(/^\((\d{4}-\d\d-\d\d)\)\s*/, "on $1: ")- .replace(/\s+\(said in ([^)]+)\)\s*$/i, " [claimed source: $1]");+ .replace(/\s+\(said in ([^()]+)\)\s*$/i, " [claimed source: $1]");return text ? [text] : [];});}diff --git a/src/sandbox/exec-process-session.ts b/src/sandbox/exec-process-session.tsindex ccad5c7d6..0fe69e51c 100644--- a/src/sandbox/exec-process-session.ts+++ b/src/sandbox/exec-process-session.ts@@ -75,7 +75,7 @@ export function redactCommand(command: string, env?: Record<string, string>): st);return redactPipedIntoWithToken(flagsRedacted).replace(- /(export\s+\w*(?:PASS|PASSWORD|SECRET|TOKEN|KEY|IDENTIFIER|CREDENTIAL|PROXY_USER)\w*=')[^']*'/gi,+ /(export\s+(?=\w*(?:PASS|PASSWORD|SECRET|TOKEN|KEY|IDENTIFIER|CREDENTIAL|PROXY_USER))\w+=')[^']*'/gi,"$1<redacted>'",).slice(0, 500);diff --git a/src/slack/external-access.ts b/src/slack/external-access.tsindex 322075bbd..57aa01271 100644--- a/src/slack/external-access.ts+++ b/src/slack/external-access.ts@@ -1,4 +1,5 @@import { createHash } from "node:crypto";+import { extractDirectives } from "./directives.ts";import type { SlackUser, ActorAssertion } from "./identity.ts";export interface ExternalSlackAccess {@@ -65,13 +66,15 @@ export function externalSlackNamespace(teamId: string, policy: ExternalSlackAcceexport const PRIVATE_CONTINUATION_INSTRUCTION ="This Slack workspace has an external audience. Answer and run code here only with the explicitly available external-safe services. Before any personal memory, files, account, calendar, email, or confidential company service is needed, end this turn with [[continue-private: a concise description of the remaining work]]. The platform acknowledges here and automatically continues in the requesting employee's private DM with this request and its channel context. Do not ask them to repeat it or ask for an additional handoff approval. Do not promise a result back to this channel. Private results stay in the DM. This directive can continue only the current requester's work, never another person's.";+const PRIVATE_CONTINUATION_DIRECTIVE = /\[\[continue-private:((?:(?!\[\[continue-private:)[^\]]|\](?!\]))*)\]\]/gi;+const TRAILING_PRIVATE_CONTINUATION = /\[\[continue-private:[\s\S]*$/i;+export function extractPrivateContinuation(text: string): { text: string; task?: string } {- if (!/\[\[continue-private:/i.test(text)) return { text };- const pattern = /\[\[continue-private:([\s\S]*?)\]\]/gi;- const tasks = [...text.matchAll(pattern)].map((m) => m[1]!.trim()).filter(Boolean);- const cleaned = text- .replace(pattern, "")- .replace(/\[\[continue-private:[\s\S]*$/gi, "")- .trim();- return { text: cleaned, ...(tasks.length ? { task: tasks[0]!.slice(0, 16_000) } : {}) };+ const { text: cleaned, matches } = extractDirectives(+ text,+ PRIVATE_CONTINUATION_DIRECTIVE,+ TRAILING_PRIVATE_CONTINUATION,+ ([inner]) => inner?.trim().slice(0, 16_000) || undefined,+ );+ return { text: cleaned, ...(matches.length ? { task: matches[0]! } : {}) };}diff --git a/src/slack/mirror.ts b/src/slack/mirror.tsindex aa13fe099..ac25d9ddc 100644--- a/src/slack/mirror.ts+++ b/src/slack/mirror.ts@@ -1,6 +1,7 @@import { isOwnStatusCard } from "./message-gating.ts";import { swallow } from "../util/errors.ts";import { decodeSlackEntities, mentionsBot } from "./lib.ts";+import { mentionedUserIds } from "./mrkdwn.ts";import { messageWithForwardedContent } from "./forwards.ts";import type { SlackCoreClient } from "../api/slack-core-client.ts";import type { IngestEvent } from "../surface-cache/surface-cache.ts";@@ -91,8 +92,7 @@ export function createMirror(deps: {}async function resolveMentionNames(client: any, text: string): Promise<Record<string, string>> {- const mentionIds = new Set<string>();- for (const match of text.matchAll(/<@(U\w+)(?:\|[^>]*)?>/g)) mentionIds.add(match[1] as string);+ const mentionIds = new Set(mentionedUserIds(text));const names = new Map<string, string>();await Promise.all([...mentionIds].slice(0, MAX_NAME_LOOKUPS).map(async (id) => {diff --git a/src/slack/mrkdwn.ts b/src/slack/mrkdwn.tsindex e130a14ca..7ab9a0bcc 100644--- a/src/slack/mrkdwn.ts+++ b/src/slack/mrkdwn.ts@@ -4,14 +4,18 @@ export function decodeSlackEntities(text: string): string {return text.replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&");}+const SLACK_MENTION = /(?<!<)<+@([A-Z0-9]+)(?:\|([^<>]*))?(?:>|(?=<))/g;+export function resolveMentionsInText(text: string, lookup: (id: string) => string | undefined): string {- return text.replace(/<@(U\w+)(?:\|([^>]*))?>/g, (_m, id: string, label?: string) => {+ return text.replace(SLACK_MENTION, (_m, id: string, label?: string) => {const name = (label && label.trim()) || lookup(id);return name ? `@${name}` : `@${id}`;});}-const SLACK_MENTION = /<@([A-Z0-9]+)(?:\|[^>]*)?>/g;+export function mentionedUserIds(text: string): string[] {+ return [...text.matchAll(SLACK_MENTION)].map((m) => m[1]!);+}export function resolveMentions(text: string, nameById: ReadonlyMap<string, string> | undefined): string {if (!nameById || !text.includes("<@")) return text;@@ -24,7 +28,7 @@ export function resolveMentions(text: string, nameById: ReadonlyMap<string, striconst BOLD_SENTINEL = String.fromCharCode(1);const STASH_OPEN = String.fromCharCode(0);-const MASS_MENTION = /<!(here|channel|everyone)(?:\|[^>]*)?>/gi;+const MASS_MENTION = /(?<!<)<+!(here|channel|everyone)(?:\|[^<>]*)?(?:>|(?=<))/gi;export function neutralizeMassMentions(text: string): string {return text.replace(MASS_MENTION, (_m, word: string) => `@\u200b${word.toLowerCase()}`);}@@ -39,7 +43,7 @@ export function setMentionIndex(index: ReadonlyMap<string, string>): void {for (const [name, id] of index) if (!byId.has(id)) byId.set(id, name);mentionNameById = byId;}-const WIRE_MENTION = /<(@[UW]\w+|!(?:here|channel|everyone|subteam\^\w+))(?:\|([^>]*))?>/gi;+const WIRE_MENTION = /(?<!<)<+(@[UW]\w+|!(?:here|channel|everyone|subteam\^\w+))(?:\|([^<>]*))?(?:>|(?=<))/gi;function neutralizedMention(kind: string, label: string | undefined): string {const name = label?.trim().replace(/^@/, "") || "";@@ -101,9 +105,13 @@ function stashFencedBlocks(text: string, keep: (s: string) => string): string {let out = "";let i = 0;let tildesExhausted = !text.includes("~~~");+ let tilde: { start: number; end: number } | undefined;while (i < text.length) {const backtick = text.indexOf("```", i);- const tilde = tildesExhausted ? undefined : nextLineMatch(text, i, TILDE_OPENER);+ if (!tildesExhausted && (tilde === undefined || tilde.start < i)) {+ tilde = nextLineMatch(text, i, TILDE_OPENER);+ tildesExhausted = tilde === undefined;+ }if (tilde === undefined && backtick < 0) break;if (backtick >= 0 && (tilde === undefined || backtick < tilde.start)) {const close = text.indexOf("```", backtick + 3);@@ -116,6 +124,7 @@ function stashFencedBlocks(text: string, keep: (s: string) => string): string {const closer = opener.end < text.length ? nextLineMatch(text, opener.end + 1, TILDE_CLOSER) : undefined;if (closer === undefined) {tildesExhausted = true;+ tilde = undefined;continue;}const info = text.slice(opener.start, opener.end).replace(/^[ \t]*~+/, "");@@ -141,7 +150,7 @@ export function toSlackMrkdwn(md: string): string {text = reformatTables(text, keep);- text = text.replace(/!?\[([^\]]*)\]\(\s*<?([^()\s>]+)>?(?:\s+"[^"]*")?\s*\)/g, (_m, label, url) =>+ text = text.replace(/!?\[([^[\]\n]*)\]\(\s*<?([^()\s>]+)>?(?:\s+"[^"]*")?\s*\)/g, (_m, label, url) =>keep(label ? `<${url}|${label}>` : `<${url}>`),);@@ -155,14 +164,14 @@ export function toSlackMrkdwn(md: string): string {text = text.replace(/^[ \t]*([-*_])\1{2,}[ \t]*$/gm, "──────────");- text = text.replace(/\*\*(?!\s)([^\n]+?)(?<!\s)\*\*/g, `${BOLD_SENTINEL}$1${BOLD_SENTINEL}`);- text = text.replace(/__(?!\s)([^\n]+?)(?<!\s)__/g, `${BOLD_SENTINEL}$1${BOLD_SENTINEL}`);+ text = text.replace(/\*\*(?!\s)((?:[^*\n]|\*(?!\*))+?)(?<!\s)\*\*/g, `${BOLD_SENTINEL}$1${BOLD_SENTINEL}`);+ text = text.replace(/__(?!\s)((?:[^_\n]|_(?!_))+?)(?<!\s)__/g, `${BOLD_SENTINEL}$1${BOLD_SENTINEL}`);- text = text.replace(/~~(?!\s)([^\n]+?)(?<!\s)~~/g, "~$1~");+ text = text.replace(/~~(?!\s)((?:[^~\n]|~(?!~))+?)(?<!\s)~~/g, "~$1~");text = text.replace(- /^[ \t]*#{1,6}[ \t]+(.+?)[ \t]*#*$/gm,- (_m, h) => `${BOLD_SENTINEL}${(h as string).replaceAll(BOLD_SENTINEL, "")}${BOLD_SENTINEL}`,+ /^[ \t]*#{1,6}[ \t]+(.+)$/gm,+ (_m, h: string) => `${BOLD_SENTINEL}${headingTitle(h).replaceAll(BOLD_SENTINEL, "")}${BOLD_SENTINEL}`,);text = text.replace(/^([ \t]*)[-*+][ \t]+/gm, "$1• ");@@ -175,26 +184,30 @@ export function toSlackMrkdwn(md: string): string {return text;}+function headingTitle(rest: string): string {+ const trimmed = rest.trimEnd();+ let end = trimmed.length;+ while (end > 0 && trimmed[end - 1] === "#") end--;+ if (end === trimmed.length || (end > 0 && trimmed[end - 1] !== " " && trimmed[end - 1] !== "\t")) return trimmed;+ return trimmed.slice(0, end).trimEnd() || trimmed;+}++const URL_CLOSER_OPENER: Record<string, string> = { ")": "(", "]": "[", "}": "{" };+const URL_BRACKETS = new Set([...Object.keys(URL_CLOSER_OPENER), ...Object.values(URL_CLOSER_OPENER)]);+function trimUrlTail(url: string): string {- const openerOf: Record<string, string> = { ")": "(", "]": "[", "}": "{" };+ const counts = new Map<string, number>();+ for (const ch of url) {+ if (URL_BRACKETS.has(ch)) counts.set(ch, (counts.get(ch) ?? 0) + 1);+ }let end = url.length;while (end > 0) {const ch = url[end - 1]!;- if ("*_~.,;:!?'\"".includes(ch)) {- end--;- continue;- }- const opener = openerOf[ch];- if (opener) {- const head = url.slice(0, end);- const opens = head.split(opener).length - 1;- const closes = head.split(ch).length - 1;- if (closes > opens) {- end--;- continue;- }- }- break;+ const opener = URL_CLOSER_OPENER[ch];+ const unbalanced = opener !== undefined && (counts.get(ch) ?? 0) > (counts.get(opener) ?? 0);+ if (!"*_~.,;:!?'\"".includes(ch) && !unbalanced) break;+ if (opener !== undefined) counts.set(ch, counts.get(ch)! - 1);+ end--;}return url.slice(0, end);}diff --git a/src/slack/reactions.ts b/src/slack/reactions.tsindex a01e88072..e5ce94fa5 100644--- a/src/slack/reactions.ts+++ b/src/slack/reactions.ts@@ -3,8 +3,8 @@ import { sleep } from "./util.ts";import { extractDirectives } from "./directives.ts";import { slackErrorCode } from "./payloads.ts";-const REACTION_DIRECTIVE = /\[\[react:([^\]]*)\]\]/gi;-const TRAILING_OPEN_DIRECTIVE = /\[\[react:[^\]]*$/i;+const REACTION_DIRECTIVE = /\[\[react:([^[\]]*)\]\]/gi;+const TRAILING_OPEN_DIRECTIVE = /\[\[react:[^[\]]*$/i;const REACTION_TS = /^\d{6,}\.\d{1,}$/;const REACTION_ID = /^~([0-9a-z]+)$/;diff --git a/src/surface-cache/ambient-judge.ts b/src/surface-cache/ambient-judge.tsindex d106222be..18ee8a439 100644--- a/src/surface-cache/ambient-judge.ts+++ b/src/surface-cache/ambient-judge.ts@@ -1,4 +1,5 @@import { resolveMentions } from "../slack/mrkdwn.ts";+import { outermostJsonObject } from "../util/text.ts";import type { CachedMessage } from "./surface-cache.ts";const AMBIENT_JUDGE_SYSTEM = `You are the ambient mind for a chat container — a thin, cheap observer that decides whether the@@ -85,10 +86,10 @@ export function renderAmbientPrompt(batch: AmbientBatch): string {export function parseAmbientDecision(raw: string | undefined): AmbientDecision {if (!raw) return { act: false };- const m = /\{[\s\S]*\}/.exec(raw);- if (!m) return { act: false };+ const object = outermostJsonObject(raw);+ if (!object) return { act: false };try {- const parsed = JSON.parse(m[0]) as { act?: unknown; reason?: unknown; asked_by?: unknown };+ const parsed = JSON.parse(object) as { act?: unknown; reason?: unknown; asked_by?: unknown };if (parsed.act !== true) return { act: false };const askedBy = typeof parsed.asked_by === "string" ? parsed.asked_by.trim().replace(/^\[|\]$/g, "") : "";return {diff --git a/src/util/markdown.ts b/src/util/markdown.tsnew file mode 100644index 000000000..bf2e9cbba--- /dev/null+++ b/src/util/markdown.ts@@ -0,0 +1,89 @@+const APP_LINK = /\[([^[\]\n]+)\]\((\/d\/[^\s)[]+)\)/g;++export interface FencedCodeBlock {+ start: number;+ end: number;+ body: string;+}++function fenceRun(line: string): string | undefined {+ let indent = 0;+ while (line[indent] === " " || line[indent] === "\t") indent++;+ const mark = line[indent];+ if (mark !== "`" && mark !== "~") return undefined;+ let run = indent;+ while (line[run] === mark) run++;+ if (run - indent < 3 || (mark === "`" && line.includes("`", run))) return undefined;+ return line.slice(indent, run);+}++export function fencedCodeBlocks(text: string): FencedCodeBlock[] {+ const blocks: FencedCodeBlock[] = [];+ let open: { start: number; run: string; bodyStart: number } | undefined;+ let offset = 0;+ for (const line of text.split("\n")) {+ const next = offset + line.length + 1;+ const run = fenceRun(line);+ if (!open) {+ if (run) open = { start: offset, run, bodyStart: next };+ } else if (run && run[0] === open.run[0] && run.length >= open.run.length && line.trim() === run) {+ blocks.push({ start: open.start, end: offset + line.length, body: text.slice(open.bodyStart, offset) });+ open = undefined;+ }+ offset = next;+ }+ if (open) {+ blocks.push({ start: open.start, end: text.length, body: text.slice(Math.min(open.bodyStart, text.length)) });+ }+ return blocks;+}++function codeSpans(line: string): Array<[number, number]> {+ const runs: Array<{ start: number; end: number }> = [];+ for (let tick = line.indexOf("`"); tick !== -1; tick = line.indexOf("`", runs.at(-1)!.end)) {+ let end = tick + 1;+ while (line[end] === "`") end++;+ runs.push({ start: tick, end });+ }+ const nextSameLength = Array.from({ length: runs.length }, () => -1);+ const lastByLength = new Map<number, number>();+ for (let i = runs.length - 1; i >= 0; i--) {+ const length = runs[i]!.end - runs[i]!.start;+ nextSameLength[i] = lastByLength.get(length) ?? -1;+ lastByLength.set(length, i);+ }+ const spans: Array<[number, number]> = [];+ for (let i = 0; i < runs.length; i++) {+ const close = nextSameLength[i]!;+ if (close === -1) continue;+ spans.push([runs[i]!.start, runs[close]!.end]);+ i = close;+ }+ return spans;+}++function rewriteLine(line: string, baseUrl: string): string {+ const spans = codeSpans(line);+ let next = 0;+ return line.replace(APP_LINK, (match: string, label: string, path: string, index: number) => {+ while (next < spans.length && spans[next]![1] <= index) next++;+ const inSpan = next < spans.length && spans[next]![0] <= index;+ return inSpan ? match : `[${label}](${new URL(path, baseUrl).href})`;+ });+}++export function absoluteAppLinks(text: string, baseUrl: string | undefined): string {+ if (!baseUrl) return text;+ const prose = (segment: string) =>+ segment+ .split("\n")+ .map((line) => rewriteLine(line, baseUrl))+ .join("\n");+ let out = "";+ let cursor = 0;+ for (const block of fencedCodeBlocks(text)) {+ out += prose(text.slice(cursor, block.start)) + text.slice(block.start, block.end);+ cursor = block.end;+ }+ return out + prose(text.slice(cursor));+}diff --git a/src/util/text.ts b/src/util/text.tsindex 810cb0f06..43fb00580 100644--- a/src/util/text.ts+++ b/src/util/text.ts@@ -30,10 +30,8 @@ export function pgTextSafe(s: string): string {return out;}-export function absoluteAppLinks(text: string, baseUrl: string | undefined): string {- if (!baseUrl) return text;- return text.replace(- /(^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\2[ \t]*$|(`+)[^\n]*?\3)|\[([^\]\n]+)\]\((\/d\/[^\s)]+)\)/gm,- (match, code, _fence, _ticks, label, path) => (code ? match : `[${label}](${new URL(path, baseUrl).href})`),- );+export function outermostJsonObject(text: string): string | undefined {+ const start = text.indexOf("{");+ const end = text.lastIndexOf("}");+ return start === -1 || end < start ? undefined : text.slice(start, end + 1);}diff --git a/test/ambient-judge.test.ts b/test/ambient-judge.test.tsindex a2d17c44d..4f17a8a4c 100644--- a/test/ambient-judge.test.ts+++ b/test/ambient-judge.test.ts@@ -117,3 +117,14 @@ test("ambient rendering resolves cached mention names without changing stored meassert.ok(prompt.includes("mentioned as <@U00000002>"));assert.deepEqual(batch, original);});++test("parseAmbientDecision reads the outermost object and stays linear-time on a brace flood", () => {+ assert.deepEqual(parseAmbientDecision('Sure. {"act": true, "reason": "asked for a digest"} done'), {+ act: true,+ reason: "asked for a digest",+ });+ const started = performance.now();+ assert.deepEqual(parseAmbientDecision("{".repeat(60_000)), { act: false });+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1_000, `brace flood took ${Math.round(elapsed)}ms`);+});diff --git a/test/exec-process-session.test.ts b/test/exec-process-session.test.tsindex 01366c1c6..27fd854d9 100644--- a/test/exec-process-session.test.ts+++ b/test/exec-process-session.test.ts@@ -312,3 +312,13 @@ test("a session from the current boot keeps running, and one with no boot marker"sessions predating this change have no marker and must not be reaped on a guess",);});++test("redactCommand hides exported secrets and stays fast on a keyword-flooded export", () => {+ assert.equal(redactCommand("export MY_API_KEY='shh' && run"), "export MY_API_KEY='<redacted>' && run");+ assert.equal(redactCommand("export REGION='us-east-1'"), "export REGION='us-east-1'");+ const flooded = `export N${"TKEYP".repeat(20_000)}`;+ const started = performance.now();+ assert.equal(redactCommand(flooded), flooded.slice(0, 500));+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1_000, `keyword flood took ${Math.round(elapsed)}ms`);+});diff --git a/test/external-slack-policy.test.ts b/test/external-slack-policy.test.tsindex 698028c83..5d47f29e6 100644--- a/test/external-slack-policy.test.ts+++ b/test/external-slack-policy.test.ts@@ -413,3 +413,20 @@ test("delegated human-origin runs cannot restart themselves as a person's privatassert.equal(await client.privateContinuationSource!(delegated.run.id), null);}});++test("private continuation extraction skips code, keeps the first directive, and stays linear-time on an opener flood", () => {+ assert.deepEqual(+ extractPrivateContinuation("OK [[continue-private: a [[continue-private: b]] tail [[continue-private: c]]"),+ { text: "OK", task: "b" },+ );+ assert.deepEqual(extractPrivateContinuation("Use `[[continue-private: like this]]` to hand off"), {+ text: "Use `[[continue-private: like this]]` to hand off",+ });+ assert.deepEqual(extractPrivateContinuation("Plain reply"), { text: "Plain reply" });+ const flood = "][[continue-private:".repeat(25_000) + "]";+ const started = performance.now();+ const out = extractPrivateContinuation(flood);+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1_000, `opener flood took ${Math.round(elapsed)}ms`);+ assert.deepEqual(out, { text: "]" });+});diff --git a/test/loop-fire.test.ts b/test/loop-fire.test.tsindex ab0e21c54..fe707e153 100644--- a/test/loop-fire.test.ts+++ b/test/loop-fire.test.ts@@ -1215,3 +1215,61 @@ test("a resolution from a non-reply Loop is ignored", async () => {const [item] = await w.items.byLoop(loop.id);assert.notEqual(item?.status, "skipped");});++test("an unclosed fence after the real reply parses in linear time", async () => {+ const padded: Responder = (req) =>+ stage(req) === "work"+ ? `Prepared.\n\`\`\`json\n{"outputs": [{"shipAction": "open_pr", "title": "Fix"}]}\n\`\`\`\nNotes:\n\`\`\`\n${"\n".repeat(4_000)}`+ : HAPPY(req);+ const s = service(padded);+ const loop = await makeLoop(s.loops);+ const started = performance.now();+ const result = await s.fire.fire(loop.id, "padded");+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 2_000, `padded reply took ${Math.round(elapsed)}ms`);+ assert.equal(result.status, "ok");+ assert.equal((await s.outputs.awaitingReview(loop.id))[0]?.title, "Fix");+});++test("a language-tagged fence before the json block does not hide it", async () => {+ const chatty: Responder = (req) =>+ stage(req) === "work"+ ? 'I ran:\n```bash\nnpm test\n```\nAll green.\n```json\n{"outputs": [{"shipAction": "open_pr", "title": "Fix"}]}\n```'+ : HAPPY(req);+ const s = service(chatty);+ const loop = await makeLoop(s.loops);+ await s.fire.fire(loop.id, "chatty");+ assert.equal((await s.outputs.awaitingReview(loop.id))[0]?.title, "Fix");+});++test("a follow-up keeps its prose and earlier code blocks in the chat and lifts only the proposal block", async () => {+ const s = service(+ () =>+ 'Current config:\n```\n{"retries": 3}\n```\nI propose:\n ```json\n {"proposal": {"body": "Retry twice"}}\n ```\nLet me know.',+ );+ const loop = await makeLoop(s.loops);+ await s.items.ingest([+ {+ loopId: loop.id,+ dedupeKey: "reply",+ source: "gmail",+ sourcePayload: { snippet: "How many retries?" },+ proposal: { data: { body: "Retry thrice" }, by: "agent" },+ },+ ]);+ const [item] = await s.items.byLoop(loop.id);+ const next = await s.fire.followUp(loop, item!, "Fewer retries please", "josh");+ assert.equal(next?.thread?.at(-1)?.text, 'Current config:\n```\n{"retries": 3}\n```\nI propose:\n\nLet me know.');+ assert.equal(next?.proposal?.data.body, "Retry twice");++ const informational = service(() => 'Current config is:\n```json\n{"retries": 3}\n```\nWant me to change anything?');+ const infoLoop = await makeLoop(informational.loops);+ await informational.items.ingest([{ loopId: infoLoop.id, dedupeKey: "info", sourcePayload: {} }]);+ const [infoItem] = await informational.items.byLoop(infoLoop.id);+ const answered = await informational.fire.followUp(infoLoop, infoItem!, "What is the config?", "josh");+ assert.equal(+ answered?.thread?.at(-1)?.text,+ 'Current config is:\n```json\n{"retries": 3}\n```\nWant me to change anything?',+ );+ assert.equal(answered?.proposal, undefined);+});diff --git a/test/slack-mrkdwn.test.ts b/test/slack-mrkdwn.test.tsindex 3c6b9df68..aff883478 100644--- a/test/slack-mrkdwn.test.ts+++ b/test/slack-mrkdwn.test.ts@@ -11,6 +11,7 @@ import {setMentionIndex,inlineCode,} from "../src/slack/lib.ts";+import { resolveMentions } from "../src/slack/mrkdwn.ts";test("inlineCode clamps long text and neutralizes backticks", () => {const clamped = inlineCode("`echo hi`" + "y".repeat(60000));@@ -274,3 +275,54 @@ test("a label-less wire mention is disarmed to the person's name when the directsetMentionIndex(new Map());}});++test("pathological inline markdown and mention floods stay linear-time", () => {+ const untouched = ["[".repeat(60_000), "**a ".repeat(25_000), "~~~~" + "\t\t~~x".repeat(12_000)];+ const heading = "#\tx" + "\t".repeat(60_000) + "\tx\n";+ const started = performance.now();+ for (const text of untouched) assert.equal(toSlackMrkdwn(text), text);+ assert.equal(toSlackMrkdwn(heading), `*${heading.slice(2, -1)}*\n`);+ assert.equal(neutralizeMentions("<@UU|".repeat(12_000)), `${"@UU".repeat(11_999)}<@UU|`);+ assert.equal(neutralizeMassMentions("<!here|".repeat(8_000)), `${"@\u200bhere".repeat(7_999)}<!here|`);+ assert.equal(+ resolveMentionsInText("<@U1|".repeat(12_000), () => undefined),+ `${"@U1".repeat(11_999)}<@U1|`,+ );+ assert.equal(resolveMentions("<@U1|".repeat(12_000), new Map([["U1", "ann"]])), `${"@ann".repeat(11_999)}<@U1|`);+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1_000, `pathological inline markdown took ${Math.round(elapsed)}ms`);+});++test("a mention token nested inside another token's label cannot re-form a live mention", () => {+ assert.equal(toSlackMrkdwn("<!here|<!channel>>"), "@\u200bhere@\u200bchannel>");+ assert.equal(neutralizeMassMentions("<!channel|<!here|x>>"), "@\u200bchannel@\u200bhere>");+ assert.equal(neutralizeMentions("<@U123|<@U456>>"), "@U123@U456>");+ assert.equal(+ resolveMentionsInText("<@U1|<@U2>>", () => undefined),+ "@U1@U2>",+ );+ assert.equal(neutralizeMentions("<<@U123>> <<@U4|x>>"), "@U123> @x>");+ assert.equal(toSlackMrkdwn("<<!channel>>"), "@\u200bchannel>");+ assert.equal(neutralizeMentions("<<<<<".repeat(5_000) + "<@U9>"), "@U9", "an opener run is consumed whole");+ assert.equal(+ neutralizeMassMentions("<!heresy> <!here|label <!date^1^{date}|then>"),+ "<!heresy> @\u200bhere<!date^1^{date}|then>",+ );+});++test("toSlackMrkdwn: a link label never swallows an earlier bracket, and closing hashes leave headings", () => {+ assert.equal(toSlackMrkdwn("see [[x](http://a)"), "see [<http://a|x>");+ assert.equal(toSlackMrkdwn("# Title ##"), "*Title*");+ assert.equal(toSlackMrkdwn("## Sub ## "), "*Sub*");+ assert.equal(toSlackMrkdwn("# C#"), "*C#*");+});++test("bare URL tail trimming stays linear-time on a flood of closing brackets", () => {+ const flood = `see http://x.y/a${")".repeat(20_000)}`;+ const started = performance.now();+ const out = toSlackMrkdwn(flood);+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1_000, `bracket flood took ${Math.round(elapsed)}ms`);+ assert.equal(out, `see <http://x.y/a>${")".repeat(20_000)}`);+ assert.equal(toSlackMrkdwn("(see http://x.y/a(b)) ok"), "(see <http://x.y/a(b)>) ok");+});diff --git a/test/slack-reactions.test.ts b/test/slack-reactions.test.tsindex a4ad75791..7ec98d190 100644--- a/test/slack-reactions.test.ts+++ b/test/slack-reactions.test.ts@@ -489,3 +489,15 @@ test("a react directive followed by a huge whitespace run strips in linear time"extractReactions("[[react: eyes]] tail" + " ".repeat(100000) + "no newline");assert.ok(Number(process.hrtime.bigint() - start) / 1e6 < 200);});++test("extractReactions stays linear-time on a flood of unterminated directives", () => {+ const opener = "[[react:";+ const flood = opener.repeat(16_000);+ const started = performance.now();+ const r = extractReactions(flood);+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1_000, `flood took ${Math.round(elapsed)}ms`);+ assert.deepEqual(r.reactions, []);+ assert.equal(r.text, flood.slice(0, -opener.length), "only the trailing unterminated directive is stripped");+ assert.deepEqual(extractReactions("[[react: eyes [[react: tada]]").reactions, [{ names: ["tada"] }]);+});diff --git a/test/util-markdown.test.ts b/test/util-markdown.test.tsnew file mode 100644index 000000000..c0eaf9ab6--- /dev/null+++ b/test/util-markdown.test.ts@@ -0,0 +1,62 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { absoluteAppLinks } from "../src/util/markdown.ts";++test("published app links resolve against the portal without rewriting code or external URLs", () => {+ assert.equal(+ absoluteAppLinks("[Pirates](/d/pirates/) [Other](https://example.com) `[/d/x/](/d/x/)`", "https://qm.example.com"),+ "[Pirates](https://qm.example.com/d/pirates/) [Other](https://example.com) `[/d/x/](/d/x/)`",+ );+ assert.equal(absoluteAppLinks("[Pirates](/d/pirates/)", undefined), "[Pirates](/d/pirates/)");+});++test("app links preserve tilde fences and multi-backtick code spans", () => {+ for (const text of ["~~~md\n[x](/d/x/)\n~~~", "``[x](/d/x/)``", "````md\n[x](/d/x/)\n````"]) {+ assert.equal(absoluteAppLinks(text, "https://qm.example.com"), text);+ }+});++test("app links stay linear-time on pathological backtick, bracket, and link floods", () => {+ const floods = ["`".repeat(40_000), "\t" + "[)".repeat(10_000), "[a](/d/".repeat(6_000)];+ const started = performance.now();+ for (const text of floods) assert.equal(absoluteAppLinks(text, "https://qm.example.com"), text);+ const elapsed = performance.now() - started;+ assert.ok(elapsed < 1_000, `floods took ${Math.round(elapsed)}ms`);+});++test("app links are rewritten outside code and left alone inside an unclosed fence", () => {+ assert.equal(+ absoluteAppLinks("see [a [b](/d/b) and ``x ` [c](/d/c)`` then [d](/d/d)", "https://qm.example.com"),+ "see [a [b](https://qm.example.com/d/b) and ``x ` [c](/d/c)`` then [d](https://qm.example.com/d/d)",+ );+ assert.equal(absoluteAppLinks("```\n[x](/d/x/)", "https://qm.example.com"), "```\n[x](/d/x/)");+});++test("app link fences close on a same-mark run at least as long as the opener, at any indent", () => {+ assert.equal(+ absoluteAppLinks("```js\n[a](/d/a)\n````\n[b](/d/b)", "https://qm.example.com"),+ "```js\n[a](/d/a)\n````\n[b](https://qm.example.com/d/b)",+ );+ assert.equal(+ absoluteAppLinks(" ```\n[a](/d/a)\n ```\n[b](/d/b)", "https://qm.example.com"),+ " ```\n[a](/d/a)\n ```\n[b](https://qm.example.com/d/b)",+ );+ assert.equal(+ absoluteAppLinks("~~~\n[a](/d/a)\n```\n[b](/d/b)", "https://qm.example.com"),+ "~~~\n[a](/d/a)\n```\n[b](/d/b)",+ );+ assert.equal(+ absoluteAppLinks(+ " ```\n [a](/d/a)\n ```\n[b](/d/b)\n\t~~~\n[c](/d/c)\n\t~~~\n[d](/d/d)",+ "https://qm.example.com",+ ),+ " ```\n [a](/d/a)\n ```\n[b](https://qm.example.com/d/b)\n\t~~~\n[c](/d/c)\n\t~~~\n[d](https://qm.example.com/d/d)",+ );+});++test("a code span inside a link label does not stop the link from resolving", () => {+ assert.equal(+ absoluteAppLinks("see [`a`](/d/1) and `[b](/d/2)`", "https://qm.example.com"),+ "see [`a`](https://qm.example.com/d/1) and `[b](/d/2)`",+ );+});diff --git a/test/util-text.test.ts b/test/util-text.test.tsindex 87b717a43..fcefbba5b 100644--- a/test/util-text.test.ts+++ b/test/util-text.test.ts@@ -1,4 +1,3 @@-import { absoluteAppLinks } from "../src/util/text.ts";import { test } from "node:test";import assert from "node:assert/strict";import { headSlice, tailSlice, hasLoneSurrogate } from "../src/util/text.ts";@@ -24,17 +23,3 @@ test("headSlice and tailSlice never strand half a surrogate pair", () => {assert.ok(!hasLoneSurrogate(tailSlice(s, n)), `tailSlice at ${n}`);}});--test("published app links resolve against the portal without rewriting code or external URLs", () => {- assert.equal(- absoluteAppLinks("[Pirates](/d/pirates/) [Other](https://example.com) `[/d/x/](/d/x/)`", "https://qm.example.com"),- "[Pirates](https://qm.example.com/d/pirates/) [Other](https://example.com) `[/d/x/](/d/x/)`",- );- assert.equal(absoluteAppLinks("[Pirates](/d/pirates/)", undefined), "[Pirates](/d/pirates/)");-});--test("app links preserve tilde fences and multi-backtick code spans", () => {- for (const text of ["~~~md\n[x](/d/x/)\n~~~", "``[x](/d/x/)``", "````md\n[x](/d/x/)\n````"]) {- assert.equal(absoluteAppLinks(text, "https://qm.example.com"), text);- }-});