@bridgebrew/sessions 0.0.0-stage → 0.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +43 -2
- package/answers.ts +167 -0
- package/browser/branch-actions.tsx +166 -0
- package/browser/changes.tsx +415 -0
- package/browser/children.tsx +650 -0
- package/browser/conversation.tsx +2381 -0
- package/browser/decision-questions.tsx +191 -0
- package/browser/elapsed.tsx +44 -0
- package/browser/gallery.tsx +218 -0
- package/browser/index.tsx +3434 -0
- package/browser/media-origins.tsx +38 -0
- package/browser/mobile.tsx +663 -0
- package/browser/open-link.tsx +30 -0
- package/browser/pull-request.tsx +116 -0
- package/browser/questions.tsx +156 -0
- package/browser/session-scheduled.tsx +203 -0
- package/browser/subagent-view.tsx +136 -0
- package/browser/subagents.tsx +339 -0
- package/browser/tabs.tsx +228 -0
- package/browser/tsconfig.json +15 -0
- package/browser/views/view.tsx +1064 -0
- package/browser/views.tsx +166 -0
- package/contract.ts +287 -0
- package/delegations.ts +1975 -0
- package/diff.ts +88 -0
- package/docs/en/images.mdx +51 -0
- package/docs/en/index.mdx +22 -0
- package/docs/en/meta.json +4 -0
- package/docs/en/organize-sessions.mdx +53 -0
- package/docs/en/start-a-session.mdx +63 -0
- package/docs/meta.json +4 -0
- package/git.ts +223 -0
- package/listing.ts +382 -0
- package/package.json +1023 -4
- package/peers.ts +677 -0
- package/pull-request-watch.ts +282 -0
- package/pull-requests.ts +606 -0
- package/server.ts +5915 -0
- package/text.ts +19 -0
- package/tsconfig.json +3 -0
- package/viewer-activity.ts +57 -0
- package/views/examples.ts +153 -0
- package/views/library.ts +1116 -0
package/delegations.ts
ADDED
|
@@ -0,0 +1,1975 @@
|
|
|
1
|
+
// Child sessions (bridge#212 S1, S2, S4 and S5, research-082 section 8): a session's agent delegates a task to a new
|
|
2
|
+
// session of the workspace, its child, gets the child's result and questions back as messages, and messages other
|
|
3
|
+
// sessions.
|
|
4
|
+
// - The record: the child keeps `parent`, its parent session's id, set at its creation and never changed; the parent
|
|
5
|
+
// keeps its `delegations` (`{ id, child, title, clientRequestId, request, status, createdAt, endedAt?, result?,
|
|
6
|
+
// error?, delivery? }`). A delegation names the work, apart from the child session that does it, so nothing here
|
|
7
|
+
// assumes the child is an agent: it is done when its child is (below), and its result is its child's last answer.
|
|
8
|
+
// - `delegate_session` (`POST /sessions/delegate`) `{ from, prompt, title?, role?, target? { profile, model, effort,
|
|
9
|
+
// options, project }, mode?, interaction?, isolation?, worktree?, wait?, clientRequestId }` → `{ delegation,
|
|
10
|
+
// session, status, title, worktree? }`. `from` is the caller's own session (an agent acts only for its own,
|
|
11
|
+
// `actsAs`); the child is made with `createSession` (its refusals kept: the harness unknown, disabled or without its
|
|
12
|
+
// driver, the model, effort, mode or options unknown), on the parent's node (bound to its worktree) or
|
|
13
|
+
// `target.project`'s. Its defaults are the parent's: its profile, model and effort (the same profile only), options
|
|
14
|
+
// and mode; explicit values win. Its mode is always set (the parent's mode, else the profile's current one) and never
|
|
15
|
+
// above the parent's (`aboveParent`): `mode_above_parent` (403). `role` other than `general` puts "Act as the <role>
|
|
16
|
+
// sub-agent for this task." before the prompt. `clientRequestId` is the caller's key: the same key and payload again
|
|
17
|
+
// answer the first delegation, another payload under it is refused (`client_request_conflict`, 409; `wait` and
|
|
18
|
+
// `timeoutMs` are not part of the payload). `wait: wait` (S4) then waits for it as `read_delegation` does, up to
|
|
19
|
+
// `timeoutMs` (10 minutes by default, 60 at most), outside the parent's one-at-a-time creation. The child gets the
|
|
20
|
+
// prompt only, never the parent's history, after a `<bridge_delegation>` block telling it its final answer is its
|
|
21
|
+
// result; it is stored in the child's queue in the write that creates it (S7: once bound to its worktree), then sent
|
|
22
|
+
// as a queued message is.
|
|
23
|
+
// - Isolation (S7): `shared` (the default), the child works where its parent does (its folder, its worktree).
|
|
24
|
+
// `isolation: worktree` with `worktree: { plugins, branch? }` gives the child a branch of its own and a stage running
|
|
25
|
+
// it (research-083; `worktree` stays the field's name): the host makes the new branch (`branch`, else
|
|
26
|
+
// `child-<title>-<8 hex>`) of the repository the workspace runs `plugins` from, as the project's Branches screen
|
|
27
|
+
// makes one (from its default branch, its folder under `.worktrees/`), then a stage of the workspace choosing it
|
|
28
|
+
// (`addWorktree`), and the child is bound to the stage (its
|
|
29
|
+
// `<bridge_delegation>` block says so). A dependency install can outlast the host's request deadline (30 s), so the
|
|
30
|
+
// call answers at once: the delegation runs with `preparing` and its child exists, unbound, nothing queued; the
|
|
31
|
+
// worktree is added in the background (`prepare`), then the child is bound to it and its task queued and sent. No
|
|
32
|
+
// turn starts in a preparing child (`preparing`, read by `server.ts`: the user's messages wait in its queue). The
|
|
33
|
+
// host's refusal ends the delegation `failed` with its reason, delivered as any failure; a restart meanwhile too
|
|
34
|
+
// (`sweep`). Refused at once without `plugins` (`worktree_plugins_required`), `worktree` without that isolation
|
|
35
|
+
// (`worktree_without_isolation`), and for an agent whose session's mode does not write (`worktree_needs_writes`,
|
|
36
|
+
// 403: `stage_add`'s rule, `writesOf`). The worktree is the child's work: kept when it ends; the delegation
|
|
37
|
+
// records it (`worktree: { slug, branch }`), its result and `read_delegation` name it; its branch merges by its pull
|
|
38
|
+
// request (the project's Branches screen), its stage is removed as any (`stage_remove`, the branch kept).
|
|
39
|
+
// - Done: the child's turn ended, not cut by this plugin's disposal (`ended`), its queue empty (or stopped by the
|
|
40
|
+
// user), no decision open, no delegation of its own still running (`check`). Its result is its last turn's text after
|
|
41
|
+
// its last tool call (`resultOf`), or that turn's error. One `change` of the parent writes the delegation's state and
|
|
42
|
+
// a result in the parent's queue (item `delegation-<id>`, beyond the queue's 20; `delegations` on the item),
|
|
43
|
+
// un-settles a settled parent, then the parent's queue is sent (`dequeue`, results only when its last turn did not
|
|
44
|
+
// complete); a parent whose turn runs on a harness that steers gets them in that turn at once (S6, `server.ts`'s
|
|
45
|
+
// `steerResults`), taken out of the queue in the write, so never both steered and sent after. An archived parent
|
|
46
|
+
// gets no message (`delivery: 'dropped'`): its result stays readable. Results waiting
|
|
47
|
+
// together go in one message (`takeQueued`): each `Delegated session <id> (<title>) [<status>]:` then its text as is,
|
|
48
|
+
// inline up to 16 KiB in all, the rest pointing at `read_delegation`, then the questions waiting (below). Taken out of
|
|
49
|
+
// the queue, a result is `sending` until the parent's `user/message` line carrying it landed, then `sent`; the start
|
|
50
|
+
// (`recover`) marks one found in the parent's history `sent` and puts any other back in its queue: never lost to a
|
|
51
|
+
// crash in between, never sent twice.
|
|
52
|
+
// - A child's question (S2): a decision none of whose options allows or denies (`isQuestion`: Claude's AskUserQuestion,
|
|
53
|
+
// Codex's request for input) asked while its parent's delegation of it runs goes in the parent's queue too (item
|
|
54
|
+
// `question-<decision>`, `questions: [{ session, decision, text }]`, beyond the queue's 20; a settled parent active
|
|
55
|
+
// again, an archived one told nothing), sent as results are; a wait on it answers with it, and one that answers it
|
|
56
|
+
// takes it out of the queue (between two slices of a wait, the next slice does). Closed before it is sent (answered
|
|
57
|
+
// by the user in the child, expired, withdrawn by its agent, or closed by a crash: the start's `sweep`), it leaves
|
|
58
|
+
// the queue (`closed`). An approval (a tool or a command to allow) never reaches the parent: the user answers it in
|
|
59
|
+
// the child; it only ends a wait on its delegation, which names it and says so. A snoozed parent stays snoozed: a
|
|
60
|
+
// turn that delivers results or questions does not wake it (`server.ts`).
|
|
61
|
+
// - `answer_delegation` (`POST /sessions/delegation/answer`) `{ from, action, delegation, request?, answers? }`: the
|
|
62
|
+
// caller's agent handles the pending questions of a delegation's child, the delegation its own or one a session
|
|
63
|
+
// below it made (`locate`). `list` gives the ids of its child's pending questions (approvals are never listed);
|
|
64
|
+
// `read` one of them (`request`, Bridge's decision id) in full: its questions, each `{ id, header?, question,
|
|
65
|
+
// options: [{ id, label, description? }], multiSelect, allowCustomAnswer, required }`, as the child's agent asked them
|
|
66
|
+
// (the harness contract's `questions`, its question tool's); `respond` answers it with `answers` (per question, its
|
|
67
|
+
// `question` id, its options, and its `text` where it takes one; a request of one question may leave `question` out),
|
|
68
|
+
// through the same answer as the user's (`decision/answered {by: <caller>}` in the child), checked as the user's
|
|
69
|
+
// (`answers.ts`): several options only with `multiSelect`, a text only with `allowCustomAnswer`
|
|
70
|
+
// (`custom_answer_unavailable`), every required question answered (`invalid_answer`). A decision of an old driver,
|
|
71
|
+
// without `questions`, is one question (the request's id) with one choice among its options, `multiSelect` and
|
|
72
|
+
// `allowCustomAnswer` false. Refused for an approval (`approval_not_yours`, 403: only the user
|
|
73
|
+
// answers it), a closed request (`decision_closed`, 409), an ended delegation (`delegation_ended`, 409), and, to
|
|
74
|
+
// respond, a child above the caller's mode now. Answered or dismissed (in the child, by the user) before its message
|
|
75
|
+
// starts a turn, a question leaves the caller's queue (`closed`).
|
|
76
|
+
// - `prompt_session` (`POST /sessions/prompt`) `{ from, to, text, delivery?: auto | queue | steer | restart }`: a
|
|
77
|
+
// message from the caller's session that starts a turn in session `to` when none runs; while one runs (S6), `auto`
|
|
78
|
+
// (the default) steers it into that turn when its harness steers, else queues it; `queue` queues it; `steer` steers
|
|
79
|
+
// it or is refused (`steer_unavailable`, `steer_declined`); `restart` stops that turn and starts one with it (none
|
|
80
|
+
// running: `steer` and `restart` refused, `turn_not_running`); the answer's `delivery` says `started`, `steered`,
|
|
81
|
+
// `queued` or `restarted` (`server.ts`'s `sendOrQueue`). Bridge's words with its `sender` (`user/message {from:
|
|
82
|
+
// 'bridge', sender}`). To the caller's own child, a follow-up: a new delegation of that child (its result wakes the
|
|
83
|
+
// caller as any; while one runs, the message joins it: decided in the parent's write, `follow`); to any other
|
|
84
|
+
// session, delivered with no delegation, nothing back. Open or join is decided with the child's queue lock held
|
|
85
|
+
// (`send` runs the `Opening` there), as the user's follow-up: a `check` delivering the earlier delegation goes first
|
|
86
|
+
// (a new one opens) or after (the message joined it and keeps the child busy), never between. The target is made
|
|
87
|
+
// active again before the message is sent, so the turn it starts reads what changed while it was settled
|
|
88
|
+
// (`settledSince`, `server.ts`) once.
|
|
89
|
+
// - The user's follow-up (S5, `fromUser`): a message the user sends a child whose parent is not archived opens a new
|
|
90
|
+
// delegation of it for its parent (title `From the user: <text>`, key `user-<id>`), whose result wakes the parent as
|
|
91
|
+
// any; while one runs, the message joins it. Opened in the child's queue lock before the message starts or waits (a
|
|
92
|
+
// `check` delivering the earlier one goes first or after), removed when it does neither. Refused for an archived
|
|
93
|
+
// target (`not_found`), one above the caller's mode (`mode_above_caller`, 403: `mayReach`), and one stopped
|
|
94
|
+
// (`session_stopped`, 409: by the user or a cancel, its next message the user's); a settled target is active again, a
|
|
95
|
+
// snoozed one wakes. `mayReach` also guards `triage_session` from agents (`server.ts`).
|
|
96
|
+
// - `read_delegation` (`POST /sessions/delegation/read`) `{ from, delegation, timeoutMs? }` waits for its end up to
|
|
97
|
+
// `timeoutMs` (25 s by default, 60 minutes at most; 0 reads at once) and answers its state, its result once done; a
|
|
98
|
+
// result read there leaves the parent's queue in the same write and is never sent. A question or an approval open in
|
|
99
|
+
// its child ends the wait (`questions`, `approvals`); its end by the timeout says `waitTimedOut`. One call waits a
|
|
100
|
+
// slice at most (`sliceOf` the host's request deadline: 25 s of 30 s), then answers `$mcp: { again: { path, body }
|
|
101
|
+
// }`, the same wait for what is left, which `bridge mcp` calls in turn as the same caller
|
|
102
|
+
// (`packages/host/src/mcp.ts`): no call outlives the host's deadline, and a reload between two slices costs none. A
|
|
103
|
+
// wait whose caller no longer runs a turn, or was stopped, takes nothing out of its queue (`listening`): its tool
|
|
104
|
+
// call was cut, its results and questions come as a message.
|
|
105
|
+
// - `cancel_delegation` (`POST /sessions/delegation/cancel`) `{ from, delegation }` stops its child and the child's
|
|
106
|
+
// descendants, each delegation of the subtree `cancelled` and delivered to nobody; refused (`descendant_above_mode`,
|
|
107
|
+
// 403) while one of them runs in a mode above the caller's. Stop on a session (`stopTree`, from `POST
|
|
108
|
+
// /sessions/interrupt`) stops its whole subtree of children, whose results then wait in their stopped parents'
|
|
109
|
+
// queues; a delegation it was making meanwhile is refused (`session_stopped`, 409) before its child exists, else
|
|
110
|
+
// its child is stopped before its task starts (its delegation ends `interrupted`).
|
|
111
|
+
// - `list_session_profiles` (`POST /sessions/profiles`) `{ from? }` → `{ current, profiles }`: each enabled profile
|
|
112
|
+
// with its models (and their efforts) and its modes (and their options), on the caller's node.
|
|
113
|
+
// - After a restart or a crash: a turn Bridge cut (the disposal, or the start's repair after a crash) is continued by
|
|
114
|
+
// `server.ts`, and its end delivers. The start's `sweep` (after the continuation's decision) checks each child of a
|
|
115
|
+
// running delegation that was neither continued nor is running nor holds a queue, and delivers what is done.
|
|
116
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
117
|
+
import { cutText } from './text.ts';
|
|
118
|
+
import { z } from 'zod';
|
|
119
|
+
import { actsAs } from './peers.ts';
|
|
120
|
+
import { checkAnswer, isQuestion, type Answer, type Answers, type Question } from './answers.ts';
|
|
121
|
+
|
|
122
|
+
export { isQuestion };
|
|
123
|
+
|
|
124
|
+
/** The roles a delegation may give its child: all but `general` put a line before the prompt. */
|
|
125
|
+
export const ROLES = ['implementation', 'research', 'review', 'design', 'test', 'general'] as const;
|
|
126
|
+
/** Bridge's permission levels, lowest first (`plugins/harness/types.ts`, `Level`). */
|
|
127
|
+
const LEVELS = ['read-only', 'ask', 'build', 'god'];
|
|
128
|
+
/** The most bytes of results one message carries inline; past it, `read_delegation` gives them. */
|
|
129
|
+
export const RESULTS_INLINE = 16 * 1024;
|
|
130
|
+
/** How long one call of a wait lasts at most (its slice), and `read_delegation`'s wait by default: within the host's
|
|
131
|
+
* request deadline (30 s), as `wait_answer`. A longer wait answers `$mcp.again` at the end of each slice. */
|
|
132
|
+
export const READ_WAIT_MS = 25_000;
|
|
133
|
+
/** How long a wait (`delegate_session` with `wait: wait`, `read_delegation`) lasts at most: 60 minutes. */
|
|
134
|
+
export const WAIT_MAX_MS = 60 * 60_000;
|
|
135
|
+
/** How long `delegate_session` with `wait: wait` waits without a `timeoutMs`: 10 minutes. */
|
|
136
|
+
export const WAIT_DEFAULT_MS = 10 * 60_000;
|
|
137
|
+
/** The slice of a wait for a host whose request deadline is `deadlineMs` (30 s when not known): five sixths of it, so
|
|
138
|
+
* the route answers before the host cuts it, READ_WAIT_MS at most, a second at least. */
|
|
139
|
+
export const sliceOf = (deadlineMs = 30_000) =>
|
|
140
|
+
Math.max(1000, Math.min(READ_WAIT_MS, Math.floor((deadlineMs * 5) / 6)));
|
|
141
|
+
/** What gives a message once its target's queue lock is held, and what undoes what it opened when the message neither
|
|
142
|
+
* starts a turn nor waits in the queue. */
|
|
143
|
+
export type Opening = () => Promise<{ text: string; undo?: (() => Promise<unknown>) | undefined }>;
|
|
144
|
+
/** The most characters of a delegated prompt. */
|
|
145
|
+
const PROMPT_MAX = 100_000;
|
|
146
|
+
|
|
147
|
+
export const delegation = z.strictObject({
|
|
148
|
+
id: z.string(),
|
|
149
|
+
/** The child session doing it: none until it is created. */
|
|
150
|
+
child: z.string().optional(),
|
|
151
|
+
title: z.string(),
|
|
152
|
+
clientRequestId: z.string(),
|
|
153
|
+
/** The payload's digest: the same `clientRequestId` with another payload is refused. */
|
|
154
|
+
request: z.string(),
|
|
155
|
+
status: z.enum(['running', 'completed', 'failed', 'interrupted', 'cancelled']),
|
|
156
|
+
createdAt: z.string(),
|
|
157
|
+
endedAt: z.string().optional(),
|
|
158
|
+
result: z.string().optional(),
|
|
159
|
+
error: z.string().optional(),
|
|
160
|
+
/** Once done: `queued` in the parent's queue, `sending` taken out of it for a turn of it (its message line not
|
|
161
|
+
* written yet: the start's `recover` sends it again unless that line is in the parent's history), `sent` in a turn
|
|
162
|
+
* of it, `read` through `read_delegation` (or cancelled by the parent), `dropped` (the parent archived). */
|
|
163
|
+
delivery: z.enum(['queued', 'sending', 'sent', 'read', 'dropped']).optional(),
|
|
164
|
+
/** `isolation: worktree` (S7): the worktree of the workspace the child works in, and its git branch. */
|
|
165
|
+
worktree: z.strictObject({ slug: z.string(), branch: z.string() }).optional(),
|
|
166
|
+
/** `isolation: worktree` (S7): its child's worktree is being made, its task not sent yet. A running delegation. */
|
|
167
|
+
preparing: z.literal(true).optional(),
|
|
168
|
+
});
|
|
169
|
+
export type Delegation = z.infer<typeof delegation>;
|
|
170
|
+
|
|
171
|
+
/** A child's open question waiting in its parent's queue: its child session, its decision, the text that asks it. */
|
|
172
|
+
export interface QueuedQuestion {
|
|
173
|
+
session: string;
|
|
174
|
+
decision: string;
|
|
175
|
+
text: string;
|
|
176
|
+
}
|
|
177
|
+
/** A queued message, as `server.ts` keeps it; a result's has `delegations`, a child's question `questions`. */
|
|
178
|
+
interface QueueItem {
|
|
179
|
+
id: string;
|
|
180
|
+
text: string;
|
|
181
|
+
at: string;
|
|
182
|
+
from?: 'bridge' | undefined;
|
|
183
|
+
delegations?: string[] | undefined;
|
|
184
|
+
questions?: QueuedQuestion[] | undefined;
|
|
185
|
+
sender?: string | undefined;
|
|
186
|
+
}
|
|
187
|
+
/** A decision as the harness asks it: a question as its driver says (`kind`), else when it has `questions` or none of
|
|
188
|
+
* its options allows or denies (`isQuestion`). */
|
|
189
|
+
export interface Decision {
|
|
190
|
+
id: string;
|
|
191
|
+
title: string;
|
|
192
|
+
options: { id: string; label: string; kind: 'allow' | 'deny' | 'other' }[];
|
|
193
|
+
kind?: 'question' | 'approval' | undefined;
|
|
194
|
+
questions?: Question[] | undefined;
|
|
195
|
+
}
|
|
196
|
+
type Options = { plan?: true | undefined; auto?: true | undefined };
|
|
197
|
+
interface Value {
|
|
198
|
+
title: string;
|
|
199
|
+
harness: string;
|
|
200
|
+
model?: string | undefined;
|
|
201
|
+
effort?: string | undefined;
|
|
202
|
+
mode?: string | undefined;
|
|
203
|
+
options?: Options | undefined;
|
|
204
|
+
worktree?: { slug: string; folder: string } | undefined;
|
|
205
|
+
settledAt?: string | undefined;
|
|
206
|
+
parent?: string | undefined;
|
|
207
|
+
delegations?: Delegation[] | undefined;
|
|
208
|
+
queue?: QueueItem[] | undefined;
|
|
209
|
+
}
|
|
210
|
+
interface Found<V> {
|
|
211
|
+
id: string;
|
|
212
|
+
node: string;
|
|
213
|
+
value: V;
|
|
214
|
+
archived?: boolean | undefined;
|
|
215
|
+
}
|
|
216
|
+
/** A permission mode as the harness lists it. */
|
|
217
|
+
interface Mode {
|
|
218
|
+
id: string;
|
|
219
|
+
name?: string;
|
|
220
|
+
current?: boolean | undefined;
|
|
221
|
+
full?: true | undefined;
|
|
222
|
+
readOnly?: true | undefined;
|
|
223
|
+
options?: string[] | undefined;
|
|
224
|
+
}
|
|
225
|
+
/** A history line of a session's last turn. */
|
|
226
|
+
type Line = { type: string } & Record<string, unknown>;
|
|
227
|
+
|
|
228
|
+
/** A session's permissions, as the cap compares them: its harness, its mode (`undefined`: the harness has none, or
|
|
229
|
+
* none is known), its options, and its harness's modes. */
|
|
230
|
+
export interface Permissions {
|
|
231
|
+
harness: string;
|
|
232
|
+
mode: string | undefined;
|
|
233
|
+
options: Options | undefined;
|
|
234
|
+
modes: Mode[];
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/** Whether `mode` writes (Ask, Build, or full): only a harness that marks its read-only mode (`readOnly`) says so, one
|
|
238
|
+
* that does not (ACP) never writes beyond full (Codex review). */
|
|
239
|
+
export const writesOf = (
|
|
240
|
+
mode: { full?: true | undefined; readOnly?: true | undefined } | undefined,
|
|
241
|
+
modes: { readOnly?: true | undefined }[],
|
|
242
|
+
) =>
|
|
243
|
+
mode !== undefined &&
|
|
244
|
+
(mode.full === true || (mode.readOnly !== true && modes.some((each) => each.readOnly)));
|
|
245
|
+
|
|
246
|
+
/** Why `child` would run above `parent`, `undefined` when it does not: a read-only mode is always below; Bridge's
|
|
247
|
+
* levels compare in order; a harness's own modes only as the parent's exact harness and mode; `auto` only when the
|
|
248
|
+
* parent has it, and a parent planning first has its child plan first too. A parent in a full mode allows any. */
|
|
249
|
+
export const aboveParent = (parent: Permissions, child: Permissions): string | undefined => {
|
|
250
|
+
const parentMode = parent.modes.find((each) => each.id === parent.mode);
|
|
251
|
+
const childMode = child.modes.find((each) => each.id === child.mode);
|
|
252
|
+
if (parentMode?.full) return undefined;
|
|
253
|
+
if (childMode?.readOnly) return undefined;
|
|
254
|
+
if (child.options?.auto && !parent.options?.auto)
|
|
255
|
+
return 'the auto option (its reviewer answers its requests) is not on this session';
|
|
256
|
+
if (parent.options?.plan && !child.options?.plan)
|
|
257
|
+
return 'this session plans first (the plan option), the other does not';
|
|
258
|
+
// A harness without modes: nothing to compare when the parent's has none either.
|
|
259
|
+
if (!child.modes.length && child.mode === undefined)
|
|
260
|
+
return parent.modes.length
|
|
261
|
+
? `harness ${child.harness} has no permission modes to keep it within this session's`
|
|
262
|
+
: undefined;
|
|
263
|
+
if (child.mode === undefined || parent.mode === undefined)
|
|
264
|
+
return "this session's permission mode is not known";
|
|
265
|
+
const rank = (mode: string) => LEVELS.indexOf(mode);
|
|
266
|
+
if (rank(child.mode) >= 0 && rank(parent.mode) >= 0)
|
|
267
|
+
return rank(child.mode) <= rank(parent.mode)
|
|
268
|
+
? undefined
|
|
269
|
+
: `mode ${child.mode} is above this session's mode ${parent.mode}`;
|
|
270
|
+
if (child.harness === parent.harness && child.mode === parent.mode) return undefined;
|
|
271
|
+
return `mode ${child.mode} of ${child.harness} is not this session's mode (${parent.mode} of ${parent.harness}), nor read-only`;
|
|
272
|
+
};
|
|
273
|
+
|
|
274
|
+
/** A delegation's text as its parent reads it (its text, then its error). */
|
|
275
|
+
const bodyOf = (each: Delegation) =>
|
|
276
|
+
[each.result, each.error && `Error: ${each.error}`].filter(Boolean).join('\n\n') || '(no answer)';
|
|
277
|
+
const headerOf = (each: Delegation) =>
|
|
278
|
+
`Delegated session ${each.id} (${each.title}) [${each.status}]:${each.worktree ? `\n${worktreeLine(each.worktree)}` : ''}`;
|
|
279
|
+
/** Where a child in a worktree of its own left its work (S7). `branch` is `detached at <commit>` when its checkout is on
|
|
280
|
+
* no branch (`headOf`; a git branch name holds no space). */
|
|
281
|
+
const worktreeLine = ({ slug, branch }: { slug: string; branch: string }) =>
|
|
282
|
+
`Its work is ${branch.startsWith('detached at ') ? branch : `on git branch ${branch}`}, run in stage ${slug}, both kept: the branch merges by its pull request (the project's Branches screen), stage_remove removes the stage (never the branch).`;
|
|
283
|
+
/** The message giving `done`'s results, in order: each inline while all of them fit `RESULTS_INLINE` bytes, from the
|
|
284
|
+
* first that does not on, a pointer to `read_delegation`. */
|
|
285
|
+
export const resultsText = (done: Delegation[]) => {
|
|
286
|
+
let used = 0;
|
|
287
|
+
let full = false;
|
|
288
|
+
return done
|
|
289
|
+
.map((each) => {
|
|
290
|
+
const body = bodyOf(each);
|
|
291
|
+
used += Buffer.byteLength(body, 'utf8');
|
|
292
|
+
if (used > RESULTS_INLINE) full = true;
|
|
293
|
+
return `${headerOf(each)}\n${full ? `Use read_delegation with delegation ${each.id} to read the result.` : body}`;
|
|
294
|
+
})
|
|
295
|
+
.join('\n\n');
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
/** Whether a queued message is Bridge's delivery to a parent: its children's results or questions. */
|
|
299
|
+
export const isDelivery = (item: QueueItem) =>
|
|
300
|
+
!!item.delegations?.length || !!item.questions?.length;
|
|
301
|
+
const automatic = isDelivery;
|
|
302
|
+
/** Delivery `item` with only `delegations` and `questions` left: none when nothing is left of it. */
|
|
303
|
+
const keep = (
|
|
304
|
+
{ delegations: _delegations, questions: _questions, ...item }: QueueItem,
|
|
305
|
+
delegations: string[] | undefined,
|
|
306
|
+
questions: QueuedQuestion[] | undefined,
|
|
307
|
+
): QueueItem[] =>
|
|
308
|
+
delegations?.length || questions?.length
|
|
309
|
+
? [
|
|
310
|
+
{
|
|
311
|
+
...item,
|
|
312
|
+
...(delegations?.length && { delegations }),
|
|
313
|
+
...(questions?.length && { questions }),
|
|
314
|
+
},
|
|
315
|
+
]
|
|
316
|
+
: [];
|
|
317
|
+
/** What `dequeue` sends next from `value`'s queue: its first message (unless `resultsOnly`), or, when that is a
|
|
318
|
+
* delivery or with `resultsOnly`, every result and question waiting but those `held` (a wait's), in one message
|
|
319
|
+
* (results first, their delegations then `sending` until its line is written; each question's text after them); the
|
|
320
|
+
* queue without it. */
|
|
321
|
+
export const takeQueued = <V extends Value>(
|
|
322
|
+
value: V,
|
|
323
|
+
resultsOnly = false,
|
|
324
|
+
held: (item: QueueItem) => boolean = () => false,
|
|
325
|
+
): { item: QueueItem | undefined; value: V } => {
|
|
326
|
+
const queue = value.queue ?? [];
|
|
327
|
+
const without = (rest: QueueItem[]) => {
|
|
328
|
+
const { queue: _queue, ...others } = value;
|
|
329
|
+
return (rest.length ? { ...others, queue: rest } : others) as V;
|
|
330
|
+
};
|
|
331
|
+
const head = queue[0];
|
|
332
|
+
if (!resultsOnly && head && !automatic(head))
|
|
333
|
+
return { item: head, value: without(queue.slice(1)) };
|
|
334
|
+
const taken = queue.filter((each) => automatic(each) && !held(each));
|
|
335
|
+
if (!taken.length) return { item: undefined, value };
|
|
336
|
+
const ids = taken.flatMap((each) => each.delegations ?? []);
|
|
337
|
+
const done = ids
|
|
338
|
+
.map((id) => value.delegations?.find((each) => each.id === id))
|
|
339
|
+
.filter((each): each is Delegation => each !== undefined && each.delivery !== 'read');
|
|
340
|
+
const questions = taken.flatMap((each) => each.questions ?? []);
|
|
341
|
+
const rest = queue.filter((each) => !taken.includes(each));
|
|
342
|
+
const next = {
|
|
343
|
+
...without(rest),
|
|
344
|
+
...(value.delegations && {
|
|
345
|
+
delegations: value.delegations.map((each) =>
|
|
346
|
+
ids.includes(each.id) && each.delivery === 'queued'
|
|
347
|
+
? { ...each, delivery: 'sending' as const }
|
|
348
|
+
: each,
|
|
349
|
+
),
|
|
350
|
+
}),
|
|
351
|
+
};
|
|
352
|
+
if (!done.length && !questions.length) return { item: undefined, value: next };
|
|
353
|
+
return {
|
|
354
|
+
item: {
|
|
355
|
+
id: taken[0]!.id,
|
|
356
|
+
text: [
|
|
357
|
+
...(done.length ? [resultsText(done)] : []),
|
|
358
|
+
...questions.map((each) => each.text),
|
|
359
|
+
].join('\n\n'),
|
|
360
|
+
at: taken[0]!.at,
|
|
361
|
+
from: 'bridge',
|
|
362
|
+
...(done.length && { delegations: done.map((each) => each.id) }),
|
|
363
|
+
...(questions.length && { questions }),
|
|
364
|
+
},
|
|
365
|
+
value: next,
|
|
366
|
+
};
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
/** The questions of decision `decision` as `answer_delegation` reads them: its own (the agent's question tool's), else
|
|
370
|
+
* one question of its title, one choice among its options (an old driver's, `id` the request's). */
|
|
371
|
+
/** A question as `answer_delegation` reads it. */
|
|
372
|
+
interface ReadQuestion {
|
|
373
|
+
id: string;
|
|
374
|
+
header?: string;
|
|
375
|
+
question: string;
|
|
376
|
+
options: { id: string; label: string; description?: string }[];
|
|
377
|
+
multiSelect: boolean;
|
|
378
|
+
allowCustomAnswer: boolean;
|
|
379
|
+
required: boolean;
|
|
380
|
+
}
|
|
381
|
+
const questionsOf = ({ id, title, options, questions }: Decision): ReadQuestion[] =>
|
|
382
|
+
questions?.length
|
|
383
|
+
? questions.map((each) => ({
|
|
384
|
+
id: each.id,
|
|
385
|
+
...(each.header !== undefined && { header: each.header }),
|
|
386
|
+
question: each.question,
|
|
387
|
+
options: each.options.map(({ id: option, label, description }) => ({
|
|
388
|
+
id: option,
|
|
389
|
+
label,
|
|
390
|
+
...(description !== undefined && { description }),
|
|
391
|
+
})),
|
|
392
|
+
multiSelect: each.multiSelect === true,
|
|
393
|
+
allowCustomAnswer: each.custom === true,
|
|
394
|
+
required: each.required !== false,
|
|
395
|
+
}))
|
|
396
|
+
: [
|
|
397
|
+
{
|
|
398
|
+
id,
|
|
399
|
+
question: title,
|
|
400
|
+
options: options.map(({ id: option, label }) => ({ id: option, label })),
|
|
401
|
+
multiSelect: false,
|
|
402
|
+
allowCustomAnswer: false,
|
|
403
|
+
required: true,
|
|
404
|
+
},
|
|
405
|
+
];
|
|
406
|
+
|
|
407
|
+
/** The message telling a parent its child `child` (`title`, working on `delegation`) asks the user `decision`: each
|
|
408
|
+
* question with its options (their ids and what they mean), whether it takes several of them or a free text. */
|
|
409
|
+
export const questionText = (
|
|
410
|
+
child: string,
|
|
411
|
+
title: string,
|
|
412
|
+
delegation: string,
|
|
413
|
+
decision: Decision,
|
|
414
|
+
) => {
|
|
415
|
+
const questions = questionsOf(decision);
|
|
416
|
+
const several = questions.length > 1;
|
|
417
|
+
const asked = questions
|
|
418
|
+
.map((each, index) =>
|
|
419
|
+
[
|
|
420
|
+
`${several ? `${index + 1}. ` : ''}${several || decision.questions?.length ? `[question ${each.id}] ` : ''}${each.header ? `${each.header}: ` : ''}${each.question}`,
|
|
421
|
+
...each.options.map(
|
|
422
|
+
(option) =>
|
|
423
|
+
` - ${option.id} "${option.label}"${option.description ? `: ${option.description}` : ''}`,
|
|
424
|
+
),
|
|
425
|
+
[
|
|
426
|
+
each.multiSelect && 'several options allowed',
|
|
427
|
+
each.allowCustomAnswer && 'a free-text answer allowed (text)',
|
|
428
|
+
!each.required && 'optional',
|
|
429
|
+
]
|
|
430
|
+
.filter(Boolean)
|
|
431
|
+
.map((note) => ` (${note})`)
|
|
432
|
+
.join('\n'),
|
|
433
|
+
]
|
|
434
|
+
.filter(Boolean)
|
|
435
|
+
.join('\n'),
|
|
436
|
+
)
|
|
437
|
+
.join('\n');
|
|
438
|
+
const shape = decision.questions?.length
|
|
439
|
+
? `answers: [{ question: <its id>, options: [option ids], text? }] for each question`
|
|
440
|
+
: 'answers: [{ options: [one of these ids] }]';
|
|
441
|
+
return `Child session ${child} (${title}), delegation ${delegation}, asks the user (request ${decision.id}):
|
|
442
|
+
${several || decision.questions?.length ? asked : `${decision.title}\nOptions: ${decision.options.map((each) => `${each.id} "${each.label}"`).join(', ')}`}
|
|
443
|
+
Answer it yourself with answer_delegation (action respond, delegation ${delegation}, request ${decision.id}, ${shape}) when you know the answer, or ask the user (who may also answer it in that session); action list gives its child's pending questions, action read one in full. The child waits until it is answered.`;
|
|
444
|
+
};
|
|
445
|
+
|
|
446
|
+
/** The result of a session's last turn (`lines`, from its `turn/start`): its status, its text after its last tool call
|
|
447
|
+
* (else its last text), its error when it failed; its sub-agents' lines (`subagent`) left out. */
|
|
448
|
+
export const resultOf = (
|
|
449
|
+
lines: Line[],
|
|
450
|
+
): { status: 'completed' | 'failed' | 'interrupted'; text?: string; error?: string } => {
|
|
451
|
+
// Stopped before its first turn started (its prompt still queued): nothing to give.
|
|
452
|
+
if (!lines.length) return { status: 'interrupted' };
|
|
453
|
+
// Its agent's own sub-agents' lines (S8) are not its answer.
|
|
454
|
+
const own = lines.filter((each) => each.subagent === undefined);
|
|
455
|
+
const end = lines.findLast((each) => each.type === 'turn/end');
|
|
456
|
+
const reason = end?.reason;
|
|
457
|
+
const status = reason === 'completed' || reason === 'failed' ? reason : 'interrupted';
|
|
458
|
+
const texts = (from: Line[]) =>
|
|
459
|
+
from
|
|
460
|
+
.filter((each) => each.type === 'assistant/message' && typeof each.text === 'string')
|
|
461
|
+
.map((each) => each.text as string);
|
|
462
|
+
const lastTool = own.findLastIndex(
|
|
463
|
+
(each) => each.type === 'tool/call' || each.type === 'tool/result',
|
|
464
|
+
);
|
|
465
|
+
const text =
|
|
466
|
+
texts(own.slice(lastTool + 1))
|
|
467
|
+
.join('')
|
|
468
|
+
.trim() || texts(own).at(-1)?.trim();
|
|
469
|
+
const message = typeof end?.message === 'string' ? end.message : undefined;
|
|
470
|
+
return {
|
|
471
|
+
status,
|
|
472
|
+
...(text && { text }),
|
|
473
|
+
...(status === 'failed' && { error: message ?? 'the turn failed' }),
|
|
474
|
+
};
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
/** What a running delegation whose child's worktree is being made says (S7). */
|
|
478
|
+
const PREPARING_HINT =
|
|
479
|
+
"Its child's worktree is being made: its task starts there once it is ready (a dependency install may take minutes). Its result reaches you as a message when it ends, a failure to make the worktree too. Call read_delegation to wait for it, or go on with other work.";
|
|
480
|
+
|
|
481
|
+
/** The answer `respond` gives decision `open` from the caller's `answers`: its questions' answers when it has
|
|
482
|
+
* `questions` (one question's `question` may be left out), else one option id. Refused (`invalid_answer`,
|
|
483
|
+
* `invalid_option`, `custom_answer_unavailable`) as the user's answer is (`checkAnswer`). */
|
|
484
|
+
const respondAnswerOf = (
|
|
485
|
+
open: Decision,
|
|
486
|
+
given: {
|
|
487
|
+
question?: string | undefined;
|
|
488
|
+
options?: string[] | undefined;
|
|
489
|
+
text?: string | undefined;
|
|
490
|
+
}[],
|
|
491
|
+
refused: (code: string, message: string) => Error,
|
|
492
|
+
): Exclude<Answer, null> => {
|
|
493
|
+
const ids = open.options.map((one) => one.id).join(', ');
|
|
494
|
+
let answer: Exclude<Answer, null>;
|
|
495
|
+
if (open.questions?.length) {
|
|
496
|
+
const only = open.questions.length === 1 ? open.questions[0]!.id : undefined;
|
|
497
|
+
const missing = given.find((each) => each.question === undefined && only === undefined);
|
|
498
|
+
if (missing)
|
|
499
|
+
throw refused(
|
|
500
|
+
'invalid_answer',
|
|
501
|
+
`request ${open.id} has several questions (${open.questions.map((one) => one.id).join(', ')}): name each answer's question`,
|
|
502
|
+
);
|
|
503
|
+
answer = {
|
|
504
|
+
answers: given.map((each) => ({
|
|
505
|
+
question: each.question ?? only!,
|
|
506
|
+
...(each.options !== undefined && { options: each.options }),
|
|
507
|
+
...(each.text !== undefined && { text: each.text }),
|
|
508
|
+
})),
|
|
509
|
+
};
|
|
510
|
+
} else {
|
|
511
|
+
// One question with one choice among its options: no free text, no second option.
|
|
512
|
+
const [only, ...more] = given;
|
|
513
|
+
if (more.length || (only!.question !== undefined && only!.question !== open.id))
|
|
514
|
+
throw refused(
|
|
515
|
+
'invalid_answer',
|
|
516
|
+
`request ${open.id} has one question, ${open.id}: give one answer for it`,
|
|
517
|
+
);
|
|
518
|
+
if (only!.text !== undefined)
|
|
519
|
+
throw refused(
|
|
520
|
+
'custom_answer_unavailable',
|
|
521
|
+
`question ${open.id} takes no custom answer (allowCustomAnswer false): choose one of its options, ${ids}`,
|
|
522
|
+
);
|
|
523
|
+
if (only!.options?.length !== 1)
|
|
524
|
+
throw refused(
|
|
525
|
+
'invalid_answer',
|
|
526
|
+
`question ${open.id} takes one option (multiSelect false): choose one of ${ids}`,
|
|
527
|
+
);
|
|
528
|
+
answer = only!.options[0]!;
|
|
529
|
+
}
|
|
530
|
+
const wrong = checkAnswer(open, answer);
|
|
531
|
+
if (wrong) throw refused(wrong.code, `request ${open.id}: ${wrong.message}`);
|
|
532
|
+
return answer;
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
/** What `respond` says it answered: per question its options (id and label) and its text. */
|
|
536
|
+
const answeredOf = (open: Decision, answer: Exclude<Answer, null>) =>
|
|
537
|
+
typeof answer === 'string'
|
|
538
|
+
? [
|
|
539
|
+
{
|
|
540
|
+
question: open.id,
|
|
541
|
+
options: [
|
|
542
|
+
{ id: answer, label: open.options.find((one) => one.id === answer)?.label ?? answer },
|
|
543
|
+
],
|
|
544
|
+
},
|
|
545
|
+
]
|
|
546
|
+
: (answer satisfies Answers).answers.map((each) => {
|
|
547
|
+
const question = open.questions?.find((one) => one.id === each.question);
|
|
548
|
+
return {
|
|
549
|
+
question: each.question,
|
|
550
|
+
options: (each.options ?? []).map((option) => ({
|
|
551
|
+
id: option,
|
|
552
|
+
label: question?.options.find((one) => one.id === option)?.label ?? option,
|
|
553
|
+
})),
|
|
554
|
+
...(each.text !== undefined && { text: each.text }),
|
|
555
|
+
};
|
|
556
|
+
});
|
|
557
|
+
|
|
558
|
+
/** A delegation as the tools answer it. */
|
|
559
|
+
const viewOf = (each: Delegation) => ({
|
|
560
|
+
delegation: each.id,
|
|
561
|
+
session: each.child,
|
|
562
|
+
title: each.title,
|
|
563
|
+
status: each.status,
|
|
564
|
+
...(each.preparing && { preparing: true }),
|
|
565
|
+
...(each.worktree && { worktree: each.worktree }),
|
|
566
|
+
createdAt: each.createdAt,
|
|
567
|
+
...(each.endedAt && { endedAt: each.endedAt }),
|
|
568
|
+
...(each.status !== 'running' &&
|
|
569
|
+
each.status !== 'cancelled' && {
|
|
570
|
+
...(each.result !== undefined && { result: each.result }),
|
|
571
|
+
...(each.error !== undefined && { error: each.error }),
|
|
572
|
+
}),
|
|
573
|
+
...(each.status === 'running' && {
|
|
574
|
+
hint: each.preparing
|
|
575
|
+
? PREPARING_HINT
|
|
576
|
+
: 'Still running: its result reaches you as a message when it ends. Call read_delegation again to wait for it, or go on with other work.',
|
|
577
|
+
}),
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
const flag = z.boolean().optional();
|
|
581
|
+
const delegateBody = z.strictObject({
|
|
582
|
+
from: z.string().min(1),
|
|
583
|
+
prompt: z.string().trim().min(1).max(PROMPT_MAX),
|
|
584
|
+
title: z.string().trim().min(1).max(200).optional(),
|
|
585
|
+
role: z.enum(ROLES).optional(),
|
|
586
|
+
target: z
|
|
587
|
+
.strictObject({
|
|
588
|
+
profile: z.string().min(1).optional(),
|
|
589
|
+
model: z.string().min(1).optional(),
|
|
590
|
+
effort: z.string().min(1).optional(),
|
|
591
|
+
options: z.strictObject({ plan: flag, auto: flag }).optional(),
|
|
592
|
+
project: z.string().min(1).optional(),
|
|
593
|
+
})
|
|
594
|
+
.optional(),
|
|
595
|
+
mode: z.string().min(1).optional(),
|
|
596
|
+
interaction: z.enum(['default', 'plan']).optional(),
|
|
597
|
+
isolation: z.enum(['shared', 'worktree']).optional(),
|
|
598
|
+
worktree: z
|
|
599
|
+
.strictObject({
|
|
600
|
+
plugins: z.array(z.string().min(1)).min(1).max(50),
|
|
601
|
+
branch: z.string().trim().min(1).max(100).optional(),
|
|
602
|
+
})
|
|
603
|
+
.optional(),
|
|
604
|
+
wait: z.enum(['async', 'wait']).optional(),
|
|
605
|
+
timeoutMs: z.number().int().min(0).optional(),
|
|
606
|
+
clientRequestId: z.string().min(1).max(200),
|
|
607
|
+
});
|
|
608
|
+
type DelegateInput = z.infer<typeof delegateBody>;
|
|
609
|
+
const readBody = z.strictObject({
|
|
610
|
+
from: z.string().min(1),
|
|
611
|
+
delegation: z.string().min(1),
|
|
612
|
+
timeoutMs: z.number().int().min(0).optional(),
|
|
613
|
+
});
|
|
614
|
+
const cancelBody = z.strictObject({ from: z.string().min(1), delegation: z.string().min(1) });
|
|
615
|
+
const answerBody = z.discriminatedUnion('action', [
|
|
616
|
+
z.strictObject({
|
|
617
|
+
from: z.string().min(1),
|
|
618
|
+
action: z.literal('list'),
|
|
619
|
+
delegation: z.string().min(1),
|
|
620
|
+
}),
|
|
621
|
+
z.strictObject({
|
|
622
|
+
from: z.string().min(1),
|
|
623
|
+
action: z.literal('read'),
|
|
624
|
+
delegation: z.string().min(1),
|
|
625
|
+
request: z.string().min(1),
|
|
626
|
+
}),
|
|
627
|
+
z.strictObject({
|
|
628
|
+
from: z.string().min(1),
|
|
629
|
+
action: z.literal('respond'),
|
|
630
|
+
delegation: z.string().min(1),
|
|
631
|
+
request: z.string().min(1),
|
|
632
|
+
answers: z
|
|
633
|
+
.array(
|
|
634
|
+
z.strictObject({
|
|
635
|
+
question: z.string().min(1).optional(),
|
|
636
|
+
options: z.array(z.string().min(1)).max(50).optional(),
|
|
637
|
+
text: z.string().max(PROMPT_MAX).optional(),
|
|
638
|
+
}),
|
|
639
|
+
)
|
|
640
|
+
.min(1)
|
|
641
|
+
.max(50),
|
|
642
|
+
}),
|
|
643
|
+
]);
|
|
644
|
+
const promptBody = z.strictObject({
|
|
645
|
+
from: z.string().min(1),
|
|
646
|
+
to: z.string().min(1),
|
|
647
|
+
text: z.string().trim().min(1).max(PROMPT_MAX),
|
|
648
|
+
delivery: z.enum(['auto', 'queue', 'steer', 'restart']).optional(),
|
|
649
|
+
});
|
|
650
|
+
const profilesBody = z.strictObject({ from: z.string().min(1).optional() });
|
|
651
|
+
/** What `prompt_session`'s message does while its target runs a turn. */
|
|
652
|
+
export type PromptDelivery = 'auto' | 'queue' | 'steer' | 'restart';
|
|
653
|
+
|
|
654
|
+
/** JSON with its keys sorted, so a payload's digest does not depend on their order. */
|
|
655
|
+
const canonical = (value: unknown): string =>
|
|
656
|
+
Array.isArray(value)
|
|
657
|
+
? `[${value.map(canonical).join(',')}]`
|
|
658
|
+
: typeof value === 'object' && value !== null
|
|
659
|
+
? `{${Object.entries(value)
|
|
660
|
+
.filter(([, each]) => each !== undefined)
|
|
661
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
662
|
+
.map(([key, each]) => `${JSON.stringify(key)}:${canonical(each)}`)
|
|
663
|
+
.join(',')}}`
|
|
664
|
+
: JSON.stringify(value);
|
|
665
|
+
|
|
666
|
+
/** A follow-up from the parent `parent` to its child, as delegation `id`. */
|
|
667
|
+
const followUpText = (parent: string, id: string, text: string) => `<bridge_delegation>
|
|
668
|
+
A follow-up from your parent session \`${parent}\` (delegation \`${id}\`): your final answer in this turn is its result, which Bridge gives back to that session when your turn ends.
|
|
669
|
+
</bridge_delegation>
|
|
670
|
+
|
|
671
|
+
${text}`;
|
|
672
|
+
/** A message from session `from` (`title`) to another session, not its child. */
|
|
673
|
+
const promptText = (from: string, title: string, text: string) => `<bridge_prompt>
|
|
674
|
+
A message from Bridge session \`${from}\` ("${title.replaceAll('"', "'")}"), not from the user. Nothing you answer here goes back to it: tell it with notify_session if it needs an answer.
|
|
675
|
+
</bridge_prompt>
|
|
676
|
+
|
|
677
|
+
${text}`;
|
|
678
|
+
|
|
679
|
+
/** The first message of a child: its role, that it is a child and its last answer is its result, then the task. */
|
|
680
|
+
const childText = (
|
|
681
|
+
input: DelegateInput,
|
|
682
|
+
parent: string,
|
|
683
|
+
id: string,
|
|
684
|
+
worktree?: { slug: string; branch: string },
|
|
685
|
+
) =>
|
|
686
|
+
`${input.role && input.role !== 'general' ? `Act as the ${input.role} sub-agent for this task.\n\n` : ''}<bridge_delegation>
|
|
687
|
+
This is a child session: Bridge session \`${parent}\` delegated this task to it (delegation \`${id}\`). It does not see that session's conversation: the task below is all it has. Your final answer in this session is its result, which Bridge gives back to that session when your turn ends: end with the complete result, not a summary pointing elsewhere.${worktree ? `\nIt works on a git branch of its own, ${worktree.branch}, in stage ${worktree.slug} (a variant of the workspace with its own data, running that branch): its folder is the branch's, and your Bridge tools act on that stage. Leave your changes on the branch: that session delivers them.` : ''}
|
|
688
|
+
</bridge_delegation>
|
|
689
|
+
|
|
690
|
+
${input.prompt}`;
|
|
691
|
+
|
|
692
|
+
/** The git branch of a child's worktree given none: `child-`, its title in kebab case (40 characters at most), then the
|
|
693
|
+
* delegation id's first 8 hex digits. */
|
|
694
|
+
export const branchOf = (title: string, id: string) => {
|
|
695
|
+
const words = title
|
|
696
|
+
.normalize('NFKD')
|
|
697
|
+
.replace(/[\u0300-\u036f]/g, '')
|
|
698
|
+
.toLowerCase()
|
|
699
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
700
|
+
.slice(0, 40)
|
|
701
|
+
.replace(/^-+|-+$/g, '');
|
|
702
|
+
return `child-${words ? `${words}-` : ''}${id.replaceAll('-', '').slice(0, 8)}`;
|
|
703
|
+
};
|
|
704
|
+
|
|
705
|
+
/** The title of a delegation made without one: its prompt's first line, cut at 60 characters. */
|
|
706
|
+
const titleOf = (prompt: string) => {
|
|
707
|
+
const line = prompt.split('\n')[0]!.trim();
|
|
708
|
+
return line.length <= 60 ? line : `${cutText(line, 59).trimEnd()}…`;
|
|
709
|
+
};
|
|
710
|
+
|
|
711
|
+
export function createDelegations<V extends Value>({
|
|
712
|
+
route,
|
|
713
|
+
get,
|
|
714
|
+
query,
|
|
715
|
+
change,
|
|
716
|
+
written,
|
|
717
|
+
create,
|
|
718
|
+
modes,
|
|
719
|
+
models,
|
|
720
|
+
harnesses,
|
|
721
|
+
folder,
|
|
722
|
+
nodeFolder,
|
|
723
|
+
nodeExists,
|
|
724
|
+
dequeue,
|
|
725
|
+
serial,
|
|
726
|
+
running,
|
|
727
|
+
halted,
|
|
728
|
+
deciding,
|
|
729
|
+
stop,
|
|
730
|
+
tail,
|
|
731
|
+
emitQueue,
|
|
732
|
+
unsettle,
|
|
733
|
+
decisions,
|
|
734
|
+
liveOpen,
|
|
735
|
+
answer,
|
|
736
|
+
send,
|
|
737
|
+
sliceMs = READ_WAIT_MS,
|
|
738
|
+
addWorktree,
|
|
739
|
+
headOf,
|
|
740
|
+
bind,
|
|
741
|
+
endSnooze,
|
|
742
|
+
refused,
|
|
743
|
+
parse,
|
|
744
|
+
log,
|
|
745
|
+
}: {
|
|
746
|
+
route: (
|
|
747
|
+
method: string,
|
|
748
|
+
path: string,
|
|
749
|
+
handle: (request: { body?: Uint8Array | undefined; actor?: string | undefined }) => unknown,
|
|
750
|
+
) => void;
|
|
751
|
+
/** Session `id`, archived too. */
|
|
752
|
+
get: (id: string) => Promise<Found<V> | undefined>;
|
|
753
|
+
/** Every session, archived ones too. */
|
|
754
|
+
query: () => Promise<Found<V>[]>;
|
|
755
|
+
change: (id: string, fn: (value: V) => V) => Promise<V>;
|
|
756
|
+
/** Settles once the writes of session `id` asked so far are done. */
|
|
757
|
+
written: (id: string) => Promise<unknown>;
|
|
758
|
+
/** `createSession` with the child's parent and its first queued message. */
|
|
759
|
+
create: (
|
|
760
|
+
node: string,
|
|
761
|
+
input: {
|
|
762
|
+
harness: string;
|
|
763
|
+
model?: string | undefined;
|
|
764
|
+
effort?: string | undefined;
|
|
765
|
+
mode?: string | undefined;
|
|
766
|
+
options?: Options | undefined;
|
|
767
|
+
title: string;
|
|
768
|
+
worktree?: string | undefined;
|
|
769
|
+
parent: string;
|
|
770
|
+
queue: QueueItem[];
|
|
771
|
+
},
|
|
772
|
+
) => Promise<Found<V>>;
|
|
773
|
+
modes: (harness: string, node: string, cwd: string) => Promise<Mode[]>;
|
|
774
|
+
models: (harness: string, node: string, cwd: string) => Promise<unknown[]>;
|
|
775
|
+
/** The enabled harnesses of `node`. */
|
|
776
|
+
harnesses: (
|
|
777
|
+
node: string,
|
|
778
|
+
) => Promise<{ name: string; displayName?: string; driver: string; available: boolean }[]>;
|
|
779
|
+
/** The folder session `found` works in. */
|
|
780
|
+
folder: (found: Found<V>) => Promise<string | undefined>;
|
|
781
|
+
/** The folder a session on `node` would work in (a project's, the workspace's on root). */
|
|
782
|
+
nodeFolder: (node: string) => Promise<string | undefined>;
|
|
783
|
+
nodeExists: (node: string) => boolean;
|
|
784
|
+
/** Sends session `id`'s queue (`resultsOnly`: its results only). */
|
|
785
|
+
dequeue: (id: string, resultsOnly?: boolean) => Promise<unknown>;
|
|
786
|
+
/** Runs `fn` with session `id`'s queue lock. */
|
|
787
|
+
serial: <T>(id: string, fn: () => Promise<T>) => Promise<T>;
|
|
788
|
+
running: Set<string>;
|
|
789
|
+
/** The sessions the user stopped: their queue waits for them. */
|
|
790
|
+
halted: Set<string>;
|
|
791
|
+
deciding: (id: string, value: V) => boolean;
|
|
792
|
+
/** Stops session `id` as the user's Stop does: its running turn, and its queue held. */
|
|
793
|
+
stop: (id: string) => Promise<void>;
|
|
794
|
+
/** Session `id`'s last turn's lines, from its `turn/start` (none when it had no turn). */
|
|
795
|
+
tail: (id: string) => Promise<Line[]>;
|
|
796
|
+
emitQueue: (id: string) => void;
|
|
797
|
+
unsettle: (value: V) => V;
|
|
798
|
+
/** Session `id`'s open decisions: its running turn's, and those a turn Bridge cut left open. */
|
|
799
|
+
decisions: (id: string) => Promise<Decision[]>;
|
|
800
|
+
/** Whether decision `decision` is still open in session `id`'s running turn (read inside a write). */
|
|
801
|
+
liveOpen: (id: string, decision: string) => boolean;
|
|
802
|
+
/** Answers decision `decision` of session `id` with `option` (an option id, or its questions' answers), as the agent
|
|
803
|
+
* of session `by`. */
|
|
804
|
+
answer: (
|
|
805
|
+
id: string,
|
|
806
|
+
decision: string,
|
|
807
|
+
option: Exclude<Answer, null>,
|
|
808
|
+
by: string,
|
|
809
|
+
) => Promise<unknown>;
|
|
810
|
+
/** Sends session `id` the message `message` gives (`Opening`, run with `id`'s queue lock held) from session
|
|
811
|
+
* `sender`'s agent (Bridge's words, `from: 'bridge'`): a turn starts when none runs; while one runs, `delivery`
|
|
812
|
+
* says what it does (`server.ts`'s `sendOrQueue`), refused as it says. Resolves to what it did. */
|
|
813
|
+
send: (
|
|
814
|
+
id: string,
|
|
815
|
+
message: Opening,
|
|
816
|
+
sender: string,
|
|
817
|
+
delivery: PromptDelivery,
|
|
818
|
+
) => Promise<{ delivery: 'started' | 'queued' | 'steered' | 'restarted' }>;
|
|
819
|
+
/** How long one call of a wait lasts at most (`sliceOf` the host's request deadline); READ_WAIT_MS when absent. */
|
|
820
|
+
sliceMs?: number | undefined;
|
|
821
|
+
/** Adds a worktree of this workspace developing `plugins` on the new git branch `branch` (S7): the host makes the
|
|
822
|
+
* branch and its git worktree. Refuses (`worktrees_unavailable`, `worktree_refused`) as the host does. */
|
|
823
|
+
addWorktree: (input: { branch: string; plugins: string[] }) => Promise<{ slug: string }>;
|
|
824
|
+
/** Where worktree `slug`'s checkout is now, read live (bridge#339: its child may switch branches): the git branch it
|
|
825
|
+
* is on, `detached at <commit>` on none; none when it cannot be read (the worktree gone). */
|
|
826
|
+
headOf: (slug: string) => Promise<string | undefined>;
|
|
827
|
+
/** Binds session `id` to worktree `slug` (S7, its folder that worktree's checkout) and puts `item` first in its queue
|
|
828
|
+
* (none: its delegation ended meanwhile). */
|
|
829
|
+
bind: (id: string, slug: string, item: QueueItem | undefined) => Promise<unknown>;
|
|
830
|
+
/** Ends session `id`'s snooze, marked Woke (a message from an agent). */
|
|
831
|
+
endSnooze: (id: string) => Promise<void>;
|
|
832
|
+
refused: (code: string, message: string, status?: number) => Error;
|
|
833
|
+
parse: <T>(schema: z.ZodType<T>, body: Uint8Array | undefined, usage: string) => T;
|
|
834
|
+
log: (what: string) => (error: unknown) => void;
|
|
835
|
+
}) {
|
|
836
|
+
/** The `read_delegation` calls waiting, by delegation. */
|
|
837
|
+
const waiting = new Map<string, Set<() => void>>();
|
|
838
|
+
const wake = (id: string) => {
|
|
839
|
+
for (const each of [...(waiting.get(id) ?? [])]) each();
|
|
840
|
+
};
|
|
841
|
+
/** Set as this plugin disposes: `read_delegation` no longer waits. */
|
|
842
|
+
let disposed = false;
|
|
843
|
+
/** The delegations a `read_delegation` waits for, from its first slice to its answer (S6: their results and their
|
|
844
|
+
* children's questions are not steered into their parent's running turn meanwhile; its wait reads them), each with
|
|
845
|
+
* its parent and, between two slices, the timer that lets it go when the next slice never comes (its tool call
|
|
846
|
+
* cancelled): a slice later. The parent's turn end lets them all go. */
|
|
847
|
+
const awaited = new Map<string, { from: string; timer?: ReturnType<typeof setTimeout> }>();
|
|
848
|
+
const release = (id: string) => {
|
|
849
|
+
clearTimeout(awaited.get(id)?.timer);
|
|
850
|
+
awaited.delete(id);
|
|
851
|
+
};
|
|
852
|
+
/** The children's questions a `read_delegation` answered: never queued after (until they close). */
|
|
853
|
+
const reported = new Set<string>();
|
|
854
|
+
/** The children whose worktree is being made (S7, `prepare`): no turn starts in them before they are bound to it. */
|
|
855
|
+
const preparing = new Set<string>();
|
|
856
|
+
/** The children `preparing` since the start (`holdUnprepared`): their worktree was being made when Bridge stopped. */
|
|
857
|
+
const unprepared = new Set<string>();
|
|
858
|
+
/** How many times the user stopped each session (`stopTree`): a delegation being made when it changes is not
|
|
859
|
+
* started. */
|
|
860
|
+
const stops = new Map<string, number>();
|
|
861
|
+
const stoppedSince = (id: string, seen: number) => (stops.get(id) ?? 0) !== seen;
|
|
862
|
+
/** Each parent's delegation being made: one at a time, so a key sent twice at once makes one child. */
|
|
863
|
+
const making = new Map<string, Promise<unknown>>();
|
|
864
|
+
const oneAtATime = <T>(id: string, fn: () => Promise<T>): Promise<T> => {
|
|
865
|
+
const run = (making.get(id) ?? Promise.resolve()).catch(() => {}).then(fn);
|
|
866
|
+
const held = run.catch(() => {});
|
|
867
|
+
making.set(id, held);
|
|
868
|
+
void held.then(() => {
|
|
869
|
+
if (making.get(id) === held) making.delete(id);
|
|
870
|
+
});
|
|
871
|
+
return run;
|
|
872
|
+
};
|
|
873
|
+
const own = (actor: string | undefined, id: string) => {
|
|
874
|
+
if (!actsAs(actor, id))
|
|
875
|
+
throw refused(
|
|
876
|
+
'not_your_session',
|
|
877
|
+
`an agent delegates, reads and cancels only for its own session, not for session ${id}`,
|
|
878
|
+
403,
|
|
879
|
+
);
|
|
880
|
+
};
|
|
881
|
+
const session = async (id: string) => {
|
|
882
|
+
const found = await get(id);
|
|
883
|
+
if (!found) throw refused('not_found', `no session ${id}`, 404);
|
|
884
|
+
return found;
|
|
885
|
+
};
|
|
886
|
+
const findOf = (found: Found<V>, id: string) => {
|
|
887
|
+
const each = found.value.delegations?.find((one) => one.id === id);
|
|
888
|
+
if (!each)
|
|
889
|
+
throw refused('delegation_unknown', `session ${found.id} made no delegation ${id}`, 404);
|
|
890
|
+
return each;
|
|
891
|
+
};
|
|
892
|
+
/** Session `found`'s permissions: its mode, else its harness's current one. */
|
|
893
|
+
const permissionsOf = async (found: Found<V>): Promise<Permissions> => {
|
|
894
|
+
const cwd = await folder(found);
|
|
895
|
+
// A harness that no longer lists its modes (disabled, its driver gone): its stored mode still compares.
|
|
896
|
+
const listed =
|
|
897
|
+
cwd === undefined
|
|
898
|
+
? []
|
|
899
|
+
: await modes(found.value.harness, found.node, cwd).catch((): Mode[] => []);
|
|
900
|
+
return {
|
|
901
|
+
harness: found.value.harness,
|
|
902
|
+
mode: found.value.mode ?? listed.find((each) => each.current)?.id,
|
|
903
|
+
options: found.value.options,
|
|
904
|
+
modes: listed,
|
|
905
|
+
};
|
|
906
|
+
};
|
|
907
|
+
|
|
908
|
+
/** The child `input` asks of `parent`: its node, harness, model, effort, mode and options, the parent's by default;
|
|
909
|
+
* refused above the parent's mode. */
|
|
910
|
+
const planOf = async (parent: Found<V>, input: DelegateInput) => {
|
|
911
|
+
const target = input.target ?? {};
|
|
912
|
+
const harness = target.profile ?? parent.value.harness;
|
|
913
|
+
const same = harness === parent.value.harness;
|
|
914
|
+
const node = target.project ?? parent.node;
|
|
915
|
+
if (target.project !== undefined && !nodeExists(node))
|
|
916
|
+
throw refused('project_unknown', `no project node ${node} in this workspace`, 400);
|
|
917
|
+
const worktree = node === parent.node ? parent.value.worktree : undefined;
|
|
918
|
+
const cwd = worktree?.folder ?? (await nodeFolder(node));
|
|
919
|
+
if (cwd === undefined)
|
|
920
|
+
throw refused(
|
|
921
|
+
'not_a_project',
|
|
922
|
+
`node ${node} is not a project: sessions live in project nodes and on the workspace (root)`,
|
|
923
|
+
);
|
|
924
|
+
const model = target.model ?? (same ? parent.value.model : undefined);
|
|
925
|
+
const effort =
|
|
926
|
+
target.effort ?? (same && target.model === undefined ? parent.value.effort : undefined);
|
|
927
|
+
let options: Options = target.options
|
|
928
|
+
? {
|
|
929
|
+
...(target.options.plan === true && { plan: true as const }),
|
|
930
|
+
...(target.options.auto === true && { auto: true as const }),
|
|
931
|
+
}
|
|
932
|
+
: { ...parent.value.options };
|
|
933
|
+
if (input.interaction === 'plan') options = { ...options, plan: true };
|
|
934
|
+
else if (input.interaction === 'default') {
|
|
935
|
+
const { plan: _plan, ...rest } = options;
|
|
936
|
+
options = rest;
|
|
937
|
+
}
|
|
938
|
+
const above = await permissionsOf(parent);
|
|
939
|
+
const listed = await modes(harness, node, cwd);
|
|
940
|
+
const mode =
|
|
941
|
+
input.mode ??
|
|
942
|
+
(same || listed.some((each) => each.id === above.mode)
|
|
943
|
+
? above.mode
|
|
944
|
+
: listed.find((each) => each.readOnly)?.id);
|
|
945
|
+
const refusal = aboveParent(above, { harness, mode, options, modes: listed });
|
|
946
|
+
if (refusal)
|
|
947
|
+
throw refused(
|
|
948
|
+
'mode_above_parent',
|
|
949
|
+
`${refusal}: a child session never has more permissions than its parent. Choose another mode (list_session_profiles lists them), or ask the user.`,
|
|
950
|
+
403,
|
|
951
|
+
);
|
|
952
|
+
return {
|
|
953
|
+
node,
|
|
954
|
+
harness,
|
|
955
|
+
model,
|
|
956
|
+
effort,
|
|
957
|
+
mode,
|
|
958
|
+
options: Object.keys(options).length ? options : undefined,
|
|
959
|
+
worktree: worktree?.slug,
|
|
960
|
+
};
|
|
961
|
+
};
|
|
962
|
+
|
|
963
|
+
/** What `delegate_session` answers for delegation `each`. */
|
|
964
|
+
const answerOf = (each: Delegation) => ({
|
|
965
|
+
delegation: each.id,
|
|
966
|
+
session: each.child,
|
|
967
|
+
status: each.status,
|
|
968
|
+
title: each.title,
|
|
969
|
+
...(each.preparing && { preparing: true as const, hint: PREPARING_HINT }),
|
|
970
|
+
...(each.worktree && { worktree: each.worktree, hint: worktreeLine(each.worktree) }),
|
|
971
|
+
});
|
|
972
|
+
/** `answer` with its worktree's branch read live (`headOf`), else the one stored when it was made. */
|
|
973
|
+
const withHead = async <T extends { worktree?: { slug: string; branch: string } | undefined }>(
|
|
974
|
+
answer: T,
|
|
975
|
+
): Promise<T> => {
|
|
976
|
+
if (!answer.worktree) return answer;
|
|
977
|
+
const branch = await headOf(answer.worktree.slug);
|
|
978
|
+
return branch === undefined ? answer : { ...answer, worktree: { ...answer.worktree, branch } };
|
|
979
|
+
};
|
|
980
|
+
/** Adds the worktree of delegation `id` of session `from` (S7), outside the route that made it: a dependency install
|
|
981
|
+
* can outlast the host's request deadline. Added, its child is bound to it and its task (`task`) goes first in its
|
|
982
|
+
* queue, then is sent; refused, the delegation ends `failed` with the host's reason, delivered as any failure. A
|
|
983
|
+
* delegation that ended meanwhile (cancelled, its child stopped) records the worktree and sends nothing. */
|
|
984
|
+
const prepare = async (
|
|
985
|
+
from: string,
|
|
986
|
+
id: string,
|
|
987
|
+
child: string,
|
|
988
|
+
branch: string,
|
|
989
|
+
plugins: string[],
|
|
990
|
+
task: (worktree: { slug: string; branch: string }) => QueueItem,
|
|
991
|
+
) => {
|
|
992
|
+
let slug: string;
|
|
993
|
+
try {
|
|
994
|
+
({ slug } = await addWorktree({ branch, plugins }));
|
|
995
|
+
} catch (error) {
|
|
996
|
+
preparing.delete(child);
|
|
997
|
+
const parent = await get(from);
|
|
998
|
+
if (!parent) return;
|
|
999
|
+
await close(parent, (each) => each.id === id && each.status === 'running', {
|
|
1000
|
+
status: 'failed',
|
|
1001
|
+
error: `its worktree (git branch ${branch}) was not made: ${error instanceof Error ? error.message : String(error)}`,
|
|
1002
|
+
});
|
|
1003
|
+
return;
|
|
1004
|
+
}
|
|
1005
|
+
const worktree = { slug, branch };
|
|
1006
|
+
try {
|
|
1007
|
+
const live = (await get(from))?.value.delegations?.some(
|
|
1008
|
+
(each) => each.id === id && each.status === 'running',
|
|
1009
|
+
);
|
|
1010
|
+
await bind(child, slug, live ? task(worktree) : undefined);
|
|
1011
|
+
await change(from, (now) => ({
|
|
1012
|
+
...now,
|
|
1013
|
+
delegations: now.delegations?.map((each) => {
|
|
1014
|
+
if (each.id !== id) return each;
|
|
1015
|
+
const { preparing: _preparing, ...rest } = each;
|
|
1016
|
+
return { ...rest, worktree };
|
|
1017
|
+
}),
|
|
1018
|
+
}));
|
|
1019
|
+
} catch (error) {
|
|
1020
|
+
preparing.delete(child);
|
|
1021
|
+
const parent = await get(from);
|
|
1022
|
+
if (parent)
|
|
1023
|
+
await close(parent, (each) => each.id === id && each.status === 'running', {
|
|
1024
|
+
status: 'failed',
|
|
1025
|
+
error: `its child was not bound to its worktree ${slug} (git branch ${branch}, kept: stage_remove removes the stage): ${error instanceof Error ? error.message : String(error)}`,
|
|
1026
|
+
});
|
|
1027
|
+
return;
|
|
1028
|
+
}
|
|
1029
|
+
preparing.delete(child);
|
|
1030
|
+
// Its task starts; a child the user stopped meanwhile keeps it queued, and its delegation ends `interrupted`.
|
|
1031
|
+
await dequeue(child).catch(log(`session ${child}: delegated task not sent`));
|
|
1032
|
+
void check(child);
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
route('POST', '/sessions/delegate', async ({ actor, body }) => {
|
|
1036
|
+
const input = parse(
|
|
1037
|
+
delegateBody,
|
|
1038
|
+
body,
|
|
1039
|
+
'POST /sessions/delegate takes { from, prompt, title?, role?, target? { profile?, model?, effort?, options?, project? }, mode?, interaction?, isolation?, worktree? { plugins, branch? }, wait?, timeoutMs?, clientRequestId }',
|
|
1040
|
+
);
|
|
1041
|
+
own(actor, input.from);
|
|
1042
|
+
if (input.worktree !== undefined && input.isolation !== 'worktree')
|
|
1043
|
+
throw refused(
|
|
1044
|
+
'worktree_without_isolation',
|
|
1045
|
+
'worktree { plugins, branch? } goes with isolation: worktree',
|
|
1046
|
+
);
|
|
1047
|
+
if (input.isolation === 'worktree' && input.worktree === undefined)
|
|
1048
|
+
throw refused(
|
|
1049
|
+
'worktree_plugins_required',
|
|
1050
|
+
'isolation: worktree takes worktree: { plugins, branch? }: the plugins of this workspace the child changes, all from one git repository, which gets the new branch',
|
|
1051
|
+
);
|
|
1052
|
+
// The wait is not the task: the same key sent again with another wait (or none) names the same delegation.
|
|
1053
|
+
const { from, clientRequestId, wait: _wait, timeoutMs: _timeoutMs, ...payload } = input;
|
|
1054
|
+
const request = createHash('sha256').update(canonical(payload)).digest('hex');
|
|
1055
|
+
// Stopped while it is made (its awaits): nothing made before its child exists, its child never started after.
|
|
1056
|
+
const seen = stops.get(from) ?? 0;
|
|
1057
|
+
const made = await oneAtATime(from, async () => {
|
|
1058
|
+
const parent = await session(from);
|
|
1059
|
+
if (parent.archived) throw refused('not_found', `no session ${from}`, 404);
|
|
1060
|
+
const known = parent.value.delegations?.find(
|
|
1061
|
+
(each) => each.clientRequestId === clientRequestId,
|
|
1062
|
+
);
|
|
1063
|
+
if (known) {
|
|
1064
|
+
if (known.request !== request)
|
|
1065
|
+
throw refused(
|
|
1066
|
+
'client_request_conflict',
|
|
1067
|
+
`clientRequestId ${clientRequestId} named another delegation: give a new clientRequestId for a new task`,
|
|
1068
|
+
409,
|
|
1069
|
+
);
|
|
1070
|
+
return answerOf(known);
|
|
1071
|
+
}
|
|
1072
|
+
const plan = await planOf(parent, input);
|
|
1073
|
+
// A branch and a stage are made as `stage_add` adds one: by the user, or by an agent whose session's mode writes.
|
|
1074
|
+
if (input.worktree !== undefined && actor?.startsWith('agent')) {
|
|
1075
|
+
const { mode, modes: listed } = await permissionsOf(parent);
|
|
1076
|
+
if (
|
|
1077
|
+
!writesOf(
|
|
1078
|
+
listed.find((each) => each.id === mode),
|
|
1079
|
+
listed,
|
|
1080
|
+
)
|
|
1081
|
+
)
|
|
1082
|
+
throw refused(
|
|
1083
|
+
'worktree_needs_writes',
|
|
1084
|
+
'a branch and a stage are made by a session in a mode that writes (Ask, Build or God), as stage_add: delegate with isolation: shared, or ask the user',
|
|
1085
|
+
403,
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
1088
|
+
if (stoppedSince(from, seen))
|
|
1089
|
+
throw refused(
|
|
1090
|
+
'session_stopped',
|
|
1091
|
+
`session ${from} was stopped while this delegation was being made: nothing was delegated`,
|
|
1092
|
+
409,
|
|
1093
|
+
);
|
|
1094
|
+
const id = randomUUID();
|
|
1095
|
+
const title = input.title ?? titleOf(input.prompt);
|
|
1096
|
+
const at = new Date().toISOString();
|
|
1097
|
+
await change(from, (now) => ({
|
|
1098
|
+
...now,
|
|
1099
|
+
delegations: [
|
|
1100
|
+
...(now.delegations ?? []),
|
|
1101
|
+
{ id, title, clientRequestId, request, status: 'running', createdAt: at },
|
|
1102
|
+
],
|
|
1103
|
+
}));
|
|
1104
|
+
let child: Found<V>;
|
|
1105
|
+
try {
|
|
1106
|
+
// A child in a worktree of its own (S7) is made at once, unbound and with nothing queued: its worktree is
|
|
1107
|
+
// added in the background (`prepare`), and its task is queued there once it is bound to it.
|
|
1108
|
+
const { worktree: shared, ...rest } = plan;
|
|
1109
|
+
child = await create(plan.node, {
|
|
1110
|
+
...rest,
|
|
1111
|
+
...(input.worktree === undefined && shared !== undefined && { worktree: shared }),
|
|
1112
|
+
title,
|
|
1113
|
+
parent: from,
|
|
1114
|
+
queue:
|
|
1115
|
+
input.worktree === undefined
|
|
1116
|
+
? [{ id: randomUUID(), text: childText(input, from, id), at }]
|
|
1117
|
+
: [],
|
|
1118
|
+
});
|
|
1119
|
+
} catch (error) {
|
|
1120
|
+
// Refused: nothing was made, the same key may be sent again.
|
|
1121
|
+
await change(from, ({ delegations, ...now }) => {
|
|
1122
|
+
const rest = delegations?.filter((each) => each.id !== id);
|
|
1123
|
+
return (rest?.length ? { ...now, delegations: rest } : now) as V;
|
|
1124
|
+
}).catch(log(`session ${from}: refused delegation ${id} not removed`));
|
|
1125
|
+
throw error;
|
|
1126
|
+
}
|
|
1127
|
+
if (input.worktree !== undefined) preparing.add(child.id);
|
|
1128
|
+
let recorded: Delegation | undefined;
|
|
1129
|
+
await change(from, (now) => ({
|
|
1130
|
+
...now,
|
|
1131
|
+
delegations: now.delegations?.map((each) => {
|
|
1132
|
+
if (each.id !== id) return each;
|
|
1133
|
+
recorded = {
|
|
1134
|
+
...each,
|
|
1135
|
+
child: child.id,
|
|
1136
|
+
...(input.worktree !== undefined && { preparing: true as const }),
|
|
1137
|
+
};
|
|
1138
|
+
return recorded;
|
|
1139
|
+
}),
|
|
1140
|
+
}));
|
|
1141
|
+
if (stoppedSince(from, seen)) {
|
|
1142
|
+
// Its child stopped as the rest of its parent's subtree: its delegation ends interrupted, its task never sent.
|
|
1143
|
+
preparing.delete(child.id);
|
|
1144
|
+
await stop(child.id).catch(log(`session ${child.id}: not stopped`));
|
|
1145
|
+
void check(child.id);
|
|
1146
|
+
} else if (input.worktree !== undefined) {
|
|
1147
|
+
const branch = input.worktree.branch ?? branchOf(title, id);
|
|
1148
|
+
void prepare(from, id, child.id, branch, input.worktree.plugins, (worktree) => ({
|
|
1149
|
+
id: randomUUID(),
|
|
1150
|
+
text: childText(input, from, id, worktree),
|
|
1151
|
+
at,
|
|
1152
|
+
})).catch(log(`session ${child.id}: its worktree not prepared`));
|
|
1153
|
+
} else void dequeue(child.id).catch(log(`session ${child.id}: delegated task not sent`));
|
|
1154
|
+
return answerOf(
|
|
1155
|
+
recorded ?? {
|
|
1156
|
+
id,
|
|
1157
|
+
child: child.id,
|
|
1158
|
+
title,
|
|
1159
|
+
clientRequestId,
|
|
1160
|
+
request,
|
|
1161
|
+
status: 'running',
|
|
1162
|
+
createdAt: at,
|
|
1163
|
+
},
|
|
1164
|
+
);
|
|
1165
|
+
});
|
|
1166
|
+
if (input.wait !== 'wait') return made;
|
|
1167
|
+
// Outside `oneAtATime`: another delegation of the same parent is not held by this wait.
|
|
1168
|
+
return withHead({
|
|
1169
|
+
...made,
|
|
1170
|
+
...(await waitFor(
|
|
1171
|
+
from,
|
|
1172
|
+
made.delegation,
|
|
1173
|
+
Math.min(input.timeoutMs ?? WAIT_DEFAULT_MS, WAIT_MAX_MS),
|
|
1174
|
+
)),
|
|
1175
|
+
});
|
|
1176
|
+
});
|
|
1177
|
+
|
|
1178
|
+
/** Whether session `id`'s agent reads what a wait answers: a turn of it runs, not stopped by the user. A wait whose
|
|
1179
|
+
* caller was stopped (its tool call cut) takes nothing out of its queue: its results and questions come as a
|
|
1180
|
+
* message. */
|
|
1181
|
+
const listening = (id: string) => running.has(id) && !halted.has(id);
|
|
1182
|
+
/** Waits for delegation `id` of session `from`, `total` ms at most, and answers its state: its result once done (read
|
|
1183
|
+
* here, it leaves the queue and is never sent), its child's open questions and approvals (each ends the wait: an
|
|
1184
|
+
* approval is the user's, in the child), or `waitTimedOut` (the child keeps running, its result comes as a message).
|
|
1185
|
+
* One call waits a slice (`sliceMs`) at most: a longer wait answers `$mcp.again`,
|
|
1186
|
+
* the same wait for what is left, which `bridge mcp` calls in turn, so no call outlives the host's request deadline. */
|
|
1187
|
+
const waitFor = async (from: string, id: string, total: number) => {
|
|
1188
|
+
// Its result is this wait's while it lasts (its slices and the calls between them): never steered meanwhile.
|
|
1189
|
+
release(id);
|
|
1190
|
+
awaited.set(id, { from });
|
|
1191
|
+
try {
|
|
1192
|
+
const answer = await waitSlice(from, id, total);
|
|
1193
|
+
if (!('$mcp' in answer)) release(id);
|
|
1194
|
+
else {
|
|
1195
|
+
// Its next slice never called (the tool call cancelled): what it held is steered or sent as any.
|
|
1196
|
+
const timer = setTimeout(() => {
|
|
1197
|
+
release(id);
|
|
1198
|
+
void dequeue(from, true).catch(log(`session ${from}: delegated results not sent`));
|
|
1199
|
+
}, sliceMs);
|
|
1200
|
+
timer.unref?.();
|
|
1201
|
+
awaited.set(id, { from, timer });
|
|
1202
|
+
}
|
|
1203
|
+
return answer;
|
|
1204
|
+
} catch (error) {
|
|
1205
|
+
release(id);
|
|
1206
|
+
throw error;
|
|
1207
|
+
}
|
|
1208
|
+
};
|
|
1209
|
+
const waitSlice = async (from: string, id: string, total: number) => {
|
|
1210
|
+
let found = findOf(await session(from), id);
|
|
1211
|
+
const slice = Math.max(0, Math.min(total, sliceMs));
|
|
1212
|
+
let waited = 0;
|
|
1213
|
+
// A decision of its child open already is answered at once, as one asked during the wait ends it.
|
|
1214
|
+
if (found.status === 'running' && slice > 0 && !disposed && !(await openOf(found)).length) {
|
|
1215
|
+
const started = Date.now();
|
|
1216
|
+
waited = await new Promise<number>((done) => {
|
|
1217
|
+
const woken = () => end(Math.min(slice, Math.max(0, Date.now() - started)));
|
|
1218
|
+
const timer = setTimeout(() => end(slice), slice);
|
|
1219
|
+
function end(after: number) {
|
|
1220
|
+
clearTimeout(timer);
|
|
1221
|
+
waiting.get(id)?.delete(woken);
|
|
1222
|
+
if (!waiting.get(id)?.size) waiting.delete(id);
|
|
1223
|
+
done(after);
|
|
1224
|
+
}
|
|
1225
|
+
if (!waiting.has(id)) waiting.set(id, new Set());
|
|
1226
|
+
waiting.get(id)!.add(woken);
|
|
1227
|
+
});
|
|
1228
|
+
found = findOf(await session(from), id);
|
|
1229
|
+
}
|
|
1230
|
+
if (found.status === 'running') {
|
|
1231
|
+
const open = await openOf(found);
|
|
1232
|
+
const questions = open.filter(isQuestion);
|
|
1233
|
+
const approvals = open.filter((each) => !isQuestion(each));
|
|
1234
|
+
// Its child's open questions are answered here: their messages leave the queue, never sent after.
|
|
1235
|
+
if (questions.length && listening(from)) {
|
|
1236
|
+
for (const each of questions) reported.add(each.id);
|
|
1237
|
+
await withdraw(
|
|
1238
|
+
from,
|
|
1239
|
+
questions.map((each) => each.id),
|
|
1240
|
+
);
|
|
1241
|
+
}
|
|
1242
|
+
if (open.length)
|
|
1243
|
+
return {
|
|
1244
|
+
...viewOf(found),
|
|
1245
|
+
...(questions.length && {
|
|
1246
|
+
hasPendingQuestion: true,
|
|
1247
|
+
questions: questions.map((each) => ({
|
|
1248
|
+
request: each.id,
|
|
1249
|
+
title: each.title,
|
|
1250
|
+
options: each.options.map(({ id: option, label }) => ({ id: option, label })),
|
|
1251
|
+
...(each.questions?.length && { questions: questionsOf(each) }),
|
|
1252
|
+
})),
|
|
1253
|
+
}),
|
|
1254
|
+
...(approvals.length && {
|
|
1255
|
+
approvals: approvals.map(({ id: request, title }) => ({ request, title })),
|
|
1256
|
+
}),
|
|
1257
|
+
hint: [
|
|
1258
|
+
questions.length &&
|
|
1259
|
+
`Its child waits for an answer to each question: answer_delegation (delegation ${id}) lists them (action list), reads one (action read, its request) and answers it (action respond, its request and answers) when you know the answer; else ask the user, who may also answer it in that session.`,
|
|
1260
|
+
approvals.length &&
|
|
1261
|
+
`Its child waits for the user to allow or deny each approval: only the user answers it, in session ${found.child}. Tell the user if they should; its result reaches you as a message when it ends (read_delegation waits for it again).`,
|
|
1262
|
+
]
|
|
1263
|
+
.filter(Boolean)
|
|
1264
|
+
.join(' '),
|
|
1265
|
+
};
|
|
1266
|
+
const left = total - waited;
|
|
1267
|
+
if (left > 0 && !disposed)
|
|
1268
|
+
return {
|
|
1269
|
+
...viewOf(found),
|
|
1270
|
+
$mcp: {
|
|
1271
|
+
again: {
|
|
1272
|
+
path: '/sessions/delegation/read',
|
|
1273
|
+
body: { from, delegation: id, timeoutMs: left },
|
|
1274
|
+
},
|
|
1275
|
+
},
|
|
1276
|
+
};
|
|
1277
|
+
if (total <= 0 || disposed) return viewOf(found);
|
|
1278
|
+
return {
|
|
1279
|
+
...viewOf(found),
|
|
1280
|
+
waitTimedOut: true,
|
|
1281
|
+
hint: 'The wait timed out: the child keeps running, and its result reaches you as a message when it ends. Go on with other work, or call read_delegation to wait again.',
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
/** Its result still waits in a queued message (one taken and put back too, its turn not started). */
|
|
1285
|
+
const queued = (value: V) => !!value.queue?.some((item) => item.delegations?.includes(id));
|
|
1286
|
+
if (!listening(from) || !queued((await session(from)).value)) return viewOf(found);
|
|
1287
|
+
// Read here: its result leaves the queue in the same write, never sent after.
|
|
1288
|
+
let read = found;
|
|
1289
|
+
await change(from, (now) => {
|
|
1290
|
+
const queue = (now.queue ?? []).flatMap((item) =>
|
|
1291
|
+
item.delegations?.includes(id)
|
|
1292
|
+
? keep(
|
|
1293
|
+
item,
|
|
1294
|
+
item.delegations.filter((each) => each !== id),
|
|
1295
|
+
item.questions,
|
|
1296
|
+
)
|
|
1297
|
+
: [item],
|
|
1298
|
+
);
|
|
1299
|
+
const { queue: _queue, ...others } = now;
|
|
1300
|
+
return {
|
|
1301
|
+
...others,
|
|
1302
|
+
...(queue.length && { queue }),
|
|
1303
|
+
delegations: now.delegations?.map((each) => {
|
|
1304
|
+
if (each.id !== id) return each;
|
|
1305
|
+
read = queued(now) ? { ...each, delivery: 'read' } : each;
|
|
1306
|
+
return read;
|
|
1307
|
+
}),
|
|
1308
|
+
} as V;
|
|
1309
|
+
});
|
|
1310
|
+
emitQueue(from);
|
|
1311
|
+
return viewOf(read);
|
|
1312
|
+
};
|
|
1313
|
+
|
|
1314
|
+
route('POST', '/sessions/delegation/read', async ({ actor, body }) => {
|
|
1315
|
+
const {
|
|
1316
|
+
from,
|
|
1317
|
+
delegation: id,
|
|
1318
|
+
timeoutMs,
|
|
1319
|
+
} = parse(
|
|
1320
|
+
readBody,
|
|
1321
|
+
body,
|
|
1322
|
+
'POST /sessions/delegation/read takes { from, delegation, timeoutMs? }',
|
|
1323
|
+
);
|
|
1324
|
+
own(actor, from);
|
|
1325
|
+
return withHead(await waitFor(from, id, Math.min(timeoutMs ?? READ_WAIT_MS, WAIT_MAX_MS)));
|
|
1326
|
+
});
|
|
1327
|
+
|
|
1328
|
+
/** The sessions below `id` whose delegations still run: its children, theirs, and so on. */
|
|
1329
|
+
const runningBelow = async (id: string): Promise<Found<V>[]> => {
|
|
1330
|
+
const found = await get(id);
|
|
1331
|
+
const below: Found<V>[] = [];
|
|
1332
|
+
for (const each of found?.value.delegations ?? []) {
|
|
1333
|
+
if (each.status !== 'running' || !each.child) continue;
|
|
1334
|
+
const child = await get(each.child);
|
|
1335
|
+
if (!child) continue;
|
|
1336
|
+
below.push(child, ...(await runningBelow(child.id)));
|
|
1337
|
+
}
|
|
1338
|
+
return below;
|
|
1339
|
+
};
|
|
1340
|
+
|
|
1341
|
+
/** Marks `id`'s running delegations cancelled (delivered to nobody), then those of its subtree, and stops each
|
|
1342
|
+
* session of it. */
|
|
1343
|
+
const cancelBelow = async (id: string) => {
|
|
1344
|
+
const ended: Delegation[] = [];
|
|
1345
|
+
await change(id, (now) => ({
|
|
1346
|
+
...now,
|
|
1347
|
+
delegations: now.delegations?.map((each) => {
|
|
1348
|
+
if (each.status !== 'running') return each;
|
|
1349
|
+
const cancelled = {
|
|
1350
|
+
...each,
|
|
1351
|
+
status: 'cancelled' as const,
|
|
1352
|
+
endedAt: new Date().toISOString(),
|
|
1353
|
+
delivery: 'read' as const,
|
|
1354
|
+
};
|
|
1355
|
+
ended.push(cancelled);
|
|
1356
|
+
return cancelled;
|
|
1357
|
+
}),
|
|
1358
|
+
}));
|
|
1359
|
+
for (const each of ended) {
|
|
1360
|
+
wake(each.id);
|
|
1361
|
+
if (!each.child) continue;
|
|
1362
|
+
await stop(each.child).catch(log(`session ${each.child}: not stopped`));
|
|
1363
|
+
await cancelBelow(each.child);
|
|
1364
|
+
}
|
|
1365
|
+
};
|
|
1366
|
+
|
|
1367
|
+
route('POST', '/sessions/delegation/cancel', async ({ actor, body }) => {
|
|
1368
|
+
const { from, delegation: id } = parse(
|
|
1369
|
+
cancelBody,
|
|
1370
|
+
body,
|
|
1371
|
+
'POST /sessions/delegation/cancel takes { from, delegation }',
|
|
1372
|
+
);
|
|
1373
|
+
own(actor, from);
|
|
1374
|
+
const parent = await session(from);
|
|
1375
|
+
const found = findOf(parent, id);
|
|
1376
|
+
if (found.status !== 'running') return viewOf(found);
|
|
1377
|
+
const child = found.child === undefined ? undefined : await get(found.child);
|
|
1378
|
+
// A descendant now above the caller's mode (the caller lowered since): its cancel is the user's.
|
|
1379
|
+
if (child) {
|
|
1380
|
+
const mine = await permissionsOf(parent);
|
|
1381
|
+
for (const each of [child, ...(await runningBelow(child.id))]) {
|
|
1382
|
+
const above = aboveParent(mine, await permissionsOf(each));
|
|
1383
|
+
if (above)
|
|
1384
|
+
throw refused(
|
|
1385
|
+
'descendant_above_mode',
|
|
1386
|
+
`session ${each.id} runs above this session's permissions (${above}): ask the user to stop it`,
|
|
1387
|
+
403,
|
|
1388
|
+
);
|
|
1389
|
+
}
|
|
1390
|
+
}
|
|
1391
|
+
const at = new Date().toISOString();
|
|
1392
|
+
let cancelled = found;
|
|
1393
|
+
await change(from, (now) => ({
|
|
1394
|
+
...now,
|
|
1395
|
+
delegations: now.delegations?.map((each) => {
|
|
1396
|
+
if (each.id !== id || each.status !== 'running') return each;
|
|
1397
|
+
cancelled = { ...each, status: 'cancelled', endedAt: at, delivery: 'read' };
|
|
1398
|
+
return cancelled;
|
|
1399
|
+
}),
|
|
1400
|
+
}));
|
|
1401
|
+
wake(id);
|
|
1402
|
+
if (found.child !== undefined) {
|
|
1403
|
+
await stop(found.child).catch(log(`session ${found.child}: not stopped`));
|
|
1404
|
+
await cancelBelow(found.child);
|
|
1405
|
+
}
|
|
1406
|
+
return viewOf(cancelled);
|
|
1407
|
+
});
|
|
1408
|
+
|
|
1409
|
+
route('POST', '/sessions/profiles', async ({ actor, body }) => {
|
|
1410
|
+
const { from } = parse(profilesBody, body, 'POST /sessions/profiles takes { from? }');
|
|
1411
|
+
if (from !== undefined) own(actor, from);
|
|
1412
|
+
const caller = from === undefined ? undefined : await session(from);
|
|
1413
|
+
const node = caller?.node ?? 'root';
|
|
1414
|
+
const cwd = caller ? await folder(caller) : await nodeFolder(node);
|
|
1415
|
+
if (cwd === undefined) throw refused('not_a_project', `node ${node} is not a project`, 400);
|
|
1416
|
+
const failure = (error: unknown) => (error instanceof Error ? error.message : String(error));
|
|
1417
|
+
return {
|
|
1418
|
+
...(caller && {
|
|
1419
|
+
current: {
|
|
1420
|
+
session: caller.id,
|
|
1421
|
+
profile: caller.value.harness,
|
|
1422
|
+
...(caller.value.model && { model: caller.value.model }),
|
|
1423
|
+
...(caller.value.effort && { effort: caller.value.effort }),
|
|
1424
|
+
...(caller.value.mode && { mode: caller.value.mode }),
|
|
1425
|
+
...(caller.value.options && { options: caller.value.options }),
|
|
1426
|
+
},
|
|
1427
|
+
}),
|
|
1428
|
+
profiles: await Promise.all(
|
|
1429
|
+
(await harnesses(node)).map(async ({ name, displayName, driver, available }) => {
|
|
1430
|
+
const base = {
|
|
1431
|
+
profile: name,
|
|
1432
|
+
...(displayName && { name: displayName }),
|
|
1433
|
+
driver,
|
|
1434
|
+
available,
|
|
1435
|
+
};
|
|
1436
|
+
if (!available) return base;
|
|
1437
|
+
const [listedModels, listedModes] = await Promise.all([
|
|
1438
|
+
models(name, node, cwd).then(
|
|
1439
|
+
(each) => ({ models: each }),
|
|
1440
|
+
(error: unknown) => ({ modelsError: failure(error) }),
|
|
1441
|
+
),
|
|
1442
|
+
modes(name, node, cwd).then(
|
|
1443
|
+
(each) => ({ modes: each }),
|
|
1444
|
+
(error: unknown) => ({ modesError: failure(error) }),
|
|
1445
|
+
),
|
|
1446
|
+
]);
|
|
1447
|
+
return { ...base, ...listedModels, ...listedModes };
|
|
1448
|
+
}),
|
|
1449
|
+
),
|
|
1450
|
+
};
|
|
1451
|
+
});
|
|
1452
|
+
|
|
1453
|
+
/** The open decisions of `each`'s child while it runs: its questions and its approvals. */
|
|
1454
|
+
const openOf = async (each: Delegation) =>
|
|
1455
|
+
each.status === 'running' && each.child !== undefined ? await decisions(each.child) : [];
|
|
1456
|
+
/** Removes the questions `closed` (their decisions) from session `parentId`'s queue: their messages not sent yet. */
|
|
1457
|
+
const withdraw = async (parentId: string, closed: string[]) => {
|
|
1458
|
+
const holds = (item: QueueItem) =>
|
|
1459
|
+
!!item.questions?.some((each) => closed.includes(each.decision));
|
|
1460
|
+
// After the writes asked before: a question being queued now is seen here, or sees it closed (`asked`).
|
|
1461
|
+
await written(parentId);
|
|
1462
|
+
if (!(await get(parentId))?.value.queue?.some(holds)) return;
|
|
1463
|
+
await change(parentId, (now) => {
|
|
1464
|
+
const queue = (now.queue ?? []).flatMap((item) =>
|
|
1465
|
+
holds(item)
|
|
1466
|
+
? keep(
|
|
1467
|
+
item,
|
|
1468
|
+
item.delegations,
|
|
1469
|
+
item.questions!.filter((each) => !closed.includes(each.decision)),
|
|
1470
|
+
)
|
|
1471
|
+
: [item],
|
|
1472
|
+
);
|
|
1473
|
+
const { queue: _queue, ...others } = now;
|
|
1474
|
+
return (queue.length ? { ...others, queue } : others) as V;
|
|
1475
|
+
});
|
|
1476
|
+
emitQueue(parentId);
|
|
1477
|
+
};
|
|
1478
|
+
/** Child `childId` asks the user `decision` (a question, not an approval) while it works for its parent: the
|
|
1479
|
+
* question waits in the parent's queue (item `question-<decision>`, beyond the queue's 20; a settled parent active
|
|
1480
|
+
* again, an archived one told nothing), a `read_delegation` waiting on it answers, and the parent's queue is sent. */
|
|
1481
|
+
const asked = async (childId: string, decision: Decision) => {
|
|
1482
|
+
const child = await get(childId);
|
|
1483
|
+
const parentId = child?.value.parent;
|
|
1484
|
+
if (!child || parentId === undefined) return;
|
|
1485
|
+
const parent = await get(parentId);
|
|
1486
|
+
const working = parent?.value.delegations?.find(
|
|
1487
|
+
(each) => each.child === childId && each.status === 'running',
|
|
1488
|
+
);
|
|
1489
|
+
// A child the user talks to on their own (no delegation of its parent running) asks them only.
|
|
1490
|
+
if (!parent || parent.archived || !working) return;
|
|
1491
|
+
// An approval is the user's, in the child: it only ends a wait for its delegation, which says so.
|
|
1492
|
+
if (!isQuestion(decision)) {
|
|
1493
|
+
wake(working.id);
|
|
1494
|
+
return;
|
|
1495
|
+
}
|
|
1496
|
+
const item = `question-${decision.id}`;
|
|
1497
|
+
let added = false;
|
|
1498
|
+
await change(parentId, (now) => {
|
|
1499
|
+
// Answered meanwhile (in the child, by the user), read through `read_delegation`, or already there.
|
|
1500
|
+
if (
|
|
1501
|
+
!liveOpen(childId, decision.id) ||
|
|
1502
|
+
reported.has(decision.id) ||
|
|
1503
|
+
now.queue?.some((each) => each.id === item)
|
|
1504
|
+
)
|
|
1505
|
+
return now;
|
|
1506
|
+
added = true;
|
|
1507
|
+
const text = questionText(childId, child.value.title, working.id, decision);
|
|
1508
|
+
return {
|
|
1509
|
+
...(now.settledAt ? unsettle(now) : now),
|
|
1510
|
+
queue: [
|
|
1511
|
+
...(now.queue ?? []),
|
|
1512
|
+
{
|
|
1513
|
+
id: item,
|
|
1514
|
+
text,
|
|
1515
|
+
at: new Date().toISOString(),
|
|
1516
|
+
from: 'bridge' as const,
|
|
1517
|
+
questions: [{ session: childId, decision: decision.id, text }],
|
|
1518
|
+
},
|
|
1519
|
+
],
|
|
1520
|
+
};
|
|
1521
|
+
});
|
|
1522
|
+
if (!added) return;
|
|
1523
|
+
emitQueue(parentId);
|
|
1524
|
+
wake(working.id);
|
|
1525
|
+
void dequeue(parentId, true).catch(log(`session ${parentId}: child's question not sent`));
|
|
1526
|
+
};
|
|
1527
|
+
|
|
1528
|
+
/** Delegation `id` of session `caller`, else of a session below it whose delegation still runs (`runningBelow`). */
|
|
1529
|
+
const locate = async (caller: Found<V>, id: string) => {
|
|
1530
|
+
const mine = caller.value.delegations?.find((one) => one.id === id);
|
|
1531
|
+
if (mine) return mine;
|
|
1532
|
+
for (const below of await runningBelow(caller.id)) {
|
|
1533
|
+
const each = below.value.delegations?.find((one) => one.id === id);
|
|
1534
|
+
if (each) return each;
|
|
1535
|
+
}
|
|
1536
|
+
throw refused(
|
|
1537
|
+
'delegation_unknown',
|
|
1538
|
+
`neither session ${caller.id} nor a session below it made a delegation ${id}`,
|
|
1539
|
+
404,
|
|
1540
|
+
);
|
|
1541
|
+
};
|
|
1542
|
+
|
|
1543
|
+
route('POST', '/sessions/delegation/answer', async ({ actor, body }) => {
|
|
1544
|
+
const input = parse(
|
|
1545
|
+
answerBody,
|
|
1546
|
+
body,
|
|
1547
|
+
'POST /sessions/delegation/answer takes { from, action: list, delegation }, { from, action: read, delegation, request } or { from, action: respond, delegation, request, answers: [{ question?, options: [option id] }] }',
|
|
1548
|
+
);
|
|
1549
|
+
const { from, delegation: id } = input;
|
|
1550
|
+
own(actor, from);
|
|
1551
|
+
const caller = await session(from);
|
|
1552
|
+
if (caller.archived) throw refused('not_found', `no session ${from}`, 404);
|
|
1553
|
+
const each = await locate(caller, id);
|
|
1554
|
+
// Its child's pending questions, never its approvals (the user's); none once it ended.
|
|
1555
|
+
if (input.action === 'list')
|
|
1556
|
+
return {
|
|
1557
|
+
delegation: id,
|
|
1558
|
+
session: each.child,
|
|
1559
|
+
status: each.status,
|
|
1560
|
+
requests: (await openOf(each)).filter(isQuestion).map((one) => one.id),
|
|
1561
|
+
};
|
|
1562
|
+
if (each.status !== 'running' || each.child === undefined)
|
|
1563
|
+
throw refused(
|
|
1564
|
+
'delegation_ended',
|
|
1565
|
+
`delegation ${id} is ${each.status}: its session's questions are the user's now`,
|
|
1566
|
+
409,
|
|
1567
|
+
);
|
|
1568
|
+
const childId = each.child;
|
|
1569
|
+
const { request } = input;
|
|
1570
|
+
const open = (await decisions(childId)).find((one) => one.id === request);
|
|
1571
|
+
if (!open)
|
|
1572
|
+
throw refused(
|
|
1573
|
+
'decision_closed',
|
|
1574
|
+
`request ${request} of session ${childId} is not pending (answered, dismissed, expired, or unknown): action list gives the pending ones`,
|
|
1575
|
+
409,
|
|
1576
|
+
);
|
|
1577
|
+
if (!isQuestion(open))
|
|
1578
|
+
throw refused(
|
|
1579
|
+
'approval_not_yours',
|
|
1580
|
+
`request ${request} of session ${childId} is an approval (a permission to allow): only the user answers it, in that session`,
|
|
1581
|
+
403,
|
|
1582
|
+
);
|
|
1583
|
+
if (input.action === 'read')
|
|
1584
|
+
return { delegation: id, session: childId, request, questions: questionsOf(open) };
|
|
1585
|
+
const reply = respondAnswerOf(open, input.answers, refused);
|
|
1586
|
+
const child = await get(childId);
|
|
1587
|
+
if (child) {
|
|
1588
|
+
// The caller lowered since: a child above it now is the user's.
|
|
1589
|
+
const above = aboveParent(await permissionsOf(caller), await permissionsOf(child));
|
|
1590
|
+
if (above)
|
|
1591
|
+
throw refused(
|
|
1592
|
+
'descendant_above_mode',
|
|
1593
|
+
`session ${childId} runs above this session's permissions (${above}): ask the user to answer it`,
|
|
1594
|
+
403,
|
|
1595
|
+
);
|
|
1596
|
+
}
|
|
1597
|
+
await answer(childId, request, reply, from);
|
|
1598
|
+
return {
|
|
1599
|
+
delegation: id,
|
|
1600
|
+
session: childId,
|
|
1601
|
+
request,
|
|
1602
|
+
answers: answeredOf(open, reply),
|
|
1603
|
+
};
|
|
1604
|
+
});
|
|
1605
|
+
|
|
1606
|
+
/** Refuses the agent `actor` reaching session `target` (`what` it does) when `target` runs above its own session's
|
|
1607
|
+
* permissions; its own session it always reaches. */
|
|
1608
|
+
const mayReach = async (actor: string, target: Found<V>, what: string) => {
|
|
1609
|
+
const from = actor.startsWith('agent:') ? actor.slice('agent:'.length) : undefined;
|
|
1610
|
+
if (from === target.id) return;
|
|
1611
|
+
const caller = from === undefined ? undefined : await get(from);
|
|
1612
|
+
if (!caller)
|
|
1613
|
+
throw refused(
|
|
1614
|
+
'not_your_session',
|
|
1615
|
+
`an agent may ${what} another session only from a session of its own`,
|
|
1616
|
+
403,
|
|
1617
|
+
);
|
|
1618
|
+
const above = aboveParent(await permissionsOf(caller), await permissionsOf(target));
|
|
1619
|
+
if (above)
|
|
1620
|
+
throw refused(
|
|
1621
|
+
'mode_above_caller',
|
|
1622
|
+
`session ${target.id} runs above this session's permissions (${above}): only the user may ${what} it`,
|
|
1623
|
+
403,
|
|
1624
|
+
);
|
|
1625
|
+
};
|
|
1626
|
+
|
|
1627
|
+
route('POST', '/sessions/prompt', async ({ actor, body }) => {
|
|
1628
|
+
const { from, to, text, delivery } = parse(
|
|
1629
|
+
promptBody,
|
|
1630
|
+
body,
|
|
1631
|
+
'POST /sessions/prompt takes { from, to, text, delivery?: auto | queue | steer | restart }',
|
|
1632
|
+
);
|
|
1633
|
+
own(actor, from);
|
|
1634
|
+
const how = delivery ?? 'auto';
|
|
1635
|
+
if (from === to) throw refused('same_session', 'a session does not prompt itself');
|
|
1636
|
+
const caller = await session(from);
|
|
1637
|
+
if (caller.archived) throw refused('not_found', `no session ${from}`, 404);
|
|
1638
|
+
const target = await get(to);
|
|
1639
|
+
if (!target || target.archived)
|
|
1640
|
+
throw refused(
|
|
1641
|
+
'not_found',
|
|
1642
|
+
target ? `session ${to} is archived: only the user may restore it` : `no session ${to}`,
|
|
1643
|
+
404,
|
|
1644
|
+
);
|
|
1645
|
+
await mayReach(`agent:${from}`, target, 'prompt');
|
|
1646
|
+
if (halted.has(to))
|
|
1647
|
+
throw refused(
|
|
1648
|
+
'session_stopped',
|
|
1649
|
+
`session ${to} was stopped (by the user, or a cancel): its next message is the user's. Ask the user, or delegate a new task`,
|
|
1650
|
+
409,
|
|
1651
|
+
);
|
|
1652
|
+
// Its own child: a follow-up, a new delegation of it whose result wakes the caller (one running takes it in).
|
|
1653
|
+
if (target.value.parent === from)
|
|
1654
|
+
return oneAtATime(from, async () => {
|
|
1655
|
+
// Active again before the message: the turn it starts reads what changed while it was settled, once.
|
|
1656
|
+
await reached(to);
|
|
1657
|
+
const opened = { id: '', joined: false };
|
|
1658
|
+
// Opened or joined with the child's queue lock held, as the user's follow-up (`fromUser`): a `check`
|
|
1659
|
+
// delivering its earlier delegation goes first (this opens a new one) or after (this one joined it).
|
|
1660
|
+
const sent = await send(
|
|
1661
|
+
to,
|
|
1662
|
+
async () => {
|
|
1663
|
+
Object.assign(opened, await follow(from, to, titleOf(text), 'prompt', text));
|
|
1664
|
+
const { id: made, joined: into } = opened;
|
|
1665
|
+
// Not sent: no delegation was opened.
|
|
1666
|
+
return {
|
|
1667
|
+
text: followUpText(from, made, text),
|
|
1668
|
+
undo: into ? undefined : () => unfollow(from, made),
|
|
1669
|
+
};
|
|
1670
|
+
},
|
|
1671
|
+
from,
|
|
1672
|
+
how,
|
|
1673
|
+
);
|
|
1674
|
+
const { id, joined } = opened;
|
|
1675
|
+
return {
|
|
1676
|
+
to,
|
|
1677
|
+
delivery: sent.delivery,
|
|
1678
|
+
delegation: id,
|
|
1679
|
+
...(joined && { joined: true }),
|
|
1680
|
+
hint: joined
|
|
1681
|
+
? 'Its delegation still runs: this message is part of it, and its one result reaches you as a message when it ends.'
|
|
1682
|
+
: 'A follow-up: its result reaches you as a message when it ends (read_delegation reads it sooner).',
|
|
1683
|
+
};
|
|
1684
|
+
});
|
|
1685
|
+
await reached(to);
|
|
1686
|
+
const sent = await send(
|
|
1687
|
+
to,
|
|
1688
|
+
async () => ({ text: promptText(from, caller.value.title, text) }),
|
|
1689
|
+
from,
|
|
1690
|
+
how,
|
|
1691
|
+
);
|
|
1692
|
+
return {
|
|
1693
|
+
to,
|
|
1694
|
+
delivery: sent.delivery,
|
|
1695
|
+
hint: 'Delivered: nothing comes back to you from its turn.',
|
|
1696
|
+
};
|
|
1697
|
+
});
|
|
1698
|
+
/** Opens a delegation of child `childId` for session `parentId` (`title`, its key `<kind>-<id>`, `text` its
|
|
1699
|
+
* payload), or joins the one running: decided in the parent's write, so two follow-ups at once open one. */
|
|
1700
|
+
const follow = async (
|
|
1701
|
+
parentId: string,
|
|
1702
|
+
childId: string,
|
|
1703
|
+
title: string,
|
|
1704
|
+
kind: string,
|
|
1705
|
+
text: string,
|
|
1706
|
+
): Promise<{ id: string; joined: boolean }> => {
|
|
1707
|
+
let id: string = randomUUID();
|
|
1708
|
+
let joined = false;
|
|
1709
|
+
await change(parentId, (was) => {
|
|
1710
|
+
const current = was.delegations?.find(
|
|
1711
|
+
(each) => each.child === childId && each.status === 'running',
|
|
1712
|
+
);
|
|
1713
|
+
if (current) {
|
|
1714
|
+
id = current.id;
|
|
1715
|
+
joined = true;
|
|
1716
|
+
return was;
|
|
1717
|
+
}
|
|
1718
|
+
const opened: Delegation = {
|
|
1719
|
+
id,
|
|
1720
|
+
child: childId,
|
|
1721
|
+
title,
|
|
1722
|
+
clientRequestId: `${kind}-${id}`,
|
|
1723
|
+
request: createHash('sha256').update(text).digest('hex'),
|
|
1724
|
+
status: 'running',
|
|
1725
|
+
createdAt: new Date().toISOString(),
|
|
1726
|
+
};
|
|
1727
|
+
return { ...was, delegations: [...(was.delegations ?? []), opened] };
|
|
1728
|
+
});
|
|
1729
|
+
return { id, joined };
|
|
1730
|
+
};
|
|
1731
|
+
/** Removes delegation `id` of session `parentId`, opened for a message that was then not sent. */
|
|
1732
|
+
const unfollow = (parentId: string, id: string) =>
|
|
1733
|
+
change(parentId, ({ delegations, ...was }) => {
|
|
1734
|
+
const rest = delegations?.filter((each) => each.id !== id);
|
|
1735
|
+
return (rest?.length ? { ...was, delegations: rest } : was) as V;
|
|
1736
|
+
}).then(() => {}, log(`session ${parentId}: unsent follow-up ${id} not removed`));
|
|
1737
|
+
/** A message from an agent reached session `id`: settled, it is active again; snoozed, it wakes. */
|
|
1738
|
+
const reached = async (id: string) => {
|
|
1739
|
+
if ((await get(id))?.value.settledAt)
|
|
1740
|
+
await change(id, (now) => (now.settledAt ? unsettle(now) : now));
|
|
1741
|
+
await endSnooze(id);
|
|
1742
|
+
};
|
|
1743
|
+
|
|
1744
|
+
/** Gives session `child`'s result to its parent, once: its running delegation there takes its state and the result
|
|
1745
|
+
* goes in the parent's queue in one write (an archived parent: the state only), then the parent's queue is sent. */
|
|
1746
|
+
const deliver = async (parentId: string, childId: string) => {
|
|
1747
|
+
const parent = await get(parentId);
|
|
1748
|
+
const mine = (each: Delegation) => each.child === childId && each.status === 'running';
|
|
1749
|
+
if (!parent?.value.delegations?.some(mine)) return;
|
|
1750
|
+
await close(parent, mine, resultOf(await tail(childId)));
|
|
1751
|
+
};
|
|
1752
|
+
/** Ends `parent`'s running delegation `mine` with `result`: its state and its result in the parent's queue in one
|
|
1753
|
+
* write (an archived parent: its state only), then the parent's queue sent. */
|
|
1754
|
+
const close = async (
|
|
1755
|
+
parent: Found<V>,
|
|
1756
|
+
mine: (each: Delegation) => boolean,
|
|
1757
|
+
result: ReturnType<typeof resultOf>,
|
|
1758
|
+
) => {
|
|
1759
|
+
const parentId = parent.id;
|
|
1760
|
+
const archived = parent.archived === true;
|
|
1761
|
+
// Its result names the branch its worktree is on as it ends, not the one it was made on.
|
|
1762
|
+
const { worktree } = await withHead({
|
|
1763
|
+
worktree: parent.value.delegations?.find(mine)?.worktree,
|
|
1764
|
+
});
|
|
1765
|
+
let done: Delegation | undefined;
|
|
1766
|
+
await change(parentId, (now) => {
|
|
1767
|
+
const open = now.delegations?.find(mine);
|
|
1768
|
+
if (!open) return now;
|
|
1769
|
+
const { preparing: _preparing, ...kept } = open;
|
|
1770
|
+
if (kept.worktree && worktree?.slug === kept.worktree.slug) kept.worktree = worktree;
|
|
1771
|
+
const finished: Delegation = {
|
|
1772
|
+
...kept,
|
|
1773
|
+
status: result.status,
|
|
1774
|
+
endedAt: new Date().toISOString(),
|
|
1775
|
+
...(result.text !== undefined && { result: result.text }),
|
|
1776
|
+
...(result.error !== undefined && { error: result.error }),
|
|
1777
|
+
delivery: archived ? 'dropped' : 'queued',
|
|
1778
|
+
};
|
|
1779
|
+
done = finished;
|
|
1780
|
+
const delegations = now.delegations!.map((each) => (each === open ? finished : each));
|
|
1781
|
+
if (archived) return { ...now, delegations };
|
|
1782
|
+
const item = `delegation-${open.id}`;
|
|
1783
|
+
const queue = now.queue?.some((each) => each.id === item)
|
|
1784
|
+
? now.queue
|
|
1785
|
+
: [
|
|
1786
|
+
...(now.queue ?? []),
|
|
1787
|
+
{
|
|
1788
|
+
id: item,
|
|
1789
|
+
text: resultsText([finished]),
|
|
1790
|
+
at: finished.endedAt!,
|
|
1791
|
+
from: 'bridge' as const,
|
|
1792
|
+
delegations: [open.id],
|
|
1793
|
+
},
|
|
1794
|
+
];
|
|
1795
|
+
// A settled parent is active again: a result is for it to read.
|
|
1796
|
+
return { ...(now.settledAt ? unsettle(now) : now), delegations, queue };
|
|
1797
|
+
});
|
|
1798
|
+
const delivered = done as Delegation | undefined;
|
|
1799
|
+
if (!delivered) return;
|
|
1800
|
+
wake(delivered.id);
|
|
1801
|
+
if (archived) {
|
|
1802
|
+
void check(parentId);
|
|
1803
|
+
return;
|
|
1804
|
+
}
|
|
1805
|
+
emitQueue(parentId);
|
|
1806
|
+
// Sent whatever its last turn's end; then the parent, itself a child maybe, may be done too.
|
|
1807
|
+
void dequeue(parentId, true)
|
|
1808
|
+
.then(() => check(parentId))
|
|
1809
|
+
.catch(log(`session ${parentId}: delegated results not sent`));
|
|
1810
|
+
};
|
|
1811
|
+
|
|
1812
|
+
/** Whether session `id`, a child, is done (its turn ended, nothing queued for it to do, no decision open, no child
|
|
1813
|
+
* of its own still running), and if so its result to its parent. Runs with its queue lock, after a `dequeue` asked
|
|
1814
|
+
* before it. */
|
|
1815
|
+
const check = (id: string) =>
|
|
1816
|
+
serial(id, async () => {
|
|
1817
|
+
if (running.has(id)) return;
|
|
1818
|
+
const found = await get(id);
|
|
1819
|
+
const parent = found?.value.parent;
|
|
1820
|
+
if (!found || parent === undefined) return;
|
|
1821
|
+
// Its worktree is being made: its task is not even queued yet.
|
|
1822
|
+
if (preparing.has(id)) return;
|
|
1823
|
+
if (deciding(id, found.value)) return;
|
|
1824
|
+
if (found.value.queue?.length && !halted.has(id)) return;
|
|
1825
|
+
if (found.value.delegations?.some((each) => each.status === 'running')) return;
|
|
1826
|
+
await deliver(parent, id);
|
|
1827
|
+
}).catch(log(`session ${id}: delegation not delivered`));
|
|
1828
|
+
|
|
1829
|
+
return {
|
|
1830
|
+
/** Whether queued delivery `item` of session `value` is for a wait of its agent (`read_delegation`, `wait: wait`):
|
|
1831
|
+
* a result of the delegation it waits for, or a question of its child; not steered into its turn (S6). */
|
|
1832
|
+
held: (value: V, item: QueueItem) =>
|
|
1833
|
+
!!item.delegations?.some((each) => awaited.has(each)) ||
|
|
1834
|
+
!!item.questions?.some((question) =>
|
|
1835
|
+
value.delegations?.some((each) => awaited.has(each.id) && each.child === question.session),
|
|
1836
|
+
),
|
|
1837
|
+
/** Session `id`'s turn ended, not cut by this plugin's disposal: no wait of it goes on. */
|
|
1838
|
+
ended: (id: string) => {
|
|
1839
|
+
for (const [each, { from }] of [...awaited]) if (from === id) release(each);
|
|
1840
|
+
void check(id);
|
|
1841
|
+
},
|
|
1842
|
+
/** Stops each running child of session `id`, and theirs (`POST /sessions/interrupt` on `id`). */
|
|
1843
|
+
stopTree: async (id: string) => {
|
|
1844
|
+
stops.set(id, (stops.get(id) ?? 0) + 1);
|
|
1845
|
+
for (const each of await runningBelow(id)) {
|
|
1846
|
+
await stop(each.id).catch(log(`session ${each.id}: not stopped`));
|
|
1847
|
+
void check(each.id);
|
|
1848
|
+
}
|
|
1849
|
+
},
|
|
1850
|
+
/** At the start, before any queue is sent: each result taken out of its parent's queue for a turn (`sending`)
|
|
1851
|
+
* when Bridge stopped is `sent` when its message line is in the parent's history (`sentIn`: the delegations its
|
|
1852
|
+
* `user/message` lines carry), else back in its queue, to be sent once. */
|
|
1853
|
+
recover: async (sentIn: (id: string) => Promise<Set<string>>) => {
|
|
1854
|
+
for (const parent of await query()) {
|
|
1855
|
+
if (
|
|
1856
|
+
parent.archived ||
|
|
1857
|
+
!parent.value.delegations?.some((each) => each.delivery === 'sending')
|
|
1858
|
+
)
|
|
1859
|
+
continue;
|
|
1860
|
+
const sent = await sentIn(parent.id);
|
|
1861
|
+
await change(parent.id, (now) => {
|
|
1862
|
+
const queued = new Set(now.queue?.flatMap((item) => item.delegations ?? []));
|
|
1863
|
+
const back: QueueItem[] = [];
|
|
1864
|
+
const delegations = now.delegations?.map((each) => {
|
|
1865
|
+
if (each.delivery !== 'sending') return each;
|
|
1866
|
+
if (sent.has(each.id)) return { ...each, delivery: 'sent' as const };
|
|
1867
|
+
const again = { ...each, delivery: 'queued' as const };
|
|
1868
|
+
if (!queued.has(each.id))
|
|
1869
|
+
back.push({
|
|
1870
|
+
id: `delegation-${each.id}`,
|
|
1871
|
+
text: resultsText([again]),
|
|
1872
|
+
at: each.endedAt ?? new Date().toISOString(),
|
|
1873
|
+
from: 'bridge',
|
|
1874
|
+
delegations: [each.id],
|
|
1875
|
+
});
|
|
1876
|
+
return again;
|
|
1877
|
+
});
|
|
1878
|
+
return {
|
|
1879
|
+
...now,
|
|
1880
|
+
delegations,
|
|
1881
|
+
...(back.length && { queue: [...(now.queue ?? []), ...back] }),
|
|
1882
|
+
};
|
|
1883
|
+
});
|
|
1884
|
+
}
|
|
1885
|
+
},
|
|
1886
|
+
/** At the start, before any queue is sent: each child whose worktree was being made when Bridge stopped (S7) is
|
|
1887
|
+
* preparing again until `sweep` fails its delegation (it never gets that worktree), so no turn starts outside it; a
|
|
1888
|
+
* message the user queued there then waits for the user, as after the host's refusal. */
|
|
1889
|
+
holdUnprepared: async () => {
|
|
1890
|
+
for (const parent of await query())
|
|
1891
|
+
for (const each of parent.value.delegations ?? [])
|
|
1892
|
+
if (each.status === 'running' && each.preparing && each.child !== undefined) {
|
|
1893
|
+
preparing.add(each.child);
|
|
1894
|
+
unprepared.add(each.child);
|
|
1895
|
+
}
|
|
1896
|
+
},
|
|
1897
|
+
/** After a restart (a crash: no `finish`), delivers each running delegation whose child is done; `continued`: the
|
|
1898
|
+
* sessions the start continued, whose end delivers. */
|
|
1899
|
+
sweep: async (continued: Set<string>) => {
|
|
1900
|
+
// A child's question its crash closed (the repair expired it) leaves its parent's queue.
|
|
1901
|
+
for (const parent of await query()) {
|
|
1902
|
+
const pending = (parent.value.queue ?? []).flatMap((item) => item.questions ?? []);
|
|
1903
|
+
const gone: string[] = [];
|
|
1904
|
+
for (const each of pending)
|
|
1905
|
+
if (!(await decisions(each.session)).some((one) => one.id === each.decision))
|
|
1906
|
+
gone.push(each.decision);
|
|
1907
|
+
if (gone.length)
|
|
1908
|
+
await withdraw(parent.id, gone).catch(
|
|
1909
|
+
log(`session ${parent.id}: questions not withdrawn`),
|
|
1910
|
+
);
|
|
1911
|
+
}
|
|
1912
|
+
for (const parent of await query())
|
|
1913
|
+
for (const each of parent.value.delegations ?? []) {
|
|
1914
|
+
if (each.status !== 'running') continue;
|
|
1915
|
+
if (each.child === undefined) {
|
|
1916
|
+
// Bridge stopped between the delegation and its child's creation: it failed, delivered as any other.
|
|
1917
|
+
await close(parent, (one) => one.id === each.id && one.status === 'running', {
|
|
1918
|
+
status: 'failed',
|
|
1919
|
+
error: 'Bridge stopped before the child session was created',
|
|
1920
|
+
}).catch(log(`session ${parent.id}: delegation ${each.id} not closed`));
|
|
1921
|
+
continue;
|
|
1922
|
+
}
|
|
1923
|
+
if (each.preparing && (unprepared.has(each.child) || !preparing.has(each.child))) {
|
|
1924
|
+
preparing.delete(each.child);
|
|
1925
|
+
unprepared.delete(each.child);
|
|
1926
|
+
// Bridge stopped while its child's worktree was being made (S7): its task was never sent.
|
|
1927
|
+
await close(parent, (one) => one.id === each.id && one.status === 'running', {
|
|
1928
|
+
status: 'failed',
|
|
1929
|
+
error:
|
|
1930
|
+
"Bridge stopped while the child session's worktree was being made: its task was not sent (a stage the host made meanwhile stays: stage_remove removes it)",
|
|
1931
|
+
}).catch(log(`session ${parent.id}: delegation ${each.id} not closed`));
|
|
1932
|
+
continue;
|
|
1933
|
+
}
|
|
1934
|
+
if (!continued.has(each.child)) void check(each.child);
|
|
1935
|
+
}
|
|
1936
|
+
},
|
|
1937
|
+
/** Session `id` asks the user `decision`: a question (`isQuestion`) of a child working for its parent reaches it. */
|
|
1938
|
+
asked: (id: string, decision: Decision) =>
|
|
1939
|
+
void asked(id, decision).catch(log(`session ${id}: question not sent to its parent`)),
|
|
1940
|
+
/** Session `id`'s decision `decision` closed (answered, expired, withdrawn): its question leaves its parent's queue. */
|
|
1941
|
+
closed: (id: string, decision: string) =>
|
|
1942
|
+
void (async () => {
|
|
1943
|
+
reported.delete(decision);
|
|
1944
|
+
const parentId = (await get(id))?.value.parent;
|
|
1945
|
+
if (parentId !== undefined) await withdraw(parentId, [decision]);
|
|
1946
|
+
})().catch(log(`session ${id}: question not withdrawn from its parent`)),
|
|
1947
|
+
mayReach,
|
|
1948
|
+
/** Whether session `id` is a child whose worktree is being made (S7): no turn starts in it until it is bound. */
|
|
1949
|
+
preparing: (id: string) => preparing.has(id),
|
|
1950
|
+
/** The user sends `text` to session `id` (bridge#212 S5), its queue lock held: a child whose parent is not archived
|
|
1951
|
+
* gets it as a follow-up, a new delegation of it for its parent, titled after it, whose result wakes the parent as
|
|
1952
|
+
* any (the delegation still running takes it in). Resolves to what undoes it when the message is not sent after
|
|
1953
|
+
* all, `undefined` when nothing was opened. */
|
|
1954
|
+
fromUser: async (id: string, text: string) => {
|
|
1955
|
+
const parentId = (await get(id))?.value.parent;
|
|
1956
|
+
if (parentId === undefined) return undefined;
|
|
1957
|
+
const parent = await get(parentId);
|
|
1958
|
+
if (!parent || parent.archived) return undefined;
|
|
1959
|
+
const { id: opened, joined } = await follow(
|
|
1960
|
+
parentId,
|
|
1961
|
+
id,
|
|
1962
|
+
titleOf(`From the user: ${text || 'images'}`),
|
|
1963
|
+
'user',
|
|
1964
|
+
text,
|
|
1965
|
+
);
|
|
1966
|
+
return joined ? undefined : () => unfollow(parentId, opened);
|
|
1967
|
+
},
|
|
1968
|
+
takeQueued,
|
|
1969
|
+
dispose: () => {
|
|
1970
|
+
disposed = true;
|
|
1971
|
+
for (const each of [...awaited.keys()]) release(each);
|
|
1972
|
+
for (const id of [...waiting.keys()]) wake(id);
|
|
1973
|
+
},
|
|
1974
|
+
};
|
|
1975
|
+
}
|