Public: anyone can read this; the crew can change it.
Watches: let Talk's agent put itself in a loop, woken by a free computed chec… #16562
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/16557-watches-let-talk-s-agent-put-itself-in-a → main 0 commits fork 3 threads · 3 unresolved
19 files
changed +860
−25
- docs/features/talk-captain.md
- forge.json
- src/core/migration-pins/20261127110000-talk-watch.pin
- src/core/migrations/20261127110000-talk-watch.ts
- src/core/talk_watch.ts
- src/crew/captain_thread.ts
- src/crew/conversation_ask.ts
- src/crew/conversation_confirm.ts
- src/crew/routines.ts
- src/crew/watches.ts
- src/http/mcp/tools/index.ts
- src/http/mcp/tools/talk_watch.ts
- src/tui/screens/captain.ts
- src/web/pages/captain.ts
- test/conversation-ask.test.ts
- test/forge-looks.test.ts
- test/mcp-forge-protocol.test.ts
- test/mixed-actions-held.test.ts
- test/talk-watch.test.ts
docs/features/talk-captain.md +2 −1
| @@ -9,9 +9,10 @@ Talk is where the forge's owner steers it. What the owner used to do in a Claude | ||
| 9 | 9 | - **Instructions.** In Talk a message that asks for work is an instruction acted on at once, with the person's own powers through the MCP and within what their role allows: file issues, assign, steer, reopen parked pulls, merge, lend credit. How the agent answers (the answer first, depth when asked, results shown, how each thing is known) is in `docs/features/talk-voice.md`. Real money, DNS and a dark roll are held as a write with Do it and Not now buttons in the thread (`crew/conversation_brief.ts`, `crew/conversation_confirm.ts`). |
| 10 | 10 | - **Memory** (`core/talk_memory.ts`, Settings › Captain, `/settings/captain`). Short durable rules and decisions, up to 60 of 400 characters. Every Talk turn carries them in its system prompt (`memoryBrief`). The first visit offers the starting rules (never `rm`, tokens off argv, never dark without a go, ask first on money, DNS and a dark roll); delete them and they stay gone. |
| 11 | 11 | - **Routines** (`core/talk_routines.ts`, `crew/routines.ts`, `crew/routine_report.ts`). The hourly forge check-in, the friends watch and the morning paper, each with an editable schedule: every 15 to 1440 minutes, or daily at an hour (UTC). Each posts at most three lines into the owner's **Captain** thread; only a report that says something needs the owner reaches the phone (the notify URL, `crew/notify.ts`). The lines are computed, not written by a model, so a routine costs no spend. A forge that was down runs an owed routine once on waking. **Post now** on the settings page runs one at once. |
| 12 | - **Watches** (`core/talk_watch.ts`, `crew/watches.ts`, `http/mcp/tools/talk_watch.ts`, #16557). A fourth routine kind: a short brief the agent leaves itself and what it waits for, as data the forge reads without a model: a pull is green, landed or changed (`pull_green`, `pull_landed`, `pull_changed`), a run ended (`run_ended`), an issue gained a comment (`issue_comment`), a check on main turned green (`main_green`), a pull merged (`merge_since`). "Done" is stated up front (`pull trevato/forge#16532 landed`). Each look (every 5 minutes by default, on the routines' minute clock) is free: nothing changed means nothing happens and nothing is spent. A change starts one ordinary Talk turn as the owner through `talk()` in the Captain thread, with the brief, the change and the memory, so the same limits apply (12 a minute, the account's budget, resting); a refused turn is tried again at the next look. A forge that was down looks once on waking, so it wakes once. The forge, not the agent, ends a watch: when its condition is met, at 7 days ("ran out"), or at its spend cap (default $2, at most $20; what its wake turns cost, found by the `[Watch <id>]` mark each starts with); each says so in one line in the thread. Safety: only the owner (a site admin who is a person) has one; at most 5 live; the agent may only propose one with the `talk_watch` tool, which is held for a Do it like money (`crew/conversation_confirm.ts`); a watch's own turn cannot start another (`wakeRunning`); a watch's turn has the owner's role at most and every write stays held as before. The owner lists, adds, pauses, deletes and ends them in Settings › Captain and in the terminal screen (`w` adds `pull_green owner/name#123: brief`, `p` pauses, `e` is Ends now, `d` deletes), each showing what it waits for, when it last looked, its wakes and what it has spent. | |
| 12 | 13 | - **Resume.** A thread resumes its Claude session (#10457). When the last turn left the context 85% full, the next turn starts a fresh session from the thread's stored record and the memory, and the thread says so (`CONTEXT_RENEWED_LINE`). |
| 13 | 14 | - **Terminal** (`tui/screens/captain.ts`, palette › Captain, owner only). The rules, then the three routines, in one list. `a` adds a rule; `enter` edits the rule or the routine's schedule under the cursor; `d` deletes a rule; `space` turns a routine on or off; `p` posts a routine now; `r` reads again. A schedule is typed as minutes, `45` for every 45 minutes (15 to 1440), or `at 7` (also `daily 7`) for daily at 07:00 UTC. |
| 14 | 15 | |
| 15 | 16 | The check-in also names the releases cut since the last one and the pillars that merged work (`crew/routine_facts_story.ts`), in one clause of its third line, since the last check-in (`lastAt`; the git changelog is cached by head oid, so this costs a `rev-parse` between releases); it never reaches the phone for that alone. |
| 16 | 17 | |
| 17 | Not here yet: child forges stuck. | |
| 18 | Not here yet: child forges stuck; a watch on a kind of change not listed above. |
forge.json +2 −2
| @@ -23,8 +23,8 @@ | ||
| 23 | 23 | { "name": "heartbeat", "cron": "5 7 * * *", "timezone": "UTC", "path": "/jobs/heartbeat", "timeout": 120, "retries": 3, "catchUp": "6h" } |
| 24 | 24 | ], |
| 25 | 25 | "app": { |
| 26 | "looks": ["/", "/docs", "/explore", "/board", "/notes", "/review", "/changelog", "/apps", "/security", "/system", "/admin/limits", "/maintenance", "/talk", "/flow", "/resilience", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/cut-over", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space", "/looks/missing", "/looks/failed", "/nope/nothing"], | |
| 27 | "looksAsOwner": ["/", "/board", "/flow", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/security/controls", "/settings/grants", "/talk", "/system", "/admin/limits", "/maintenance", "/resilience", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/cut-over", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"], | |
| 26 | "looks": ["/", "/docs", "/explore", "/board", "/notes", "/review", "/changelog", "/apps", "/security", "/system", "/admin/limits", "/maintenance", "/talk", "/flow", "/resilience", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/captain", "/settings/security/controls", "/settings/grants", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/cut-over", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space", "/looks/missing", "/looks/failed"], | |
| 27 | "looksAsOwner": ["/", "/board", "/flow", "/boards?help", "/settings/crew", "/settings/crew?help", "/settings/captain", "/settings/security/controls", "/settings/grants", "/talk", "/system", "/admin/limits", "/maintenance", "/resilience", "/preview-admin/sample", "/preview-admin/sample/drop", "/preview-admin/sample/data-move", "/preview-admin/sample/cut-over", "/preview-admin/sample/pulls/3", "/preview-admin/sample/next?pick", "/preview-admin/sample/bets", "/preview-admin/sample/waves", "/preview-admin/sample/space"], | |
| 28 | 28 | "run": "bun run src/main.ts", |
| 29 | 29 | "install": "", |
| 30 | 30 | "health": "/healthz", |
src/core/migration-pins/20261127110000-talk-watch.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 991a8cff1d37faa3ce1fe48eeb0dab530052e917285a62b7906db1f63d451478 |
src/core/migrations/20261127110000-talk-watch.ts added +25
| @@ -0,0 +1,25 @@ | ||
| 1 | // Watches (#16557): a brief Talk's agent leaves itself and the one thing the forge looks for, free, | |
| 2 | // until it changes. One row a watch; an ended one stays so the Captain list can say how it ended. | |
| 3 | export default ` | |
| 4 | CREATE TABLE IF NOT EXISTS talk_watch ( | |
| 5 | id TEXT PRIMARY KEY, | |
| 6 | user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, | |
| 7 | brief TEXT NOT NULL, | |
| 8 | kind TEXT NOT NULL, | |
| 9 | target TEXT NOT NULL, | |
| 10 | done_state TEXT, | |
| 11 | baseline TEXT NOT NULL DEFAULT '', | |
| 12 | every_min INTEGER NOT NULL DEFAULT 5, | |
| 13 | state TEXT NOT NULL DEFAULT 'live' CHECK (state IN ('live','paused','met','ran_out','spent','ended')), | |
| 14 | created_at TEXT NOT NULL, | |
| 15 | expires_at TEXT NOT NULL, | |
| 16 | last_look_at TEXT, | |
| 17 | last_wake_at TEXT, | |
| 18 | wakes INTEGER NOT NULL DEFAULT 0, | |
| 19 | spent_usd REAL NOT NULL DEFAULT 0, | |
| 20 | cap_usd REAL NOT NULL, | |
| 21 | ended_at TEXT, | |
| 22 | ended_line TEXT NOT NULL DEFAULT '' | |
| 23 | ); | |
| 24 | CREATE INDEX IF NOT EXISTS talk_watch_by_person ON talk_watch(user_id, created_at); | |
| 25 | `; |
src/core/talk_watch.ts added +272
| @@ -0,0 +1,272 @@ | ||
| 1 | /** | |
| 2 | * Watches (#16557): a short brief Talk's agent leaves itself, and what it waits for, as data the | |
| 3 | * forge reads without a model: a pull is green or landed or changed, a run ended, an issue gained a | |
| 4 | * comment, a check on main turned green, a pull merged. `readWatch` is the free look; the runner is | |
| 5 | * `crew/watches.ts`. Every limit lives here, not in the agent's word: at most `WATCH_MAX` live, a | |
| 6 | * spend cap each, a longest age, and only the forge's owner (a site admin who is a person) has one. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { Database } from "bun:sqlite"; | |
| 10 | import { id } from "../kernel/id.ts"; | |
| 11 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 12 | import { getIssue } from "./issues.ts"; | |
| 13 | import { getRun } from "./runs.ts"; | |
| 14 | import { canRead, getRepo, getRepoById, type Repo } from "./repos.ts"; | |
| 15 | import type { User } from "./users.ts"; | |
| 16 | ||
| 17 | export const WATCH_KINDS = ["pull_green", "pull_landed", "pull_changed", "run_ended", "issue_comment", "main_green", "merge_since"] as const; | |
| 18 | export type WatchKind = (typeof WATCH_KINDS)[number]; | |
| 19 | ||
| 20 | export const WATCH_MAX = 5; | |
| 21 | export const WATCH_DAYS = 7; | |
| 22 | export const WATCH_BRIEF_MAX = 400; | |
| 23 | export const CAP_DEFAULT = 2; | |
| 24 | export const CAP_MAX = 20; | |
| 25 | export const EVERY_DEFAULT = 5; | |
| 26 | export const EVERY_MIN_WATCH = 5; | |
| 27 | export const EVERY_MAX_WATCH = 1440; | |
| 28 | /** How many ended watches the list keeps to say how they ended. */ | |
| 29 | export const ENDED_KEPT = 10; | |
| 30 | /** Every wake's text starts with this: how a running turn is known to be a watch's. */ | |
| 31 | export const WAKE_MARK = "[Watch "; | |
| 32 | ||
| 33 | /** What each kind waits for, with the target it takes. */ | |
| 34 | export const KIND_WORDS: Readonly<Record<WatchKind, { target: string; says: (t: string) => string }>> = { | |
| 35 | pull_green: { target: "owner/name#number", says: (t) => `pull ${t} is green` }, | |
| 36 | pull_landed: { target: "owner/name#number", says: (t) => `pull ${t} landed` }, | |
| 37 | pull_changed: { target: "owner/name#number", says: (t) => `pull ${t} changed` }, | |
| 38 | run_ended: { target: "a run id", says: (t) => `run ${t} ended` }, | |
| 39 | issue_comment: { target: "owner/name#number", says: (t) => `${t} gained a comment` }, | |
| 40 | main_green: { target: "owner/name", says: (t) => `a check on ${t}'s main turned green` }, | |
| 41 | merge_since: { target: "owner/name", says: (t) => `a pull merged into ${t}` }, | |
| 42 | }; | |
| 43 | ||
| 44 | /** The states each kind may end on, the first being its default; none means it ends only by age. */ | |
| 45 | const DONE: Readonly<Record<WatchKind, readonly string[]>> = { | |
| 46 | pull_green: ["green", "landed"], | |
| 47 | pull_landed: ["landed"], | |
| 48 | pull_changed: ["landed"], | |
| 49 | run_ended: ["ended"], | |
| 50 | issue_comment: [], | |
| 51 | main_green: ["green"], | |
| 52 | merge_since: ["merged"], | |
| 53 | }; | |
| 54 | ||
| 55 | const DEFAULT_DONE: Readonly<Partial<Record<WatchKind, string>>> = { pull_green: "green", pull_landed: "landed", run_ended: "ended", main_green: "green", merge_since: "merged" }; | |
| 56 | ||
| 57 | export type WatchState = "live" | "paused" | "met" | "ran_out" | "spent" | "ended"; | |
| 58 | ||
| 59 | export interface Watch { | |
| 60 | readonly id: string; | |
| 61 | readonly userId: string; | |
| 62 | readonly brief: string; | |
| 63 | readonly kind: WatchKind; | |
| 64 | readonly target: string; | |
| 65 | readonly doneState: string | null; | |
| 66 | readonly baseline: string; | |
| 67 | readonly everyMin: number; | |
| 68 | readonly state: WatchState; | |
| 69 | readonly createdAt: string; | |
| 70 | readonly expiresAt: string; | |
| 71 | readonly lastLookAt: string | null; | |
| 72 | readonly lastWakeAt: string | null; | |
| 73 | readonly wakes: number; | |
| 74 | readonly spentUsd: number; | |
| 75 | readonly capUsd: number; | |
| 76 | readonly endedAt: string | null; | |
| 77 | readonly endedLine: string; | |
| 78 | } | |
| 79 | ||
| 80 | interface Row { | |
| 81 | id: string; | |
| 82 | user_id: string; | |
| 83 | brief: string; | |
| 84 | kind: WatchKind; | |
| 85 | target: string; | |
| 86 | done_state: string | null; | |
| 87 | baseline: string; | |
| 88 | every_min: number; | |
| 89 | state: WatchState; | |
| 90 | created_at: string; | |
| 91 | expires_at: string; | |
| 92 | last_look_at: string | null; | |
| 93 | last_wake_at: string | null; | |
| 94 | wakes: number; | |
| 95 | spent_usd: number; | |
| 96 | cap_usd: number; | |
| 97 | ended_at: string | null; | |
| 98 | ended_line: string; | |
| 99 | } | |
| 100 | ||
| 101 | const of = (r: Row): Watch => ({ | |
| 102 | id: r.id, userId: r.user_id, brief: r.brief, kind: r.kind, target: r.target, doneState: r.done_state, baseline: r.baseline, everyMin: r.every_min, state: r.state, | |
| 103 | createdAt: r.created_at, expiresAt: r.expires_at, lastLookAt: r.last_look_at, lastWakeAt: r.last_wake_at, wakes: r.wakes, spentUsd: r.spent_usd, capUsd: r.cap_usd, endedAt: r.ended_at, endedLine: r.ended_line, | |
| 104 | }); | |
| 105 | ||
| 106 | /** What the watch waits for and when it ends, in one clause: stated up front. */ | |
| 107 | export const waitsText = (w: Pick<Watch, "kind" | "target" | "doneState">): string => { | |
| 108 | const says = KIND_WORDS[w.kind].says(w.target); | |
| 109 | return w.doneState === null ? `${says} (until it runs out)` : w.doneState === DEFAULT_DONE[w.kind] ? says : `${says}; done when it ${w.doneState}`; | |
| 110 | }; | |
| 111 | ||
| 112 | export function listWatches(db: Database, userId: string): Watch[] { | |
| 113 | return db.query<Row, [string]>("SELECT * FROM talk_watch WHERE user_id = ?1 ORDER BY created_at").all(userId).map(of); | |
| 114 | } | |
| 115 | ||
| 116 | export function getWatch(db: Database, userId: string, watchId: string): Watch | undefined { | |
| 117 | const r = db.query<Row, [string, string]>("SELECT * FROM talk_watch WHERE id = ?1 AND user_id = ?2").get(watchId, userId); | |
| 118 | return r === null ? undefined : of(r); | |
| 119 | } | |
| 120 | ||
| 121 | /** Every watch that is live, for the runner: all people's. */ | |
| 122 | export const liveWatches = (db: Database): Watch[] => db.query<Row, []>("SELECT * FROM talk_watch WHERE state = 'live'").all().map(of); | |
| 123 | ||
| 124 | /** | |
| 125 | * Whether a Talk turn of this person is a watch's waking now: a watch's turn may not start another. | |
| 126 | */ | |
| 127 | export const wakeRunning = (db: Database, userId: string): boolean => | |
| 128 | db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM conversation_run WHERE user_id = ?1 AND state = 'running' AND prompt LIKE '[Watch %'").get(userId)!.n > 0; | |
| 129 | ||
| 130 | export type WatchError = "not_owner" | "bad_brief" | "bad_kind" | "bad_target" | "bad_done" | "bad_cap" | "bad_every" | "too_many" | "from_watch"; | |
| 131 | ||
| 132 | export const WATCH_WORDS: Readonly<Record<WatchError, string>> = { | |
| 133 | not_owner: "Only the forge's owner starts a watch.", | |
| 134 | bad_brief: `Say what to do when it changes, in up to ${WATCH_BRIEF_MAX} characters.`, | |
| 135 | bad_kind: `A watch waits for one of: ${WATCH_KINDS.join(", ")}.`, | |
| 136 | bad_target: "That is not something you can read here; name it as owner/name#number, owner/name or a run id as its kind says.", | |
| 137 | bad_done: "That kind cannot end on that.", | |
| 138 | bad_cap: `The spend cap is more than 0 and at most $${CAP_MAX}.`, | |
| 139 | bad_every: `Look every ${EVERY_MIN_WATCH} to ${EVERY_MAX_WATCH} minutes.`, | |
| 140 | too_many: `You have ${WATCH_MAX} watches live, the most; end one first.`, | |
| 141 | from_watch: "A watch's own turn cannot start another watch.", | |
| 142 | }; | |
| 143 | ||
| 144 | /** | |
| 145 | * What a look found: the signature that changes when something happened, and where the thing | |
| 146 | * stands. | |
| 147 | */ | |
| 148 | export interface Reading { | |
| 149 | readonly sig: string; | |
| 150 | /** Whether this signature is worth waking for; a pull still checking is not. */ | |
| 151 | readonly wake: boolean; | |
| 152 | /** The state the end condition names. */ | |
| 153 | readonly state: string; | |
| 154 | /** In words, computed: what changed. */ | |
| 155 | readonly says: string; | |
| 156 | } | |
| 157 | ||
| 158 | const REF = /^([A-Za-z0-9][\w.-]{0,38})\/([A-Za-z0-9][\w.-]{0,99})(?:#(\d{1,9}))?$/; | |
| 159 | ||
| 160 | function repoOf(db: Database, user: User, owner: string, name: string): Repo | undefined { | |
| 161 | const repo = getRepo(db, owner, name); | |
| 162 | return repo !== undefined && canRead(db, repo, user) ? repo : undefined; | |
| 163 | } | |
| 164 | ||
| 165 | /** | |
| 166 | * The free look at one watch's target as `user` reads it; undefined when it is gone or not theirs | |
| 167 | * to read. No model, no spend. | |
| 168 | */ | |
| 169 | export function readWatch(db: Database, user: User, w: Pick<Watch, "kind" | "target">): Reading | undefined { | |
| 170 | if (w.kind === "run_ended") { | |
| 171 | if (!/^[0-9a-z]{1,40}$/.test(w.target)) return undefined; | |
| 172 | const run = getRun(db, w.target); | |
| 173 | const repo = run === undefined ? undefined : getRepoById(db, run.repoId); | |
| 174 | if (run === undefined || repo === undefined || !canRead(db, repo, user)) return undefined; | |
| 175 | const ended = run.state === "ok" || run.state === "failed" || run.state === "cancelled"; | |
| 176 | return { sig: ended ? `ended:${run.state}` : "running", wake: ended, state: ended ? "ended" : "running", says: `run ${run.id} ended: ${run.state}${run.summary === "" ? "" : ` (${run.summary.slice(0, 120)})`}` }; | |
| 177 | } | |
| 178 | const m = REF.exec(w.target); | |
| 179 | if (m === null) return undefined; | |
| 180 | const repo = repoOf(db, user, m[1]!, m[2]!); | |
| 181 | if (repo === undefined) return undefined; | |
| 182 | const label = `${m[1]}/${m[2]}`; | |
| 183 | if (w.kind === "main_green") { | |
| 184 | const last = db | |
| 185 | .query<{ id: string; state: string }, [string, string]>("SELECT id, state FROM run WHERE repo_id = ?1 AND kind = 'check' AND issue_id IS NULL AND env = ?2 AND state IN ('ok','failed') ORDER BY id DESC LIMIT 1") | |
| 186 | .get(repo.id, repo.defaultBranch); | |
| 187 | if (last === null) return { sig: "none", wake: false, state: "none", says: "no finished check on main yet" }; | |
| 188 | return last.state === "ok" | |
| 189 | ? { sig: `green:${last.id}`, wake: true, state: "green", says: `a check on ${label}'s main turned green (run ${last.id})` } | |
| 190 | : { sig: `red:${last.id}`, wake: false, state: "red", says: `main of ${label} is red` }; | |
| 191 | } | |
| 192 | if (w.kind === "merge_since") { | |
| 193 | const last = db | |
| 194 | .query<{ at: string | null }, [string]>("SELECT MAX(p.merged_at) AS at FROM pull p JOIN issue i ON i.id = p.issue_id WHERE i.repo_id = ?1 AND p.merged_at IS NOT NULL") | |
| 195 | .get(repo.id)?.at ?? null; | |
| 196 | return { sig: `merged:${last ?? ""}`, wake: last !== null, state: "merged", says: `a pull merged into ${label} at ${(last ?? "").slice(0, 16).replace("T", " ")} UTC` }; | |
| 197 | } | |
| 198 | if (m[3] === undefined) return undefined; | |
| 199 | const issue = getIssue(db, repo.id, Number(m[3])); | |
| 200 | if (issue === undefined) return undefined; | |
| 201 | const comments = db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM comment WHERE issue_id = ?1").get(issue.id)!.n; | |
| 202 | if (w.kind === "issue_comment") return { sig: `comments:${comments}`, wake: true, state: "open", says: `${label}#${issue.number} now has ${comments} comments` }; | |
| 203 | if (issue.kind !== "pull") return undefined; | |
| 204 | const pull = db.query<{ merged_at: string | null; head_oid: string }, [string]>("SELECT merged_at, head_oid FROM pull WHERE issue_id = ?1").get(issue.id); | |
| 205 | if (pull === null) return undefined; | |
| 206 | const head = pull.head_oid.slice(0, 12); | |
| 207 | const check = db.query<{ state: string }, [string]>("SELECT state FROM run WHERE issue_id = ?1 AND kind = 'check' ORDER BY id DESC LIMIT 1").get(issue.id)?.state; | |
| 208 | const state = pull.merged_at !== null ? "landed" : issue.state === "closed" ? "closed" : check === "ok" ? "green" : check === "failed" ? "red" : "pending"; | |
| 209 | const here = `pull ${label}#${issue.number}`; | |
| 210 | const says = `${here} ${state === "landed" ? "landed" : state === "closed" ? "was closed without landing" : state === "green" ? `is green at ${head}` : state === "red" ? `failed its check at ${head}` : "is still checking"}`; | |
| 211 | if (w.kind === "pull_changed") return { sig: `${head}:${state}:${comments}`, wake: true, state, says: `${here} changed (now ${state} at ${head}, ${comments} comments)` }; | |
| 212 | if (w.kind === "pull_landed") return { sig: state, wake: state === "landed" || state === "closed", state, says }; | |
| 213 | return { sig: `${state}:${head}`, wake: state !== "pending", state, says }; | |
| 214 | } | |
| 215 | ||
| 216 | export interface NewWatch { | |
| 217 | readonly brief: string; | |
| 218 | readonly kind: string; | |
| 219 | readonly target: string; | |
| 220 | readonly done?: string | undefined; | |
| 221 | readonly capUsd?: number | undefined; | |
| 222 | readonly everyMin?: number | undefined; | |
| 223 | } | |
| 224 | ||
| 225 | /** | |
| 226 | * Start a watch for the forge's owner. Its first look is the baseline: only a change after now | |
| 227 | * wakes it. | |
| 228 | */ | |
| 229 | export function createWatch(db: Database, user: User, input: NewWatch, now: Date = new Date()): Result<Watch, WatchError> { | |
| 230 | if (!user.isAdmin || user.kind !== "user") return err("not_owner"); | |
| 231 | if (wakeRunning(db, user.id)) return err("from_watch"); | |
| 232 | const brief = input.brief.replace(/\s+/g, " ").trim(); | |
| 233 | if (brief === "" || brief.length > WATCH_BRIEF_MAX) return err("bad_brief"); | |
| 234 | if (!(WATCH_KINDS as readonly string[]).includes(input.kind)) return err("bad_kind"); | |
| 235 | const kind = input.kind as WatchKind; | |
| 236 | const target = input.target.trim(); | |
| 237 | const done = input.done === undefined || input.done === "" ? (DEFAULT_DONE[kind] ?? null) : input.done; | |
| 238 | if (done !== null && !DONE[kind].includes(done)) return err("bad_done"); | |
| 239 | const cap = input.capUsd ?? CAP_DEFAULT; | |
| 240 | if (!Number.isFinite(cap) || cap <= 0 || cap > CAP_MAX) return err("bad_cap"); | |
| 241 | const every = input.everyMin ?? EVERY_DEFAULT; | |
| 242 | if (!Number.isInteger(every) || every < EVERY_MIN_WATCH || every > EVERY_MAX_WATCH) return err("bad_every"); | |
| 243 | const first = readWatch(db, user, { kind, target }); | |
| 244 | if (first === undefined) return err("bad_target"); | |
| 245 | const at = now.toISOString(); | |
| 246 | const row = db.transaction((): Watch | undefined => { | |
| 247 | const live = db.query<{ n: number }, [string]>("SELECT COUNT(*) AS n FROM talk_watch WHERE user_id = ?1 AND state IN ('live','paused')").get(user.id)!.n; | |
| 248 | if (live >= WATCH_MAX) return undefined; | |
| 249 | db.query( | |
| 250 | "DELETE FROM talk_watch WHERE user_id = ?1 AND state NOT IN ('live','paused') AND id NOT IN (SELECT id FROM talk_watch WHERE user_id = ?1 AND state NOT IN ('live','paused') ORDER BY ended_at DESC LIMIT ?2)", | |
| 251 | ).run(user.id, ENDED_KEPT - 1); | |
| 252 | const wid = id(); | |
| 253 | db.query( | |
| 254 | "INSERT INTO talk_watch (id, user_id, brief, kind, target, done_state, baseline, every_min, created_at, expires_at, cap_usd) VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11)", | |
| 255 | ).run(wid, user.id, brief, kind, target, done, first.sig, every, at, new Date(now.getTime() + WATCH_DAYS * 86_400_000).toISOString(), cap); | |
| 256 | return getWatch(db, user.id, wid); | |
| 257 | })(); | |
| 258 | return row === undefined ? err("too_many") : ok(row); | |
| 259 | } | |
| 260 | ||
| 261 | /** Pause or resume; false when it is not the person's or already ended. */ | |
| 262 | export function pauseWatch(db: Database, userId: string, watchId: string, paused: boolean): boolean { | |
| 263 | return db.query("UPDATE talk_watch SET state = ?3 WHERE id = ?1 AND user_id = ?2 AND state IN ('live','paused')").run(watchId, userId, paused ? "paused" : "live").changes > 0; | |
| 264 | } | |
| 265 | ||
| 266 | /** End a live or paused watch with one line saying how. */ | |
| 267 | export function endWatch(db: Database, userId: string, watchId: string, state: Exclude<WatchState, "live" | "paused">, line: string, now: Date = new Date()): boolean { | |
| 268 | return db.query("UPDATE talk_watch SET state = ?3, ended_at = ?4, ended_line = ?5 WHERE id = ?1 AND user_id = ?2 AND state IN ('live','paused')").run(watchId, userId, state, now.toISOString(), line.slice(0, 200)).changes > 0; | |
| 269 | } | |
| 270 | ||
| 271 | /** Take a watch off the list altogether. */ | |
| 272 | export const deleteWatch = (db: Database, userId: string, watchId: string): boolean => db.query("DELETE FROM talk_watch WHERE id = ?1 AND user_id = ?2").run(watchId, userId).changes > 0; |
src/crew/captain_thread.ts added +20
| @@ -0,0 +1,20 @@ | ||
| 1 | /** The Captain thread (#11011): where routines and watches post, made once per person. */ | |
| 2 | ||
| 3 | import type { App } from "../app.ts"; | |
| 4 | import { getConversation, listConversations, newConversation, renameConversation, type Conversation } from "../core/conversations.ts"; | |
| 5 | ||
| 6 | export const THREAD_TITLE = "Captain"; | |
| 7 | ||
| 8 | /** | |
| 9 | * The thread routines post into: the stored one while it stands, else the person's "Captain" | |
| 10 | * conversation, made once. | |
| 11 | */ | |
| 12 | export function captainThread(app: App, userId: string, stored: string | null): Conversation { | |
| 13 | const kept = stored === null ? undefined : getConversation(app.db, userId, stored); | |
| 14 | if (kept !== undefined && kept.archivedAt === null) return kept; | |
| 15 | const named = listConversations(app.db, userId).find((c) => c.title === THREAD_TITLE); | |
| 16 | if (named !== undefined) return named; | |
| 17 | const fresh = newConversation(app.db, userId); | |
| 18 | renameConversation(app.db, userId, fresh.id, THREAD_TITLE); | |
| 19 | return { ...fresh, title: THREAD_TITLE }; | |
| 20 | } |
src/crew/conversation_ask.ts +1
| @@ -227,6 +227,7 @@ export const ASKED_AS: Readonly<Record<string, Form>> = { | ||
| 227 | 227 | subscription_budget: (a) => |
| 228 | 228 | a["usd"] === null ? `Clear subscription ${own(val(a, "id"))} lifetime budget` : `Set subscription ${own(val(a, "id"))} lifetime budget to ${dollars(a["usd"])}`, |
| 229 | 229 | subscription_headroom: (a) => `Leave ${val(a, "percent")}% of each window of subscription ${val(a, "id")} for people`, |
| 230 | talk_watch: (a) => `Watch ${val(a, "target")} and wake your agent when ${val(a, "kind").replace(/_/g, " ")}`, | |
| 230 | 231 | subscription_wake: (a) => `Use the resting subscription ${val(a, "id")} again now`, |
| 231 | 232 | model_grant: (a) => |
| 232 | 233 | a["usdPerMonth"] === 0 ? `Take back ${own(val(a, "username"))} monthly model grant` : `Give ${val(a, "username")} ${dollars(a["usdPerMonth"])} a month for models`, |
src/crew/conversation_confirm.ts +2
| @@ -71,6 +71,8 @@ export const ASKING: Readonly<Record<string, Asking>> = { | ||
| 71 | 71 | subscription_budget: { undo: () => "`subscription_budget` with the old `usd` sets it back" }, |
| 72 | 72 | subscription_headroom: {}, |
| 73 | 73 | subscription_wake: {}, |
| 74 | // A watch wakes the agent without the owner: starting one is the owner's yes (#16557). | |
| 75 | talk_watch: { asks: (a) => a["action"] === "add" }, | |
| 74 | 76 | model_grant: { undo: () => "`model_grant` with `usdPerMonth: 0` takes it back" }, |
| 75 | 77 | model_ceiling: { undo: () => "`model_ceiling` with both `null` clears it" }, |
| 76 | 78 | limits: { undo: () => "`limits` with `value: \"\"` restores the default" }, |
src/crew/routines.ts +7 −15
| @@ -9,24 +9,13 @@ | ||
| 9 | 9 | |
| 10 | 10 | import { during } from "../perf/jobs.ts"; |
| 11 | 11 | import type { App } from "../app.ts"; |
| 12 | import { appendTurn, getConversation, listConversations, newConversation, renameConversation, type Conversation } from "../core/conversations.ts"; | |
| 12 | import { appendTurn } from "../core/conversations.ts"; | |
| 13 | 13 | import { due, listRoutines, markRan, ROUTINE_NAMES, type RoutineKind } from "../core/talk_routines.ts"; |
| 14 | 14 | import { getUserById, type User } from "../core/users.ts"; |
| 15 | 15 | import { compose, facts, type Report } from "./routine_report.ts"; |
| 16 | 16 | import { notifyUrlOf, post, type Sender } from "./notify.ts"; |
| 17 | ||
| 18 | export const THREAD_TITLE = "Captain"; | |
| 19 | ||
| 20 | /** The thread routines post into: the stored one while it stands, else the person's "Captain" conversation, made once. */ | |
| 21 | export function captainThread(app: App, userId: string, stored: string | null): Conversation { | |
| 22 | const kept = stored === null ? undefined : getConversation(app.db, userId, stored); | |
| 23 | if (kept !== undefined && kept.archivedAt === null) return kept; | |
| 24 | const named = listConversations(app.db, userId).find((c) => c.title === THREAD_TITLE); | |
| 25 | if (named !== undefined) return named; | |
| 26 | const fresh = newConversation(app.db, userId); | |
| 27 | renameConversation(app.db, userId, fresh.id, THREAD_TITLE); | |
| 28 | return { ...fresh, title: THREAD_TITLE }; | |
| 29 | } | |
| 17 | import { lookDue } from "./watches.ts"; | |
| 18 | import { captainThread } from "./captain_thread.ts"; | |
| 30 | 19 | |
| 31 | 20 | /** The text posted: the routine's name, then its lines. */ |
| 32 | 21 | export const routineText = (kind: RoutineKind, report: Report): string => `**${ROUTINE_NAMES[kind]}**\n${report.lines.map((l) => `- ${l}`).join("\n")}`; |
| @@ -76,10 +65,13 @@ export async function runDue(app: App, now: Date, send: Sender = post): Promise< | ||
| 76 | 65 | /** Start the minute clock; returns what stops it. The first pass waits 30 s so the boot is not slowed. */ |
| 77 | 66 | export function startRoutines(app: App, signal: AbortSignal): () => void { |
| 78 | 67 | let timer: ReturnType<typeof setTimeout> | undefined; |
| 68 | const look = async (): Promise<void> => { | |
| 69 | try { await lookDue(app, new Date()); } catch (error) { app.log.warn("watch look failed", { error: String(error) }); } | |
| 70 | }; | |
| 79 | 71 | const loop = (wait: number): void => { |
| 80 | 72 | timer = setTimeout(() => { |
| 81 | 73 | if (signal.aborted) return; |
| 82 | void during("routines", () => runDue(app, new Date()), undefined, app).finally(() => loop(60_000)); | |
| 74 | void during("routines", async () => (await look(), await runDue(app, new Date())), undefined, app).finally(() => loop(60_000)); | |
| 83 | 75 | }, wait); |
| 84 | 76 | timer.unref(); |
| 85 | 77 | }; |
src/crew/watches.ts added +104
| @@ -0,0 +1,104 @@ | ||
| 1 | /** | |
| 2 | * The watches' look (#16557), run on the routines' minute clock (`startRoutines`): each live watch | |
| 3 | * whose interval has passed is read for free (`readWatch`, no model). Nothing changed: nothing | |
| 4 | * happens and nothing is spent. Changed: one ordinary Talk turn as the owner through `talk()`, with | |
| 5 | * the brief and the change, so its limits (12 a minute, the account's budget, resting) and every | |
| 6 | * held write apply unchanged. A forge that was down looks once on waking, so it wakes once, not | |
| 7 | * once per missed tick. Age and spend end a watch with one line in the Captain thread; a met | |
| 8 | * condition does the same. | |
| 9 | */ | |
| 10 | ||
| 11 | import type { App } from "../app.ts"; | |
| 12 | import { talk } from "../actions/talk.ts"; | |
| 13 | import { appendTurn, type Conversation } from "../core/conversations.ts"; | |
| 14 | import { listRoutines } from "../core/talk_routines.ts"; | |
| 15 | import { endWatch, liveWatches, readWatch, waitsText, WAKE_MARK, WATCH_DAYS, type Watch } from "../core/talk_watch.ts"; | |
| 16 | import { getUserById, type User } from "../core/users.ts"; | |
| 17 | import { notifyUrlOf, post, type Sender } from "./notify.ts"; | |
| 18 | import { captainThread } from "./captain_thread.ts"; | |
| 19 | ||
| 20 | export interface Looked { | |
| 21 | readonly id: string; | |
| 22 | readonly outcome: "quiet" | "woke" | "ended" | "waiting"; | |
| 23 | readonly line?: string; | |
| 24 | /** Settles when the woken turn does (a test awaits it; the clock does not). */ | |
| 25 | readonly done?: Promise<void> | undefined; | |
| 26 | } | |
| 27 | ||
| 28 | /** The words a turn is started with: the mark, the brief, the change, and what ends it. */ | |
| 29 | export const wakeText = (w: Pick<Watch, "id" | "brief" | "kind" | "target" | "doneState">, says: string): string => | |
| 30 | `${WAKE_MARK}${w.id}] ${w.brief}\nWhat changed: ${says}.\nWaiting for: ${waitsText(w)}. This is a watch's turn: you cannot start another watch, and every write still waits for the owner's yes where it did before.`; | |
| 31 | ||
| 32 | /** | |
| 33 | * What the owner has spent on one watch: its wakes' turns, by the mark their prompt starts with. | |
| 34 | */ | |
| 35 | export const spentOn = (app: App, w: Pick<Watch, "id" | "userId">): number => | |
| 36 | app.db.query<{ s: number | null }, [string, string]>("SELECT SUM(cost_usd) AS s FROM conversation_run WHERE user_id = ?1 AND prompt LIKE ?2").get(w.userId, `${WAKE_MARK}${w.id}]%`)?.s ?? 0; | |
| 37 | ||
| 38 | const threadOf = (app: App, user: User): Conversation => | |
| 39 | captainThread(app, user.id, listRoutines(app.db, user.id).find((r) => r.conversationId !== null)?.conversationId ?? null); | |
| 40 | ||
| 41 | async function finish(app: App, user: User, w: Watch, state: "met" | "ran_out" | "spent" | "ended", line: string, now: Date, send: Sender): Promise<void> { | |
| 42 | if (!endWatch(app.db, user.id, w.id, state, line, now)) return; | |
| 43 | const thread = threadOf(app, user); | |
| 44 | appendTurn(app.db, user.id, thread.id, { role: "agent", text: `**Watch ended**\n- ${line}` }); | |
| 45 | const url = notifyUrlOf(app.db, user.id); | |
| 46 | if (url !== undefined) await send(url, `Watch ended: ${line}\n${app.config.url ?? ""}/talk/${thread.id}`, { title: "Watch ended" }); | |
| 47 | } | |
| 48 | ||
| 49 | async function lookOne(app: App, w: Watch, now: Date, send: Sender): Promise<Looked> { | |
| 50 | const db = app.db; | |
| 51 | const user = getUserById(db, w.userId); | |
| 52 | const waits = waitsText(w); | |
| 53 | if (user === undefined || !user.isAdmin || user.kind !== "user") { | |
| 54 | endWatch(db, w.userId, w.id, "ended", "Ended: its owner is no longer an admin.", now); | |
| 55 | return { id: w.id, outcome: "ended" }; | |
| 56 | } | |
| 57 | const spent = spentOn(app, w); | |
| 58 | db.query("UPDATE talk_watch SET spent_usd = ?2, last_look_at = ?3 WHERE id = ?1").run(w.id, spent, now.toISOString()); | |
| 59 | if (now.getTime() >= Date.parse(w.expiresAt)) { | |
| 60 | const line = `Ran out: ${waits} did not happen in ${WATCH_DAYS} days.`; | |
| 61 | await finish(app, user, w, "ran_out", line, now, send); | |
| 62 | return { id: w.id, outcome: "ended", line }; | |
| 63 | } | |
| 64 | if (spent >= w.capUsd) { | |
| 65 | const line = `Spent its $${w.capUsd.toFixed(2)} cap while waiting for: ${waits}.`; | |
| 66 | await finish(app, user, w, "spent", line, now, send); | |
| 67 | return { id: w.id, outcome: "ended", line }; | |
| 68 | } | |
| 69 | const reading = readWatch(db, user, w); | |
| 70 | if (reading === undefined) { | |
| 71 | const line = `Ended: ${waits} can no longer be read.`; | |
| 72 | await finish(app, user, w, "ended", line, now, send); | |
| 73 | return { id: w.id, outcome: "ended", line }; | |
| 74 | } | |
| 75 | if (!reading.wake || reading.sig === w.baseline) return { id: w.id, outcome: "quiet" }; | |
| 76 | const started = talk(app, user, wakeText(w, reading.says), [], "queue", threadOf(app, user).id); | |
| 77 | // Refused (resting, rate-limited, off): the baseline stays, so the next look tries again. | |
| 78 | if (!started.ok) return { id: w.id, outcome: "waiting", line: started.error }; | |
| 79 | db.query("UPDATE talk_watch SET baseline = ?2, wakes = wakes + 1, last_wake_at = ?3 WHERE id = ?1").run(w.id, reading.sig, now.toISOString()); | |
| 80 | const closed = reading.state === "closed" && w.kind.startsWith("pull_"); | |
| 81 | if (closed || reading.state === w.doneState) { | |
| 82 | const line = `${closed ? "Ended" : "Done"}: ${reading.says}.`; | |
| 83 | await finish(app, user, w, "met", line, now, send); | |
| 84 | return { id: w.id, outcome: "ended", line, done: started.value.done }; | |
| 85 | } | |
| 86 | return { id: w.id, outcome: "woke", line: reading.says, done: started.value.done }; | |
| 87 | } | |
| 88 | ||
| 89 | /** | |
| 90 | * One pass: every live watch whose interval has passed is looked at, one failing never stopping the | |
| 91 | * rest. | |
| 92 | */ | |
| 93 | export async function lookDue(app: App, now: Date, send: Sender = post): Promise<Looked[]> { | |
| 94 | const out: Looked[] = []; | |
| 95 | for (const w of liveWatches(app.db)) { | |
| 96 | if (w.lastLookAt !== null && now.getTime() - Date.parse(w.lastLookAt) < w.everyMin * 60_000) continue; | |
| 97 | try { | |
| 98 | out.push(await lookOne(app, w, now, send)); | |
| 99 | } catch (error) { | |
| 100 | app.log.warn("watch failed", { id: w.id, error: String(error) }); | |
| 101 | } | |
| 102 | } | |
| 103 | return out; | |
| 104 | } |
src/http/mcp/tools/index.ts +1
| @@ -186,6 +186,7 @@ export { tool as sync } from "./sync.ts"; | ||
| 186 | 186 | export { tool as system } from "./system.ts"; |
| 187 | 187 | export { tool as take_back } from "./take_back.ts"; |
| 188 | 188 | export { tool as take_updates } from "./take_updates.ts"; |
| 189 | export { tool as talk_watch } from "./talk_watch.ts"; | |
| 189 | 190 | export { tool as teams } from "./teams.ts"; |
| 190 | 191 | export { tool as telemetry_grant } from "./telemetry_grant.ts"; |
| 191 | 192 | export { tool as telemetry_history } from "./telemetry_history.ts"; |
src/http/mcp/tools/talk_watch.ts added +43
| @@ -0,0 +1,43 @@ | ||
| 1 | import { createWatch, KIND_WORDS, listWatches, readWatch, waitsText, wakeRunning, WATCH_KINDS, WATCH_WORDS } from "../../../core/talk_watch.ts"; | |
| 2 | import { good, bad, type Answer, type Tool } from "../shared.ts"; | |
| 3 | ||
| 4 | const READS = ["list"]; | |
| 5 | ||
| 6 | export const tool: Tool = { | |
| 7 | name: "talk_watch", | |
| 8 | doc: "`{ action: list }` reads the owner's watches; `{ action: add, brief, kind, target, done?, capUsd?, everyMin? }` leaves yourself a brief and what to wait for (kind: pull_green, pull_landed, pull_changed, run_ended, issue_comment, main_green, merge_since; target: owner/name#number, owner/name or a run id), held for the owner's Do it; the forge looks for free and wakes one Talk turn when it changes; an admin's, with an `admin` token", | |
| 9 | description: "Admin: list the watches that wake Talk's agent, or propose one (held for a Do it).", | |
| 10 | inputSchema: { | |
| 11 | type: "object", | |
| 12 | properties: { | |
| 13 | action: { type: "string", enum: ["list", "add"] }, | |
| 14 | brief: { type: "string", description: "What to do when it changes, up to 400 characters." }, | |
| 15 | kind: { type: "string", enum: [...WATCH_KINDS] }, | |
| 16 | target: { type: "string", description: "owner/name#N, owner/name, or a run id." }, | |
| 17 | done: { type: "string", description: "End: landed, green, ended, merged; default per kind." }, | |
| 18 | capUsd: { type: "number", description: "Spend cap in dollars (default 2, max 20)." }, | |
| 19 | everyMin: { type: "integer", description: "Look every this many minutes (5 to 1440, default 5)." }, | |
| 20 | }, | |
| 21 | required: ["action"], | |
| 22 | }, | |
| 23 | writes: true, | |
| 24 | adminOnly: true, | |
| 25 | readsWhen: (args) => typeof args["action"] === "string" && READS.includes(args["action"]), | |
| 26 | heldNotWhen: (args) => args["action"] === "list", | |
| 27 | // A watch's own turn may not start another, and no Do it is drawn for one that cannot run. | |
| 28 | refusesFirst: (ctx, user, args): Answer | undefined => | |
| 29 | args["action"] === "add" && wakeRunning(ctx.app.db, user.id) ? bad("from_watch", WATCH_WORDS.from_watch) : undefined, | |
| 30 | run(ctx, user, args) { | |
| 31 | const db = ctx.app.db; | |
| 32 | if (args["action"] === "list") | |
| 33 | return good({ watches: listWatches(db, user.id).map((w) => ({ id: w.id, waitsFor: waitsText(w), state: w.state, wakes: w.wakes, spentUsd: w.spentUsd, capUsd: w.capUsd, expiresAt: w.expiresAt, lastLookAt: w.lastLookAt })), kinds: KIND_WORDS }); | |
| 34 | if (args["action"] !== "add") return bad("invalid_action", "action is list or add"); | |
| 35 | const { brief, kind, target, done, capUsd, everyMin } = args; | |
| 36 | if (typeof brief !== "string" || typeof kind !== "string" || typeof target !== "string") return bad("invalid", "add needs brief, kind and target as text"); | |
| 37 | if ((done !== undefined && typeof done !== "string") || (capUsd !== undefined && typeof capUsd !== "number") || (everyMin !== undefined && typeof everyMin !== "number")) return bad("invalid", "done is text; capUsd and everyMin are numbers"); | |
| 38 | const made = createWatch(db, user, { brief, kind, target, done, capUsd, everyMin }); | |
| 39 | if (!made.ok) return bad(made.error, WATCH_WORDS[made.error]); | |
| 40 | const now = readWatch(db, user, made.value); | |
| 41 | return good({ id: made.value.id, waitsFor: waitsText(made.value), expiresAt: made.value.expiresAt, capUsd: made.value.capUsd, says: `Watching: ${waitsText(made.value)}. Now: ${now?.says ?? "unknown"}.` }); | |
| 42 | }, | |
| 43 | }; |
src/tui/screens/captain.ts +45 −5
| @@ -11,6 +11,7 @@ | ||
| 11 | 11 | import { runRoutine } from "../../crew/routines.ts"; |
| 12 | 12 | import { addMemory, editMemory, MEMORY_TEXT_MAX, MEMORY_WORDS, removeMemory, rulesOf, type Memory } from "../../core/talk_memory.ts"; |
| 13 | 13 | import { EVERY_MAX, EVERY_MIN, listRoutines, ROUTINE_NAMES, setRoutine, type Routine } from "../../core/talk_routines.ts"; |
| 14 | import { createWatch, deleteWatch, endWatch, listWatches, pauseWatch, waitsText, WATCH_KINDS, WATCH_WORDS, type Watch } from "../../core/talk_watch.ts"; | |
| 14 | 15 | import type { Ctx, Screen } from "../app/app.ts"; |
| 15 | 16 | import { binding } from "../app/keys.ts"; |
| 16 | 17 | import type { Session } from "../session.ts"; |
| @@ -32,13 +33,27 @@ export function parseSchedule(text: string): { everyMin: number; atHour: number | ||
| 32 | 33 | |
| 33 | 34 | export const scheduleText = (r: Pick<Routine, "everyMin" | "atHour">): string => (r.atHour === null ? String(r.everyMin) : `at ${r.atHour}`); |
| 34 | 35 | |
| 35 | type Line = { kind: "rule"; rule: Memory } | { kind: "routine"; routine: Routine }; | |
| 36 | type Line = { kind: "rule"; rule: Memory } | { kind: "routine"; routine: Routine } | { kind: "watch"; watch: Watch }; | |
| 37 | ||
| 38 | /** | |
| 39 | * "pull_green trevato/forge#16532: merge it once green" is a watch: its kind, its target, then the | |
| 40 | * brief. | |
| 41 | */ | |
| 42 | export function parseWatch(text: string): { kind: string; target: string; brief: string } | undefined { | |
| 43 | const m = /^(\w+)\s+(\S+)\s*[:-]\s*(.+)$/s.exec(text.trim()); | |
| 44 | return m === null ? undefined : { kind: m[1]!, target: m[2]!, brief: m[3]! }; | |
| 45 | } | |
| 46 | ||
| 47 | const watchMeta = (w: Watch): string => | |
| 48 | metaOf(w.state === "live" || w.state === "paused" ? w.state : w.endedLine, `looked ${w.lastLookAt === null ? "not yet" : w.lastLookAt.slice(0, 16).replace("T", " ")}`, `${w.wakes} wakes`, `$${w.spentUsd.toFixed(2)} of $${w.capUsd.toFixed(2)}`); | |
| 36 | 49 | |
| 37 | 50 | export function captainRows(lines: readonly Line[]): ListRow[] { |
| 38 | 51 | return lines.map((l) => |
| 39 | 52 | l.kind === "rule" |
| 40 | 53 | ? { title: l.rule.text, meta: "rule" } |
| 41 | : { title: ROUTINE_NAMES[l.routine.kind], meta: metaOf(l.routine.enabled ? "on" : "off", l.routine.atHour === null ? `every ${l.routine.everyMin} min` : `daily ${String(l.routine.atHour).padStart(2, "0")}:00 UTC`, l.routine.lastAt === null ? "not yet" : l.routine.lastAt.slice(0, 16).replace("T", " ")) }, | |
| 54 | : l.kind === "watch" | |
| 55 | ? { title: `Watch: ${waitsText(l.watch)}`, meta: watchMeta(l.watch) } | |
| 56 | : { title: ROUTINE_NAMES[l.routine.kind], meta: metaOf(l.routine.enabled ? "on" : "off", l.routine.atHour === null ? `every ${l.routine.everyMin} min` : `daily ${String(l.routine.atHour).padStart(2, "0")}:00 UTC`, l.routine.lastAt === null ? "not yet" : l.routine.lastAt.slice(0, 16).replace("T", " ")) }, | |
| 42 | 57 | ); |
| 43 | 58 | } |
| 44 | 59 | |
| @@ -46,7 +61,7 @@ export function captainScreen(f: Session, ctx: Ctx): Screen { | ||
| 46 | 61 | const state = new ListState(); |
| 47 | 62 | let lines: Line[] = []; |
| 48 | 63 | const read = async (): Promise<void> => { |
| 49 | lines = [...rulesOf(f.app.db, f.user!.id).map((rule): Line => ({ kind: "rule", rule })), ...listRoutines(f.app.db, f.user!.id).map((routine): Line => ({ kind: "routine", routine }))]; | |
| 64 | lines = [...rulesOf(f.app.db, f.user!.id).map((rule): Line => ({ kind: "rule", rule })), ...listRoutines(f.app.db, f.user!.id).map((routine): Line => ({ kind: "routine", routine })), ...listWatches(f.app.db, f.user!.id).map((watch): Line => ({ kind: "watch", watch }))]; | |
| 50 | 65 | state.clamp(lines.length); |
| 51 | 66 | ctx.invalidate(); |
| 52 | 67 | }; |
| @@ -57,7 +72,7 @@ export function captainScreen(f: Session, ctx: Ctx): Screen { | ||
| 57 | 72 | }; |
| 58 | 73 | const screen: Screen = { |
| 59 | 74 | title: "Captain", |
| 60 | keys: [binding(["j", "k"], "move"), binding(["a"], "add a rule"), binding(["enter"], "edit"), binding(["d"], "delete"), binding(["space"], "on/off"), binding(["p"], "post now"), binding(["esc", "q"], "close")], | |
| 75 | keys: [binding(["j", "k"], "move"), binding(["a"], "add a rule"), binding(["enter"], "edit"), binding(["d"], "delete"), binding(["space"], "on/off"), binding(["p"], "post now / pause a watch"), binding(["w"], "add a watch"), binding(["e"], "end a watch now"), binding(["esc", "q"], "close")], | |
| 61 | 76 | load: read, |
| 62 | 77 | render(area, s) { |
| 63 | 78 | drawList(s, area, ctx.theme.c, state, captainRows(lines)); |
| @@ -65,7 +80,32 @@ export function captainScreen(f: Session, ctx: Ctx): Screen { | ||
| 65 | 80 | key(e) { |
| 66 | 81 | const at = lines[state.index]; |
| 67 | 82 | if (e.key === "esc" || e.key === "q") ctx.pop(); |
| 68 | else if (e.key === "a") | |
| 83 | else if (e.key === "w") | |
| 84 | ctx.push( | |
| 85 | promptScreen(ctx, screen, { | |
| 86 | title: "Watch", | |
| 87 | label: "kind target: brief", | |
| 88 | hint: `Kinds: ${WATCH_KINDS.join(", ")}.`, | |
| 89 | onSubmit: (v) => { | |
| 90 | const w = parseWatch(v); | |
| 91 | if (w === undefined) return "Type: kind target: what to do when it changes."; | |
| 92 | const made = createWatch(f.app.db, f.user!, w); | |
| 93 | return say(made.ok ? undefined : WATCH_WORDS[made.error]); | |
| 94 | }, | |
| 95 | }), | |
| 96 | ); | |
| 97 | else if (e.key === "e" && at?.kind === "watch") { | |
| 98 | endWatch(f.app.db, f.user!.id, at.watch.id, "ended", "Ended by you."); | |
| 99 | ctx.toast("Ended.", "success"); | |
| 100 | refresh(); | |
| 101 | } else if (e.key === "p" && at?.kind === "watch") { | |
| 102 | pauseWatch(f.app.db, f.user!.id, at.watch.id, at.watch.state === "live"); | |
| 103 | refresh(); | |
| 104 | } else if (e.key === "d" && at?.kind === "watch") { | |
| 105 | deleteWatch(f.app.db, f.user!.id, at.watch.id); | |
| 106 | ctx.toast("Deleted.", "success"); | |
| 107 | refresh(); | |
| 108 | } else if (e.key === "a") | |
| 69 | 109 | ctx.push(promptScreen(ctx, screen, { title: "Remember", label: "A rule or decision", hint: `Up to ${MEMORY_TEXT_MAX} characters.`, onSubmit: (v) => say(((r) => (r.ok ? undefined : MEMORY_WORDS[r.error]))(addMemory(f.app.db, f.user!.id, v))) })); |
| 70 | 110 | else if (e.key === "enter" && at?.kind === "rule") { |
| 71 | 111 | const rule = at.rule; |
src/web/pages/captain.ts +43 −1
| @@ -9,6 +9,7 @@ | ||
| 9 | 9 | import { sshOn } from "../../settings/ssh.ts"; |
| 10 | 10 | import { addMemory, editMemory, MEMORY_TEXT_MAX, MEMORY_WORDS, removeMemory, rulesOf } from "../../core/talk_memory.ts"; |
| 11 | 11 | import { EVERY_MAX, EVERY_MIN, listRoutines, ROUTINE_KINDS, ROUTINE_NAMES, setRoutine } from "../../core/talk_routines.ts"; |
| 12 | import { CAP_DEFAULT, CAP_MAX, createWatch, deleteWatch, endWatch, KIND_WORDS, listWatches, pauseWatch, waitsText, WATCH_BRIEF_MAX, WATCH_KINDS, WATCH_WORDS } from "../../core/talk_watch.ts"; | |
| 12 | 13 | import { runRoutine } from "../../crew/routines.ts"; |
| 13 | 14 | import type { Ctx } from "../../http/context.ts"; |
| 14 | 15 | import { notePhase, takeSessionTime } from "../../core/route_timing.ts"; |
| @@ -16,7 +17,7 @@ import { forbiddenPage, notFoundPage, pageHead, settingsLayout, signInFirst } fr | ||
| 16 | 17 | import { field, readForm } from "../form.ts"; |
| 17 | 18 | import { html, type Html } from "../html.ts"; |
| 18 | 19 | import { flashTo, page } from "../layout.ts"; |
| 19 | import { btn, field as uiField } from "../ui.ts"; | |
| 20 | import { btn, field as uiField, row, rowList } from "../ui.ts"; | |
| 20 | 21 | import { accountSections } from "./origins.ts"; |
| 21 | 22 | |
| 22 | 23 | const BACK = "/settings/captain"; |
| @@ -33,6 +34,7 @@ function view(ctx: Ctx, error?: string, status = 200): Response { | ||
| 33 | 34 | const user = ctx.auth.user!; |
| 34 | 35 | const memory = rulesOf(ctx.app.db, user.id); |
| 35 | 36 | const routines = listRoutines(ctx.app.db, user.id); |
| 37 | const watches = listWatches(ctx.app.db, user.id); | |
| 36 | 38 | const body: Html = html`<section class="settings-block"> |
| 37 | 39 | <h2>Memory</h2> |
| 38 | 40 | ${error ? html`<p class="field-error" role="alert">${error}</p>` : null} |
| @@ -61,6 +63,33 @@ function view(ctx: Ctx, error?: string, status = 200): Response { | ||
| 61 | 63 | <div class="form-actions">${btn("Save", { variant: "primary", name: "do", value: "routine" })}${btn("Post now", { name: "do", value: "run" })}</div> |
| 62 | 64 | </form> |
| 63 | 65 | </li>`)}</ul> |
| 66 | </section> | |
| 67 | <section class="settings-block"> | |
| 68 | <h2>Watches</h2> | |
| 69 | <p class="muted small">What Talk's agent waits on for you, checked free until something changes.</p> | |
| 70 | ${rowList(watches.map((w) => { | |
| 71 | const live = w.state === "live" || w.state === "paused"; | |
| 72 | return row({ | |
| 73 | title: waitsText(w), | |
| 74 | meta: html`${w.brief}`, | |
| 75 | facts: [ | |
| 76 | { label: live ? "State" : "Ended", value: live ? w.state : w.endedLine }, | |
| 77 | { label: "Last looked", value: when(w.lastLookAt) }, | |
| 78 | { label: "Wakes", value: String(w.wakes) }, | |
| 79 | { label: "Spent", value: `$${w.spentUsd.toFixed(2)} of $${w.capUsd.toFixed(2)}` }, | |
| 80 | ], | |
| 81 | trail: html`<form method="post" action="${BACK}"><input type="hidden" name="id" value="${w.id}">${live ? html`${btn(w.state === "live" ? "Pause" : "Resume", { name: "do", value: "watch_pause" })}${btn("Ends now", { name: "do", value: "watch_end" })}` : null}${btn("Delete", { name: "do", value: "watch_delete" })}</form>`, | |
| 82 | }); | |
| 83 | }))} | |
| 84 | <form method="post" action="${BACK}"> | |
| 85 | <input type="hidden" name="do" value="watch_add"> | |
| 86 | ${uiField({ label: "Brief", name: "brief", maxlength: WATCH_BRIEF_MAX, placeholder: "Merge it once green and tell me.", id: "w-brief" })} | |
| 87 | <label for="w-kind">Waits for</label> | |
| 88 | <select name="kind" id="w-kind">${WATCH_KINDS.map((k) => html`<option value="${k}">${KIND_WORDS[k].says(`(${KIND_WORDS[k].target})`)}</option>`)}</select> | |
| 89 | ${uiField({ label: "Target", name: "target", placeholder: "trevato/forge#16532", id: "w-target" })} | |
| 90 | ${uiField({ label: "Spend cap ($)", name: "cap", type: "number", value: String(CAP_DEFAULT), min: 0.5, max: CAP_MAX, step: "0.5", id: "w-cap" })} | |
| 91 | <div class="form-actions">${btn("Watch", { variant: "primary" })}</div> | |
| 92 | </form> | |
| 64 | 93 | </section>`; |
| 65 | 94 | const rendering = performance.now(); |
| 66 | 95 | const response = page( |
| @@ -100,6 +129,19 @@ export async function captainAct(ctx: Ctx): Promise<Response> { | ||
| 100 | 129 | const gone = removeMemory(db, user.id, field(form, "id")); |
| 101 | 130 | return gone.ok ? flashTo(ctx, BACK, { message: "Forgotten." }) : view(ctx, MEMORY_WORDS.not_found, 404); |
| 102 | 131 | } |
| 132 | if (what === "watch_add") { | |
| 133 | const made = createWatch(db, user, { brief: field(form, "brief"), kind: field(form, "kind"), target: field(form, "target"), capUsd: Number(field(form, "cap") || CAP_DEFAULT) }); | |
| 134 | return made.ok ? flashTo(ctx, BACK, { message: "Watching." }) : view(ctx, WATCH_WORDS[made.error], 422); | |
| 135 | } | |
| 136 | if (what === "watch_pause" || what === "watch_end" || what === "watch_delete") { | |
| 137 | const wid = field(form, "id"); | |
| 138 | const mine = listWatches(db, user.id).find((w) => w.id === wid); | |
| 139 | if (mine === undefined) return view(ctx, "That watch is gone.", 404); | |
| 140 | if (what === "watch_delete") deleteWatch(db, user.id, wid); | |
| 141 | else if (what === "watch_end") endWatch(db, user.id, wid, "ended", "Ended by you."); | |
| 142 | else pauseWatch(db, user.id, wid, mine.state === "live"); | |
| 143 | return flashTo(ctx, BACK, { message: what === "watch_pause" ? (mine.state === "live" ? "Paused." : "Resumed.") : what === "watch_end" ? "Ended." : "Deleted." }); | |
| 144 | } | |
| 103 | 145 | if (what === "routine" || what === "run") { |
| 104 | 146 | const kind = field(form, "kind"); |
| 105 | 147 | if (what === "run") { |
test/conversation-ask.test.ts +5
| @@ -289,6 +289,11 @@ const SAID: readonly (readonly [string, Record<string, unknown>, string])[] = [ | ||
| 289 | 289 | { id: "s1" }, |
| 290 | 290 | "Use the resting subscription s1 again now.", |
| 291 | 291 | ], |
| 292 | [ | |
| 293 | "talk_watch", | |
| 294 | { action: "add", kind: "pull_green", target: "trevato/forge#16532", brief: "merge it" }, | |
| 295 | "Watch trevato/forge#16532 and wake your agent when pull green.", | |
| 296 | ], | |
| 292 | 297 | [ |
| 293 | 298 | "model_grant", |
| 294 | 299 | { username: "omato", usdPerMonth: 10 }, |
test/forge-looks.test.ts +1 −1
| @@ -200,7 +200,7 @@ test("`/` signed out is its own look at phone and desktop, taken with no session | ||
| 200 | 200 | test("a look below the top level is the preview seed's, taken as the owner", () => { |
| 201 | 201 | const { looks, looksAsOwner } = manifest(); |
| 202 | 202 | for (const p of looks.filter((p) => !isTopLevel(p))) { |
| 203 | expect(p.startsWith("/preview-admin/sample") || p === "/settings/crew" || p === "/settings/security/controls" || p === "/settings/grants" || p === "/admin/limits" || p === "/looks/missing" || p === "/looks/failed" || p === "/nope/nothing" || isHelpLook(p)).toBe(true); | |
| 203 | expect(p.startsWith("/preview-admin/sample") || p === "/settings/crew" || p === "/settings/captain" || p === "/settings/security/controls" || p === "/settings/grants" || p === "/admin/limits" || p === "/looks/missing" || p === "/looks/failed" || p === "/nope/nothing" || isHelpLook(p)).toBe(true); | |
| 204 | 204 | // the not-found and failed pages are the same page to everyone: no owner needed |
| 205 | 205 | if (!p.startsWith("/looks/") && p !== "/nope/nothing") expect(looksAsOwner).toContain(p); |
| 206 | 206 | } |
test/mcp-forge-protocol.test.ts +1
test/mixed-actions-held.test.ts +1
test/talk-watch.test.ts added +284
| @@ -0,0 +1,284 @@ | ||
| 1 | /** | |
| 2 | * Watches (#16557): a brief the agent leaves itself and what the forge looks for, free. Nothing | |
| 3 | * changed means no model turn; a change wakes exactly one; the limits are the forge's, not the | |
| 4 | * agent's word. The model is a fake binary that counts its calls, so a turn is a file. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { chmodSync, readdirSync, writeFileSync } from "node:fs"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createRepo } from "../src/actions/repos.ts"; | |
| 12 | import { createApp, type App } from "../src/app.ts"; | |
| 13 | import { createConversation, listTurns } from "../src/core/conversations.ts"; | |
| 14 | import { mintViaToken } from "../src/core/via_token.ts"; | |
| 15 | import { createToken } from "../src/core/tokens.ts"; | |
| 16 | import { addComment, createIssue } from "../src/core/issues.ts"; | |
| 17 | import { createRun } from "../src/core/runs.ts"; | |
| 18 | import { createWatch, endWatch, listWatches, pauseWatch, WATCH_MAX } from "../src/core/talk_watch.ts"; | |
| 19 | import { createUser, type User } from "../src/core/users.ts"; | |
| 20 | import { configureConversation } from "../src/crew/conversation.ts"; | |
| 21 | import { ASKING } from "../src/crew/conversation_confirm.ts"; | |
| 22 | import { lookDue, spentOn, wakeText } from "../src/crew/watches.ts"; | |
| 23 | import { parseWatch } from "../src/tui/screens/captain.ts"; | |
| 24 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 25 | import { tool } from "../src/http/mcp/tools/talk_watch.ts"; | |
| 26 | import { quietLogs } from "./helpers/globals.ts"; | |
| 27 | ||
| 28 | quietLogs(); | |
| 29 | ||
| 30 | let dir: string; | |
| 31 | let app: App; | |
| 32 | let servers: Servers; | |
| 33 | let owner: User; | |
| 34 | let stranger: User; | |
| 35 | let repoId: string; | |
| 36 | let pullId: string; | |
| 37 | const slug = "watchowner/widgets"; | |
| 38 | ||
| 39 | const turns = (): number => readdirSync(dir).filter((f) => f.endsWith(".first")).length; | |
| 40 | const t0 = new Date("2026-11-27T10:00:00Z"); | |
| 41 | const min = (n: number): Date => new Date(t0.getTime() + n * 60_000); | |
| 42 | const noPush = async (): Promise<boolean> => false; | |
| 43 | ||
| 44 | beforeAll(async () => { | |
| 45 | dir = await mkdtemp(join(tmpdir(), "forge-watch-")); | |
| 46 | app = createApp({ dataDir: dir, port: 0 }); | |
| 47 | servers = await serve(app); | |
| 48 | const person = async (username: string, first = false) => { | |
| 49 | const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first }); | |
| 50 | if (!u.ok) throw new Error(u.error); | |
| 51 | return u.value; | |
| 52 | }; | |
| 53 | owner = await person("watchowner", true); | |
| 54 | stranger = await person("stranger"); | |
| 55 | const bin = join(dir, "claude"); | |
| 56 | writeFileSync( | |
| 57 | bin, | |
| 58 | `#!/bin/sh | |
| 59 | if [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi | |
| 60 | IFS= read -r first | |
| 61 | n=$(ls "${dir}"/call-*.first 2>/dev/null | wc -l) | |
| 62 | printf '%s' "$first" > "${dir}/call-$n.first" | |
| 63 | echo '{"type":"system","subtype":"init","session_id":"sess-'$n'","model":"fake"}' | |
| 64 | echo '{"type":"result","subtype":"success","is_error":false,"result":"Done.","total_cost_usd":0.01,"num_turns":1,"session_id":"sess-'$n'","terminal_reason":"completed","usage":{"input_tokens":1,"output_tokens":1}}' | |
| 65 | `, | |
| 66 | ); | |
| 67 | chmodSync(bin, 0o755); | |
| 68 | configureConversation(app, { binary: bin, localUrl: servers.url, budgetUsd: 1, timeoutMs: 30_000, signal: new AbortController().signal }); | |
| 69 | const repo = await createRepo(app, owner, { name: "widgets", visibility: "public" }); | |
| 70 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 71 | repoId = repo.value.id; | |
| 72 | const pull = createIssue(app.db, { repoId, authorId: owner.id, title: "A pull", kind: "pull" }); | |
| 73 | if (!pull.ok) throw new Error(pull.error); | |
| 74 | pullId = pull.value.id; | |
| 75 | app.db.query("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1,'main','work','a','b1b1b1b1b1b1b1b1')").run(pullId); | |
| 76 | }, 30_000); | |
| 77 | ||
| 78 | afterAll(async () => { | |
| 79 | servers.stop(); | |
| 80 | await rm(dir, { recursive: true, force: true }); | |
| 81 | }); | |
| 82 | ||
| 83 | const mkWatch = (over: Partial<Parameters<typeof createWatch>[2]> = {}) => { | |
| 84 | const made = createWatch(app.db, owner, { brief: "Merge it once green, then tell me.", kind: "pull_green", target: `${slug}#1`, ...over }, t0); | |
| 85 | if (!made.ok) throw new Error(made.error); | |
| 86 | return made.value; | |
| 87 | }; | |
| 88 | const clear = (): void => void app.db.query("DELETE FROM talk_watch").run(); | |
| 89 | const looks = async (at: Date): Promise<Awaited<ReturnType<typeof lookDue>>> => { | |
| 90 | const out = await lookDue(app, at, noPush); | |
| 91 | await Promise.all(out.map((l) => l.done)); | |
| 92 | return out; | |
| 93 | }; | |
| 94 | ||
| 95 | describe("a watch looks for free", () => { | |
| 96 | test("no change means zero model turns and nothing spent", async () => { | |
| 97 | clear(); | |
| 98 | const w = mkWatch(); | |
| 99 | const before = turns(); | |
| 100 | for (let i = 1; i <= 5; i++) expect((await looks(min(i * 5))).map((l) => l.outcome)).toEqual(["quiet"]); | |
| 101 | expect(turns()).toBe(before); | |
| 102 | const kept = listWatches(app.db, owner.id)[0]!; | |
| 103 | expect(kept.spentUsd).toBe(0); | |
| 104 | expect(kept.wakes).toBe(0); | |
| 105 | expect(kept.lastLookAt).toBe(min(25).toISOString()); | |
| 106 | expect(kept.id).toBe(w.id); | |
| 107 | }); | |
| 108 | ||
| 109 | test("a change wakes exactly one turn, with the brief and the change, as the owner", async () => { | |
| 110 | clear(); | |
| 111 | const w = mkWatch({ kind: "pull_changed", target: `${slug}#1`, done: "landed" }); | |
| 112 | const before = turns(); | |
| 113 | addComment(app.db, { issueId: pullId, authorId: owner.id, body: "looks fine" }); | |
| 114 | const looked = await looks(min(5)); | |
| 115 | expect(looked.map((l) => l.outcome)).toEqual(["woke"]); | |
| 116 | expect(turns()).toBe(before + 1); | |
| 117 | const first = (await Bun.file(join(dir, `call-${before}.first`)).text()).toString(); | |
| 118 | expect(first).toContain(wakeText(w, "").split("\n")[0]!.slice(0, 20)); | |
| 119 | expect(first).toContain("Merge it once green"); | |
| 120 | expect(first).toContain("1 comments"); | |
| 121 | // The same state looked at again wakes nothing. | |
| 122 | expect((await looks(min(10))).map((l) => l.outcome)).toEqual(["quiet"]); | |
| 123 | expect(turns()).toBe(before + 1); | |
| 124 | expect(listWatches(app.db, owner.id)[0]!.wakes).toBe(1); | |
| 125 | // The wake's turn is what the watch spent: found by the mark its prompt starts with. | |
| 126 | expect(spentOn(app, w)).toBeCloseTo(0.01, 5); | |
| 127 | expect(parseWatch("pull_green trevato/forge#16532: merge it once green")).toEqual({ kind: "pull_green", target: "trevato/forge#16532", brief: "merge it once green" }); | |
| 128 | expect(parseWatch("nonsense")).toBeUndefined(); | |
| 129 | }); | |
| 130 | ||
| 131 | test("a forge that was down for many ticks wakes once", async () => { | |
| 132 | clear(); | |
| 133 | mkWatch({ kind: "issue_comment", target: `${slug}#1` }); | |
| 134 | const before = turns(); | |
| 135 | for (let i = 0; i < 3; i++) addComment(app.db, { issueId: pullId, authorId: owner.id, body: `c${i}` }); | |
| 136 | // Three hours of ticks were missed: one look on waking. | |
| 137 | expect((await looks(min(180))).map((l) => l.outcome)).toEqual(["woke"]); | |
| 138 | expect(turns()).toBe(before + 1); | |
| 139 | expect((await looks(min(240))).map((l) => l.outcome)).toEqual(["quiet"]); | |
| 140 | }); | |
| 141 | ||
| 142 | test("a met condition ends the watch with one line, and a final wake", async () => { | |
| 143 | clear(); | |
| 144 | const w = mkWatch({ kind: "pull_green", target: `${slug}#1`, done: "landed" }); | |
| 145 | const before = turns(); | |
| 146 | const run = { id: "chk1" + Date.now().toString(36) }; | |
| 147 | app.db.query("INSERT INTO run (id, repo_id, kind, issue_id, state) VALUES (?1, ?2, 'check', ?3, 'running')").run(run.id, repoId, pullId); | |
| 148 | app.db.query("UPDATE run SET state = 'ok' WHERE id = ?1").run(run.id); | |
| 149 | expect((await looks(min(5))).map((l) => l.outcome)).toEqual(["woke"]); | |
| 150 | expect(listWatches(app.db, owner.id)[0]!.state).toBe("live"); | |
| 151 | app.db.query("UPDATE pull SET merged_at = ?2 WHERE issue_id = ?1").run(pullId, min(6).toISOString()); | |
| 152 | const done = await looks(min(10)); | |
| 153 | expect(done[0]!.outcome).toBe("ended"); | |
| 154 | expect(done[0]!.line).toContain("landed"); | |
| 155 | expect(turns()).toBe(before + 2); | |
| 156 | const ended = listWatches(app.db, owner.id)[0]!; | |
| 157 | expect(ended).toMatchObject({ id: w.id, state: "met" }); | |
| 158 | expect((listTurns(app.db, owner.id, await captainId()) as { ok: true; value: { text: string }[] }).value.some((x) => x.text.includes("Watch ended"))).toBe(true); | |
| 159 | expect(await looks(min(15))).toEqual([]); | |
| 160 | }); | |
| 161 | ||
| 162 | test("a run that ended is a change", async () => { | |
| 163 | clear(); | |
| 164 | const run = createRun(app.db, { repoId, kind: "deploy", env: "production" }); | |
| 165 | mkWatch({ kind: "run_ended", target: run.id }); | |
| 166 | expect((await looks(min(5))).map((l) => l.outcome)).toEqual(["quiet"]); | |
| 167 | app.db.query("UPDATE run SET state = 'failed', summary = 'boom' WHERE id = ?1").run(run.id); | |
| 168 | expect((await looks(min(10)))[0]!.outcome).toBe("ended"); | |
| 169 | }); | |
| 170 | }); | |
| 171 | ||
| 172 | async function captainId(): Promise<string> { | |
| 173 | const { listConversations } = await import("../src/core/conversations.ts"); | |
| 174 | return listConversations(app.db, owner.id).find((c) => c.title === "Captain")!.id; | |
| 175 | } | |
| 176 | ||
| 177 | describe("the forge's limits end it, not the agent's word", () => { | |
| 178 | test("age ends it and says it ran out", async () => { | |
| 179 | clear(); | |
| 180 | mkWatch({ kind: "issue_comment", target: `${slug}#1` }); | |
| 181 | const out = await looks(new Date(t0.getTime() + 8 * 86_400_000)); | |
| 182 | expect(out[0]!.line).toContain("Ran out"); | |
| 183 | expect(listWatches(app.db, owner.id)[0]!.state).toBe("ran_out"); | |
| 184 | }); | |
| 185 | ||
| 186 | test("its spend cap ends it before another turn", async () => { | |
| 187 | clear(); | |
| 188 | const w = mkWatch({ kind: "issue_comment", target: `${slug}#1`, capUsd: 0.5 }); | |
| 189 | const before = turns(); | |
| 190 | app.db.query("INSERT INTO conversation_run (id, conversation_id, user_id, state, prompt, cost_usd, started_at) SELECT 'spent1', id, ?1, 'ok', ?2, 0.6, ?3 FROM conversation LIMIT 1").run(owner.id, `[Watch ${w.id}] earlier`, t0.toISOString()); | |
| 191 | addComment(app.db, { issueId: pullId, authorId: owner.id, body: "more" }); | |
| 192 | const out = await looks(min(5)); | |
| 193 | expect(out[0]!.line).toContain("cap"); | |
| 194 | expect(turns()).toBe(before); | |
| 195 | expect(listWatches(app.db, owner.id)[0]).toMatchObject({ state: "spent", spentUsd: 0.6 }); | |
| 196 | app.db.query("DELETE FROM conversation_run WHERE id = 'spent1'").run(); | |
| 197 | }); | |
| 198 | ||
| 199 | test("at most five live, a longer brief, a bad target or an unreadable one is refused", () => { | |
| 200 | clear(); | |
| 201 | for (let i = 0; i < WATCH_MAX; i++) mkWatch(); | |
| 202 | expect(createWatch(app.db, owner, { brief: "x", kind: "pull_green", target: `${slug}#1` })).toEqual({ ok: false, error: "too_many" }); | |
| 203 | clear(); | |
| 204 | expect(createWatch(app.db, owner, { brief: "x".repeat(401), kind: "pull_green", target: `${slug}#1` })).toEqual({ ok: false, error: "bad_brief" }); | |
| 205 | expect(createWatch(app.db, owner, { brief: "x", kind: "pull_green", target: "nobody/none#1" })).toEqual({ ok: false, error: "bad_target" }); | |
| 206 | expect(createWatch(app.db, owner, { brief: "x", kind: "nope", target: `${slug}#1` })).toEqual({ ok: false, error: "bad_kind" }); | |
| 207 | expect(createWatch(app.db, owner, { brief: "x", kind: "pull_green", target: `${slug}#1`, capUsd: 500 })).toEqual({ ok: false, error: "bad_cap" }); | |
| 208 | expect(createWatch(app.db, owner, { brief: "x", kind: "issue_comment", target: `${slug}#1`, done: "landed" })).toEqual({ ok: false, error: "bad_done" }); | |
| 209 | }); | |
| 210 | ||
| 211 | test("a paused watch is not looked at, and ending one frees its place", async () => { | |
| 212 | clear(); | |
| 213 | const w = mkWatch({ kind: "issue_comment", target: `${slug}#1` }); | |
| 214 | addComment(app.db, { issueId: pullId, authorId: owner.id, body: "again" }); | |
| 215 | pauseWatch(app.db, owner.id, w.id, true); | |
| 216 | expect(await looks(min(5))).toEqual([]); | |
| 217 | expect(endWatch(app.db, owner.id, w.id, "ended", "Ended by you.")).toBe(true); | |
| 218 | expect(listWatches(app.db, owner.id)[0]!.state).toBe("ended"); | |
| 219 | }); | |
| 220 | }); | |
| 221 | ||
| 222 | describe("a watch never widens what the agent may do", () => { | |
| 223 | test("a stranger cannot make one", () => { | |
| 224 | expect(createWatch(app.db, stranger, { brief: "x", kind: "pull_green", target: `${slug}#1` })).toEqual({ ok: false, error: "not_owner" }); | |
| 225 | }); | |
| 226 | ||
| 227 | test("the tool is the owner's, and the agent's proposal is held for a Do it", () => { | |
| 228 | expect(tool.adminOnly).toBe(true); | |
| 229 | ||
| 230 | expect(ASKING["talk_watch"]?.asks?.({ action: "add" })).toBe(true); | |
| 231 | expect(ASKING["talk_watch"]?.asks?.({ action: "list" })).toBe(false); | |
| 232 | expect(tool.readsWhen?.({ action: "list" })).toBe(true); | |
| 233 | expect(tool.readsWhen?.({ action: "add" })).toBe(false); | |
| 234 | }); | |
| 235 | ||
| 236 | test("a watch's own turn cannot start another", () => { | |
| 237 | clear(); | |
| 238 | const conversation = app.db.query<{ id: string }, []>("SELECT id FROM conversation LIMIT 1").get()!; | |
| 239 | app.db.query("INSERT INTO conversation_run (id, conversation_id, user_id, state, prompt, started_at) VALUES ('w1', ?1, ?2, 'running', '[Watch abc] go', ?3)").run(conversation.id, owner.id, t0.toISOString()); | |
| 240 | expect(createWatch(app.db, owner, { brief: "x", kind: "pull_green", target: `${slug}#1` })).toEqual({ ok: false, error: "from_watch" }); | |
| 241 | expect(tool.refusesFirst).toBeDefined(); | |
| 242 | app.db.query("DELETE FROM conversation_run WHERE id = 'w1'").run(); | |
| 243 | expect(createWatch(app.db, owner, { brief: "x", kind: "pull_green", target: `${slug}#1` }).ok).toBe(true); | |
| 244 | }); | |
| 245 | ||
| 246 | test("the wake says the agent cannot start a watch and its writes still wait for a yes", () => { | |
| 247 | const text = wakeText({ id: "abc", brief: "go", kind: "pull_green", target: `${slug}#1`, doneState: "green" }, "it is green"); | |
| 248 | expect(text.startsWith("[Watch abc]")).toBe(true); | |
| 249 | expect(text).toContain("cannot start another watch"); | |
| 250 | expect(text).toContain("owner's yes"); | |
| 251 | }); | |
| 252 | }); | |
| 253 | ||
| 254 | describe("over the MCP", () => { | |
| 255 | const call = async (token: string, args: Record<string, unknown>): Promise<string> => { | |
| 256 | const res = await fetch(`${servers.url}/mcp`, { | |
| 257 | method: "POST", | |
| 258 | headers: { "content-type": "application/json", accept: "application/json, text/event-stream", authorization: `Bearer ${token}` }, | |
| 259 | body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "talk_watch", arguments: args } }), | |
| 260 | }); | |
| 261 | return JSON.stringify(await res.json()); | |
| 262 | }; | |
| 263 | const add = { action: "add", brief: "merge it", kind: "pull_green", target: `${slug}#1` }; | |
| 264 | ||
| 265 | test("the agent's own token only proposes: the add is held and no watch exists until a yes", async () => { | |
| 266 | clear(); | |
| 267 | const c = createConversation(app.db, owner.id); | |
| 268 | if (!c.ok) throw new Error(c.error); | |
| 269 | const via = mintViaToken(app.db, owner.id, `conversation:${c.value.id}`, "watch it", new Date(Date.now() + 600_000).toISOString()); | |
| 270 | if (!via.ok) throw new Error(via.error); | |
| 271 | expect(await call(via.value.token, add)).toContain("needs_confirm"); | |
| 272 | expect(listWatches(app.db, owner.id)).toEqual([]); | |
| 273 | // Reading is never held. | |
| 274 | expect(await call(via.value.token, { action: "list" })).not.toContain("needs_confirm"); | |
| 275 | }); | |
| 276 | ||
| 277 | test("a stranger's token is refused and makes none", async () => { | |
| 278 | clear(); | |
| 279 | const token = createToken(app.db, stranger.id, "t", "rw").token; | |
| 280 | expect(await call(token, add)).not.toContain("watchowner"); | |
| 281 | expect(listWatches(app.db, stranger.id)).toEqual([]); | |
| 282 | expect(listWatches(app.db, owner.id)).toEqual([]); | |
| 283 | }); | |
| 284 | }); |
new above
offline
Cycle: routines.ts imports lookDue from this module and this imports captainThread from routines.ts. Extract captainThread into its own module.