@aisac/cli 0.4.0-beta.2 → 0.4.0-beta.22

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.
Files changed (60) hide show
  1. package/README.md +146 -10
  2. package/dist/assets/claude/hooks/context-compaction.ts +17 -5
  3. package/dist/assets/claude/hooks/native-host-contract-runtime.ts +1 -1
  4. package/dist/assets/claude/hooks/native-host-contract.test.ts +8 -4
  5. package/dist/assets/claude/hooks/provider-window.d.ts +83 -0
  6. package/dist/assets/codex-context-compaction.mjs +846 -14
  7. package/dist/assets/jev-paid-pilot-terminal.mjs +12 -1
  8. package/dist/claude-compatibility.mjs +26 -25
  9. package/dist/claude-observation.mjs +2 -1
  10. package/dist/cli.mjs +641 -35
  11. package/dist/codex-compatibility.mjs +48 -2
  12. package/dist/codex-engineering.mjs +165 -0
  13. package/dist/codex-hooks.mjs +411 -0
  14. package/dist/codex-permissions.mjs +67 -34
  15. package/dist/codex-protocol-fingerprint.json +11 -11
  16. package/dist/engineering-init.mjs +615 -0
  17. package/dist/engineering-pack.mjs +276 -23
  18. package/dist/engineering-scan-pins.json +42 -0
  19. package/dist/engineering-scan-report.mjs +1274 -0
  20. package/dist/engineering-scan-tools.mjs +1418 -0
  21. package/dist/engineering-scan.mjs +1265 -0
  22. package/dist/extensions-catalog.mjs +390 -0
  23. package/dist/extensions-cli.mjs +492 -0
  24. package/dist/extensions-preferences.mjs +151 -0
  25. package/dist/guardrails/continuity.mjs +239 -0
  26. package/dist/guardrails/format.mjs +111 -0
  27. package/dist/guardrails/guards.mjs +1557 -0
  28. package/dist/guardrails/patch.mjs +33 -0
  29. package/dist/guardrails/run.mjs +286 -0
  30. package/dist/guardrails/shell-words.mjs +206 -0
  31. package/dist/guardrails-plugin.mjs +207 -0
  32. package/dist/launch.mjs +403 -47
  33. package/dist/managed-host.mjs +977 -0
  34. package/dist/manager/bus.mjs +1921 -0
  35. package/dist/manager/delegation.mjs +354 -0
  36. package/dist/manager/hooks.mjs +918 -0
  37. package/dist/manager/launch-role.mjs +476 -0
  38. package/dist/manager/mcp-stdio.mjs +463 -0
  39. package/dist/manager/messages.mjs +791 -0
  40. package/dist/manager/reserve.mjs +2166 -0
  41. package/dist/manager/room.mjs +106 -0
  42. package/dist/manager/server.mjs +1792 -0
  43. package/dist/manager/status.mjs +118 -0
  44. package/dist/manager/watch.mjs +87 -0
  45. package/dist/manager/worker.mjs +2793 -0
  46. package/dist/manager/workers-cli.mjs +1403 -0
  47. package/dist/mcp-servers.mjs +192 -0
  48. package/dist/mcp.mjs +10 -2
  49. package/dist/monitor.mjs +76 -1
  50. package/dist/package.json +1 -1
  51. package/dist/platform.mjs +78 -29
  52. package/dist/release-manifest-public-keys.json +10 -0
  53. package/dist/release-manifest.json +328 -0
  54. package/dist/release-manifest.mjs +817 -0
  55. package/dist/release-settings.mjs +210 -0
  56. package/dist/self-update.mjs +1036 -0
  57. package/dist/state.mjs +25 -1
  58. package/dist/token-guide.mjs +132 -0
  59. package/dist/update-actions.mjs +442 -0
  60. package/package.json +1 -1
@@ -0,0 +1,2793 @@
1
+ // The worker role of the manager feature (spec aisac-engineering-manager D1,
2
+ // D5-D8, D16, FR4, FR13; ADR-0058). The Codex adapter feeds it every frame it
3
+ // passes between the terminal and the app-server. The role delivers a manager
4
+ // request as one `turn/start` on an idle thread and sends the turn's last
5
+ // assistant message back. While the user has delegated approvals to the
6
+ // manager, it holds approval requests outside the reserve for the manager's
7
+ // decision. It never writes any other response to the app-server. Node
8
+ // built-ins and the bus modules only: this runs inside the adapter process.
9
+
10
+ import { randomUUID } from 'node:crypto';
11
+ import { lstat, realpath, rename } from 'node:fs/promises';
12
+ import { homedir } from 'node:os';
13
+ import { basename, dirname, isAbsolute, join, normalize } from 'node:path';
14
+ import {
15
+ CODE_PATTERN,
16
+ LIMITS,
17
+ MANAGER_RECIPIENT,
18
+ WORKER_ROLE_ENV,
19
+ audit,
20
+ liveManager,
21
+ mailboxDirectory,
22
+ parseRoleEnvironment,
23
+ readSession,
24
+ removeSession,
25
+ roomPaths,
26
+ withRoomLock,
27
+ writeSession,
28
+ } from './bus.mjs';
29
+ import {
30
+ authorizeForWorker,
31
+ buildApprovalRequest,
32
+ buildReply,
33
+ claimMailboxFile,
34
+ deliverMessage,
35
+ listMailbox,
36
+ readMailboxFile,
37
+ rejectMailboxFile,
38
+ removeMailboxFile,
39
+ workerInputText,
40
+ } from './messages.mjs';
41
+ import { appendDecision, readGrant } from './delegation.mjs';
42
+ import { classifyApproval, describeApproval } from './reserve.mjs';
43
+ import { repositoryRoots } from './room.mjs';
44
+ import { createDirectoryWatch } from './watch.mjs';
45
+
46
+ /** Every server request whose method ends with this is an approval request (spike: "Approval requests"). */
47
+ const APPROVAL_METHOD_SUFFIX = 'requestApproval';
48
+ /** @type {ReadonlyMap<string, 'command' | 'fileChange' | 'permissions'>} */
49
+ const APPROVAL_KINDS_BY_METHOD = new Map(
50
+ /** @type {const} */ ([
51
+ ['item/commandExecution/requestApproval', 'command'],
52
+ ['item/fileChange/requestApproval', 'fileChange'],
53
+ ['item/permissions/requestApproval', 'permissions'],
54
+ // The v1 forms of the protocol schema: tracked so that nothing is delivered
55
+ // while one is open, never held.
56
+ ['execCommandApproval', 'command'],
57
+ ['applyPatchApproval', 'fileChange'],
58
+ ]),
59
+ );
60
+ /**
61
+ * The only requests the role may hold and answer (`WORKER_HOLDABLE_METHODS`
62
+ * in `scripts/codex-context-compaction.mjs`): the two approvals whose answers
63
+ * are `accept` and `decline`. Every other request goes to the terminal.
64
+ */
65
+ const HOLDABLE_METHODS = new Set([
66
+ 'item/commandExecution/requestApproval',
67
+ 'item/fileChange/requestApproval',
68
+ ]);
69
+ const THREAD_OPEN_METHODS = new Set(['thread/start', 'thread/resume', 'thread/fork']);
70
+ /** The terminal's input to a turn: either one during a message turn makes it `shared`. */
71
+ const TURN_INPUT_METHODS = new Set(['turn/start', 'turn/steer']);
72
+ /**
73
+ * The terminal's requests that may start a turn on their thread (0.166.0
74
+ * protocol schema; `/compact` runs as a turn, spike). From the request until
75
+ * the thread's next status after the answer, no message is delivered there.
76
+ */
77
+ const WORK_METHODS = new Set([
78
+ 'turn/start',
79
+ 'thread/compact/start',
80
+ 'review/start',
81
+ 'thread/shellCommand',
82
+ ]);
83
+ const THREAD_GONE_METHODS = new Set(['thread/closed', 'thread/deleted']);
84
+ const ITEM_METHODS = new Set(['item/started', 'item/completed']);
85
+ const PATCH_UPDATED_METHOD = 'item/fileChange/patchUpdated';
86
+ const THREAD_STATUSES = new Set(['idle', 'active', 'systemError', 'notLoaded']);
87
+ /** @type {ReadonlyMap<string, import('./messages.mjs').ReplyOutcome>} */
88
+ const OUTCOME_BY_TURN_STATUS = new Map([
89
+ ['completed', 'completed'],
90
+ ['interrupted', 'interrupted'],
91
+ ['failed', 'failed'],
92
+ ]);
93
+ /** A rejection's JSON-RPC code becomes `rpc_<code without its sign>` (reply codes allow no `-`). */
94
+ const RPC_CODE_PREFIX = 'rpc_';
95
+ const AUDIT_KINDS = Object.freeze({
96
+ command: 'command',
97
+ fileChange: 'file_change',
98
+ permissions: 'permissions',
99
+ unknown: 'unknown',
100
+ });
101
+ const UNKNOWN = 'unknown';
102
+ const RESERVE_OPAQUE = 'opaque';
103
+ const RESERVE_FILES = 'files';
104
+ const RESERVE_PERMISSIONS = 'permissions';
105
+ /** Codes the role writes itself: reply codes, decision reasons, audit reasons. */
106
+ const CODES = Object.freeze({
107
+ turnRejected: 'turn_rejected',
108
+ threadClosed: 'thread_closed',
109
+ turnEndUnobserved: 'turn_end_unobserved',
110
+ unknownStatus: 'unknown_status',
111
+ deliveryFailed: 'delivery_failed',
112
+ holdTimeout: 'hold_timeout',
113
+ delegationEnded: 'delegation_ended',
114
+ workerStopped: 'worker_stopped',
115
+ workerMoved: 'worker_moved',
116
+ answerFailed: 'answer_failed',
117
+ patchChanged: 'patch_changed',
118
+ resolved: 'resolved',
119
+ turnEnded: 'turn_ended',
120
+ unknownApproval: 'unknown_approval',
121
+ tooLate: 'too_late',
122
+ notDelegated: 'not_delegated',
123
+ queueFull: 'queue_full',
124
+ workerClosed: 'worker_closed',
125
+ name: 'name',
126
+ kind: 'kind',
127
+ });
128
+ /** A rejected `turn/start` is retried once (FR4 step 5). */
129
+ const DELIVERY_ATTEMPTS = 2;
130
+ const DELIVERY_RETRY_DELAY_MS = 2_000;
131
+ const LINE_BOUNDARY_RETRY_MS = 50;
132
+ /**
133
+ * The app-server reports a thread idle right before the turn's `turn/completed`
134
+ * (measured on 0.166.0). A turn whose thread went idle, failed or closed and
135
+ * that still has no `turn/completed` after this long ended unobserved (FR4
136
+ * step 5): the reply is `failed` rather than never written.
137
+ */
138
+ const TURN_END_GRACE_MS = 30_000;
139
+ /**
140
+ * A role `turn/start` with neither a response nor a frame of its turn after
141
+ * this long gets the reply `failed` `turn_end_unobserved`: a claimed request
142
+ * never stays without a reply. The adapter refuses another role `turn/start`
143
+ * while that one is unanswered, so the next delivery cannot merge into it.
144
+ */
145
+ const TURN_START_RESPONSE_WAIT_MS = 120_000;
146
+ /**
147
+ * The app-server answers a `turn/start` before it reports the thread active
148
+ * (spike: wire order). After the terminal's work request is answered, the gate
149
+ * stays closed until the thread's next status, or this long when none comes
150
+ * (a request that started nothing).
151
+ */
152
+ const CLIENT_WORK_SETTLE_MS = 1_000;
153
+ const REPLY_WRITE_ATTEMPTS = 2;
154
+ const HOUR_MS = 60 * 60_000;
155
+ const TIMER_DELAY_MAX_MS = 2_147_483_647;
156
+ const WIRE_ID_MAX = 256;
157
+ const PATH_LENGTH_MAX = 4096;
158
+ /** How many missing levels a new file's path may have below its deepest existing ancestor. */
159
+ const MISSING_LEVELS_MAX = 64;
160
+ /** `buildApprovalRequest` keeps this many paths: a longer list would reach the manager cut. */
161
+ const APPROVAL_PATHS_MAX = 200;
162
+ const REPORTED_VALUE_PATTERN = /^[A-Za-z0-9_.:-]{1,64}$/u;
163
+ const ERROR_KIND_PATTERN = /^[A-Za-z0-9_]{1,64}$/u;
164
+ const TRACKED_THREADS_MAX = 256;
165
+ const TRACKED_TURNS_MAX = 128;
166
+ const TRACKED_FILE_CHANGES_MAX = 256;
167
+ const TRACKED_CLIENT_REQUESTS_MAX = 256;
168
+ const OPEN_APPROVALS_MAX = 64;
169
+ /** The session record lists at most this many held ids (`isSessionRecord`). */
170
+ const HELD_APPROVALS_MAX = 32;
171
+ /**
172
+ * The adapter keeps at most this many lines for the role
173
+ * (`MAX_WORKER_HELD_REQUESTS` in `scripts/codex-context-compaction.mjs`) and
174
+ * forwards any line past it itself: the role mirrors that map so it never
175
+ * decides a request the terminal already shows.
176
+ */
177
+ const ADAPTER_HELD_MAX = 32;
178
+ const ENDED_APPROVALS_MAX = 64;
179
+ const REJECTED_NAMES_MAX = 256;
180
+ /** Bus read failures (`ReadFailure` in `bus.mjs`) that say nothing about the file's content. */
181
+ const MISSING_FILE = 'missing';
182
+ const READ_ERROR = 'io_error';
183
+ /** The manager queues at most 8 per worker; this bounds what a forger can make the role index. */
184
+ const QUEUE_INDEX_MAX = 64;
185
+
186
+ /** @typedef {import('./bus.mjs').RoleEnvironment} RoleEnvironment */
187
+ /** @typedef {import('./bus.mjs').SessionRecord} SessionRecord */
188
+ /** @typedef {import('./bus.mjs').SessionState} SessionState */
189
+ /** @typedef {import('./bus.mjs').SessionApproval} SessionApproval */
190
+ /** @typedef {import('./bus.mjs').AuditEvent} AuditEvent */
191
+ /** @typedef {import('./messages.mjs').RequestMessage} RequestMessage */
192
+ /** @typedef {import('./messages.mjs').ApprovalDecisionMessage} ApprovalDecisionMessage */
193
+ /** @typedef {import('./messages.mjs').ApprovalSubject} ApprovalSubject */
194
+ /** @typedef {import('./messages.mjs').ReplyOutcome} ReplyOutcome */
195
+ /** @typedef {import('./delegation.mjs').Grant} Grant */
196
+ /** @typedef {import('./delegation.mjs').DecisionOutcome} DecisionOutcome */
197
+ /** @typedef {import('./watch.mjs').DirectoryWatch} DirectoryWatch */
198
+
199
+ /**
200
+ * What the adapter provides.
201
+ * @typedef {object} AdapterPort
202
+ * @property {(method: string, params: unknown) => Promise<unknown>} request
203
+ * An adapter-owned request to the app-server; its response never reaches the terminal. Resolves with `result`; rejects (an Error, possibly with a numeric `rpcCode`) when the app-server answers an error or the adapter cannot write.
204
+ * @property {(requestId: string | number, result: unknown) => unknown} respond
205
+ * Answer a server request the terminal never saw (a held approval request). Returns `true` when the answer was written or waits only for the terminal's frame to end; anything else means it refused, and the role sends the request to the terminal.
206
+ * @property {(line: string) => void} forward
207
+ * Show the terminal a server line the role was holding, unchanged (the exact text it was given, with its newline).
208
+ * @property {(threadId: string) => boolean} threadBusy
209
+ * True while one of the adapter's own lifecycles (compaction, recovery notes, a pending resume) runs or is about to run on that thread.
210
+ * @property {() => boolean} clientAtLineBoundary
211
+ * False while a terminal frame is only partly written to the app-server; the role must not write then.
212
+ */
213
+ /**
214
+ * @typedef {object} WorkerRole
215
+ * @property {() => Promise<void>} start arm the role; it touches nothing on the bus. The role stays dormant, observing frames only, until this adapter sees the terminal start, resume or fork a thread that is not ephemeral; then it writes its pid as the record's `childPid` and owns the session (FR2). Never rejects
216
+ * @property {(message: unknown) => void} onClientMessage every parsed terminal -> app-server frame, before the adapter writes it (observation only; never calls the port synchronously; never throws)
217
+ * @property {(message: unknown, line: string, options?: { canHold?: boolean }) => boolean} onServerMessage every parsed app-server -> terminal frame the adapter is about to forward. False: the role holds `line` and later forwards it through `port.forward` or answers it through `port.respond`. With `canHold` false the adapter forwards the line whatever the role returns, and the role treats the request as the user's; a missing third argument means `canHold: true`. Only command and file change approvals are ever held. Synchronous; never throws
218
+ * @property {(threadId: string) => void} onAdapterIdle the adapter's own lifecycle on that thread ended: try a delivery again
219
+ * @property {() => Promise<void>} stop forward anything held and stop timers and watches. The owner also writes `worker_closed` for every queued or running request and removes the record and mailboxes; a role that never owned the session or lost it removes nothing (only its own running turn, if any, is answered). Idempotent
220
+ * @property {() => Promise<void>} settled resolves once no internal task is pending (tests and diagnostics)
221
+ */
222
+ /** @typedef {{ reserved: true, class: string } | { reserved: false }} ReserveVerdict */
223
+ /** @typedef {{ kind: 'command' | 'fileChange' | 'permissions' | 'unknown', command: string | null, cwd: string | null }} ApprovalDescription */
224
+ /**
225
+ * @typedef {(request: { method: string, params: unknown, filePaths: string[] | null }, context: { roots: string[], stateRoot: string, home: string, hostConfigDirs: string[] }) => ReserveVerdict | Promise<ReserveVerdict>} ClassifyApproval
226
+ */
227
+ /** @typedef {(request: { method: string, params: unknown }) => ApprovalDescription | Promise<ApprovalDescription>} DescribeApproval */
228
+ /** @typedef {(callback: () => void, ms: number) => () => void} Schedule */
229
+ /**
230
+ * @typedef {object} WorkerRoleOptions
231
+ * @property {RoleEnvironment} role
232
+ * @property {AdapterPort} port
233
+ * @property {string} cwd
234
+ * @property {string} [home]
235
+ * @property {string[]} [hostConfigDirs]
236
+ * @property {{ now?: () => number, alive?: (pid: number) => boolean, delay?: (ms: number) => Promise<void> }} [clock]
237
+ * @property {Schedule} [schedule]
238
+ * @property {DirectoryWatch} [watch]
239
+ * @property {ClassifyApproval} [classify]
240
+ * @property {DescribeApproval} [describe]
241
+ * @property {(cwd: string) => Promise<string[]>} [roots]
242
+ * @property {number} [pid] this adapter's process id, written as the record's `childPid` (default `process.pid`)
243
+ * @property {RealPath} [realPath] the real path of one absolute path, or null (default: node's fs)
244
+ */
245
+ /** @typedef {(path: string) => Promise<string | null>} RealPath */
246
+ /**
247
+ * @typedef {Pick<SessionRecord, 'childPid' | 'childStartTime' | 'state' | 'stateSince' | 'turnOrigin' | 'queued' | 'sandbox' | 'approvalPolicy' | 'approval' | 'heldApprovals'>} RecordFields
248
+ */
249
+
250
+ /**
251
+ * @typedef {object} ThreadView
252
+ * @property {string} status the type of the last status the app-server reported, `unknown` before one
253
+ * @property {number} statusSeq when that status arrived, in the tracker's sequence
254
+ * @property {boolean} ephemeral
255
+ * @property {string} sandbox
256
+ * @property {string} approvalPolicy
257
+ * @property {number} clientWork the terminal's requests that start work on the thread (`WORK_METHODS`) not answered yet
258
+ */
259
+ /** @typedef {{ status: string, error: unknown, items: unknown }} TurnEnd */
260
+ /**
261
+ * @typedef {object} TurnView
262
+ * @property {Map<string, string | null>} userMessages item id -> the `clientId` it echoed
263
+ * @property {string | null} lastAgentText the last `agentMessage` item completed in the turn
264
+ * @property {string | null} errorKind from an `error` notification that will not be retried
265
+ * @property {TurnEnd | null} end
266
+ */
267
+ /** @typedef {{ paths: string[] | null, bytes: number, turnId: string | null }} FileChangeSummary */
268
+ /**
269
+ * @typedef {object} ClientRequest
270
+ * @property {string} method
271
+ * @property {string | null} threadId
272
+ * @property {boolean} ephemeral
273
+ * @property {number} seq the tracker's sequence when the request was seen
274
+ * @property {unknown} approvalPolicy
275
+ * @property {unknown} sandboxPolicy
276
+ */
277
+ /**
278
+ * @typedef {{ type: 'thread_opened', threadId: string, ephemeral: boolean }
279
+ * | { type: 'status', threadId: string, status: string }
280
+ * | { type: 'user_message', threadId: string, turnId: string, clientId: string | null }
281
+ * | { type: 'turn_completed', threadId: string, turnId: string }
282
+ * | { type: 'client_turn', threadId: string }
283
+ * | { type: 'client_settled', threadId: string, accepted: boolean }
284
+ * | { type: 'client_answer', key: string }
285
+ * | { type: 'resolved', key: string }
286
+ * | { type: 'patch_updated', itemId: string }
287
+ * | { type: 'thread_closed', threadId: string }} WireEvent
288
+ */
289
+ /**
290
+ * @typedef {object} OpenApproval
291
+ * @property {string} key
292
+ * @property {string | number} requestId
293
+ * @property {string} method
294
+ * @property {'command' | 'fileChange' | 'permissions' | 'unknown'} kind
295
+ * @property {string | null} threadId
296
+ * @property {string | null} turnId
297
+ * @property {string | null} itemId
298
+ * @property {Record<string, unknown>} params
299
+ * @property {string} line
300
+ * @property {'deciding' | 'held' | 'answering' | 'user' | 'closed'} phase
301
+ * @property {number} since
302
+ * @property {string[] | null} filePaths
303
+ * @property {number | null} changeBytes
304
+ * @property {string | null} approvalId
305
+ * @property {string | null} grantId
306
+ * @property {number} holdUntil
307
+ * @property {string} text what the decision record keeps: the command, or the paths one per line
308
+ * @property {(() => void) | null} cancelTimer
309
+ * @property {'approve' | 'deny' | null} verdict
310
+ * @property {string | null} decisionReason
311
+ */
312
+ /** @typedef {{ name: string, message: RequestMessage }} QueuedEntry */
313
+ /** @typedef {QueuedEntry & { attempts: number, notBefore: number }} Claimed a request in `claimed/` whose turn has not started */
314
+ /**
315
+ * @typedef {Claimed & {
316
+ * clientId: string, threadId: string, turnId: string | null, shared: boolean,
317
+ * responded: boolean, sawActive: boolean, ended: boolean, done: boolean,
318
+ * cancelGrace: (() => void) | null, cancelResponseWait: (() => void) | null,
319
+ * }} Delivery `ended`: the thread reported the end of a turn after this one started
320
+ */
321
+ /** @typedef {{ outcome: ReplyOutcome, code: string | null, shared: boolean, text: string }} ReplyContent */
322
+ /**
323
+ * @typedef {object} OutcomeNote
324
+ * @property {DecisionOutcome} outcome
325
+ * @property {string | null} reason the decision record's reason: the manager's text or the role's code
326
+ * @property {string | null} [code] the audit's reason: a code of the role, never text
327
+ * @property {string | null} [reserveClass]
328
+ */
329
+
330
+ /** @param {unknown} value @returns {value is Record<string, unknown>} */
331
+ function isObject(value) {
332
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
333
+ }
334
+
335
+ /** @param {unknown} value @returns {string | null} */
336
+ function wireId(value) {
337
+ return typeof value === 'string' && value.length > 0 && value.length <= WIRE_ID_MAX
338
+ ? value
339
+ : null;
340
+ }
341
+
342
+ /**
343
+ * A JSON-RPC id as a map key; the two id types never collide.
344
+ * @param {unknown} id
345
+ * @returns {string | null}
346
+ */
347
+ function requestKey(id) {
348
+ if (typeof id === 'string' && id.length > 0 && id.length <= WIRE_ID_MAX) return `s:${id}`;
349
+ if (typeof id === 'number' && Number.isSafeInteger(id)) return `n:${String(id)}`;
350
+ return null;
351
+ }
352
+
353
+ /** @param {unknown} value @returns {value is string} */
354
+ function isAbsolutePath(value) {
355
+ return (
356
+ typeof value === 'string' &&
357
+ value.length > 0 &&
358
+ value.length <= PATH_LENGTH_MAX &&
359
+ isAbsolute(value)
360
+ );
361
+ }
362
+
363
+ /**
364
+ * `thread/status/changed` carries `status: { type, activeFlags? }`. A type the
365
+ * role does not know is `unknown`, which is never idle.
366
+ * @param {unknown} status
367
+ * @returns {string | null}
368
+ */
369
+ function threadStatusOf(status) {
370
+ if (!isObject(status) || typeof status.type !== 'string') return null;
371
+ return THREAD_STATUSES.has(status.type) ? status.type : UNKNOWN;
372
+ }
373
+
374
+ /**
375
+ * The response to `thread/start` reports `sandbox` as `{ type, ... }` (0.166.0
376
+ * protocol schema); a plain string is taken as it is.
377
+ * @param {unknown} value
378
+ */
379
+ function reportedSandbox(value) {
380
+ const name = isObject(value) ? value.type : null;
381
+ return typeof name === 'string' && REPORTED_VALUE_PATTERN.test(name) ? name : UNKNOWN;
382
+ }
383
+
384
+ /** The policy as the app-server names it; any other shape is `unknown`. @param {unknown} value */
385
+ function reportedApprovalPolicy(value) {
386
+ return typeof value === 'string' && REPORTED_VALUE_PATTERN.test(value) ? value : UNKNOWN;
387
+ }
388
+
389
+ /**
390
+ * The app-server's error kind: `error.codexErrorInfo`, a name or an object with
391
+ * one key (0.166.0 protocol schema). Null when there is none.
392
+ * @param {unknown} error
393
+ * @returns {string | null}
394
+ */
395
+ function errorKindOf(error) {
396
+ if (!isObject(error)) return null;
397
+ const info = error.codexErrorInfo;
398
+ if (typeof info === 'string') return ERROR_KIND_PATTERN.test(info) ? info : null;
399
+ if (!isObject(info)) return null;
400
+ const keys = Object.keys(info);
401
+ const [only] = keys;
402
+ return keys.length === 1 && only !== undefined && ERROR_KIND_PATTERN.test(only) ? only : null;
403
+ }
404
+
405
+ /**
406
+ * The last assistant message of `turn.items` (spike S4: a completed turn
407
+ * carries the last `agentMessage` only).
408
+ * @param {unknown} items
409
+ * @returns {string | null}
410
+ */
411
+ function lastAgentText(items) {
412
+ if (!Array.isArray(items)) return null;
413
+ for (let index = items.length - 1; index >= 0; index -= 1) {
414
+ const item = /** @type {unknown} */ (items[index]);
415
+ if (isObject(item) && item.type === 'agentMessage' && typeof item.text === 'string')
416
+ return item.text;
417
+ }
418
+ return null;
419
+ }
420
+
421
+ /**
422
+ * The absolute paths a `fileChange` item touches and the size of its diffs.
423
+ * Any path that is not absolute makes the whole list unknown (fail closed).
424
+ * @param {unknown} changes
425
+ * @param {string | null} turnId
426
+ * @returns {FileChangeSummary}
427
+ */
428
+ function summarizeChanges(changes, turnId) {
429
+ if (!Array.isArray(changes)) return { paths: null, bytes: 0, turnId };
430
+ /** @type {string[]} */
431
+ const paths = [];
432
+ let bytes = 0;
433
+ for (const change of /** @type {unknown[]} */ (changes)) {
434
+ if (!isObject(change) || !isAbsolutePath(change.path)) return { paths: null, bytes: 0, turnId };
435
+ paths.push(change.path);
436
+ if (typeof change.diff === 'string') bytes += Buffer.byteLength(change.diff, 'utf8');
437
+ const movePath = isObject(change.kind) ? change.kind.move_path : null;
438
+ if (movePath === null || movePath === undefined) continue;
439
+ if (!isAbsolutePath(movePath)) return { paths: null, bytes: 0, turnId };
440
+ paths.push(movePath);
441
+ }
442
+ return { paths, bytes, turnId };
443
+ }
444
+
445
+ /**
446
+ * @param {string} method
447
+ * @returns {OpenApproval['kind'] | null} null when the request is not an approval request
448
+ */
449
+ function approvalKindOf(method) {
450
+ const known = APPROVAL_KINDS_BY_METHOD.get(method);
451
+ if (known !== undefined) return known;
452
+ return method.endsWith(APPROVAL_METHOD_SUFFIX) ? 'unknown' : null;
453
+ }
454
+
455
+ /** @param {OpenApproval['kind']} kind @returns {SessionApproval['kind']} */
456
+ function sessionKindOf(kind) {
457
+ return kind === 'unknown' ? 'permissions' : kind;
458
+ }
459
+
460
+ /** @param {unknown} error */
461
+ function rejectionCodeOf(error) {
462
+ const rpcCode = isObject(error) ? error.rpcCode : undefined;
463
+ if (typeof rpcCode !== 'number' || !Number.isSafeInteger(rpcCode)) return CODES.turnRejected;
464
+ return `${RPC_CODE_PREFIX}${Math.abs(rpcCode)}`;
465
+ }
466
+
467
+ /** @param {number} milliseconds */
468
+ function boundedDelay(milliseconds) {
469
+ return Math.min(Math.max(0, milliseconds), TIMER_DELAY_MAX_MS);
470
+ }
471
+
472
+ /** @type {Schedule} */
473
+ function defaultSchedule(callback, milliseconds) {
474
+ const timer = setTimeout(callback, boundedDelay(milliseconds));
475
+ timer.unref();
476
+ return () => clearTimeout(timer);
477
+ }
478
+
479
+ /**
480
+ * A cancel function that never throws.
481
+ * @param {unknown} cancel
482
+ * @returns {() => void}
483
+ */
484
+ function containedCancel(cancel) {
485
+ return () => {
486
+ try {
487
+ if (typeof cancel === 'function') cancel();
488
+ } catch {
489
+ // Contained: a throw here would reach the adapter.
490
+ }
491
+ };
492
+ }
493
+
494
+ /**
495
+ * A schedule whose callbacks and cancels never throw: a throw in a timer
496
+ * reaches the event loop and ends the adapter, and the Codex session with it.
497
+ * @param {Schedule} schedule
498
+ * @returns {Schedule}
499
+ */
500
+ function containedSchedule(schedule) {
501
+ return (callback, milliseconds) => {
502
+ const contained = () => {
503
+ try {
504
+ callback();
505
+ } catch {
506
+ // Contained: the next frame, watch event or timer acts again.
507
+ }
508
+ };
509
+ try {
510
+ return containedCancel(schedule(contained, milliseconds));
511
+ } catch {
512
+ return () => undefined;
513
+ }
514
+ };
515
+ }
516
+
517
+ /**
518
+ * Add to a set kept within a size by dropping its oldest values.
519
+ * @param {Set<string>} set
520
+ * @param {string} value
521
+ * @param {number} max
522
+ */
523
+ function addBounded(set, value, max) {
524
+ set.add(value);
525
+ for (const oldest of set) {
526
+ if (set.size <= max) return;
527
+ set.delete(oldest);
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Keep a map within a size by dropping its oldest entries.
533
+ * @template K, V
534
+ * @param {Map<K, V>} map
535
+ * @param {number} max
536
+ * @param {(value: V) => void} [onEvict]
537
+ */
538
+ function trimOldest(map, max, onEvict) {
539
+ while (map.size > max) {
540
+ const first = map.entries().next();
541
+ if (first.done) return;
542
+ map.delete(first.value[0]);
543
+ onEvict?.(first.value[1]);
544
+ }
545
+ }
546
+
547
+ /** @param {unknown} error */
548
+ function isMissing(error) {
549
+ return isObject(error) && error.code === 'ENOENT';
550
+ }
551
+
552
+ /**
553
+ * Where a file change really writes (FR13, class `files`): the real path of
554
+ * the file, or for a new file the real path of its deepest existing ancestor
555
+ * with the missing names after it. Null when it cannot be resolved: a path
556
+ * that is not normalized, a dangling link, or any other error.
557
+ * @param {string} path an absolute path
558
+ * @returns {Promise<string | null>}
559
+ */
560
+ async function realTarget(path) {
561
+ if (normalize(path) !== path) return null;
562
+ /** @type {string[]} */
563
+ const missing = [];
564
+ let current = path;
565
+ while (missing.length <= MISSING_LEVELS_MAX) {
566
+ try {
567
+ return join(await realpath(current), ...missing);
568
+ } catch (error) {
569
+ if (!isMissing(error)) return null;
570
+ }
571
+ // Present but not resolvable: a link whose target is gone.
572
+ if (
573
+ await lstat(current).then(
574
+ () => true,
575
+ () => false,
576
+ )
577
+ )
578
+ return null;
579
+ const parent = dirname(current);
580
+ if (parent === current) return null;
581
+ missing.unshift(basename(current));
582
+ current = parent;
583
+ }
584
+ return null;
585
+ }
586
+
587
+ /**
588
+ * @param {string[] | null} paths
589
+ * @param {RealPath} resolvePath
590
+ * @returns {Promise<string[] | null>} null unless every path resolves to an absolute path
591
+ */
592
+ async function realTargets(paths, resolvePath) {
593
+ if (paths === null || paths.length === 0 || paths.length > APPROVAL_PATHS_MAX) return null;
594
+ /** @type {string[]} */
595
+ const resolved = [];
596
+ for (const path of paths) {
597
+ let real;
598
+ try {
599
+ real = await resolvePath(path);
600
+ } catch {
601
+ return null;
602
+ }
603
+ if (!isAbsolutePath(real)) return null;
604
+ resolved.push(real);
605
+ }
606
+ return resolved;
607
+ }
608
+
609
+ /**
610
+ * The configuration directories of the hosts: a command that names one is
611
+ * reserved (FR13, class `privilege`).
612
+ * @param {string} home
613
+ * @param {string | undefined} [codexHome]
614
+ */
615
+ function defaultHostConfigDirs(home, codexHome) {
616
+ const directories = [join(home, '.codex'), join(home, '.claude')];
617
+ if (
618
+ typeof codexHome === 'string' &&
619
+ isAbsolute(codexHome) &&
620
+ normalize(codexHome) === codexHome &&
621
+ !directories.includes(codexHome)
622
+ )
623
+ directories.push(codexHome);
624
+ return directories;
625
+ }
626
+
627
+ /**
628
+ * What the role reads from the frames: threads, turns, items and the
629
+ * terminal's own requests. It decides nothing; it reports what changed.
630
+ */
631
+ function createWireTracker() {
632
+ /** @type {Map<string, ThreadView>} */
633
+ const threads = new Map();
634
+ /** @type {Map<string, TurnView>} */
635
+ const turns = new Map();
636
+ /** @type {Map<string, FileChangeSummary>} */
637
+ const fileChanges = new Map();
638
+ /** @type {Map<string, ClientRequest>} */
639
+ const clientRequests = new Map();
640
+ let sequence = 0;
641
+
642
+ /** @param {string} threadId */
643
+ function threadView(threadId) {
644
+ const existing = threads.get(threadId);
645
+ if (existing !== undefined) {
646
+ // Most recently used last, so that trimming drops threads nobody uses.
647
+ threads.delete(threadId);
648
+ threads.set(threadId, existing);
649
+ return existing;
650
+ }
651
+ /** @type {ThreadView} */
652
+ const created = {
653
+ status: UNKNOWN,
654
+ statusSeq: 0,
655
+ ephemeral: false,
656
+ sandbox: UNKNOWN,
657
+ approvalPolicy: UNKNOWN,
658
+ clientWork: 0,
659
+ };
660
+ threads.set(threadId, created);
661
+ trimOldest(threads, TRACKED_THREADS_MAX);
662
+ return created;
663
+ }
664
+
665
+ /** @param {string} turnId */
666
+ function turnView(turnId) {
667
+ const existing = turns.get(turnId);
668
+ if (existing !== undefined) return existing;
669
+ /** @type {TurnView} */
670
+ const created = { userMessages: new Map(), lastAgentText: null, errorKind: null, end: null };
671
+ turns.set(turnId, created);
672
+ trimOldest(turns, TRACKED_TURNS_MAX);
673
+ return created;
674
+ }
675
+
676
+ /** @param {string} key @param {ClientRequest} request */
677
+ function rememberClientRequest(key, request) {
678
+ clientRequests.set(key, request);
679
+ trimOldest(clientRequests, TRACKED_CLIENT_REQUESTS_MAX, (evicted) => {
680
+ if (!WORK_METHODS.has(evicted.method) || evicted.threadId === null) return;
681
+ const view = threads.get(evicted.threadId);
682
+ if (view !== undefined) view.clientWork = Math.max(0, view.clientWork - 1);
683
+ });
684
+ }
685
+
686
+ /**
687
+ * One terminal -> app-server frame.
688
+ * @param {Record<string, unknown>} message
689
+ * @returns {WireEvent[]}
690
+ */
691
+ function client(message) {
692
+ const key = requestKey(message.id);
693
+ const method = typeof message.method === 'string' ? message.method : null;
694
+ if (method === null) return key === null ? [] : [{ type: 'client_answer', key }];
695
+ const params = isObject(message.params) ? message.params : {};
696
+ const threadId = wireId(params.threadId);
697
+ if (key !== null && THREAD_OPEN_METHODS.has(method))
698
+ rememberClientRequest(key, {
699
+ method,
700
+ threadId,
701
+ ephemeral: params.ephemeral === true,
702
+ seq: sequence,
703
+ approvalPolicy: null,
704
+ sandboxPolicy: null,
705
+ });
706
+ if (method === 'thread/unsubscribe' && threadId !== null && threads.get(threadId)?.ephemeral)
707
+ threads.delete(threadId);
708
+ if (threadId === null) return [];
709
+ if (key !== null && WORK_METHODS.has(method)) {
710
+ threadView(threadId).clientWork += 1;
711
+ rememberClientRequest(key, {
712
+ method,
713
+ threadId,
714
+ ephemeral: false,
715
+ seq: sequence,
716
+ approvalPolicy: params.approvalPolicy ?? null,
717
+ sandboxPolicy: params.sandboxPolicy ?? null,
718
+ });
719
+ }
720
+ return TURN_INPUT_METHODS.has(method) ? [{ type: 'client_turn', threadId }] : [];
721
+ }
722
+
723
+ /**
724
+ * The app-server's answer to a terminal request the tracker remembers.
725
+ * @param {string} key
726
+ * @param {Record<string, unknown>} message
727
+ * @returns {WireEvent[]}
728
+ */
729
+ function settleClientRequest(key, message) {
730
+ const request = clientRequests.get(key);
731
+ if (request === undefined) return [];
732
+ clientRequests.delete(key);
733
+ const result = !('error' in message) && isObject(message.result) ? message.result : null;
734
+ if (THREAD_OPEN_METHODS.has(request.method)) return openThread(request, result);
735
+ if (!WORK_METHODS.has(request.method) || request.threadId === null) return [];
736
+ const view = threadView(request.threadId);
737
+ view.clientWork = Math.max(0, view.clientWork - 1);
738
+ if (result !== null && request.method === 'turn/start') {
739
+ // The terminal's own turn sends its policy again (spike "Which thread").
740
+ if (request.approvalPolicy !== null)
741
+ view.approvalPolicy = reportedApprovalPolicy(request.approvalPolicy);
742
+ if (request.sandboxPolicy !== null) view.sandbox = reportedSandbox(request.sandboxPolicy);
743
+ }
744
+ return [{ type: 'client_settled', threadId: request.threadId, accepted: result !== null }];
745
+ }
746
+
747
+ /**
748
+ * @param {ClientRequest} request
749
+ * @param {Record<string, unknown> | null} result
750
+ * @returns {WireEvent[]}
751
+ */
752
+ function openThread(request, result) {
753
+ const thread = result !== null && isObject(result.thread) ? result.thread : null;
754
+ const threadId = thread === null ? null : wireId(thread.id);
755
+ if (result === null || thread === null || threadId === null) return [];
756
+ const view = threadView(threadId);
757
+ view.ephemeral = view.ephemeral || request.ephemeral || thread.ephemeral === true;
758
+ view.sandbox = reportedSandbox(result.sandbox);
759
+ view.approvalPolicy = reportedApprovalPolicy(result.approvalPolicy);
760
+ // The thread's status in the response is used only when no
761
+ // `thread/status/changed` for it arrived after the request.
762
+ const seeded = threadStatusOf(thread.status);
763
+ if (seeded !== null && view.statusSeq <= request.seq) view.status = seeded;
764
+ return [{ type: 'thread_opened', threadId, ephemeral: view.ephemeral }];
765
+ }
766
+
767
+ /**
768
+ * @param {string} method
769
+ * @param {Record<string, unknown>} params
770
+ * @returns {WireEvent[]}
771
+ */
772
+ function item(method, params) {
773
+ const entry = isObject(params.item) ? params.item : null;
774
+ const threadId = wireId(params.threadId);
775
+ const turnId = wireId(params.turnId);
776
+ const itemId = entry === null ? null : wireId(entry.id);
777
+ if (entry === null || itemId === null) return [];
778
+ if (entry.type === 'fileChange') {
779
+ // Its approval request comes after `item/started` and before `item/completed`.
780
+ if (method === 'item/completed') fileChanges.delete(itemId);
781
+ else {
782
+ fileChanges.set(itemId, summarizeChanges(entry.changes, turnId));
783
+ trimOldest(fileChanges, TRACKED_FILE_CHANGES_MAX);
784
+ }
785
+ return [];
786
+ }
787
+ if (threadId === null || turnId === null) return [];
788
+ const view = turnView(turnId);
789
+ if (entry.type === 'agentMessage' && method === 'item/completed') {
790
+ if (typeof entry.text === 'string') view.lastAgentText = entry.text;
791
+ return [];
792
+ }
793
+ if (entry.type !== 'userMessage' || view.userMessages.has(itemId)) return [];
794
+ const clientId = typeof entry.clientId === 'string' ? entry.clientId : null;
795
+ view.userMessages.set(itemId, clientId);
796
+ return [{ type: 'user_message', threadId, turnId, clientId }];
797
+ }
798
+
799
+ /**
800
+ * @param {string} method
801
+ * @param {Record<string, unknown>} params
802
+ * @returns {WireEvent[]}
803
+ */
804
+ function notification(method, params) {
805
+ const threadId = wireId(params.threadId);
806
+ if (method === 'thread/status/changed') {
807
+ const status = threadStatusOf(params.status);
808
+ if (threadId === null || status === null) return [];
809
+ const view = threadView(threadId);
810
+ sequence += 1;
811
+ view.status = status;
812
+ view.statusSeq = sequence;
813
+ return [{ type: 'status', threadId, status }];
814
+ }
815
+ if (ITEM_METHODS.has(method)) return item(method, params);
816
+ if (method === PATCH_UPDATED_METHOD) {
817
+ const itemId = wireId(params.itemId);
818
+ if (itemId === null) return [];
819
+ fileChanges.set(itemId, summarizeChanges(params.changes, wireId(params.turnId)));
820
+ trimOldest(fileChanges, TRACKED_FILE_CHANGES_MAX);
821
+ return [{ type: 'patch_updated', itemId }];
822
+ }
823
+ if (method === 'error') {
824
+ const turnId = wireId(params.turnId);
825
+ if (turnId !== null && params.willRetry !== true) {
826
+ const view = turnView(turnId);
827
+ view.errorKind = errorKindOf(params.error) ?? view.errorKind;
828
+ }
829
+ return [];
830
+ }
831
+ if (method === 'turn/completed') {
832
+ const turn = isObject(params.turn) ? params.turn : null;
833
+ const turnId = turn === null ? null : wireId(turn.id);
834
+ if (turn === null || turnId === null || threadId === null) return [];
835
+ for (const [itemId, change] of fileChanges)
836
+ if (change.turnId === turnId) fileChanges.delete(itemId);
837
+ turnView(turnId).end = {
838
+ status: typeof turn.status === 'string' ? turn.status : UNKNOWN,
839
+ error: turn.error ?? null,
840
+ items: turn.items,
841
+ };
842
+ return [{ type: 'turn_completed', threadId, turnId }];
843
+ }
844
+ if (method === 'serverRequest/resolved') {
845
+ const key = requestKey(params.requestId);
846
+ return key === null ? [] : [{ type: 'resolved', key }];
847
+ }
848
+ if (THREAD_GONE_METHODS.has(method) && threadId !== null) {
849
+ const view = threadView(threadId);
850
+ sequence += 1;
851
+ view.status = 'notLoaded';
852
+ view.statusSeq = sequence;
853
+ return [{ type: 'thread_closed', threadId }];
854
+ }
855
+ return [];
856
+ }
857
+
858
+ /**
859
+ * One app-server -> terminal frame.
860
+ * @param {Record<string, unknown>} message
861
+ * @returns {WireEvent[]}
862
+ */
863
+ function server(message) {
864
+ const method = typeof message.method === 'string' ? message.method : null;
865
+ const key = requestKey(message.id);
866
+ if (method === null) return key === null ? [] : settleClientRequest(key, message);
867
+ // A server request (approval, user input, ...) is the role's business, not the tracker's.
868
+ if (message.id !== undefined) return [];
869
+ return isObject(message.params) ? notification(method, message.params) : [];
870
+ }
871
+
872
+ return {
873
+ client,
874
+ server,
875
+ /** @param {string} threadId */
876
+ thread: (threadId) => threads.get(threadId),
877
+ /** @param {string} turnId */
878
+ turn: (turnId) => turns.get(turnId),
879
+ /** @param {string} itemId */
880
+ fileChange: (itemId) => fileChanges.get(itemId),
881
+ };
882
+ }
883
+
884
+ /**
885
+ * The worker role (FR4, FR13). One closure owns the state; every handler the
886
+ * adapter calls is synchronous and never throws, and every effect on files
887
+ * runs as a tracked task.
888
+ * @param {WorkerRoleOptions} options
889
+ * @returns {WorkerRole}
890
+ */
891
+ export function createWorkerRole(options) {
892
+ const { role, port, cwd } = options;
893
+ const home = options.home ?? homedir();
894
+ const hostConfigDirs = options.hostConfigDirs ?? defaultHostConfigDirs(home);
895
+ const now = options.clock?.now ?? (() => Date.now());
896
+ const busClock =
897
+ options.clock?.alive === undefined ? { now } : { now, alive: options.clock.alive };
898
+ const schedule = containedSchedule(options.schedule ?? defaultSchedule);
899
+ const watch = options.watch ?? createDirectoryWatch();
900
+ const classify = options.classify ?? classifyApproval;
901
+ const describe = options.describe ?? describeApproval;
902
+ const roots = options.roots ?? ((directory) => repositoryRoots(directory));
903
+ const pid = options.pid ?? process.pid;
904
+ const resolvePath = options.realPath ?? realTarget;
905
+ const lockClock =
906
+ options.clock?.delay === undefined ? busClock : { ...busClock, delay: options.clock.delay };
907
+ const paths = roomPaths(role.stateRoot, role.roomId);
908
+ const self = { sessionId: role.sessionId, name: role.name };
909
+ const inboxDirectory = mailboxDirectory(paths, 'inbox', self.sessionId);
910
+ const claimedDirectory = mailboxDirectory(paths, 'claimed', self.sessionId);
911
+ const tracker = createWireTracker();
912
+
913
+ /** `start()` was called: the role may activate. */
914
+ let armed = false;
915
+ let stopped = false;
916
+ /**
917
+ * Who owns the session (FR2): `dormant` until this adapter sees the terminal
918
+ * open a thread, `active` once its pid is the record's `childPid`, `lost`
919
+ * when another adapter of the session took it over, `gone` when the record
920
+ * disappeared (never written again).
921
+ * @type {'dormant' | 'activating' | 'active' | 'lost' | 'gone'}
922
+ */
923
+ let owner = 'dormant';
924
+ /** The adapter's gate refused the last `turn/start`: wait for its next idle. */
925
+ let gateRefused = false;
926
+ /** @type {string | null} */
927
+ let currentThreadId = null;
928
+ /** @type {Map<string, QueuedEntry>} */
929
+ const queued = new Map();
930
+ /** @type {Set<string>} names being claimed right now: a scan must not index them again */
931
+ const claiming = new Set();
932
+ /** @type {Claimed | null} */
933
+ let staged = null;
934
+ /** @type {Delivery | null} */
935
+ let running = null;
936
+ /** @type {Map<string, OpenApproval>} */
937
+ const approvals = new Map();
938
+ /**
939
+ * The lines the adapter keeps for the role, by request key, with their
940
+ * thread: added when the role takes a line, removed when the role forwards
941
+ * or answers it and when the adapter drops it itself (the request resolved,
942
+ * its thread closed). A request withdrawn by the end of its turn keeps its
943
+ * line until then, as in the adapter.
944
+ * @type {Map<string, string | null>}
945
+ */
946
+ const adapterHeld = new Map();
947
+ /** @type {Set<OpenApproval>} */
948
+ const waitingAnswers = new Set();
949
+ /** @type {Map<string, () => void>} threads where the terminal's accepted work may not be reported yet */
950
+ const settling = new Map();
951
+ /** @type {Set<string>} approval ids that ended: a decision for one is `too_late` */
952
+ const endedApprovals = new Set();
953
+ /** @type {Set<string>} inbox entries already rejected once */
954
+ const rejectedNames = new Set();
955
+ /** @type {number[]} */
956
+ const delegatedAt = [];
957
+ /** @type {Grant | null} */
958
+ let knownGrant = null;
959
+ /** @type {Record<'expiry' | 'grant' | 'retry' | 'answers' | 'boundary' | 'activate', (() => void) | null>} */
960
+ const timers = {
961
+ expiry: null,
962
+ grant: null,
963
+ retry: null,
964
+ answers: null,
965
+ boundary: null,
966
+ activate: null,
967
+ };
968
+ /** @type {(() => void) | null} */
969
+ let stopWatch = null;
970
+ /** @type {Set<Promise<void>>} */
971
+ const tasks = new Set();
972
+ /** @type {Promise<void> | null} */
973
+ let stopping = null;
974
+
975
+ // ---- tasks and port calls -------------------------------------------------
976
+
977
+ /** @param {Promise<unknown>} work */
978
+ function spawn(work) {
979
+ const task = work.then(
980
+ () => undefined,
981
+ () => undefined,
982
+ );
983
+ tasks.add(task);
984
+ void task.then(() => tasks.delete(task));
985
+ }
986
+
987
+ async function drainTasks() {
988
+ while (tasks.size > 0) await Promise.allSettled([...tasks]);
989
+ }
990
+
991
+ async function settled() {
992
+ for (;;) {
993
+ await new Promise((resolve) => setImmediate(resolve));
994
+ if (tasks.size === 0) return;
995
+ await drainTasks();
996
+ }
997
+ }
998
+
999
+ function atLineBoundary() {
1000
+ try {
1001
+ return port.clientAtLineBoundary() === true;
1002
+ } catch {
1003
+ return false;
1004
+ }
1005
+ }
1006
+
1007
+ /** @param {string} threadId */
1008
+ function adapterBusy(threadId) {
1009
+ try {
1010
+ return port.threadBusy(threadId) !== false;
1011
+ } catch {
1012
+ return true;
1013
+ }
1014
+ }
1015
+
1016
+ /**
1017
+ * The adapter sends the request's exact line to the terminal.
1018
+ * @param {OpenApproval} entry
1019
+ */
1020
+ function forwardEntry(entry) {
1021
+ adapterHeld.delete(entry.key);
1022
+ try {
1023
+ port.forward(entry.line);
1024
+ } catch {
1025
+ // Nothing else can show the request; the user still sees the turn wait.
1026
+ }
1027
+ }
1028
+
1029
+ // ---- ownership of the session (FR2) ---------------------------------------
1030
+
1031
+ function isActive() {
1032
+ return owner === 'active' && !stopped;
1033
+ }
1034
+
1035
+ /** @param {SessionRecord | null} record @returns {'owner' | 'lost' | 'gone'} */
1036
+ function ownershipOf(record) {
1037
+ if (record === null || record.role !== 'worker' || record.name !== self.name) return 'gone';
1038
+ return record.childPid === pid ? 'owner' : 'lost';
1039
+ }
1040
+
1041
+ /**
1042
+ * Run one bus write only while this adapter owns the session, under the
1043
+ * room's lock so that no takeover lands between the check and the write.
1044
+ * A record that names another adapter, or no record, deactivates the role.
1045
+ * @template T
1046
+ * @param {(record: SessionRecord) => Promise<T>} task
1047
+ * @returns {Promise<{ ok: true, value: T } | { ok: false }>}
1048
+ */
1049
+ async function asOwner(task) {
1050
+ if (!isActive()) return { ok: false };
1051
+ /** @type {{ verdict: 'owner' | 'lost' | 'gone', outcome: { ok: true, value: T } | { ok: false } }} */
1052
+ let result;
1053
+ try {
1054
+ result = await withRoomLock(
1055
+ paths,
1056
+ async () => {
1057
+ const record = await readSession(paths, self.sessionId);
1058
+ const verdict = ownershipOf(record);
1059
+ if (verdict !== 'owner' || record === null || !isActive())
1060
+ return { verdict, outcome: { ok: false } };
1061
+ return { verdict, outcome: { ok: true, value: await task(record) } };
1062
+ },
1063
+ lockClock,
1064
+ );
1065
+ } catch {
1066
+ // The lock or the write failed: nothing changed, the caller tries again later.
1067
+ return { ok: false };
1068
+ }
1069
+ if (result.verdict !== 'owner') deactivate(result.verdict);
1070
+ return result.outcome;
1071
+ }
1072
+
1073
+ /** The role may append audit and decision lines: it owns the session, stopping or not. */
1074
+ function ownsSession() {
1075
+ return owner === 'active';
1076
+ }
1077
+
1078
+ /**
1079
+ * Another adapter of this session owns it now, or its record is gone (FR2):
1080
+ * take no more work, give the terminal everything held and write nothing
1081
+ * more but the outcome of each hold it made. A turn of the role that is
1082
+ * running here still gets its reply when it ends; a request claimed and not
1083
+ * started goes back to the inbox.
1084
+ * @param {'lost' | 'gone'} verdict
1085
+ */
1086
+ function deactivate(verdict) {
1087
+ if (owner !== 'active') return;
1088
+ owner = verdict;
1089
+ stopWatch?.();
1090
+ stopWatch = null;
1091
+ for (const name of /** @type {const} */ (['expiry', 'grant', 'retry', 'answers', 'boundary'])) {
1092
+ timers[name]?.();
1093
+ timers[name] = null;
1094
+ }
1095
+ knownGrant = null;
1096
+ queued.clear();
1097
+ gateRefused = false;
1098
+ nextFields = null;
1099
+ lastFieldsText = '';
1100
+ releaseApprovals();
1101
+ const unstarted = staged;
1102
+ staged = null;
1103
+ if (unstarted !== null) spawn(returnToInbox(unstarted));
1104
+ }
1105
+
1106
+ function activateSoon() {
1107
+ if (!armed || stopped || owner === 'gone' || owner === 'active' || owner === 'activating')
1108
+ return;
1109
+ timers.activate?.();
1110
+ timers.activate = null;
1111
+ spawn(activate());
1112
+ }
1113
+
1114
+ /**
1115
+ * The terminal opened a thread through this adapter: write this adapter's
1116
+ * pid as the record's `childPid` and own the session (FR2). The launcher's
1117
+ * fields come from the record on disk; a missing record is never written.
1118
+ */
1119
+ async function activate() {
1120
+ const previous = owner;
1121
+ owner = 'activating';
1122
+ const fields = currentFields();
1123
+ /** @type {'owner' | 'gone' | 'unavailable'} */
1124
+ let verdict;
1125
+ try {
1126
+ verdict = await withRoomLock(
1127
+ paths,
1128
+ async () => {
1129
+ const record = await readSession(paths, self.sessionId);
1130
+ if (ownershipOf(record) === 'gone' || record === null) return 'gone';
1131
+ if (stopped) return 'unavailable';
1132
+ await writeSession(paths, { ...record, ...fields });
1133
+ return 'owner';
1134
+ },
1135
+ lockClock,
1136
+ );
1137
+ } catch {
1138
+ verdict = 'unavailable';
1139
+ }
1140
+ if (verdict === 'gone') {
1141
+ owner = 'gone';
1142
+ return;
1143
+ }
1144
+ if (verdict === 'unavailable') {
1145
+ owner = previous;
1146
+ if (!stopped)
1147
+ timers.activate = schedule(() => {
1148
+ timers.activate = null;
1149
+ activateSoon();
1150
+ }, DELIVERY_RETRY_DELAY_MS);
1151
+ return;
1152
+ }
1153
+ owner = 'active';
1154
+ lastFieldsText = JSON.stringify(fields);
1155
+ // Stopped meanwhile: `stop()` cleans up as the owner.
1156
+ if (stopped) return;
1157
+ const grant = await readGrant(paths, self.sessionId, now()).catch(() => null);
1158
+ if (!isActive()) return;
1159
+ cacheGrant(grant);
1160
+ try {
1161
+ stopWatch = containedCancel(watch([inboxDirectory, paths.delegation], onWatch));
1162
+ } catch {
1163
+ // The default watch never throws; with one that does, the scan below is the only reading.
1164
+ stopWatch = null;
1165
+ }
1166
+ refresh();
1167
+ spawn(scan());
1168
+ }
1169
+
1170
+ // ---- the session record ---------------------------------------------------
1171
+
1172
+ let stateKey = '';
1173
+ let stateSince = 0;
1174
+ let lastFieldsText = '';
1175
+ /** @type {RecordFields | null} */
1176
+ let nextFields = null;
1177
+ let recordDirty = false;
1178
+ /** The last write of the record failed: the record on disk may not show the role's state. */
1179
+ let recordFailed = false;
1180
+ /** @type {Promise<void> | null} */
1181
+ let recordFlush = null;
1182
+
1183
+ /** @param {string | null} turnId @returns {'user' | 'manager'} */
1184
+ function originOfTurn(turnId) {
1185
+ return running !== null && turnId !== null && running.turnId === turnId ? 'manager' : 'user';
1186
+ }
1187
+
1188
+ /** @returns {{ state: SessionState, turnOrigin: 'user' | 'manager' | null, approval: SessionApproval | null }} */
1189
+ function deriveView() {
1190
+ const open = [...approvals.values()];
1191
+ const [first] = open;
1192
+ if (first !== undefined) {
1193
+ const oldest = open.reduce((left, right) => (right.since < left.since ? right : left), first);
1194
+ const withUser = open.some((entry) => entry.phase === 'user' || entry.phase === 'deciding');
1195
+ return {
1196
+ state: 'waiting_approval',
1197
+ turnOrigin: originOfTurn(oldest.turnId),
1198
+ approval: {
1199
+ kind: sessionKindOf(oldest.kind),
1200
+ decider: withUser ? 'user' : 'manager',
1201
+ since: oldest.since,
1202
+ },
1203
+ };
1204
+ }
1205
+ if (running !== null) return { state: 'busy', turnOrigin: 'manager', approval: null };
1206
+ const thread = currentThreadId === null ? undefined : tracker.thread(currentThreadId);
1207
+ if (thread?.status === 'active') return { state: 'busy', turnOrigin: 'user', approval: null };
1208
+ if (thread?.status === 'idle' || thread?.status === 'systemError')
1209
+ return { state: 'idle', turnOrigin: null, approval: null };
1210
+ return { state: 'starting', turnOrigin: null, approval: null };
1211
+ }
1212
+
1213
+ /** @returns {string[]} */
1214
+ function heldIds() {
1215
+ /** @type {string[]} */
1216
+ const ids = [];
1217
+ for (const entry of approvals.values())
1218
+ if (entry.phase === 'held' && entry.approvalId !== null) ids.push(entry.approvalId);
1219
+ return ids.slice(0, HELD_APPROVALS_MAX);
1220
+ }
1221
+
1222
+ /**
1223
+ * The fields of the record this role writes; the launcher's fields come
1224
+ * from the record on disk at each write.
1225
+ * @returns {RecordFields}
1226
+ */
1227
+ function currentFields() {
1228
+ const view = deriveView();
1229
+ const key = `${view.state}|${view.turnOrigin ?? ''}|${view.approval?.kind ?? ''}|${view.approval?.decider ?? ''}`;
1230
+ if (key !== stateKey) {
1231
+ stateKey = key;
1232
+ stateSince = now();
1233
+ }
1234
+ const thread = currentThreadId === null ? undefined : tracker.thread(currentThreadId);
1235
+ return {
1236
+ childPid: pid,
1237
+ // `writeSession` fills it when the pid is this process's; never another owner's.
1238
+ childStartTime: null,
1239
+ state: view.state,
1240
+ stateSince,
1241
+ turnOrigin: view.turnOrigin,
1242
+ queued: queued.size + (staged === null ? 0 : 1),
1243
+ sandbox: thread?.sandbox ?? UNKNOWN,
1244
+ approvalPolicy: thread?.approvalPolicy ?? UNKNOWN,
1245
+ approval: view.approval,
1246
+ heldApprovals: heldIds(),
1247
+ };
1248
+ }
1249
+
1250
+ /** Recompute the record and write it when it changed (coalesced; the owner only). */
1251
+ function refresh() {
1252
+ if (!isActive()) return;
1253
+ const fields = currentFields();
1254
+ const text = JSON.stringify(fields);
1255
+ if (text === lastFieldsText) return;
1256
+ lastFieldsText = text;
1257
+ nextFields = fields;
1258
+ startFlush();
1259
+ }
1260
+
1261
+ function startFlush() {
1262
+ recordDirty = true;
1263
+ if (recordFlush !== null) return;
1264
+ const flush = async () => {
1265
+ while (recordDirty && nextFields !== null && isActive()) {
1266
+ recordDirty = false;
1267
+ const fields = nextFields;
1268
+ const written = await asOwner((record) => writeSession(paths, { ...record, ...fields }));
1269
+ // A write that failed is made again at the next change; frames are never affected.
1270
+ recordFailed = !written.ok;
1271
+ if (recordFailed) lastFieldsText = '';
1272
+ }
1273
+ };
1274
+ const run = flush().finally(() => {
1275
+ recordFlush = null;
1276
+ if (recordDirty && isActive()) startFlush();
1277
+ });
1278
+ recordFlush = run;
1279
+ spawn(run);
1280
+ }
1281
+
1282
+ async function awaitRecord() {
1283
+ while (recordFlush !== null) await recordFlush.catch(() => undefined);
1284
+ }
1285
+
1286
+ // ---- the mailbox ----------------------------------------------------------
1287
+
1288
+ /**
1289
+ * Gone, or not readable for a reason other than its content (`io_error`: a
1290
+ * permission, the system's file table). The bus keeps such a file, so it is
1291
+ * neither rejected nor remembered: a later scan reads it again.
1292
+ * @param {Awaited<ReturnType<typeof readMailboxFile>>} file
1293
+ */
1294
+ function unreadForNow(file) {
1295
+ return !file.ok && (file.reason === MISSING_FILE || file.reason === READ_ERROR);
1296
+ }
1297
+
1298
+ /** @param {string} name @param {string} reason @param {number} bytes */
1299
+ function rejectInbox(name, reason, bytes) {
1300
+ // An entry that cannot be deleted (a directory) is audited once, not at every scan.
1301
+ addBounded(rejectedNames, name, REJECTED_NAMES_MAX);
1302
+ return rejectMailboxFile(
1303
+ paths,
1304
+ self.sessionId,
1305
+ name,
1306
+ { reason, bytes, sessionId: self.sessionId },
1307
+ busClock,
1308
+ );
1309
+ }
1310
+
1311
+ /** @param {string} name @param {string} reason @param {number} bytes */
1312
+ async function rejectClaimed(name, reason, bytes) {
1313
+ await removeMailboxFile(paths, 'claimed', self.sessionId, name);
1314
+ await audit(paths, { event: 'rejected', sessionId: self.sessionId, bytes, reason }, busClock);
1315
+ }
1316
+
1317
+ /** @returns {QueuedEntry[]} */
1318
+ function sortedQueue() {
1319
+ return [...queued.values()].sort((left, right) => (left.name < right.name ? -1 : 1));
1320
+ }
1321
+
1322
+ /**
1323
+ * @param {Awaited<ReturnType<typeof readMailboxFile>>} file
1324
+ * @param {SessionRecord | null} manager
1325
+ * @returns {{ ok: true, message: RequestMessage | ApprovalDecisionMessage } | { ok: false, reason: string, bytes: number }}
1326
+ */
1327
+ function checkFile(file, manager) {
1328
+ if (!file.ok) return file;
1329
+ const verdict = authorizeForWorker(file.message, { roomId: role.roomId, self, manager });
1330
+ if (!verdict.ok) return { ok: false, reason: verdict.reason, bytes: file.bytes };
1331
+ const message = file.message;
1332
+ if (message.kind === 'request' || message.kind === 'approval_decision')
1333
+ return { ok: true, message };
1334
+ return { ok: false, reason: CODES.kind, bytes: file.bytes };
1335
+ }
1336
+
1337
+ /**
1338
+ * Claim one inbox request while this adapter owns the session (FR2).
1339
+ * @param {string} name
1340
+ */
1341
+ async function claimAsOwner(name) {
1342
+ const claimed = await asOwner(() => claimMailboxFile(paths, self.sessionId, name));
1343
+ return claimed.ok && claimed.value;
1344
+ }
1345
+
1346
+ /**
1347
+ * Put a request this role claimed but never started back in the inbox, for
1348
+ * the adapter that owns the session now. When that fails it is answered, so
1349
+ * that no claimed request stays without a reply.
1350
+ * @param {QueuedEntry} entry
1351
+ */
1352
+ async function returnToInbox(entry) {
1353
+ try {
1354
+ await rename(join(claimedDirectory, entry.name), join(inboxDirectory, entry.name));
1355
+ } catch {
1356
+ await finishUnstarted(entry, 'refused', CODES.workerMoved);
1357
+ }
1358
+ }
1359
+
1360
+ /**
1361
+ * Validate one new inbox file (FR3): a request is indexed, a decision is
1362
+ * applied, anything else is deleted and audited.
1363
+ * @param {string} name
1364
+ * @param {SessionRecord | null} manager
1365
+ */
1366
+ async function admit(name, manager) {
1367
+ const file = await readMailboxFile(paths, 'inbox', self.sessionId, name);
1368
+ if (unreadForNow(file)) return;
1369
+ const checked = checkFile(file, manager);
1370
+ if (!checked.ok) return rejectInbox(name, checked.reason, checked.bytes);
1371
+ const bytes = file.ok ? file.bytes : 0;
1372
+ if (checked.message.kind === 'approval_decision')
1373
+ return applyDecision(checked.message, name, bytes);
1374
+ const entry = { name, message: checked.message };
1375
+ // Past the bound a request of the live manager is still answered, never dropped.
1376
+ if (queued.size >= QUEUE_INDEX_MAX) {
1377
+ if (await claimAsOwner(name)) await finishUnstarted(entry, 'refused', CODES.queueFull);
1378
+ return;
1379
+ }
1380
+ queued.set(name, entry);
1381
+ await audit(
1382
+ paths,
1383
+ {
1384
+ event: 'queued',
1385
+ sessionId: self.sessionId,
1386
+ peerSessionId: checked.message.sender.sessionId,
1387
+ messageId: checked.message.id,
1388
+ bytes,
1389
+ },
1390
+ busClock,
1391
+ );
1392
+ }
1393
+
1394
+ async function scanOnce() {
1395
+ if (!isActive()) return;
1396
+ const { names, foreign } = await listMailbox(paths, 'inbox', self.sessionId);
1397
+ for (const name of foreign)
1398
+ if (!rejectedNames.has(name) && isActive()) await rejectInbox(name, CODES.name, 0);
1399
+ const present = new Set(names);
1400
+ // Gone from the inbox without being claimed: the manager cancelled it.
1401
+ for (const name of [...queued.keys()]) if (!present.has(name)) queued.delete(name);
1402
+ const fresh = names.filter(
1403
+ (name) => !queued.has(name) && !claiming.has(name) && !rejectedNames.has(name),
1404
+ );
1405
+ if (fresh.length === 0) return;
1406
+ const manager = await liveManager(paths, busClock).catch(() => null);
1407
+ for (const name of fresh) {
1408
+ if (!isActive()) return;
1409
+ await admit(name, manager);
1410
+ }
1411
+ }
1412
+
1413
+ let scanning = false;
1414
+ let scanAgain = false;
1415
+
1416
+ async function scan() {
1417
+ if (scanning) {
1418
+ scanAgain = true;
1419
+ return;
1420
+ }
1421
+ scanning = true;
1422
+ try {
1423
+ do {
1424
+ scanAgain = false;
1425
+ await scanOnce();
1426
+ } while (scanAgain && isActive());
1427
+ } finally {
1428
+ scanning = false;
1429
+ }
1430
+ refresh();
1431
+ armExpiry();
1432
+ kick();
1433
+ }
1434
+
1435
+ // ---- delivery (FR4) -------------------------------------------------------
1436
+
1437
+ /**
1438
+ * Every condition of FR4 step 1, read synchronously right before a write.
1439
+ * The app-server merges a second `turn/start` into a running turn (spike
1440
+ * S3), so this gate is the only protection.
1441
+ */
1442
+ function gateOpen() {
1443
+ if (!isActive() || gateRefused || running !== null || currentThreadId === null) return false;
1444
+ const thread = tracker.thread(currentThreadId);
1445
+ if (thread === undefined || thread.ephemeral) return false;
1446
+ // A failed turn leaves `systemError` and no `idle` after it; a new turn works there.
1447
+ if (thread.status !== 'idle' && thread.status !== 'systemError') return false;
1448
+ if (thread.clientWork > 0 || settling.has(currentThreadId) || approvals.size > 0) return false;
1449
+ if (adapterBusy(currentThreadId)) return false;
1450
+ return atLineBoundary();
1451
+ }
1452
+
1453
+ function kick() {
1454
+ if (!isActive()) return;
1455
+ if (queued.size === 0 && staged === null) return;
1456
+ spawn(pump());
1457
+ }
1458
+
1459
+ /**
1460
+ * The gate was closed only because a terminal frame was half written: no
1461
+ * frame may come to reopen it, so try again shortly.
1462
+ */
1463
+ function armBoundaryRetry() {
1464
+ if (timers.boundary !== null || !isActive()) return;
1465
+ timers.boundary = schedule(() => {
1466
+ timers.boundary = null;
1467
+ kick();
1468
+ }, LINE_BOUNDARY_RETRY_MS);
1469
+ }
1470
+
1471
+ function armExpiry() {
1472
+ timers.expiry?.();
1473
+ timers.expiry = null;
1474
+ if (!isActive()) return;
1475
+ const times = [...queued.values()].map((entry) => entry.message.expiresAt);
1476
+ if (staged !== null) times.push(staged.message.expiresAt);
1477
+ if (times.length === 0) return;
1478
+ const earliest = Math.min(...times);
1479
+ timers.expiry = schedule(
1480
+ () => {
1481
+ timers.expiry = null;
1482
+ spawn(pump());
1483
+ },
1484
+ boundedDelay(earliest - now()),
1485
+ );
1486
+ }
1487
+
1488
+ /**
1489
+ * @param {RequestMessage} message
1490
+ * @param {ReplyContent} content
1491
+ */
1492
+ async function writeReply(message, content) {
1493
+ const reply = buildReply({
1494
+ roomId: role.roomId,
1495
+ inReplyTo: message.id,
1496
+ sender: self,
1497
+ outcome: content.outcome,
1498
+ code: content.code,
1499
+ shared: content.shared,
1500
+ text: content.text,
1501
+ now: now(),
1502
+ });
1503
+ for (let attempt = 0; attempt < REPLY_WRITE_ATTEMPTS; attempt += 1) {
1504
+ try {
1505
+ return await deliverMessage(paths, MANAGER_RECIPIENT, reply);
1506
+ } catch {
1507
+ // Written again once; a second failure is audited.
1508
+ }
1509
+ }
1510
+ return null;
1511
+ }
1512
+
1513
+ /**
1514
+ * Reply to one claimed request, delete the claimed file, audit (FR4 step 4).
1515
+ * @param {QueuedEntry} entry
1516
+ * @param {ReplyContent} content
1517
+ * @param {'replied' | 'expired' | 'refused'} event
1518
+ */
1519
+ async function sendReply(entry, content, event) {
1520
+ const bytes = await writeReply(entry.message, content);
1521
+ await removeMailboxFile(paths, 'claimed', self.sessionId, entry.name);
1522
+ /** @type {AuditEvent} */
1523
+ const line = {
1524
+ event,
1525
+ sessionId: self.sessionId,
1526
+ peerSessionId: entry.message.sender.sessionId,
1527
+ messageId: entry.message.id,
1528
+ outcome: content.outcome,
1529
+ };
1530
+ if (bytes === null) line.reason = CODES.deliveryFailed;
1531
+ else line.bytes = bytes;
1532
+ if (bytes !== null && content.code !== null) line.reason = content.code;
1533
+ await audit(paths, line, busClock);
1534
+ }
1535
+
1536
+ /**
1537
+ * @param {QueuedEntry} entry
1538
+ * @param {'expired' | 'refused'} outcome
1539
+ * @param {string | null} code
1540
+ */
1541
+ async function finishUnstarted(entry, outcome, code) {
1542
+ await sendReply(entry, { outcome, code, shared: false, text: '' }, outcome);
1543
+ refresh();
1544
+ }
1545
+
1546
+ async function expireDue() {
1547
+ const at = now();
1548
+ for (const entry of sortedQueue()) {
1549
+ if (entry.message.expiresAt > at || !isActive()) continue;
1550
+ queued.delete(entry.name);
1551
+ claiming.add(entry.name);
1552
+ const claimed = await claimAsOwner(entry.name);
1553
+ claiming.delete(entry.name);
1554
+ if (claimed) await finishUnstarted(entry, 'expired', null);
1555
+ }
1556
+ if (staged !== null && staged.message.expiresAt <= at) {
1557
+ const expired = staged;
1558
+ staged = null;
1559
+ await finishUnstarted(expired, 'expired', null);
1560
+ }
1561
+ armExpiry();
1562
+ }
1563
+
1564
+ /**
1565
+ * Claim the oldest queued request and validate it again from `claimed/`,
1566
+ * with the room's live manager of this moment.
1567
+ * @returns {Promise<Claimed | null>}
1568
+ */
1569
+ async function takeOldest() {
1570
+ for (const entry of sortedQueue()) {
1571
+ if (!isActive()) return null;
1572
+ queued.delete(entry.name);
1573
+ claiming.add(entry.name);
1574
+ try {
1575
+ // Not claimed (taken over, or the lock was busy): a later scan indexes it again.
1576
+ if (!(await claimAsOwner(entry.name))) continue;
1577
+ const file = await readMailboxFile(paths, 'claimed', self.sessionId, entry.name);
1578
+ // The file may be valid (FR3): it goes back for a later scan, never to the bin.
1579
+ if (!file.ok && file.reason === READ_ERROR) {
1580
+ await returnToInbox(entry);
1581
+ continue;
1582
+ }
1583
+ const manager = await liveManager(paths, busClock).catch(() => null);
1584
+ const checked = checkFile(file, manager);
1585
+ if (!checked.ok) {
1586
+ await rejectClaimed(entry.name, checked.reason, checked.bytes);
1587
+ continue;
1588
+ }
1589
+ if (checked.message.kind !== 'request') {
1590
+ await rejectClaimed(entry.name, CODES.kind, file.ok ? file.bytes : 0);
1591
+ continue;
1592
+ }
1593
+ return { name: entry.name, message: checked.message, attempts: 0, notBefore: 0 };
1594
+ } finally {
1595
+ claiming.delete(entry.name);
1596
+ }
1597
+ }
1598
+ return null;
1599
+ }
1600
+
1601
+ function gateClosed() {
1602
+ if (!atLineBoundary()) armBoundaryRetry();
1603
+ }
1604
+
1605
+ async function deliverOnce() {
1606
+ await expireDue();
1607
+ if (!gateOpen()) return gateClosed();
1608
+ if (staged === null) {
1609
+ const taken = await takeOldest();
1610
+ if (taken !== null && !isActive()) {
1611
+ await returnToInbox(taken);
1612
+ return;
1613
+ }
1614
+ staged = taken;
1615
+ refresh();
1616
+ armExpiry();
1617
+ if (staged === null) return;
1618
+ }
1619
+ const next = staged;
1620
+ if (next.message.expiresAt <= now()) {
1621
+ staged = null;
1622
+ await finishUnstarted(next, 'expired', null);
1623
+ pumpAgain = true;
1624
+ return;
1625
+ }
1626
+ if (next.notBefore > now()) return;
1627
+ // Synchronously, right before the write: nothing may have changed since.
1628
+ if (!gateOpen() || currentThreadId === null) return;
1629
+ startTurn(next, currentThreadId);
1630
+ }
1631
+
1632
+ let pumping = false;
1633
+ let pumpAgain = false;
1634
+
1635
+ async function pump() {
1636
+ if (pumping) {
1637
+ pumpAgain = true;
1638
+ return;
1639
+ }
1640
+ pumping = true;
1641
+ try {
1642
+ do {
1643
+ pumpAgain = false;
1644
+ await deliverOnce();
1645
+ } while (pumpAgain && isActive());
1646
+ } finally {
1647
+ pumping = false;
1648
+ }
1649
+ }
1650
+
1651
+ /**
1652
+ * Write one `turn/start` for a claimed request (FR4 step 2): the FR5 text as
1653
+ * the only input, a `clientUserMessageId` of the role's own, no override.
1654
+ * @param {Claimed} claimed
1655
+ * @param {string} threadId
1656
+ */
1657
+ function startTurn(claimed, threadId) {
1658
+ /** @type {Delivery} */
1659
+ const delivery = {
1660
+ ...claimed,
1661
+ clientId: randomUUID(),
1662
+ threadId,
1663
+ turnId: null,
1664
+ shared: false,
1665
+ responded: false,
1666
+ sawActive: false,
1667
+ ended: false,
1668
+ done: false,
1669
+ cancelGrace: null,
1670
+ cancelResponseWait: null,
1671
+ };
1672
+ running = delivery;
1673
+ staged = null;
1674
+ delivery.cancelResponseWait = schedule(() => {
1675
+ delivery.cancelResponseWait = null;
1676
+ if (!delivery.responded && delivery.turnId === null)
1677
+ endDelivery(delivery, failure(delivery, CODES.turnEndUnobserved));
1678
+ }, TURN_START_RESPONSE_WAIT_MS);
1679
+ const params = {
1680
+ threadId,
1681
+ clientUserMessageId: delivery.clientId,
1682
+ input: [
1683
+ {
1684
+ type: 'text',
1685
+ text: workerInputText({
1686
+ workerName: role.name,
1687
+ locale: role.locale,
1688
+ text: claimed.message.text,
1689
+ }),
1690
+ },
1691
+ ],
1692
+ };
1693
+ /** @type {Promise<unknown>} */
1694
+ let response;
1695
+ try {
1696
+ response = Promise.resolve(port.request('turn/start', params));
1697
+ } catch (error) {
1698
+ response = Promise.reject(error);
1699
+ }
1700
+ // Not a tracked task: `settled()` must not wait for the app-server's answer.
1701
+ response
1702
+ .then(
1703
+ (result) => onTurnStartResult(delivery, result),
1704
+ (error) => onTurnStartRejected(delivery, error),
1705
+ )
1706
+ .catch(() => undefined);
1707
+ spawn(
1708
+ audit(
1709
+ paths,
1710
+ {
1711
+ event: 'started',
1712
+ sessionId: self.sessionId,
1713
+ peerSessionId: claimed.message.sender.sessionId,
1714
+ messageId: claimed.message.id,
1715
+ },
1716
+ busClock,
1717
+ ),
1718
+ );
1719
+ refresh();
1720
+ armExpiry();
1721
+ }
1722
+
1723
+ /** @param {Delivery} delivery */
1724
+ function cancelWaits(delivery) {
1725
+ delivery.cancelGrace?.();
1726
+ delivery.cancelGrace = null;
1727
+ delivery.cancelResponseWait?.();
1728
+ delivery.cancelResponseWait = null;
1729
+ }
1730
+
1731
+ /** @param {Delivery} delivery @param {unknown} result */
1732
+ function onTurnStartResult(delivery, result) {
1733
+ if (stopped || delivery.done) return;
1734
+ delivery.responded = true;
1735
+ delivery.cancelResponseWait?.();
1736
+ delivery.cancelResponseWait = null;
1737
+ const turn = isObject(result) && isObject(result.turn) ? result.turn : null;
1738
+ const turnId = turn === null ? null : wireId(turn.id);
1739
+ if (turnId !== null) bind(delivery, turnId);
1740
+ else if (delivery.turnId === null && delivery.ended)
1741
+ endDelivery(delivery, failure(delivery, CODES.turnEndUnobserved));
1742
+ refresh();
1743
+ }
1744
+
1745
+ /** @param {Delivery} delivery @param {unknown} error */
1746
+ function onTurnStartRejected(delivery, error) {
1747
+ // Bound by its `clientId` already: a turn exists and will end on its own.
1748
+ if (stopped || delivery.done || delivery.turnId !== null) return;
1749
+ delivery.done = true;
1750
+ cancelWaits(delivery);
1751
+ if (running === delivery) running = null;
1752
+ // The adapter's own gate refused before writing anything: not an attempt.
1753
+ // The request waits for the adapter's next idle (FR4 step 1); its time to
1754
+ // live still bounds it.
1755
+ const gateRefusal = isObject(error) && error.adapterGate === true;
1756
+ const attempts = gateRefusal ? delivery.attempts : delivery.attempts + 1;
1757
+ const claimed = { name: delivery.name, message: delivery.message };
1758
+ if (attempts >= DELIVERY_ATTEMPTS) {
1759
+ spawn(finishUnstarted(claimed, 'refused', rejectionCodeOf(error)));
1760
+ } else if (!isActive()) {
1761
+ // Another adapter owns the session now: it delivers the request.
1762
+ spawn(returnToInbox(claimed));
1763
+ } else {
1764
+ staged = {
1765
+ ...claimed,
1766
+ attempts,
1767
+ notBefore: gateRefusal ? 0 : now() + DELIVERY_RETRY_DELAY_MS,
1768
+ };
1769
+ gateRefused = gateRefused || gateRefusal;
1770
+ // When no idle comes, the next try is still made after the delay.
1771
+ timers.retry?.();
1772
+ timers.retry = schedule(() => {
1773
+ timers.retry = null;
1774
+ gateRefused = false;
1775
+ kick();
1776
+ }, DELIVERY_RETRY_DELAY_MS);
1777
+ }
1778
+ refresh();
1779
+ kick();
1780
+ }
1781
+
1782
+ /** @param {Delivery} delivery @param {string} code @returns {ReplyContent} */
1783
+ function failure(delivery, code) {
1784
+ return { outcome: 'failed', code, shared: delivery.shared, text: '' };
1785
+ }
1786
+
1787
+ /** @param {Delivery} delivery @param {string} turnId */
1788
+ function bind(delivery, turnId) {
1789
+ if (delivery.turnId !== null || delivery.done) return;
1790
+ delivery.turnId = turnId;
1791
+ const view = tracker.turn(turnId);
1792
+ if (view === undefined) return;
1793
+ for (const clientId of view.userMessages.values())
1794
+ if (clientId !== delivery.clientId) delivery.shared = true;
1795
+ if (view.end !== null) completeDelivery(delivery);
1796
+ else if (delivery.ended) armEndGrace(delivery);
1797
+ }
1798
+
1799
+ /**
1800
+ * The thread reported the turn's end; its `turn/completed` must follow.
1801
+ * @param {Delivery} delivery
1802
+ */
1803
+ function armEndGrace(delivery) {
1804
+ if (delivery.cancelGrace !== null || delivery.done) return;
1805
+ delivery.cancelGrace = schedule(() => {
1806
+ delivery.cancelGrace = null;
1807
+ endDelivery(delivery, failure(delivery, CODES.turnEndUnobserved));
1808
+ }, TURN_END_GRACE_MS);
1809
+ }
1810
+
1811
+ /** @param {Delivery} delivery */
1812
+ function completeDelivery(delivery) {
1813
+ if (delivery.turnId === null) return;
1814
+ const view = tracker.turn(delivery.turnId);
1815
+ const end = view?.end ?? null;
1816
+ if (view === undefined || end === null) return;
1817
+ const outcome = OUTCOME_BY_TURN_STATUS.get(end.status) ?? 'failed';
1818
+ const known = OUTCOME_BY_TURN_STATUS.has(end.status);
1819
+ const code =
1820
+ outcome !== 'failed'
1821
+ ? null
1822
+ : (errorKindOf(end.error) ?? view.errorKind ?? (known ? null : CODES.unknownStatus));
1823
+ endDelivery(delivery, {
1824
+ outcome,
1825
+ code,
1826
+ shared: delivery.shared,
1827
+ text: lastAgentText(end.items) ?? view.lastAgentText ?? '',
1828
+ });
1829
+ }
1830
+
1831
+ /** @param {Delivery} delivery @param {ReplyContent} content */
1832
+ function endDelivery(delivery, content) {
1833
+ if (delivery.done || stopped) return;
1834
+ delivery.done = true;
1835
+ cancelWaits(delivery);
1836
+ spawn(finishDelivery(delivery, content));
1837
+ }
1838
+
1839
+ /** @param {Delivery} delivery @param {ReplyContent} content */
1840
+ async function finishDelivery(delivery, content) {
1841
+ await sendReply(delivery, content, 'replied');
1842
+ if (running === delivery) running = null;
1843
+ refresh();
1844
+ kick();
1845
+ }
1846
+
1847
+ // ---- frames -> reactions --------------------------------------------------
1848
+
1849
+ /** @param {string} threadId @param {string} status */
1850
+ function onStatus(threadId, status) {
1851
+ const delivery = running;
1852
+ if (delivery === null || delivery.done || delivery.threadId !== threadId) return;
1853
+ if (status === 'active') {
1854
+ delivery.sawActive = true;
1855
+ return;
1856
+ }
1857
+ // An `idle` before the turn went active is a report that was already on its way.
1858
+ const turnEnded =
1859
+ status === 'systemError' ||
1860
+ status === 'notLoaded' ||
1861
+ (status === 'idle' && delivery.sawActive);
1862
+ if (turnEnded) onTurnEndSignal(delivery);
1863
+ }
1864
+
1865
+ /**
1866
+ * The thread reported that the turn ended (idle, failed, unloaded or
1867
+ * closed): its `turn/completed` must follow, or the reply is `failed`.
1868
+ * @param {Delivery} delivery
1869
+ */
1870
+ function onTurnEndSignal(delivery) {
1871
+ delivery.ended = true;
1872
+ if (delivery.turnId !== null) armEndGrace(delivery);
1873
+ else if (delivery.responded) endDelivery(delivery, failure(delivery, CODES.turnEndUnobserved));
1874
+ }
1875
+
1876
+ /** @param {{ threadId: string, turnId: string, clientId: string | null }} event */
1877
+ function onUserMessage(event) {
1878
+ const delivery = running;
1879
+ if (delivery === null || delivery.done) return;
1880
+ if (
1881
+ delivery.turnId === null &&
1882
+ event.clientId === delivery.clientId &&
1883
+ event.threadId === delivery.threadId
1884
+ ) {
1885
+ bind(delivery, event.turnId);
1886
+ return;
1887
+ }
1888
+ if (delivery.turnId === event.turnId && event.clientId !== delivery.clientId)
1889
+ delivery.shared = true;
1890
+ }
1891
+
1892
+ /** @param {string} threadId */
1893
+ function onClientTurn(threadId) {
1894
+ const delivery = running;
1895
+ if (delivery !== null && !delivery.done && delivery.threadId === threadId)
1896
+ delivery.shared = true;
1897
+ }
1898
+
1899
+ /** @param {string} turnId */
1900
+ function onTurnCompleted(turnId) {
1901
+ for (const entry of [...approvals.values()])
1902
+ if (entry.turnId === turnId) closeApproval(entry, CODES.turnEnded);
1903
+ const delivery = running;
1904
+ if (delivery !== null && !delivery.done && delivery.turnId === turnId)
1905
+ completeDelivery(delivery);
1906
+ }
1907
+
1908
+ /** @param {string} threadId */
1909
+ function onThreadClosed(threadId) {
1910
+ for (const entry of [...approvals.values()])
1911
+ if (entry.threadId === threadId) closeApproval(entry, CODES.threadClosed);
1912
+ const delivery = running;
1913
+ if (delivery !== null && !delivery.done && delivery.threadId === threadId)
1914
+ onTurnEndSignal(delivery);
1915
+ }
1916
+
1917
+ /** @param {string} itemId */
1918
+ function onPatchUpdated(itemId) {
1919
+ for (const entry of [...approvals.values()]) {
1920
+ if (entry.itemId !== itemId || entry.kind !== 'fileChange') continue;
1921
+ // The manager would judge a patch that is no longer the one that runs.
1922
+ if (entry.phase === 'deciding') sendToUser(entry);
1923
+ else forwardHeld(entry, 'escalated', CODES.patchChanged, CODES.patchChanged);
1924
+ }
1925
+ }
1926
+
1927
+ /** @param {string} threadId */
1928
+ function endSettling(threadId) {
1929
+ settling.get(threadId)?.();
1930
+ settling.delete(threadId);
1931
+ }
1932
+
1933
+ /**
1934
+ * The terminal's work request was accepted: its turn may not be reported yet.
1935
+ * @param {string} threadId
1936
+ */
1937
+ function startSettling(threadId) {
1938
+ endSettling(threadId);
1939
+ settling.set(
1940
+ threadId,
1941
+ schedule(() => {
1942
+ settling.delete(threadId);
1943
+ kick();
1944
+ }, CLIENT_WORK_SETTLE_MS),
1945
+ );
1946
+ }
1947
+
1948
+ /** @param {WireEvent[]} events */
1949
+ function react(events) {
1950
+ for (const event of events) {
1951
+ if (event.type === 'thread_opened' && !event.ephemeral) {
1952
+ currentThreadId = event.threadId;
1953
+ activateSoon();
1954
+ } else if (event.type === 'status') {
1955
+ // Any status may be the adapter's idle after a refusal of its gate.
1956
+ gateRefused = false;
1957
+ endSettling(event.threadId);
1958
+ onStatus(event.threadId, event.status);
1959
+ } else if (event.type === 'client_settled') {
1960
+ if (event.accepted) startSettling(event.threadId);
1961
+ } else if (event.type === 'user_message') onUserMessage(event);
1962
+ else if (event.type === 'turn_completed') onTurnCompleted(event.turnId);
1963
+ else if (event.type === 'client_turn') onClientTurn(event.threadId);
1964
+ else if (event.type === 'client_answer') closeAnsweredByUser(event.key);
1965
+ else if (event.type === 'resolved') {
1966
+ // The adapter dropped its line before this frame reached the role.
1967
+ adapterHeld.delete(event.key);
1968
+ const entry = approvals.get(event.key);
1969
+ if (entry !== undefined) closeApproval(entry, CODES.resolved);
1970
+ } else if (event.type === 'patch_updated') onPatchUpdated(event.itemId);
1971
+ else if (event.type === 'thread_closed') {
1972
+ for (const [key, threadId] of [...adapterHeld])
1973
+ if (threadId === event.threadId) adapterHeld.delete(key);
1974
+ endSettling(event.threadId);
1975
+ onThreadClosed(event.threadId);
1976
+ }
1977
+ }
1978
+ if (events.length === 0) return;
1979
+ refresh();
1980
+ kick();
1981
+ }
1982
+
1983
+ // ---- approvals (FR4 step 8, FR13) -----------------------------------------
1984
+
1985
+ function grantAbsent() {
1986
+ return knownGrant === null || knownGrant.expiresAt <= now();
1987
+ }
1988
+
1989
+ /** @param {Grant | null} grant */
1990
+ function cacheGrant(grant) {
1991
+ knownGrant = grant;
1992
+ timers.grant?.();
1993
+ timers.grant = null;
1994
+ if (grant === null || !isActive()) return;
1995
+ timers.grant = schedule(
1996
+ () => {
1997
+ timers.grant = null;
1998
+ spawn(refreshGrant());
1999
+ },
2000
+ boundedDelay(grant.expiresAt - now()),
2001
+ );
2002
+ }
2003
+
2004
+ /**
2005
+ * Take the grant read from the file as the truth: a hold made under any
2006
+ * other grant (ended, revoked, or replaced by a new one) goes to the terminal.
2007
+ * @param {Grant | null} grant
2008
+ */
2009
+ function adoptGrant(grant) {
2010
+ cacheGrant(grant);
2011
+ for (const entry of [...approvals.values()]) {
2012
+ const delegated = entry.phase === 'held' || entry.phase === 'answering';
2013
+ if (delegated && entry.grantId !== grant?.grantId)
2014
+ forwardHeld(entry, 'escalated', CODES.delegationEnded, CODES.delegationEnded);
2015
+ }
2016
+ }
2017
+
2018
+ async function refreshGrant() {
2019
+ const grant = await readGrant(paths, self.sessionId, now()).catch(() => null);
2020
+ if (isActive()) adoptGrant(grant);
2021
+ }
2022
+
2023
+ function withinHourlyLimit() {
2024
+ const since = now() - HOUR_MS;
2025
+ while (delegatedAt.length > 0 && /** @type {number} */ (delegatedAt[0]) <= since)
2026
+ delegatedAt.shift();
2027
+ return delegatedAt.length < LIMITS.delegatedPerHour;
2028
+ }
2029
+
2030
+ /** @param {string | null} approvalId */
2031
+ function rememberEnded(approvalId) {
2032
+ if (approvalId !== null) addBounded(endedApprovals, approvalId, ENDED_APPROVALS_MAX);
2033
+ }
2034
+
2035
+ /** @param {OpenApproval} entry */
2036
+ function clearTimer(entry) {
2037
+ entry.cancelTimer?.();
2038
+ entry.cancelTimer = null;
2039
+ }
2040
+
2041
+ /** @param {OpenApproval} entry */
2042
+ function noteUserWait(entry) {
2043
+ if (!ownsSession()) return;
2044
+ spawn(
2045
+ audit(
2046
+ paths,
2047
+ { event: 'approval_wait', sessionId: self.sessionId, kind: AUDIT_KINDS[entry.kind] },
2048
+ busClock,
2049
+ ),
2050
+ );
2051
+ }
2052
+
2053
+ /**
2054
+ * One decision line with the request's text, one audit line without it.
2055
+ * @param {OpenApproval} entry
2056
+ * @param {OutcomeNote} note
2057
+ */
2058
+ async function recordOutcome(entry, note) {
2059
+ if (entry.grantId === null) return;
2060
+ // A role that lost the session (or whose record is gone) writes nothing more
2061
+ // (FR2), except the outcome of a hold it made itself: every held request
2062
+ // gets one in the decision record.
2063
+ if (!ownsSession() && entry.approvalId === null) return;
2064
+ await appendDecision(paths, {
2065
+ at: now(),
2066
+ grantId: entry.grantId,
2067
+ workerSessionId: self.sessionId,
2068
+ workerName: self.name,
2069
+ approvalId: entry.approvalId,
2070
+ turnId: entry.turnId,
2071
+ itemId: entry.itemId,
2072
+ kind: entry.kind,
2073
+ reserveClass: note.reserveClass ?? null,
2074
+ outcome: note.outcome,
2075
+ reason: note.reason,
2076
+ text: entry.text,
2077
+ }).catch(() => undefined);
2078
+ /** @type {AuditEvent} */
2079
+ const line = {
2080
+ event: 'approval_outcome',
2081
+ sessionId: self.sessionId,
2082
+ kind: AUDIT_KINDS[entry.kind],
2083
+ outcome: note.outcome,
2084
+ };
2085
+ if (entry.approvalId !== null) line.messageId = entry.approvalId;
2086
+ if (note.code !== undefined && note.code !== null) line.reason = note.code;
2087
+ await audit(paths, line, busClock);
2088
+ }
2089
+
2090
+ /**
2091
+ * The only function that writes a response to the app-server: `accept` or
2092
+ * `decline`, for one request the manager decided while the role held it
2093
+ * (FR13 step 4). It cannot emit anything else (criteria 23 and 24).
2094
+ * @param {OpenApproval} entry
2095
+ * @returns {boolean} whether the adapter confirmed the answer
2096
+ */
2097
+ function writeVerdict(entry) {
2098
+ if (entry.phase !== 'answering') return false;
2099
+ // Only `true` from the adapter counts as written; anything else is a refusal.
2100
+ if (entry.verdict === 'approve')
2101
+ return port.respond(entry.requestId, { decision: 'accept' }) === true;
2102
+ if (entry.verdict === 'deny')
2103
+ return port.respond(entry.requestId, { decision: 'decline' }) === true;
2104
+ return false;
2105
+ }
2106
+
2107
+ /** @param {OpenApproval} entry */
2108
+ function isDeciding(entry) {
2109
+ return !stopped && entry.phase === 'deciding' && approvals.get(entry.key) === entry;
2110
+ }
2111
+
2112
+ /**
2113
+ * A request the role was deciding goes to the terminal at once.
2114
+ * @param {OpenApproval} entry
2115
+ */
2116
+ function sendToUser(entry) {
2117
+ if (entry.phase !== 'deciding') return;
2118
+ entry.phase = 'user';
2119
+ forwardEntry(entry);
2120
+ noteUserWait(entry);
2121
+ refresh();
2122
+ }
2123
+
2124
+ /**
2125
+ * A request held for the manager goes to the terminal, and the outcome is
2126
+ * recorded.
2127
+ * @param {OpenApproval} entry
2128
+ * @param {DecisionOutcome} outcome
2129
+ * @param {string | null} reason
2130
+ * @param {string | null} code
2131
+ */
2132
+ function forwardHeld(entry, outcome, reason, code) {
2133
+ if (entry.phase !== 'held' && entry.phase !== 'answering') return;
2134
+ clearTimer(entry);
2135
+ waitingAnswers.delete(entry);
2136
+ entry.phase = 'user';
2137
+ forwardEntry(entry);
2138
+ rememberEnded(entry.approvalId);
2139
+ spawn(recordOutcome(entry, { outcome, reason, code }));
2140
+ noteUserWait(entry);
2141
+ refresh();
2142
+ }
2143
+
2144
+ /**
2145
+ * The app-server no longer waits for this request (resolved, its turn
2146
+ * ended, its thread closed).
2147
+ * @param {OpenApproval} entry
2148
+ * @param {string} code
2149
+ */
2150
+ function closeApproval(entry, code) {
2151
+ approvals.delete(entry.key);
2152
+ clearTimer(entry);
2153
+ waitingAnswers.delete(entry);
2154
+ const delegated = entry.phase === 'held' || entry.phase === 'answering';
2155
+ entry.phase = 'closed';
2156
+ if (delegated) {
2157
+ rememberEnded(entry.approvalId);
2158
+ spawn(recordOutcome(entry, { outcome: 'withdrawn', reason: code, code }));
2159
+ }
2160
+ refresh();
2161
+ kick();
2162
+ }
2163
+
2164
+ /** @param {string} key */
2165
+ function closeAnsweredByUser(key) {
2166
+ const entry = approvals.get(key);
2167
+ if (entry === undefined || entry.phase !== 'user') return;
2168
+ approvals.delete(key);
2169
+ entry.phase = 'closed';
2170
+ }
2171
+
2172
+ /** @param {OpenApproval} entry */
2173
+ function answer(entry) {
2174
+ if (!isActive() || entry.phase !== 'answering' || approvals.get(entry.key) !== entry) return;
2175
+ if (!atLineBoundary()) {
2176
+ waitingAnswers.add(entry);
2177
+ timers.answers ??= schedule(() => {
2178
+ timers.answers = null;
2179
+ flushAnswers();
2180
+ }, LINE_BOUNDARY_RETRY_MS);
2181
+ return;
2182
+ }
2183
+ let written = false;
2184
+ try {
2185
+ written = writeVerdict(entry);
2186
+ } catch {
2187
+ written = false;
2188
+ }
2189
+ if (!written) {
2190
+ forwardHeld(entry, 'escalated', CODES.answerFailed, CODES.answerFailed);
2191
+ return;
2192
+ }
2193
+ adapterHeld.delete(entry.key);
2194
+ approvals.delete(entry.key);
2195
+ entry.phase = 'closed';
2196
+ rememberEnded(entry.approvalId);
2197
+ spawn(
2198
+ recordOutcome(entry, {
2199
+ outcome: entry.verdict === 'approve' ? 'approved' : 'denied',
2200
+ reason: entry.decisionReason,
2201
+ }),
2202
+ );
2203
+ refresh();
2204
+ kick();
2205
+ }
2206
+
2207
+ function flushAnswers() {
2208
+ for (const entry of [...waitingAnswers]) {
2209
+ waitingAnswers.delete(entry);
2210
+ answer(entry);
2211
+ }
2212
+ }
2213
+
2214
+ /** @param {OpenApproval} entry */
2215
+ function onHoldTimeout(entry) {
2216
+ entry.cancelTimer = null;
2217
+ if (entry.phase === 'held')
2218
+ forwardHeld(entry, 'timed_out', CODES.holdTimeout, CODES.holdTimeout);
2219
+ }
2220
+
2221
+ /** @param {string} approvalId */
2222
+ function heldEntry(approvalId) {
2223
+ for (const entry of approvals.values())
2224
+ if (entry.approvalId === approvalId && entry.phase === 'held') return entry;
2225
+ return null;
2226
+ }
2227
+
2228
+ /**
2229
+ * A decision of the manager (FR13 steps 3-5): the sender was checked by
2230
+ * `authorizeForWorker`; the id must be held and the grant still live.
2231
+ * @param {ApprovalDecisionMessage} message
2232
+ * @param {string} name
2233
+ * @param {number} bytes
2234
+ */
2235
+ async function applyDecision(message, name, bytes) {
2236
+ const entry = heldEntry(message.approvalId);
2237
+ if (entry === null) {
2238
+ const reason = endedApprovals.has(message.approvalId) ? CODES.tooLate : CODES.unknownApproval;
2239
+ return rejectInbox(name, reason, bytes);
2240
+ }
2241
+ // Answered only while this adapter owns the session (FR2). Otherwise the
2242
+ // hold already went to the terminal, and the file is left as it is.
2243
+ const read = await asOwner(() => readGrant(paths, self.sessionId, now()).catch(() => null));
2244
+ if (!read.ok || !isActive()) return;
2245
+ const grant = read.value;
2246
+ adoptGrant(grant);
2247
+ if (grant === null || grant.grantId !== entry.grantId)
2248
+ return rejectInbox(name, CODES.notDelegated, bytes);
2249
+ if (entry.phase !== 'held') return rejectInbox(name, CODES.tooLate, bytes);
2250
+ if (now() >= entry.holdUntil) {
2251
+ forwardHeld(entry, 'timed_out', CODES.holdTimeout, CODES.holdTimeout);
2252
+ return rejectInbox(name, CODES.tooLate, bytes);
2253
+ }
2254
+ entry.phase = 'answering';
2255
+ clearTimer(entry);
2256
+ entry.decisionReason = message.reason;
2257
+ if (message.decision === 'escalate') forwardHeld(entry, 'escalated', message.reason, null);
2258
+ else {
2259
+ entry.verdict = message.decision === 'approve' ? 'approve' : 'deny';
2260
+ answer(entry);
2261
+ }
2262
+ await removeMailboxFile(paths, 'inbox', self.sessionId, name);
2263
+ }
2264
+
2265
+ /** @param {OpenApproval} entry @returns {Promise<ApprovalDescription | null>} */
2266
+ async function describeSafely(entry) {
2267
+ try {
2268
+ const value = /** @type {unknown} */ (
2269
+ await describe({ method: entry.method, params: entry.params })
2270
+ );
2271
+ if (!isObject(value)) return null;
2272
+ const kind = value.kind;
2273
+ if (kind !== 'command' && kind !== 'fileChange' && kind !== 'permissions') return null;
2274
+ return {
2275
+ kind,
2276
+ command: typeof value.command === 'string' ? value.command : null,
2277
+ cwd: typeof value.cwd === 'string' ? value.cwd : null,
2278
+ };
2279
+ } catch {
2280
+ return null;
2281
+ }
2282
+ }
2283
+
2284
+ /**
2285
+ * @param {OpenApproval} entry
2286
+ * @param {string[] | null} realPaths the real paths of a file change, null for any other request or when they cannot be resolved
2287
+ * @returns {Promise<string | null>} the class, or null when not reserved
2288
+ */
2289
+ async function classifySafely(entry, realPaths) {
2290
+ try {
2291
+ const repositoryRootList = await roots(cwd).catch(() => []);
2292
+ const verdict = /** @type {unknown} */ (
2293
+ await classify(
2294
+ { method: entry.method, params: entry.params, filePaths: realPaths },
2295
+ { roots: repositoryRootList, stateRoot: role.stateRoot, home, hostConfigDirs },
2296
+ )
2297
+ );
2298
+ if (isObject(verdict) && verdict.reserved === false) return null;
2299
+ if (isObject(verdict) && verdict.reserved === true)
2300
+ return typeof verdict.class === 'string' && CODE_PATTERN.test(verdict.class)
2301
+ ? verdict.class
2302
+ : RESERVE_OPAQUE;
2303
+ return RESERVE_OPAQUE;
2304
+ } catch {
2305
+ // A reserve that cannot answer reserves everything (fail closed).
2306
+ return RESERVE_OPAQUE;
2307
+ }
2308
+ }
2309
+
2310
+ /**
2311
+ * What the manager could not judge in full is reserved whatever the
2312
+ * classifier said: only command and file change requests are ever held, a
2313
+ * command must be readable and fit the request message uncut, and a file
2314
+ * change must name every path, each resolved to a real path.
2315
+ * @param {OpenApproval} entry
2316
+ * @param {ApprovalDescription | null} description
2317
+ * @param {string[] | null} realPaths
2318
+ * @returns {string | null}
2319
+ */
2320
+ function structuralReserve(entry, description, realPaths) {
2321
+ if (entry.kind !== 'command' && entry.kind !== 'fileChange') return RESERVE_PERMISSIONS;
2322
+ if (description === null || description.kind !== entry.kind) return RESERVE_OPAQUE;
2323
+ if (description.cwd !== null && description.cwd.length > PATH_LENGTH_MAX) return RESERVE_OPAQUE;
2324
+ if (entry.kind === 'command') {
2325
+ const command = description.command;
2326
+ if (command === null || command.length === 0 || command.length > LIMITS.commandTextMax)
2327
+ return RESERVE_OPAQUE;
2328
+ return null;
2329
+ }
2330
+ const filePaths = entry.filePaths;
2331
+ if (filePaths === null || filePaths.length === 0 || filePaths.length > APPROVAL_PATHS_MAX)
2332
+ return RESERVE_FILES;
2333
+ return realPaths === null || realPaths.length !== filePaths.length ? RESERVE_FILES : null;
2334
+ }
2335
+
2336
+ /**
2337
+ * @param {OpenApproval} entry
2338
+ * @param {ApprovalDescription | null} description
2339
+ */
2340
+ function requestText(entry, description) {
2341
+ if (entry.kind === 'fileChange') return (entry.filePaths ?? []).join('\n');
2342
+ if (entry.kind !== 'command') return '';
2343
+ if (description?.command !== null && description?.command !== undefined)
2344
+ return description.command;
2345
+ return typeof entry.params.command === 'string' ? entry.params.command : '';
2346
+ }
2347
+
2348
+ /**
2349
+ * @param {OpenApproval} entry
2350
+ * @param {ApprovalDescription | null} description
2351
+ * @returns {ApprovalSubject}
2352
+ */
2353
+ function subjectOf(entry, description) {
2354
+ const fileChange = entry.kind === 'fileChange';
2355
+ return {
2356
+ kind: fileChange ? 'fileChange' : 'command',
2357
+ command: fileChange ? null : (description?.command ?? null),
2358
+ cwd: description?.cwd ?? null,
2359
+ paths: fileChange ? entry.filePaths : null,
2360
+ changeBytes: fileChange ? entry.changeBytes : null,
2361
+ reason: typeof entry.params.reason === 'string' ? entry.params.reason : null,
2362
+ turnOrigin: originOfTurn(entry.turnId),
2363
+ };
2364
+ }
2365
+
2366
+ /**
2367
+ * Hold one request for the manager (FR13 step 1). The record lists the id
2368
+ * before the request reaches the manager's inbox, so that the manager never
2369
+ * reads a request as already ended.
2370
+ * @param {OpenApproval} entry
2371
+ * @param {Grant} grant
2372
+ * @param {ApprovalSubject} subject
2373
+ * @param {SessionRecord} manager
2374
+ */
2375
+ async function holdForManager(entry, grant, subject, manager) {
2376
+ const message = buildApprovalRequest({
2377
+ roomId: role.roomId,
2378
+ sender: self,
2379
+ approval: subject,
2380
+ now: now(),
2381
+ holdMs: LIMITS.holdMs,
2382
+ });
2383
+ entry.phase = 'held';
2384
+ entry.approvalId = message.id;
2385
+ entry.grantId = grant.grantId;
2386
+ entry.holdUntil = message.holdUntil;
2387
+ delegatedAt.push(now());
2388
+ entry.cancelTimer = schedule(() => onHoldTimeout(entry), boundedDelay(entry.holdUntil - now()));
2389
+ refresh();
2390
+ await awaitRecord();
2391
+ // Stopped or no longer the owner: the hold already went to the terminal.
2392
+ if (!isActive() || entry.phase !== 'held') return;
2393
+ // The server deletes a request the record does not list, and the manager
2394
+ // reads it as ended: the record read under the same lock as the delivery
2395
+ // must list the id.
2396
+ const delivered = await asOwner(async (record) =>
2397
+ entry.phase === 'held' && record.heldApprovals.includes(message.id)
2398
+ ? deliverMessage(paths, MANAGER_RECIPIENT, message)
2399
+ : null,
2400
+ );
2401
+ if (!delivered.ok || delivered.value === null) {
2402
+ forwardHeld(entry, 'escalated', CODES.deliveryFailed, CODES.deliveryFailed);
2403
+ return;
2404
+ }
2405
+ const bytes = delivered.value;
2406
+ await audit(
2407
+ paths,
2408
+ {
2409
+ event: 'approval_held',
2410
+ sessionId: self.sessionId,
2411
+ peerSessionId: manager.sessionId,
2412
+ messageId: message.id,
2413
+ kind: AUDIT_KINDS[entry.kind],
2414
+ bytes,
2415
+ },
2416
+ busClock,
2417
+ );
2418
+ }
2419
+
2420
+ /**
2421
+ * Decide where one approval request goes (FR13): the terminal without a live
2422
+ * grant, for the reserve, without a live manager or over the hourly limit;
2423
+ * otherwise it is held for the manager. Any failure sends it to the terminal.
2424
+ * @param {OpenApproval} entry
2425
+ */
2426
+ async function decideApproval(entry) {
2427
+ try {
2428
+ const grant = await readGrant(paths, self.sessionId, now()).catch(() => null);
2429
+ if (!isActive()) return;
2430
+ adoptGrant(grant);
2431
+ if (!isDeciding(entry)) return;
2432
+ if (grant === null) return sendToUser(entry);
2433
+ entry.grantId = grant.grantId;
2434
+ const description = await describeSafely(entry);
2435
+ entry.text = requestText(entry, description);
2436
+ const realPaths =
2437
+ entry.kind === 'fileChange' ? await realTargets(entry.filePaths, resolvePath) : null;
2438
+ const reserveClass =
2439
+ (await classifySafely(entry, realPaths)) ??
2440
+ structuralReserve(entry, description, realPaths);
2441
+ if (!isDeciding(entry)) return;
2442
+ if (reserveClass !== null) {
2443
+ sendToUser(entry);
2444
+ spawn(
2445
+ recordOutcome(entry, {
2446
+ outcome: 'reserved',
2447
+ reason: null,
2448
+ code: reserveClass,
2449
+ reserveClass,
2450
+ }),
2451
+ );
2452
+ return;
2453
+ }
2454
+ const manager = await liveManager(paths, busClock).catch(() => null);
2455
+ if (!isDeciding(entry)) return;
2456
+ if (manager === null || !withinHourlyLimit() || heldIds().length >= HELD_APPROVALS_MAX)
2457
+ return sendToUser(entry);
2458
+ // The grant may have ended or been replaced while the request was judged.
2459
+ if (grantAbsent() || knownGrant?.grantId !== grant.grantId) return sendToUser(entry);
2460
+ await holdForManager(entry, grant, subjectOf(entry, description), manager);
2461
+ } catch {
2462
+ if (isDeciding(entry)) sendToUser(entry);
2463
+ }
2464
+ }
2465
+
2466
+ /**
2467
+ * A permission request, or an approval method this client does not know, is
2468
+ * never held: it goes to the terminal at once, and under a live grant it is
2469
+ * recorded as reserved (criterion 25).
2470
+ * @param {OpenApproval} entry
2471
+ */
2472
+ async function recordReservedPermission(entry) {
2473
+ if (!isActive() || grantAbsent()) return;
2474
+ const grant = await readGrant(paths, self.sessionId, now()).catch(() => null);
2475
+ if (!isActive()) return;
2476
+ adoptGrant(grant);
2477
+ if (grant === null) return;
2478
+ entry.grantId = grant.grantId;
2479
+ await recordOutcome(entry, {
2480
+ outcome: 'reserved',
2481
+ reason: null,
2482
+ code: RESERVE_PERMISSIONS,
2483
+ reserveClass: RESERVE_PERMISSIONS,
2484
+ });
2485
+ }
2486
+
2487
+ /**
2488
+ * @param {Record<string, unknown>} message a server request
2489
+ * @param {OpenApproval['kind']} kind
2490
+ * @param {string} method
2491
+ * @param {unknown} line
2492
+ * @param {boolean} canHold the adapter would keep this line for the role
2493
+ */
2494
+ function openApproval(message, kind, method, line, canHold) {
2495
+ const key = requestKey(message.id);
2496
+ const requestId = message.id;
2497
+ if (key === null || (typeof requestId !== 'string' && typeof requestId !== 'number'))
2498
+ return true;
2499
+ if (approvals.has(key) || approvals.size >= OPEN_APPROVALS_MAX) return true;
2500
+ const params = isObject(message.params) ? message.params : {};
2501
+ const itemId = wireId(params.itemId);
2502
+ const change =
2503
+ kind === 'fileChange' && itemId !== null ? tracker.fileChange(itemId) : undefined;
2504
+ /** @type {OpenApproval} */
2505
+ const entry = {
2506
+ key,
2507
+ requestId,
2508
+ method,
2509
+ kind,
2510
+ threadId: wireId(params.threadId) ?? wireId(params.conversationId),
2511
+ turnId: wireId(params.turnId),
2512
+ itemId,
2513
+ params,
2514
+ line: typeof line === 'string' ? line : '',
2515
+ phase: 'user',
2516
+ since: now(),
2517
+ filePaths: change?.paths ?? null,
2518
+ changeBytes: change === undefined ? null : change.bytes,
2519
+ approvalId: null,
2520
+ grantId: null,
2521
+ holdUntil: 0,
2522
+ text: '',
2523
+ cancelTimer: null,
2524
+ verdict: null,
2525
+ decisionReason: null,
2526
+ };
2527
+ approvals.set(key, entry);
2528
+ // The thread the adapter files the line under: its own check reads `params.threadId` only.
2529
+ const heldThreadId = wireId(params.threadId);
2530
+ const delegable =
2531
+ canHold &&
2532
+ typeof line === 'string' &&
2533
+ HOLDABLE_METHODS.has(method) &&
2534
+ heldThreadId !== null &&
2535
+ isActive() &&
2536
+ !grantAbsent() &&
2537
+ !adapterHeld.has(key) &&
2538
+ adapterHeld.size < ADAPTER_HELD_MAX;
2539
+ if (!delegable) {
2540
+ // Exactly today's pass-through: the adapter forwards the line itself.
2541
+ noteUserWait(entry);
2542
+ refresh();
2543
+ if (kind === 'permissions' || kind === 'unknown') spawn(recordReservedPermission(entry));
2544
+ return true;
2545
+ }
2546
+ adapterHeld.set(key, heldThreadId);
2547
+ entry.phase = 'deciding';
2548
+ refresh();
2549
+ spawn(decideApproval(entry));
2550
+ return false;
2551
+ }
2552
+
2553
+ // ---- the adapter's calls --------------------------------------------------
2554
+
2555
+ /**
2556
+ * The adapter writes the frame after this returns: nothing here calls the
2557
+ * port synchronously (a delivery runs after an `await`; an answer waiting
2558
+ * for the line boundary runs from its timer).
2559
+ * @param {unknown} message
2560
+ */
2561
+ function onClientMessage(message) {
2562
+ try {
2563
+ if (stopped || !isObject(message)) return;
2564
+ react(tracker.client(message));
2565
+ kick();
2566
+ } catch {
2567
+ // Observation only: a frame the role cannot read changes nothing.
2568
+ }
2569
+ }
2570
+
2571
+ /**
2572
+ * @param {unknown} message
2573
+ * @param {string} line
2574
+ * @param {{ canHold?: boolean }} [options] from the adapter: `canHold` false means it will forward this line whatever the role returns. Without the argument it would hold
2575
+ */
2576
+ function onServerMessage(message, line, options) {
2577
+ try {
2578
+ if (stopped || !isObject(message)) return true;
2579
+ // Read once; anything but an explicit `true` is a no.
2580
+ const canHold = options === undefined || (isObject(options) && options.canHold === true);
2581
+ react(tracker.server(message));
2582
+ const method = message.method;
2583
+ if (typeof method !== 'string' || message.id === undefined) return true;
2584
+ const kind = approvalKindOf(method);
2585
+ return kind === null ? true : openApproval(message, kind, method, line, canHold);
2586
+ } catch {
2587
+ return true;
2588
+ }
2589
+ }
2590
+
2591
+ /** Takes the thread id of the WorkerRole contract; every delivery re-reads the whole gate. */
2592
+ function onAdapterIdle() {
2593
+ try {
2594
+ // The adapter's lifecycle that refused the last `turn/start` ended.
2595
+ gateRefused = false;
2596
+ kick();
2597
+ } catch {
2598
+ // A delivery is tried again at the next frame.
2599
+ }
2600
+ }
2601
+
2602
+ /** Every watch event checks first that this adapter still owns the session (FR2). */
2603
+ async function onWatchEvent() {
2604
+ if (!isActive()) return;
2605
+ const record = await readSession(paths, self.sessionId);
2606
+ if (!isActive()) return;
2607
+ const verdict = ownershipOf(record);
2608
+ if (verdict !== 'owner') {
2609
+ deactivate(verdict);
2610
+ return;
2611
+ }
2612
+ spawn(scan());
2613
+ spawn(refreshGrant());
2614
+ }
2615
+
2616
+ /** The watch's change callback: it never throws into the watcher. */
2617
+ function onWatch() {
2618
+ try {
2619
+ spawn(onWatchEvent());
2620
+ } catch {
2621
+ // Contained: the next event reads the directories again.
2622
+ }
2623
+ }
2624
+
2625
+ /** Arm the role. It touches nothing on the bus until it activates (FR2). */
2626
+ async function start() {
2627
+ try {
2628
+ if (armed || stopped) return;
2629
+ armed = true;
2630
+ stateSince = now();
2631
+ // A thread the terminal opened before `start()` ran.
2632
+ if (currentThreadId !== null) activateSoon();
2633
+ } catch {
2634
+ // Never rejects: the next thread open activates the role.
2635
+ }
2636
+ }
2637
+
2638
+ // ---- stop -----------------------------------------------------------------
2639
+
2640
+ function cancelTimers() {
2641
+ for (const name of /** @type {const} */ ([
2642
+ 'expiry',
2643
+ 'grant',
2644
+ 'retry',
2645
+ 'answers',
2646
+ 'boundary',
2647
+ 'activate',
2648
+ ])) {
2649
+ timers[name]?.();
2650
+ timers[name] = null;
2651
+ }
2652
+ for (const entry of approvals.values()) clearTimer(entry);
2653
+ if (running !== null) cancelWaits(running);
2654
+ for (const cancel of settling.values()) cancel();
2655
+ settling.clear();
2656
+ }
2657
+
2658
+ /** Every approval the terminal has not seen goes to it (FR13: `stop()` forwards). */
2659
+ function releaseApprovals() {
2660
+ for (const entry of [...approvals.values()]) {
2661
+ if (entry.phase === 'deciding') {
2662
+ entry.phase = 'user';
2663
+ forwardEntry(entry);
2664
+ } else forwardHeld(entry, 'escalated', CODES.workerStopped, CODES.workerStopped);
2665
+ }
2666
+ }
2667
+
2668
+ /** @returns {Promise<QueuedEntry[]>} valid requests that arrived but were not indexed yet */
2669
+ async function claimUnindexed() {
2670
+ const { names } = await listMailbox(paths, 'inbox', self.sessionId);
2671
+ if (names.length === 0) return [];
2672
+ const manager = await liveManager(paths, busClock).catch(() => null);
2673
+ /** @type {QueuedEntry[]} */
2674
+ const claimed = [];
2675
+ for (const name of names) {
2676
+ const file = await readMailboxFile(paths, 'inbox', self.sessionId, name);
2677
+ if (unreadForNow(file)) continue;
2678
+ const checked = checkFile(file, manager);
2679
+ if (!checked.ok) await rejectInbox(name, checked.reason, checked.bytes);
2680
+ else if (checked.message.kind !== 'request')
2681
+ await rejectInbox(name, CODES.workerClosed, file.ok ? file.bytes : 0);
2682
+ else if (await claimMailboxFile(paths, self.sessionId, name))
2683
+ claimed.push({ name, message: checked.message });
2684
+ }
2685
+ return claimed;
2686
+ }
2687
+
2688
+ const WORKER_CLOSED = { outcome: /** @type {const} */ ('worker_closed'), code: null, text: '' };
2689
+
2690
+ /** `worker_closed` for the role's own running turn: this app-server is exiting. */
2691
+ async function closeRunning() {
2692
+ const turn = running !== null && !running.done ? running : null;
2693
+ running = null;
2694
+ if (turn === null) return;
2695
+ turn.done = true;
2696
+ cancelWaits(turn);
2697
+ await sendReply(turn, { ...WORKER_CLOSED, shared: turn.shared }, 'replied');
2698
+ }
2699
+
2700
+ /** `worker_closed` for each queued and running request (FR4 step 7). */
2701
+ async function closeDeliveries() {
2702
+ /** @type {QueuedEntry[]} */
2703
+ const closing = staged === null ? [] : [staged];
2704
+ staged = null;
2705
+ for (const entry of sortedQueue()) {
2706
+ queued.delete(entry.name);
2707
+ if (await claimMailboxFile(paths, self.sessionId, entry.name)) closing.push(entry);
2708
+ }
2709
+ closing.push(...(await claimUnindexed()));
2710
+ await closeRunning();
2711
+ for (const entry of closing)
2712
+ await sendReply(entry, { ...WORKER_CLOSED, shared: false }, 'replied');
2713
+ }
2714
+
2715
+ /** Remove the session, under the room's lock, only while the record still names this adapter. */
2716
+ async function removeAsOwner() {
2717
+ await withRoomLock(
2718
+ paths,
2719
+ async () => {
2720
+ if (ownershipOf(await readSession(paths, self.sessionId)) === 'owner')
2721
+ await removeSession(paths, self.sessionId, 'worker');
2722
+ },
2723
+ lockClock,
2724
+ ).catch(() => undefined);
2725
+ }
2726
+
2727
+ /**
2728
+ * The owner closes what it queued, forwards what it holds and removes the
2729
+ * session. A role that lost the session (or never had it) touches nothing
2730
+ * of it: it forwards what it holds and answers only its own running turn.
2731
+ */
2732
+ async function stopNow() {
2733
+ stopped = true;
2734
+ cancelTimers();
2735
+ stopWatch?.();
2736
+ stopWatch = null;
2737
+ // An activation in flight decides who owns the session.
2738
+ await drainTasks();
2739
+ if (owner === 'dormant') return;
2740
+ if (owner === 'active') {
2741
+ const verdict = ownershipOf(await readSession(paths, self.sessionId));
2742
+ if (verdict !== 'owner') owner = verdict;
2743
+ }
2744
+ releaseApprovals();
2745
+ await drainTasks();
2746
+ if (owner !== 'active') {
2747
+ const unstarted = staged;
2748
+ staged = null;
2749
+ if (unstarted !== null) await returnToInbox(unstarted);
2750
+ await closeRunning();
2751
+ return;
2752
+ }
2753
+ await closeDeliveries();
2754
+ await awaitRecord();
2755
+ await removeAsOwner();
2756
+ }
2757
+
2758
+ function stop() {
2759
+ stopping ??= stopNow().catch(() => undefined);
2760
+ return stopping;
2761
+ }
2762
+
2763
+ return { start, onClientMessage, onServerMessage, onAdapterIdle, stop, settled };
2764
+ }
2765
+
2766
+ /**
2767
+ * The role the launcher gave this process, or null without one (D2: a session
2768
+ * launched without `--worker` accepts nothing). Never throws.
2769
+ * @param {Record<string, string | undefined>} env
2770
+ * @param {AdapterPort} port
2771
+ * @param {Partial<Omit<WorkerRoleOptions, 'role' | 'port'>>} [options]
2772
+ * @returns {WorkerRole | null}
2773
+ */
2774
+ export function createWorkerRoleFromEnvironment(env, port, options = {}) {
2775
+ try {
2776
+ const role = parseRoleEnvironment(env[WORKER_ROLE_ENV], 'worker');
2777
+ if (role === null) return null;
2778
+ const home = options.home ?? homedir();
2779
+ // The adapter passes CODEX_HOME with the role variable; the process's own
2780
+ // value is the fallback. Either names a host config directory the reserve protects.
2781
+ const codexHome = env.CODEX_HOME ?? process.env.CODEX_HOME;
2782
+ return createWorkerRole({
2783
+ ...options,
2784
+ role,
2785
+ port,
2786
+ cwd: options.cwd ?? process.cwd(),
2787
+ home,
2788
+ hostConfigDirs: options.hostConfigDirs ?? defaultHostConfigDirs(home, codexHome),
2789
+ });
2790
+ } catch {
2791
+ return null;
2792
+ }
2793
+ }