diff --git a/apps/server/src/mcp/McpHttpServer.ts b/apps/server/src/mcp/McpHttpServer.ts index 84ca2bc995f0..921c3a9214c6 100644 --- a/apps/server/src/mcp/McpHttpServer.ts +++ b/apps/server/src/mcp/McpHttpServer.ts @@ -1220,6 +1220,7 @@ export const T4_ALWAYS_LOAD = new Set([ "t3_thread_update", "schedule_task", "watch_workflow_run", + "wait_for_reply", "release_queue", "request_secret", "link_pull_request", diff --git a/apps/server/src/mcp/toolkits/t4/handlers.ts b/apps/server/src/mcp/toolkits/t4/handlers.ts index a4a58592451a..5b62ecd2bff6 100644 --- a/apps/server/src/mcp/toolkits/t4/handlers.ts +++ b/apps/server/src/mcp/toolkits/t4/handlers.ts @@ -29,6 +29,7 @@ import * as T4Delivery from "../../../t4/T4Delivery.ts"; import * as FyiDigest from "../../../t4/fyiDigest.ts"; import * as T4Ledger from "../../../t4/T4Ledger.ts"; import * as T4Releases from "../../../t4/T4Releases.ts"; +import * as T4ReplyWatch from "../../../t4/T4ReplyWatch.ts"; import * as T4RunWatch from "../../../t4/T4RunWatch.ts"; import * as T4Store from "../../../t4/T4Store.ts"; import * as ToolCallLog from "../../../t4/toolCallLog.ts"; @@ -985,6 +986,96 @@ export const layer = McpToolAccess.toLayer(T4Toolkit, { }), ), + wait_for_reply: McpToolAccess.actsAsCaller((input) => + Effect.gen(function* () { + const me = yield* callerThread; + const replyWatch = yield* T4ReplyWatch.T4ReplyWatch; + const who = input.who.trim(); + if (who.length === 0) return yield* invalid("`who` is required: who you wait on"); + if (input.cancel === true) { + const gone = yield* replyWatch.cancel(me.id, who); + return { + waiting: false, + who, + check: gone[0]?.check ?? "", + deadline: "", + next: + gone.length > 0 + ? `Stopped waiting on ${who}.` + : `You weren't waiting on ${who}; nothing to cancel.`, + }; + } + const now = yield* Clock.currentTimeMillis; + let check = input.check?.trim() ?? ""; + let via: string | null = null; + if (input.email !== undefined) { + if (check.length > 0) return yield* invalid("give `check` or `email`, not both"); + const from = input.email.from?.trim() ?? ""; + const thread = input.email.thread?.trim() ?? ""; + if (from.length === 0 && thread.length === 0) + return yield* invalid( + "`email` needs `from` (their address) and/or `thread` (a message id)", + ); + const quote = (text: string) => `'${text.replaceAll("'", "'\\''")}'`; + check = [ + "email replies", + `--since ${DateTime.formatIso(DateTime.makeUnsafe(now))}`, + from.length > 0 ? `--from ${quote(from)}` : null, + thread.length > 0 ? `--thread ${quote(thread)}` : null, + ] + .filter((part) => part !== null) + .join(" "); + via = "email"; + } + if (check.length === 0) + return yield* invalid( + "give `check` (a command that prints their reply once it exists) or `email` ({from} / {thread})", + ); + const deadlineMs = T4ReplyWatch.parseDuration( + input.deadline ?? (via === "email" ? "2d" : "1h"), + ); + if (deadlineMs === null || deadlineMs < 60_000 || deadlineMs > T4ReplyWatch.MAX_DEADLINE_MS) + return yield* invalid("`deadline` is a time from 1m to 14d, like 30m, 2h or 3d"); + const everyMs = + input.every === undefined + ? T4ReplyWatch.defaultEvery(deadlineMs) + : T4ReplyWatch.parseDuration(input.every); + if ( + everyMs === null || + everyMs < T4ReplyWatch.MIN_EVERY_MS || + everyMs > T4ReplyWatch.MAX_EVERY_MS + ) + return yield* invalid("`every` is 1m to 60m"); + const project = + me.worktreePath === null + ? yield* Project.ProjectService.pipe( + Effect.flatMap((projects) => projects.getById(me.projectId)), + Effect.map(Option.getOrUndefined), + Effect.orElseSucceed(() => undefined), + ) + : undefined; + const { watch, replaced } = yield* replyWatch + .watch({ + threadId: me.id, + who, + about: input.about?.trim() || null, + check, + via: via ?? (/^\s*usars\s+chat\b/.test(check) ? "chat" : null), + cwd: me.worktreePath ?? project?.workspaceRoot ?? null, + deadlineMs, + everyMs, + }) + .pipe(Effect.mapError((error) => invalid(error.message))); + return { + waiting: true, + who, + check, + deadline: T4ReplyWatch.pacific(watch.deadline), + next: `${replaced ? "Replaced your earlier watch on " + who + ". " : ""}End your turn now. You get one message when ${who} replies (checked every ${Math.round(everyMs / 60_000)} min) or at ${T4ReplyWatch.pacific(watch.deadline)} if nobody has; the dashboard shows you as waiting on ${who}. Don't post the user a card while you wait.`, + }; + }), + ), + release_queue: McpToolAccess.actsAsCaller((input) => Effect.gen(function* () { const ledger = yield* T4Ledger.T4Ledger; diff --git a/apps/server/src/mcp/toolkits/t4/release.test.ts b/apps/server/src/mcp/toolkits/t4/release.test.ts index d07ed2fe9db5..f488b9ef5b2d 100644 --- a/apps/server/src/mcp/toolkits/t4/release.test.ts +++ b/apps/server/src/mcp/toolkits/t4/release.test.ts @@ -14,6 +14,7 @@ import * as Project from "../../../project/ProjectService.ts"; import * as T4Config from "../../../t4/T4Config.ts"; import * as T4Delivery from "../../../t4/T4Delivery.ts"; import * as T4Ledger from "../../../t4/T4Ledger.ts"; +import * as T4ReplyWatch from "../../../t4/T4ReplyWatch.ts"; import * as T4RunWatch from "../../../t4/T4RunWatch.ts"; import * as T4Releases from "../../../t4/T4Releases.ts"; import * as T4Sql from "../../../t4/T4Sql.ts"; @@ -201,6 +202,7 @@ const layer = McpHttpServer.layerT4Toolkit.pipe( }), Layer.mock(ThreadLaunch.ThreadLaunchService)({}), Layer.mock(T4RunWatch.T4RunWatch)({}), + Layer.mock(T4ReplyWatch.T4ReplyWatch)({}), Layer.succeed(T4Config.T4ServerConfig, T4Config.defaultT4ServerConfig), ), ), diff --git a/apps/server/src/mcp/toolkits/t4/tools.ts b/apps/server/src/mcp/toolkits/t4/tools.ts index 8cfe85c7e117..9ef99e8ba8e6 100644 --- a/apps/server/src/mcp/toolkits/t4/tools.ts +++ b/apps/server/src/mcp/toolkits/t4/tools.ts @@ -17,6 +17,7 @@ import * as Project from "../../../project/ProjectService.ts"; import * as T4Config from "../../../t4/T4Config.ts"; import * as T4Delivery from "../../../t4/T4Delivery.ts"; import * as T4Ledger from "../../../t4/T4Ledger.ts"; +import * as T4ReplyWatch from "../../../t4/T4ReplyWatch.ts"; import * as T4RunWatch from "../../../t4/T4RunWatch.ts"; import * as T4Store from "../../../t4/T4Store.ts"; @@ -269,6 +270,65 @@ const WatchWorkflowRunTool = Tool.make("watch_workflow_run", { // t4 fork: acts as the calling thread, so outside clients never see it. .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); +// t4 fork (AI-143): a thread waiting on someone outside t4 - a customer, supplier or staff member. +const WaitForReplyTool = Tool.make("wait_for_reply", { + ...common, + dependencies: [...common.dependencies, T4ReplyWatch.T4ReplyWatch], + description: + "After you ask a customer, supplier or staff member something (an email, the client's own chat - the client's AGENTS.md says where each answers), be woken when they reply instead of scheduling wakes to look, then END YOUR TURN. t4 runs `check` in your checkout every minute or so at no AI cost; the first time it prints anything you get one message with that output, or one saying nobody replied by `deadline`. `email` builds the check from the user's mailbox (`email replies`). The dashboard shows you as waiting on `who`. Same `who` again replaces that watch; `cancel: true` ends it (for instance when the answer reached you another way).", + parameters: Schema.Struct({ + who: Schema.String.annotate({ + description: 'Who you wait on, as the user knows them: "Dolma", "Korin at Vollrath".', + }), + about: Schema.optional( + Schema.String.annotate({ + description: 'A few words: what you asked ("USA-3097 early-pay terms").', + }), + ), + check: Schema.optional( + Schema.String.annotate({ + description: + "A shell command that prints the reply once it exists and nothing before (exit 0 either way), e.g. `usars chat replies USA-3097 --since 2026-11-23T20:09:43Z --from Dolma`. It must return at once, never wait.", + }), + ), + email: Schema.optional( + Schema.Struct({ + from: Schema.optional( + Schema.String.annotate({ description: "Their address(es), comma-separated." }), + ), + thread: Schema.optional( + Schema.String.annotate({ + description: "A message id in the conversation (from `email`).", + }), + ), + }).annotate({ + description: "Wait for mail from them and/or in that conversation, instead of `check`.", + }), + ), + deadline: Schema.optional( + Schema.String.annotate({ + description: + "How long to wait: 5m, 1h, 2d (up to 14d). Default 1h for `check`, 2d for `email`; the client's AGENTS.md may set it by urgency.", + }), + ), + every: Schema.optional( + Schema.String.annotate({ + description: "How often to check (1m-60m). Default 1m for waits of 3h or less, else 5m.", + }), + ), + cancel: Schema.optional(Schema.Boolean), + }), + success: Schema.Struct({ + waiting: Schema.Boolean, + who: Schema.String, + check: Schema.String, + deadline: Schema.String, + next: Schema.String, + }), +}) + .annotate(Tool.Destructive, false) + .annotate(McpSchema.EnabledWhen, McpInvocationContext.hiddenFromOutsideClients); + const ReleaseState = Schema.Literals(T4Store.RELEASE_STATES); const ReleaseEntry = Schema.Struct({ @@ -365,5 +425,6 @@ export const T4Toolkit = Toolkit.make( ListThreadIssuesTool, SetThreadRoleTool, WatchWorkflowRunTool, + WaitForReplyTool, ReleaseQueueTool, ); diff --git a/apps/server/src/provider/AgentContextBudget.test.ts b/apps/server/src/provider/AgentContextBudget.test.ts index caf5f9e42daf..b1ad09bf3555 100644 --- a/apps/server/src/provider/AgentContextBudget.test.ts +++ b/apps/server/src/provider/AgentContextBudget.test.ts @@ -50,6 +50,7 @@ import { VcsStatusBroadcaster } from "../vcs/VcsStatusBroadcaster.ts"; import { T4ServerConfig, defaultT4ServerConfig } from "../t4/T4Config.ts"; import { T4Delivery } from "../t4/T4Delivery.ts"; import { T4Ledger } from "../t4/T4Ledger.ts"; +import { T4ReplyWatch } from "../t4/T4ReplyWatch.ts"; import { T4RunWatch } from "../t4/T4RunWatch.ts"; import { T4Store } from "../t4/T4Store.ts"; import { buildCodexAdditionalContext } from "./CodexDeveloperInstructions.ts"; @@ -80,6 +81,7 @@ const toolHandlerServices = Layer.mergeAll( // t4 fork: t3_decisions reads T3's database (t4/T4Decisions.ts). NodeSqliteClient.layer({ filename: ":memory:" }), Layer.mock(T4RunWatch)({}), + Layer.mock(T4ReplyWatch)({}), Layer.succeed(T4ServerConfig, defaultT4ServerConfig), Layer.mock(PeerLinkRequests)({}), Layer.mock(PeerLinks)({}), diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index f266b6f1bb67..91033dac5326 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 9583, "codexAdditionalContextBytes": 10987, - "mcpToolListJsonBytes": 67186 + "mcpToolListJsonBytes": 69016 } diff --git a/apps/server/src/t4/T4Http.ts b/apps/server/src/t4/T4Http.ts index f89ce8d36832..55d95f5a7a4d 100644 --- a/apps/server/src/t4/T4Http.ts +++ b/apps/server/src/t4/T4Http.ts @@ -41,6 +41,7 @@ import * as T4Config from "./T4Config.ts"; import * as T4Delivery from "./T4Delivery.ts"; import { factsFor } from "./T4Facts.ts"; import * as T4Ledger from "./T4Ledger.ts"; +import * as T4ReplyWatch from "./T4ReplyWatch.ts"; import * as T4RunWatch from "./T4RunWatch.ts"; import * as T4Schedules from "./T4Schedules.ts"; import * as T4Spawn from "./T4Spawn.ts"; @@ -242,6 +243,25 @@ export const layer = Layer.mergeAll( service._tag === "Some" ? service.value.watches : Effect.succeed([]), ), ), + // Who a thread waits on outside t4 (wait_for_reply, AI-143): "Waiting on Dolma". + replyWatches: yield* Effect.serviceOption(T4ReplyWatch.T4ReplyWatch).pipe( + Effect.flatMap((service) => + service._tag === "Some" ? service.value.watches : Effect.succeed([]), + ), + Effect.map((list) => + list.map((w) => ({ + threadId: w.threadId, + who: w.who, + about: w.about, + via: w.via, + since: DateTime.formatIso(DateTime.makeUnsafe(w.since)), + deadline: DateTime.formatIso(DateTime.makeUnsafe(w.deadline)), + lastCheck: + w.lastCheck > 0 ? DateTime.formatIso(DateTime.makeUnsafe(w.lastCheck)) : null, + failing: w.failures > 0 ? w.lastError : null, + })), + ), + ), }); }), ), diff --git a/apps/server/src/t4/T4Jobs.ts b/apps/server/src/t4/T4Jobs.ts index 8b467716385f..142139e34bd1 100644 --- a/apps/server/src/t4/T4Jobs.ts +++ b/apps/server/src/t4/T4Jobs.ts @@ -15,6 +15,7 @@ import * as T4AutoArchive from "./T4AutoArchive.ts"; import * as T4ReleaseGuard from "./T4ReleaseGuard.ts"; import * as T4Releases from "./T4Releases.ts"; import * as T4Schedules from "./T4Schedules.ts"; +import * as T4ReplyWatch from "./T4ReplyWatch.ts"; import * as T4RunWatch from "./T4RunWatch.ts"; import * as T4Settle from "./T4Settle.ts"; import * as T4Stalls from "./T4Stalls.ts"; @@ -43,6 +44,9 @@ export const layer = Layer.effectDiscard( yield* scheduler.register("t4-stall-recovery", yield* throttled(60_000, T4Stalls.sweep)); const runWatch = yield* T4RunWatch.T4RunWatch; yield* scheduler.register("t4-workflow-runs", yield* throttled(30_000, runWatch.sweep)); + // Each watch keeps its own interval (a minute at the least); the job only looks. + const replyWatch = yield* T4ReplyWatch.T4ReplyWatch; + yield* scheduler.register("t4-reply-watches", yield* throttled(30_000, replyWatch.sweep)); yield* scheduler.register("t4-fyi-digests", yield* throttled(60_000, FyiDigest.sweep)); yield* scheduler.register("t4-release-guard", yield* throttled(120_000, T4ReleaseGuard.sweep)); yield* scheduler.register("t4-release-stale", yield* throttled(600_000, T4Releases.sweepStale)); diff --git a/apps/server/src/t4/T4ReplyWatch.test.ts b/apps/server/src/t4/T4ReplyWatch.test.ts new file mode 100644 index 000000000000..495754d5c4aa --- /dev/null +++ b/apps/server/src/t4/T4ReplyWatch.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as T4Delivery from "./T4Delivery.ts"; +import * as T4ReplyWatch from "./T4ReplyWatch.ts"; +import * as T4Store from "./T4Store.ts"; + +const harness = () => { + const meta = new Map(); + const delivered: Array<{ threadId: string; text: string }> = []; + const ran: Array<{ check: string; cwd: string | undefined }> = []; + const settled = new Set(); + // What the next check prints: stdout, or a failing exit. + const answer = { stdout: "", code: 0, stderr: "" }; + const layer = T4ReplyWatch.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.mock(T4Store.T4Store)({ + meta: (key: string) => Effect.succeed(meta.get(key)), + setMeta: (key: string, value: string) => Effect.sync(() => void meta.set(key, value)), + }), + Layer.mock(T4Delivery.T4Delivery)({ + deliver: (input) => + Effect.sync(() => { + delivered.push({ threadId: input.target.id, text: input.text }); + return { delivery: "started", how: "" } as never; + }), + }), + Layer.mock(ThreadManagementService.ThreadManagementService)({ + getThreadShell: (id) => + Effect.succeed({ + id, + deletedAt: null, + archivedAt: null, + settledOverride: null, + settledAt: settled.has(id) ? "2026-11-23T00:00:00.000Z" : null, + } as never), + }), + Layer.mock(ProcessRunner.ProcessRunner)({ + run: (input) => + Effect.sync(() => { + ran.push({ check: String(input.args[1]), cwd: input.cwd }); + return { ...answer, timedOut: false } as never; + }), + }), + ), + ), + ); + const use = (f: (w: T4ReplyWatch.T4ReplyWatchShape) => Effect.Effect) => + T4ReplyWatch.T4ReplyWatch.pipe(Effect.flatMap(f), Effect.provide(layer)); + return { meta, delivered, ran, settled, answer, use }; +}; + +const dolma = { + threadId: "t-triage", + who: "Dolma", + about: "USA-3097 early-pay terms", + check: "usars chat replies USA-3097 --since 2026-11-23T20:09:43Z --from Dolma", + via: "chat", + cwd: "/srv/Code/usa-rs", + deadlineMs: 3_600_000, + everyMs: 60_000, +}; + +describe("t4 wait_for_reply", () => { + it.effect("checks on its interval and posts the reply once, then ends", () => + Effect.gen(function* () { + const h = harness(); + yield* TestClock.setTime(Date.parse("2026-11-23T20:10:00Z")); + yield* h.use((w) => w.watch(dolma)); + + yield* h.use((w) => w.sweep); + expect(h.ran).toEqual([{ check: dolma.check, cwd: "/srv/Code/usa-rs" }]); + expect(h.delivered).toEqual([]); + + // Within the minute: no second check. + yield* TestClock.adjust("30 seconds"); + yield* h.use((w) => w.sweep); + expect(h.ran).toHaveLength(1); + + h.answer.stdout = + "2026-11-23 12:49 Dolma: Dexter, Vollrath and Vulcan are all JLA and net 30.\n"; + yield* TestClock.adjust("40 seconds"); + yield* h.use((w) => w.sweep); + expect(h.ran).toHaveLength(2); + expect(h.delivered).toHaveLength(1); + expect(h.delivered[0]!.threadId).toBe("t-triage"); + expect(h.delivered[0]!.text).toContain("REPLY from Dolma (USA-3097 early-pay terms)"); + expect(h.delivered[0]!.text).toContain("all JLA and net 30"); + expect(yield* h.use((w) => w.watches)).toEqual([]); + + yield* TestClock.adjust("5 minutes"); + yield* h.use((w) => w.sweep); + expect(h.ran).toHaveLength(2); + }), + ); + + it.effect("tells the thread when nobody replied by the deadline", () => + Effect.gen(function* () { + const h = harness(); + yield* TestClock.setTime(Date.parse("2026-11-23T20:10:00Z")); + yield* h.use((w) => w.watch({ ...dolma, deadlineMs: 5 * 60_000 })); + yield* h.use((w) => w.sweep); + yield* TestClock.adjust("5 minutes"); + yield* h.use((w) => w.sweep); + expect(h.delivered).toHaveLength(1); + expect(h.delivered[0]!.text).toContain( + "NO REPLY from Dolma (USA-3097 early-pay terms) by Mon 12:15 PM PT", + ); + expect(yield* h.use((w) => w.watches)).toEqual([]); + }), + ); + + it.effect("ends a check that keeps failing, with its error", () => + Effect.gen(function* () { + const h = harness(); + yield* TestClock.setTime(Date.parse("2026-11-23T20:10:00Z")); + Object.assign(h.answer, { code: 2, stderr: "usars: unknown command 'chat'" }); + yield* h.use((w) => w.watch(dolma)); + for (let i = 0; i < 5; i++) { + yield* h.use((w) => w.sweep); + yield* TestClock.adjust("61 seconds"); + } + expect(h.ran).toHaveLength(5); + expect(h.delivered).toHaveLength(1); + expect(h.delivered[0]!.text).toContain("failed 5 times in a row"); + expect(h.delivered[0]!.text).toContain("unknown command 'chat'"); + }), + ); + + it.effect("replaces a watch on the same person, cancels, and drops a settled thread's", () => + Effect.gen(function* () { + const h = harness(); + const first = yield* h.use((w) => w.watch(dolma)); + expect(first.replaced).toBe(false); + const again = yield* h.use((w) => w.watch({ ...dolma, who: "dolma", deadlineMs: 7_200_000 })); + expect(again.replaced).toBe(true); + expect(yield* h.use((w) => w.watches)).toHaveLength(1); + + yield* h.use((w) => w.watch({ ...dolma, who: "Korin" })); + const gone = yield* h.use((w) => w.cancel("t-triage", "Korin")); + expect(gone.map((w) => w.who)).toEqual(["Korin"]); + + h.settled.add("t-triage"); + yield* h.use((w) => w.sweep); + expect(h.ran).toEqual([]); + expect(h.delivered).toEqual([]); + expect(yield* h.use((w) => w.watches)).toEqual([]); + }), + ); + + it("reads durations", () => { + expect(T4ReplyWatch.parseDuration("5m")).toBe(300_000); + expect(T4ReplyWatch.parseDuration("2h")).toBe(7_200_000); + expect(T4ReplyWatch.parseDuration("3d")).toBe(259_200_000); + expect(T4ReplyWatch.parseDuration("30")).toBe(1_800_000); + expect(T4ReplyWatch.parseDuration("soon")).toBeNull(); + expect(T4ReplyWatch.defaultEvery(3_600_000)).toBe(60_000); + expect(T4ReplyWatch.defaultEvery(2 * 86_400_000)).toBe(300_000); + }); +}); diff --git a/apps/server/src/t4/T4ReplyWatch.ts b/apps/server/src/t4/T4ReplyWatch.ts new file mode 100644 index 000000000000..06e9db96d79c --- /dev/null +++ b/apps/server/src/t4/T4ReplyWatch.ts @@ -0,0 +1,331 @@ +/** + * t4 fork (AI-143): wake a thread when someone outside t4 answers. t4 runs the thread's check (a + * command that prints the reply once it exists) on an interval and posts one message on the + * reply, at the deadline, or when the check keeps failing. Watches live in t4_meta. + */ +import { ThreadId } from "@t3tools/contracts"; +import * as Clock from "effect/Clock"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as Semaphore from "effect/Semaphore"; + +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import * as ProcessRunner from "../processRunner.ts"; +import * as T4Delivery from "./T4Delivery.ts"; +import * as T4Store from "./T4Store.ts"; + +const META_KEY = "reply-watches"; +const MAX_PER_THREAD = 5; +/** A check that fails this many times in a row ends the watch with a note. */ +const MAX_FAILURES = 5; +const OUTPUT_CAP = 8_000; +export const MIN_EVERY_MS = 60_000; +export const MAX_EVERY_MS = 60 * 60_000; +export const MAX_DEADLINE_MS = 14 * 86_400_000; + +const Watch = Schema.Struct({ + threadId: Schema.String, + who: Schema.String, + about: Schema.NullOr(Schema.String), + check: Schema.String, + /** How the check reaches them, for the dashboard ("email", "usa-rs chat", ...). */ + via: Schema.NullOr(Schema.String), + cwd: Schema.NullOr(Schema.String), + since: Schema.Number, + deadline: Schema.Number, + everyMs: Schema.Number, + lastCheck: Schema.Number, + failures: Schema.Number, + lastError: Schema.NullOr(Schema.String), +}); +export type Watch = typeof Watch.Type; +const Watches = Schema.fromJsonString(Schema.Array(Watch)); +const decodeWatches = Schema.decodeUnknownEffect(Watches); +const encodeWatches = Schema.encodeEffect(Watches); + +export class T4ReplyWatchError extends Schema.TaggedError()( + "T4ReplyWatchError", + { message: Schema.String }, +) {} + +const PACIFIC = new Intl.DateTimeFormat("en-US", { + timeZone: "America/Los_Angeles", + weekday: "short", + hour: "numeric", + minute: "2-digit", +}); +/** "Mon 2:40 PM PT" - the user reads these notes, and the user reads Pacific (AI-142). */ +export const pacific = (ms: number) => `${PACIFIC.format(ms)} PT`; + +/** "90s", "5m", "1h", "2d" (or a bare number of minutes) to milliseconds. */ +export const parseDuration = (text: string): number | null => { + const m = /^\s*(\d+(?:\.\d+)?)\s*(s|m|min|h|d|w)?\s*$/i.exec(text); + if (m === null) return null; + const n = Number(m[1]); + const unit = (m[2] ?? "m").toLowerCase(); + const scale = + unit === "s" + ? 1_000 + : unit === "h" + ? 3_600_000 + : unit === "d" + ? 86_400_000 + : unit === "w" + ? 604_800_000 + : 60_000; + return Math.round(n * scale); +}; + +/** One check a minute while the wait is short (staff answer within the hour), five after. */ +export const defaultEvery = (deadlineMs: number) => + deadlineMs <= 3 * 3_600_000 ? MIN_EVERY_MS : 5 * MIN_EVERY_MS; + +const clip = (text: string, cap: number) => + text.length > cap ? `${text.slice(0, cap)}\n[cut at ${cap.toLocaleString()} characters]` : text; + +const label = (w: Watch) => `${w.who}${w.about ? ` (${w.about})` : ""}`; + +const replyMessage = (w: Watch, output: string) => + [ + `REPLY from ${label(w)} - your wait_for_reply check found it:`, + "", + clip(output.trim(), OUTPUT_CAP), + "", + "The watch has ended. Act on the reply now; to wait for another answer, call wait_for_reply again.", + ].join("\n"); + +const deadlineMessage = (w: Watch) => + [ + `NO REPLY from ${label(w)} by ${pacific(w.deadline)} (asked ${pacific(w.since)}); the watch has ended.`, + `Check: \`${w.check}\``, + "Decide what's next: follow up with them and wait again, or bring it to the user as a card (wait longer, or go ahead without the answer).", + ].join("\n"); + +const failingMessage = (w: Watch) => + [ + `The wait_for_reply check for ${label(w)} failed ${MAX_FAILURES} times in a row, so the watch has ended.`, + `Check: \`${w.check}\``, + `Last error: ${clip(w.lastError ?? "(no output)", 600)}`, + "Fix the command (run it yourself first) and call wait_for_reply again.", + ].join("\n"); + +export interface T4ReplyWatchShape { + /** Starts (or replaces: same thread and `who`) a watch. */ + readonly watch: (input: { + readonly threadId: string; + readonly who: string; + readonly about: string | null; + readonly check: string; + readonly via: string | null; + readonly cwd: string | null; + readonly deadlineMs: number; + readonly everyMs: number; + }) => Effect.Effect<{ readonly watch: Watch; readonly replaced: boolean }, T4ReplyWatchError>; + /** Ends a thread's watches - one by `who`, or all of them. */ + readonly cancel: (threadId: string, who: string | null) => Effect.Effect>; + readonly sweep: Effect.Effect; + readonly watches: Effect.Effect>; +} + +export class T4ReplyWatch extends Context.Service()( + "t3/t4/T4ReplyWatch", +) {} + +const sameWho = (a: string, b: string) => a.trim().toLowerCase() === b.trim().toLowerCase(); + +const make = Effect.gen(function* () { + const store = yield* T4Store.T4Store; + const delivery = yield* T4Delivery.T4Delivery; + const threads = yield* ThreadManagementService.ThreadManagementService; + const processes = yield* ProcessRunner.ProcessRunner; + const lock = yield* Semaphore.make(1); + + const load = store.meta(META_KEY).pipe( + Effect.flatMap((text) => (text === undefined ? Effect.succeed([]) : decodeWatches(text))), + Effect.orElseSucceed((): ReadonlyArray => []), + ); + const save = (list: ReadonlyArray) => + encodeWatches(list).pipe( + Effect.flatMap((text) => store.setMeta(META_KEY, text)), + Effect.ignore, + ); + + const watch: T4ReplyWatchShape["watch"] = Effect.fn("t4.T4ReplyWatch.watch")(function* (input) { + const now = yield* Clock.currentTimeMillis; + return yield* lock.withPermits(1)( + Effect.gen(function* () { + const all = yield* load; + const mine = all.filter((w) => w.threadId === input.threadId); + const replaced = mine.some((w) => sameWho(w.who, input.who)); + if (!replaced && mine.length >= MAX_PER_THREAD) { + return yield* new T4ReplyWatchError({ + message: `this thread already waits on ${MAX_PER_THREAD} people (${mine.map((w) => w.who).join(", ")}); cancel one first`, + }); + } + const next: Watch = { + threadId: input.threadId, + who: input.who, + about: input.about, + check: input.check, + via: input.via, + cwd: input.cwd, + since: now, + deadline: now + input.deadlineMs, + everyMs: input.everyMs, + // The first check runs at the next sweep. + lastCheck: 0, + failures: 0, + lastError: null, + }; + yield* save([ + ...all.filter((w) => !(w.threadId === input.threadId && sameWho(w.who, input.who))), + next, + ]); + return { watch: next, replaced }; + }), + ); + }); + + const cancel: T4ReplyWatchShape["cancel"] = (threadId, who) => + lock.withPermits(1)( + Effect.gen(function* () { + const all = yield* load; + const gone = all.filter( + (w) => w.threadId === threadId && (who === null || sameWho(w.who, who)), + ); + if (gone.length > 0) yield* save(all.filter((w) => !gone.includes(w))); + return gone; + }), + ); + + const runCheck = (w: Watch) => + processes + .run({ + command: "bash", + // BASH_ENV (/etc/t4-env.sh) loads the client's keys and t4's helpers. + args: ["-c", w.check], + ...(w.cwd === null ? {} : { cwd: w.cwd }), + timeout: "90 seconds", + timeoutBehavior: "timedOutResult", + }) + .pipe( + Effect.map((result) => + result.timedOut + ? ({ kind: "failed", error: "the check ran past 90 seconds" } as const) + : result.code !== 0 + ? ({ + kind: "failed", + error: `exit ${result.code}: ${(result.stderr || result.stdout).trim()}`.slice( + 0, + 600, + ), + } as const) + : result.stdout.trim().length > 0 + ? ({ kind: "reply", output: result.stdout } as const) + : ({ kind: "none" } as const), + ), + Effect.catch((cause) => Effect.succeed({ kind: "failed", error: String(cause) } as const)), + ); + + /** Gone, archived or settled: nobody to wake, and a message would reopen a settled thread. */ + const liveTarget = (threadId: string) => + threads.getThreadShell(ThreadId.make(threadId)).pipe( + Effect.map((target) => + target === null || + target.deletedAt !== null || + target.archivedAt !== null || + target.settledOverride === "settled" || + target.settledAt != null + ? null + : target, + ), + Effect.orElseSucceed(() => null), + ); + + const post = (threadId: string, text: string) => + liveTarget(threadId).pipe( + Effect.flatMap((target) => + target === null + ? Effect.void + : delivery + .deliver({ + target, + text, + force: true, + // Waits for a running turn to end instead of cutting its command. + patient: true, + createdBy: "system", + creationSource: "server", + }) + .pipe(Effect.asVoid), + ), + Effect.ignore, + ); + + const sweep: T4ReplyWatchShape["sweep"] = Effect.gen(function* () { + const list = yield* load; + if (list.length === 0) return; + const now = yield* Clock.currentTimeMillis; + const ended = new Set(); + const updated = new Map(); + for (const w of list) { + if ((yield* liveTarget(w.threadId)) === null) { + ended.add(w); + continue; + } + if (now - w.lastCheck < w.everyMs && now < w.deadline) continue; + const result = yield* runCheck(w); + if (result.kind === "reply") { + ended.add(w); + yield* post(w.threadId, replyMessage(w, result.output)); + yield* Effect.logInfo("t4.reply-watch-replied", { + threadId: w.threadId, + who: w.who, + waitedMinutes: Math.round((now - w.since) / 60_000), + }); + continue; + } + if (result.kind === "failed" && w.failures + 1 >= MAX_FAILURES) { + ended.add(w); + yield* post(w.threadId, failingMessage({ ...w, lastError: result.error })); + yield* Effect.logWarning("t4.reply-watch-failing", { + threadId: w.threadId, + who: w.who, + error: result.error, + }); + continue; + } + if (now >= w.deadline) { + ended.add(w); + yield* post(w.threadId, deadlineMessage(w)); + yield* Effect.logInfo("t4.reply-watch-deadline", { threadId: w.threadId, who: w.who }); + continue; + } + updated.set(w, { + ...w, + lastCheck: now, + failures: result.kind === "failed" ? w.failures + 1 : 0, + lastError: result.kind === "failed" ? result.error : null, + }); + } + if (ended.size === 0 && updated.size === 0) return; + yield* lock.withPermits(1)( + Effect.gen(function* () { + // Re-read: a watch started or cancelled while the checks ran stays as the tool left it. + const latest = yield* load; + const key = (w: Watch) => `${w.threadId}\u0000${w.who.toLowerCase()}\u0000${w.since}`; + const endedKeys = new Set([...ended].map(key)); + const updates = new Map([...updated].map(([before, after]) => [key(before), after])); + yield* save( + latest.filter((w) => !endedKeys.has(key(w))).map((w) => updates.get(key(w)) ?? w), + ); + }), + ); + }).pipe(Effect.ignoreCause({ log: true })); + + return T4ReplyWatch.of({ watch, cancel, sweep, watches: load }); +}); + +export const layer = Layer.effect(T4ReplyWatch, make); diff --git a/apps/server/src/t4/layer.ts b/apps/server/src/t4/layer.ts index a42b22fa1a00..b2ba6c8bbc8d 100644 --- a/apps/server/src/t4/layer.ts +++ b/apps/server/src/t4/layer.ts @@ -6,12 +6,13 @@ import * as Layer from "effect/Layer"; import * as T4Config from "./T4Config.ts"; import * as T4Delivery from "./T4Delivery.ts"; import * as T4Ledger from "./T4Ledger.ts"; +import * as T4ReplyWatch from "./T4ReplyWatch.ts"; import * as T4RunWatch from "./T4RunWatch.ts"; import * as T4Settle from "./T4Settle.ts"; import * as T4Sql from "./T4Sql.ts"; import * as T4Store from "./T4Store.ts"; -export const layer = Layer.merge(T4Settle.layer, T4RunWatch.layer).pipe( +export const layer = Layer.mergeAll(T4Settle.layer, T4RunWatch.layer, T4ReplyWatch.layer).pipe( Layer.provideMerge(T4Delivery.layer), Layer.provideMerge(T4Ledger.layer), // T4Store gets t4's own database; nothing else sees that SqlClient. diff --git a/docs/t4/DESIGN.md b/docs/t4/DESIGN.md index c3e05c2bd2be..3f0f88cd6b40 100644 --- a/docs/t4/DESIGN.md +++ b/docs/t4/DESIGN.md @@ -37,11 +37,12 @@ unchanged. ### New T3 tools -| Tool | From | Behaviour | -| -------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `t3_handoff` | `cmd_handoff`, `settle_owed`, `record_handoff`, `find_rm` | Hand work over with an explicit ledger effect. Parameters: `message`, `threadId?`, `done?`, `ask?`, `fyi?`, `interrupt?`, `check?`, `includeRetired?`. Without `threadId`: to the project's release manager, always `ask` (the RM itself is refused; `fyi` refused); if none exists, create `Release manager — ` on the RM model, pin it, record it, and deliver intro + handoff as its first turn. With `threadId`: one of `done`/`ask`/`fyi` required, `fyi`+`ask` refused, self refused; an owner's handoff to a release manager is forced to `ask` (with the note). `done` settles every open entry from target→caller. Header `HANDOFF from "" (<short>, <where>) — <labels>:`; reply footer when asking (not to a release manager, whose handoffs and run-watch wakes open with its queue and the threads it owes instead). Non-asking deliveries are recorded as notices; a pure `fyi` waits for a running turn to end, `done`/`ask` steer in. A repeat with the same `clientRequestId`, or the same message within an hour, returns the first result. `ask` opens or updates the single (from, to) entry. Result: delivery mode, entries settled, "now owes you", and "you still owe them". `check` returns the release manager or none. | -| `t3_owed` | `cmd_owed`, `requester_closed` | What the caller owes (or, with `all`, the whole project), oldest first; debts to a settled, archived or deleted asker are void and omitted. | -| `t3_decisions` | `cmd_decisions` | The user's answers to ask-user questions over `days` (default 14), this project or `all`, newest first; an answer that isn't an offered option is reported as a note (a standing rule). | +| Tool | From | Behaviour | +| ---------------- | --------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `t3_handoff` | `cmd_handoff`, `settle_owed`, `record_handoff`, `find_rm` | Hand work over with an explicit ledger effect. Parameters: `message`, `threadId?`, `done?`, `ask?`, `fyi?`, `interrupt?`, `check?`, `includeRetired?`. Without `threadId`: to the project's release manager, always `ask` (the RM itself is refused; `fyi` refused); if none exists, create `Release manager — <project>` on the RM model, pin it, record it, and deliver intro + handoff as its first turn. With `threadId`: one of `done`/`ask`/`fyi` required, `fyi`+`ask` refused, self refused; an owner's handoff to a release manager is forced to `ask` (with the note). `done` settles every open entry from target→caller. Header `HANDOFF from "<title>" (<short>, <where>) — <labels>:`; reply footer when asking (not to a release manager, whose handoffs and run-watch wakes open with its queue and the threads it owes instead). Non-asking deliveries are recorded as notices; a pure `fyi` waits for a running turn to end, `done`/`ask` steer in. A repeat with the same `clientRequestId`, or the same message within an hour, returns the first result. `ask` opens or updates the single (from, to) entry. Result: delivery mode, entries settled, "now owes you", and "you still owe them". `check` returns the release manager or none. | +| `t3_owed` | `cmd_owed`, `requester_closed` | What the caller owes (or, with `all`, the whole project), oldest first; debts to a settled, archived or deleted asker are void and omitted. | +| `t3_decisions` | `cmd_decisions` | The user's answers to ask-user questions over `days` (default 14), this project or `all`, newest first; an answer that isn't an offered option is reported as a note (a standing rule). | +| `wait_for_reply` | (new, AI-143) | A thread waiting on someone outside t4 (customer, supplier, staff): `who`, `about?`, and `check` (a shell command that prints the reply once it exists, nothing before, and returns at once) or `email` (`from` / `thread`, built into `email replies --since <now> ...`), `deadline?` (1m-14d; default 1h, 2d for email), `every?` (1m-60m; default 1m up to a 3h wait, else 5m), `cancel?`. Same `who` replaces the watch; at most 5 per thread. Stored in `t4_meta` (`reply-watches`); the `t4-reply-watches` job runs each due check with `bash -c` in the thread's checkout (BASH_ENV gives it the client's keys and t4's helpers, 90 s timeout) and posts one message: `REPLY from ...` with the output, `NO REPLY ... by <deadline PT>`, or after 5 failures in a row the error. A settled, archived or deleted thread's watches are dropped silently. `/api/t4/state` lists them as `replyWatches`; the dashboard's "Waiting on a reply" lane. | ### Linked issues (Linear)