GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — opencode-workflows/src/mailbox.ts at main · rphang/opencode-workflows

Expand file tree

/

mailbox.ts

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
271 lines (243 loc) · 10.5 KB
/

mailbox.ts

Copy path

File metadata and controls

271 lines (243 loc) · 10.5 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
// Per-agent message window for steering (docs/design/steering-and-live-tree.md §A.4, PARITY X01–X04).
// Host-agnostic: the engine creates one mailbox per live agent, and the host runner attaches a
// sender once the agent has a session.
//
// attach() first prompt sent turn finished (wait() resolved)
// pending ─────────► between ────────────────► open ─────────────────────────────► finishing
// (queued: held, (messages wait ▲ │
// go into the for open()) └──────── next (schema-retry) turn ◄───┤
// first prompt) │ seal
// any state ───────────────────────────── stop / settle ──────────────────────────────► closed
//
// post() decides from the state synchronously (JS is single-threaded, so the check and the state
// change cannot interleave): pending → held; between → sent at open(); open → sent now; finishing →
// refused `finishing`; closed → refused `finished`. close() awaits every send that started while the
// window was open, so a message accepted just before the turn ended is always verified by the runner.
// quiesce() (the opencode 2.3+ idle hook, X22) moves open → finishing ahead of close() and awaits the
// sends in flight; the hook reopens the window when the execution goes on (open()).
export const MAX_MESSAGE_CHARS = 4000
export const MAX_MESSAGES_PER_AGENT = 20
export const MAX_HELD_MESSAGES = 5
/** Message text kept in AgentRecord.messages (the full text is in journal.jsonl). */
export const RECORD_TEXT_CHARS = 500
export type MessageFrom = "user" | "model"
/** command: /workflows msg; tool: workflow_control; rpc: the dynamic-workflows RPC (the TUI tree or another server-API client). */
export type MessageVia = "command" | "tool" | "rpc"
export interface AgentMessage {
/** `wm_<agentIndex>_<n>`, unique within a run. */
id: string
from: MessageFrom
via: MessageVia
text: string
urgent: boolean
at: number
}
export type MessageStatus = "held" | "sent" | "delivered" | "undelivered" | "refused"
/** One message as shown on the agent (AgentRecord.messages). */
export interface MessageRecord {
id: string
from: MessageFrom
via: MessageVia
urgent: boolean
at: number
/** Clipped to RECORD_TEXT_CHARS. */
text: string
status: MessageStatus
error?: string
}
export type RefusalReason = "finished" | "finishing" | "submitted" | "limit" | "send_failed"
export type PostResult =
| { ok: true; state: "sent"; deliveryId: string }
| { ok: true; state: "held" }
| { ok: false; reason: RefusalReason; detail?: string }
export type MailboxState = "pending" | "between" | "open" | "finishing" | "closed"
/** A message sent in one window: its id and the id of the context message it becomes. */
export interface SentMessage {
id: string
deliveryId: string
}
/** Delivers one message to the agent's session; resolves with the id of the resulting context message. */
export type MessageSender = (m: AgentMessage) => Promise<{ id: string }>
/** Checked before each send; a string is the refusal reason (e.g. "submitted"). */
export type MessageGuard = () => Promise<RefusalReason | undefined>
function errText(e: unknown): string {
if (e instanceof Error) return e.message
if (e && typeof e === "object" && "message" in e) return String((e as { message: unknown }).message)
return String(e)
}
function clipText(s: string): string {
return s.length > RECORD_TEXT_CHARS ? `${s.slice(0, RECORD_TEXT_CHARS - 1)}…` : s
}
export class AgentMailbox {
private _state: MailboxState = "pending"
private readonly entries: MessageRecord[] = []
private held: AgentMessage[] = []
private deferred: { msg: AgentMessage; resolve: (r: PostResult) => void }[] = []
private readonly inflight = new Set<Promise<unknown>>()
private windowSent: SentMessage[] = []
/** quiesce() closed the window and the runner has not touched it since (reopen() may undo it). */
private quiesced = false
private reserved = 0
private send?: MessageSender
private guard?: MessageGuard
private readonly onChange?: () => void
constructor(opts: { onChange?: () => void } = {}) {
this.onChange = opts.onChange
}
get state(): MailboxState {
return this._state
}
/** Snapshot copies of every message this agent got (held, sent, delivered, …). */
records(): MessageRecord[] {
return this.entries.map((e) => ({ ...e }))
}
/** Messages accepted so far (held, sent, delivered or undelivered), plus sends in flight. */
accepted(): number {
return this.entries.filter((e) => e.status !== "refused").length + this.reserved
}
post(msg: AgentMessage): Promise<PostResult> {
const text = msg.text ?? ""
if (!text.trim() || text.length > MAX_MESSAGE_CHARS) {
return Promise.resolve({ ok: false, reason: "limit", detail: `the text must be 1 to ${MAX_MESSAGE_CHARS} characters` })
}
switch (this._state) {
case "closed":
return Promise.resolve({ ok: false, reason: "finished" })
case "finishing":
return Promise.resolve({ ok: false, reason: "finishing" })
}
if (this.accepted() >= MAX_MESSAGES_PER_AGENT) {
return Promise.resolve({ ok: false, reason: "limit", detail: `an agent accepts at most ${MAX_MESSAGES_PER_AGENT} messages` })
}
if (this._state === "pending") {
if (this.held.length >= MAX_HELD_MESSAGES) {
return Promise.resolve({ ok: false, reason: "limit", detail: `a queued agent holds at most ${MAX_HELD_MESSAGES} messages` })
}
this.held.push(msg)
this.entries.push(this.entryOf(msg, "held"))
this.changed()
return Promise.resolve({ ok: true, state: "held" })
}
// between or open: the slot is reserved now, so concurrent posts respect the limit.
this.reserved++
if (this._state === "between") {
return new Promise((resolve) => this.deferred.push({ msg, resolve }))
}
return this.dispatch(msg)
}
/**
* Runner side: the agent has a session. Returns the held messages (to append to the first
* prompt; report them delivered once it is sent) and moves to `between`.
*/
attach(send: MessageSender, guard?: MessageGuard): AgentMessage[] {
this.send = send
this.guard = guard
if (this._state === "pending") this._state = "between"
const held = this.held
this.held = []
return held
}
/** Runner side: a turn's prompt has been sent; messages go out right away until close(). */
open(): void {
if (this._state === "closed") return
this.quiesced = false
this._state = "open"
const waiting = this.deferred
this.deferred = []
for (const d of waiting) void this.dispatch(d.msg).then(d.resolve)
}
/**
* Runner side: the turn finished. New messages are refused (`finishing`) until the next open().
* Resolves, once every send started in this window has settled, with the messages sent in it.
*/
async close(): Promise<SentMessage[]> {
this.quiesced = false // the runner owns the window from here: reopen() no longer applies
if (this._state !== "closed") this._state = "finishing"
while (this.inflight.size) await Promise.all([...this.inflight])
const sent = this.windowSent
this.windowSent = []
return sent
}
/**
* Idle-hook side (X22): the agent's execution is about to end. An open window moves to `finishing`
* (new messages are refused until the next open()), and every send in flight is awaited. Unlike
* close(), the window's sent list is kept, so close() still returns it for verification. Resolves
* with the messages sent in this window so far.
*/
async quiesce(): Promise<SentMessage[]> {
if (this._state === "open") {
this._state = "finishing"
this.quiesced = true
}
while (this.inflight.size) await Promise.all([...this.inflight])
return this.windowSent.map((s) => ({ ...s }))
}
/**
* Hook side (X22): reopens a window that quiesce() closed, as long as the runner has not taken
* it over since (close(), open() or seal()). Used when the execution goes on after all: the idle
* hook's own continuation, or the next model step (another plugin's hook or a user prompt
* continued it). Returns whether it reopened.
*/
reopen(): boolean {
if (!this.quiesced || this._state !== "finishing") return false
this.open()
return true
}
/** Runner side: confirms (or not) that a held or sent message reached the agent. */
report(id: string, status: "delivered" | "undelivered"): void {
const e = this.entries.find((x) => x.id === id)
if (!e || (e.status !== "held" && e.status !== "sent")) return
e.status = status
this.changed()
}
/** The agent settled (or was stopped): every later message is refused with `finished`. */
seal(): void {
this.quiesced = false
this._state = "closed"
const waiting = this.deferred
this.deferred = []
for (const d of waiting) {
this.reserved--
d.resolve({ ok: false, reason: "finished" })
}
this.held = []
}
private dispatch(msg: AgentMessage): Promise<PostResult> {
const p = (async (): Promise<PostResult> => {
try {
const refusal = this.guard ? await this.guard().catch(() => undefined) : undefined
if (refusal) return { ok: false, reason: refusal }
if (!this.send) return { ok: false, reason: "finished" }
let res: { id: string }
try {
res = await this.send(msg)
} catch (e) {
const detail = errText(e)
this.entries.push({ ...this.entryOf(msg, "refused"), error: detail })
this.changed()
return { ok: false, reason: "send_failed", detail }
}
const deliveryId = String(res?.id ?? "")
this.entries.push(this.entryOf(msg, "sent"))
this.windowSent.push({ id: msg.id, deliveryId })
this.changed()
return { ok: true, state: "sent", deliveryId }
} finally {
this.reserved--
}
})()
this.inflight.add(p)
void p.then(() => this.inflight.delete(p))
return p
}
private entryOf(msg: AgentMessage, status: MessageStatus): MessageRecord {
return { id: msg.id, from: msg.from, via: msg.via, urgent: !!msg.urgent, at: msg.at, text: clipText(msg.text), status }
}
private changed(): void {
try {
this.onChange?.()
} catch {
// listeners must not break delivery
}
}
}
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.