rookery-agent 0.2.0 → 0.3.0

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 (159) hide show
  1. package/README.md +4 -4
  2. package/package.json +3 -1
  3. package/packages/cli/dist/commands/tasks.js +1 -1
  4. package/packages/cli/dist/commands/tasks.js.map +1 -1
  5. package/packages/cli/package.json +1 -1
  6. package/packages/core/dist/agents/persona.js +1 -1
  7. package/packages/core/dist/agents/persona.js.map +1 -1
  8. package/packages/core/dist/config.d.ts +34 -1
  9. package/packages/core/dist/config.d.ts.map +1 -1
  10. package/packages/core/dist/config.js +79 -2
  11. package/packages/core/dist/config.js.map +1 -1
  12. package/packages/core/dist/cron/scheduler.d.ts +10 -3
  13. package/packages/core/dist/cron/scheduler.d.ts.map +1 -1
  14. package/packages/core/dist/cron/scheduler.js +38 -13
  15. package/packages/core/dist/cron/scheduler.js.map +1 -1
  16. package/packages/core/dist/gateway/policy.d.ts +20 -3
  17. package/packages/core/dist/gateway/policy.d.ts.map +1 -1
  18. package/packages/core/dist/gateway/policy.js +18 -2
  19. package/packages/core/dist/gateway/policy.js.map +1 -1
  20. package/packages/core/dist/index.d.ts +4 -4
  21. package/packages/core/dist/index.d.ts.map +1 -1
  22. package/packages/core/dist/index.js +3 -3
  23. package/packages/core/dist/index.js.map +1 -1
  24. package/packages/core/dist/memory/db.d.ts +1 -1
  25. package/packages/core/dist/memory/db.d.ts.map +1 -1
  26. package/packages/core/dist/memory/db.js +138 -1
  27. package/packages/core/dist/memory/db.js.map +1 -1
  28. package/packages/core/dist/org/controller.d.ts +98 -113
  29. package/packages/core/dist/org/controller.d.ts.map +1 -1
  30. package/packages/core/dist/org/controller.js +679 -726
  31. package/packages/core/dist/org/controller.js.map +1 -1
  32. package/packages/core/dist/org/prompts.d.ts +17 -16
  33. package/packages/core/dist/org/prompts.d.ts.map +1 -1
  34. package/packages/core/dist/org/prompts.js +76 -146
  35. package/packages/core/dist/org/prompts.js.map +1 -1
  36. package/packages/core/dist/org/store.d.ts +67 -5
  37. package/packages/core/dist/org/store.d.ts.map +1 -1
  38. package/packages/core/dist/org/store.js +202 -8
  39. package/packages/core/dist/org/store.js.map +1 -1
  40. package/packages/core/dist/org/tools.d.ts +9 -3
  41. package/packages/core/dist/org/tools.d.ts.map +1 -1
  42. package/packages/core/dist/org/tools.js +59 -35
  43. package/packages/core/dist/org/tools.js.map +1 -1
  44. package/packages/core/dist/providers/claude-code.d.ts +2 -1
  45. package/packages/core/dist/providers/claude-code.d.ts.map +1 -1
  46. package/packages/core/dist/providers/claude-code.js +21 -10
  47. package/packages/core/dist/providers/claude-code.js.map +1 -1
  48. package/packages/core/dist/providers/claude-tui.d.ts +120 -7
  49. package/packages/core/dist/providers/claude-tui.d.ts.map +1 -1
  50. package/packages/core/dist/providers/claude-tui.js +476 -41
  51. package/packages/core/dist/providers/claude-tui.js.map +1 -1
  52. package/packages/core/dist/runtime.d.ts +64 -12
  53. package/packages/core/dist/runtime.d.ts.map +1 -1
  54. package/packages/core/dist/runtime.js +520 -150
  55. package/packages/core/dist/runtime.js.map +1 -1
  56. package/packages/core/dist/types.d.ts +191 -13
  57. package/packages/core/dist/types.d.ts.map +1 -1
  58. package/packages/core/dist/types.js.map +1 -1
  59. package/packages/core/package.json +1 -1
  60. package/packages/server/dist/context.d.ts.map +1 -1
  61. package/packages/server/dist/context.js +11 -2
  62. package/packages/server/dist/context.js.map +1 -1
  63. package/packages/server/dist/gateways/push.d.ts.map +1 -1
  64. package/packages/server/dist/gateways/push.js +135 -69
  65. package/packages/server/dist/gateways/push.js.map +1 -1
  66. package/packages/server/dist/gateways/telegram.d.ts +31 -8
  67. package/packages/server/dist/gateways/telegram.d.ts.map +1 -1
  68. package/packages/server/dist/gateways/telegram.js +148 -47
  69. package/packages/server/dist/gateways/telegram.js.map +1 -1
  70. package/packages/server/dist/gateways/threads.d.ts +6 -1
  71. package/packages/server/dist/gateways/threads.d.ts.map +1 -1
  72. package/packages/server/dist/gateways/threads.js +21 -11
  73. package/packages/server/dist/gateways/threads.js.map +1 -1
  74. package/packages/server/dist/routes/config.d.ts.map +1 -1
  75. package/packages/server/dist/routes/config.js +27 -0
  76. package/packages/server/dist/routes/config.js.map +1 -1
  77. package/packages/server/dist/routes/org.d.ts.map +1 -1
  78. package/packages/server/dist/routes/org.js +68 -64
  79. package/packages/server/dist/routes/org.js.map +1 -1
  80. package/packages/server/dist/routes/ws.d.ts.map +1 -1
  81. package/packages/server/dist/routes/ws.js +13 -7
  82. package/packages/server/dist/routes/ws.js.map +1 -1
  83. package/packages/server/dist/schemas.d.ts +116 -68
  84. package/packages/server/dist/schemas.d.ts.map +1 -1
  85. package/packages/server/dist/schemas.js +34 -17
  86. package/packages/server/dist/schemas.js.map +1 -1
  87. package/packages/server/dist/server.d.ts.map +1 -1
  88. package/packages/server/dist/server.js +28 -4
  89. package/packages/server/dist/server.js.map +1 -1
  90. package/packages/server/dist/services/stream.d.ts +9 -4
  91. package/packages/server/dist/services/stream.d.ts.map +1 -1
  92. package/packages/server/dist/services/stream.js.map +1 -1
  93. package/packages/server/dist/services/turns.d.ts +5 -0
  94. package/packages/server/dist/services/turns.d.ts.map +1 -1
  95. package/packages/server/dist/services/turns.js +48 -0
  96. package/packages/server/dist/services/turns.js.map +1 -1
  97. package/packages/server/package.json +1 -1
  98. package/packages/web/dist/assets/{abnfDiagram-O67JEVCF-B4qWcqra.js → abnfDiagram-O67JEVCF-D7YyFndQ.js} +1 -1
  99. package/packages/web/dist/assets/{arc-CQult7TN.js → arc-C_Zgk2dJ.js} +1 -1
  100. package/packages/web/dist/assets/{architectureDiagram-NJMV4G6O-DFTRvl66.js → architectureDiagram-NJMV4G6O-eI0adu1B.js} +1 -1
  101. package/packages/web/dist/assets/{blockDiagram-BEXU5L5S-TCFoK_k-.js → blockDiagram-BEXU5L5S-WAoOFUA9.js} +1 -1
  102. package/packages/web/dist/assets/{c4Diagram-YGBWAQC7-i5_GqhJa.js → c4Diagram-YGBWAQC7-DE8Zyhng.js} +1 -1
  103. package/packages/web/dist/assets/channel-egZxcyUK.js +1 -0
  104. package/packages/web/dist/assets/{chunk-2Q5K7J3B-BK6I2wfW.js → chunk-2Q5K7J3B-bnqLP2XD.js} +1 -1
  105. package/packages/web/dist/assets/{chunk-3FUC2YCW-Dw-TfKT0.js → chunk-3FUC2YCW-Ck1_SVe0.js} +2 -2
  106. package/packages/web/dist/assets/{chunk-5VM5RSS4-AE_XRNTT.js → chunk-5VM5RSS4-hDmC41gD.js} +1 -1
  107. package/packages/web/dist/assets/{chunk-GTNCS2PH-DO18WaaJ.js → chunk-GTNCS2PH-PoWvfCrT.js} +1 -1
  108. package/packages/web/dist/assets/{chunk-GWA4HPMP-3rdjszP_.js → chunk-GWA4HPMP-D3V0IG43.js} +1 -1
  109. package/packages/web/dist/assets/{chunk-JWPE2WC7-C93LH2D0.js → chunk-JWPE2WC7-BryfpHM5.js} +1 -1
  110. package/packages/web/dist/assets/{chunk-NETBCI7D-Dj7O3-H-.js → chunk-NETBCI7D-8ic1iEdT.js} +1 -1
  111. package/packages/web/dist/assets/{chunk-WEXAMYUT-BRFvQUIn.js → chunk-WEXAMYUT-nM8tmQT2.js} +1 -1
  112. package/packages/web/dist/assets/{chunk-XXDRQBXY-CXx6HMbz.js → chunk-XXDRQBXY-Do28F482.js} +1 -1
  113. package/packages/web/dist/assets/{classDiagram-v2-NBCMYWYE-BGXszxjn.js → classDiagram-v2-NBCMYWYE-Bop9oNNO.js} +1 -1
  114. package/packages/web/dist/assets/{cose-bilkent-JH36ORCC-BAuXqkne.js → cose-bilkent-JH36ORCC-a7f_bpnt.js} +1 -1
  115. package/packages/web/dist/assets/{cynefin-OW5HDTMX-plNzhY7J.js → cynefin-OW5HDTMX-DnArcis_.js} +1 -1
  116. package/packages/web/dist/assets/{cynefinDiagram-VND7K2PF-DuPlljFS.js → cynefinDiagram-VND7K2PF-vEuTb1GD.js} +1 -1
  117. package/packages/web/dist/assets/{dagre-6A5THRUB-CXzwdR-6.js → dagre-6A5THRUB-BgG4MynJ.js} +1 -1
  118. package/packages/web/dist/assets/{diagram-22UHCM2B-B7iv_V2D.js → diagram-22UHCM2B-DRCQpafv.js} +1 -1
  119. package/packages/web/dist/assets/{diagram-3UASUU5V-BMvi7gSi.js → diagram-3UASUU5V-BKgmAXde.js} +1 -1
  120. package/packages/web/dist/assets/{diagram-ATOU4E4O-NJ7EB5Qg.js → diagram-ATOU4E4O-B6Hsy36X.js} +1 -1
  121. package/packages/web/dist/assets/{diagram-CDSNMT55-DccMMNJ-.js → diagram-CDSNMT55-JflyfyoB.js} +1 -1
  122. package/packages/web/dist/assets/{diagram-MLGK6HIB-BbwGHK4g.js → diagram-MLGK6HIB-Dd2QPJjT.js} +1 -1
  123. package/packages/web/dist/assets/{diagram-MPIPVDR6-BbSSZfM3.js → diagram-MPIPVDR6-DE5QU60x.js} +1 -1
  124. package/packages/web/dist/assets/{ebnfDiagram-ZINNZB2B-BBfPNM85.js → ebnfDiagram-ZINNZB2B-D7AQ741b.js} +1 -1
  125. package/packages/web/dist/assets/{elk-276RUBZZ-dM3Y1d2a.js → elk-276RUBZZ-CeewBVLF.js} +1 -1
  126. package/packages/web/dist/assets/{erDiagram-OPXOYQCR-iWrUegxy.js → erDiagram-OPXOYQCR-mLLYkZ5c.js} +1 -1
  127. package/packages/web/dist/assets/{flowDiagram-KWPJA3E3-B6DYlbkV.js → flowDiagram-KWPJA3E3-DtpSpsQN.js} +1 -1
  128. package/packages/web/dist/assets/{ganttDiagram-FUAMR5RP-D7dSWZcC.js → ganttDiagram-FUAMR5RP-1_lh-3ky.js} +1 -1
  129. package/packages/web/dist/assets/{gitGraphDiagram-X574FWY7-DguFgcbW.js → gitGraphDiagram-X574FWY7-DoPXZuT5.js} +1 -1
  130. package/packages/web/dist/assets/index-Cw2Opmx7.js +648 -0
  131. package/packages/web/dist/assets/index-j0zBRCgT.css +32 -0
  132. package/packages/web/dist/assets/{infoDiagram-VRGFBTTK-CuiuO3uo.js → infoDiagram-VRGFBTTK-DQpRGGiD.js} +1 -1
  133. package/packages/web/dist/assets/{ishikawaDiagram-OU5B5YK6-wBS1_40m.js → ishikawaDiagram-OU5B5YK6-gH5C9Q2e.js} +1 -1
  134. package/packages/web/dist/assets/{journeyDiagram-ZHPQQLJL-Bd1YE2gP.js → journeyDiagram-ZHPQQLJL-Bg-oeFjb.js} +1 -1
  135. package/packages/web/dist/assets/{kanban-definition-PNTS6WVX-BlQzv_X1.js → kanban-definition-PNTS6WVX-BnpI4VH8.js} +1 -1
  136. package/packages/web/dist/assets/{mermaid.core-p3CwmLUb.js → mermaid.core-BwBKxlRA.js} +4 -4
  137. package/packages/web/dist/assets/{mindmap-definition-NLK3R4M7-BlticnKl.js → mindmap-definition-NLK3R4M7-NBnnxEoO.js} +1 -1
  138. package/packages/web/dist/assets/{pegDiagram-GJSIUBJH-BbXsP47B.js → pegDiagram-GJSIUBJH-RrXXbIvO.js} +1 -1
  139. package/packages/web/dist/assets/{pieDiagram-5QR66LMP-BooBSBug.js → pieDiagram-5QR66LMP-B27q6Gso.js} +1 -1
  140. package/packages/web/dist/assets/{quadrantDiagram-O4NWA36T-CkXC6VCh.js → quadrantDiagram-O4NWA36T-DGDsdur2.js} +1 -1
  141. package/packages/web/dist/assets/{railroadDiagram-XR7U4H2S-BphzYiW-.js → railroadDiagram-XR7U4H2S-GdjkE3mI.js} +1 -1
  142. package/packages/web/dist/assets/{requirementDiagram-PLB6GJNP-PWpD4zpQ.js → requirementDiagram-PLB6GJNP-DjK0GfgO.js} +1 -1
  143. package/packages/web/dist/assets/{sankeyDiagram-IPEJSGJF-5Qm39Vfz.js → sankeyDiagram-IPEJSGJF-BG_AIkwF.js} +1 -1
  144. package/packages/web/dist/assets/{sequenceDiagram-PO4LG4MO-DA673J_w.js → sequenceDiagram-PO4LG4MO-CIQwUb4y.js} +1 -1
  145. package/packages/web/dist/assets/{sizeCapture-INFHLROL-1KsNwBhd.js → sizeCapture-INFHLROL-bpIoPxdJ.js} +1 -1
  146. package/packages/web/dist/assets/{stateDiagram-v2-GCMORJYK-D7O0UyHr.js → stateDiagram-v2-GCMORJYK-8hYXvPPv.js} +1 -1
  147. package/packages/web/dist/assets/{swimlanes-2SLR337P-culFSb1R.js → swimlanes-2SLR337P-gfflUMF9.js} +1 -1
  148. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-9wdzGXU-.js +8 -0
  149. package/packages/web/dist/assets/{timeline-definition-EJHVYXUP-6GIO5p-k.js → timeline-definition-EJHVYXUP-PHMNoGTZ.js} +1 -1
  150. package/packages/web/dist/assets/{usecaseDiagram-POWQR4AR-BAGHDBzZ.js → usecaseDiagram-POWQR4AR-B2j5iteO.js} +1 -1
  151. package/packages/web/dist/assets/{vennDiagram-UO4OBE2U-PbtBvPRE.js → vennDiagram-UO4OBE2U-BzxtZ-_2.js} +1 -1
  152. package/packages/web/dist/assets/{wardleyDiagram-VNRHLVJA-9scbtDvX.js → wardleyDiagram-VNRHLVJA-DL7YbMpY.js} +1 -1
  153. package/packages/web/dist/assets/{xychartDiagram-PMCCYNJV-C51PiF4p.js → xychartDiagram-PMCCYNJV-CisgP1cT.js} +1 -1
  154. package/packages/web/dist/index.html +2 -2
  155. package/packages/web/package.json +1 -1
  156. package/packages/web/dist/assets/channel-D_4EmqNR.js +0 -1
  157. package/packages/web/dist/assets/index-B1QvSHA5.js +0 -660
  158. package/packages/web/dist/assets/index-zwMuaz90.css +0 -32
  159. package/packages/web/dist/assets/swimlanesDiagram-TC7HE7FX-kzTmK2BP.js +0 -8
@@ -10,6 +10,8 @@ import { isUsageLimitError, providerBlocked, providerLow, rememberUsageFailure }
10
10
  import { sharedCodexBridge } from './providers/codex-bridge.js';
11
11
  import { tuiSessions } from './providers/claude-tui.js';
12
12
  import { ModelGateway } from './providers/model-gateway.js';
13
+ import { loadPty } from './providers/claude-tui.js';
14
+ import { renderMemoryBlock } from './memory/recall.js';
13
15
  import { Store } from './memory/store.js';
14
16
  import { byScoreThenId, coreProfile, dropContradicted, recall } from './memory/recall.js';
15
17
  import { fetchFrame } from './memory/dream/frame.js';
@@ -21,7 +23,7 @@ import { admitCandidates, linkEntities } from './memory/gate.js';
21
23
  import { SleepRunner } from './memory/sleep.js';
22
24
  import { buildSystemPrompt, deriveTitle } from './agents/persona.js';
23
25
  import { BridgeServer } from './org/bridge.js';
24
- import { OrgController } from './org/controller.js';
26
+ import { OrgController, taskNotification } from './org/controller.js';
25
27
  import { QuestionRegistry } from './org/questions.js';
26
28
  import { assistantOrgBlock } from './org/prompts.js';
27
29
  import { dormantToolsHint, externalTurnExtras, toolServersFor } from './tools/hub.js';
@@ -92,11 +94,13 @@ const BOARD_WATCH_SCHEDULE = '*/30 * * * *';
92
94
  const BOARD_WATCH_PROMPT = 'Watch the board and report what needs a person. Check list_tasks for anything failed, and for ' +
93
95
  'anything running far longer than it should. You are a backstop, not a worker: you cannot start, ' +
94
96
  'reassign, restart or close anything, and that is deliberate - deciding what to do about what you ' +
95
- 'find belongs to the user. Mail the user at most once per pass, and only when something truly ' +
96
- 'needs a human decision: say what you saw, how long it has been that way, and what you would ' +
97
- 'suggest. A task waiting on an answer is working as intended, not a fault, and never a reason to ' +
98
- 'write. If none of what you were shown is worth interrupting somebody over, do not report that ' +
99
- 'everything is fine - answer with exactly [SILENT] instead.';
97
+ 'find belongs to the user. Leave the user one report with report_to_user at most once per pass, ' +
98
+ 'and only when something truly needs a human decision: say what you saw, how long it has been ' +
99
+ 'that way, and what you would suggest. Once you have, answer with exactly [SILENT], so the same ' +
100
+ 'thing does not reach them a second time as this run\'s outcome. A task waiting on an answer is ' +
101
+ 'working as intended, not a fault, and never a reason to write. If none of what you were shown ' +
102
+ 'is worth interrupting somebody over, do not report that everything is fine - answer with ' +
103
+ 'exactly [SILENT] instead.';
100
104
  /** Add up what two passes of one turn cost; the last pass owns the context gauge. */
101
105
  function mergeUsage(base, next) {
102
106
  if (!base)
@@ -178,6 +182,10 @@ function declaredDreamBox(policy, limitMax) {
178
182
  minImportance: policy.minImportance,
179
183
  };
180
184
  }
185
+ /** Where the rights a conversation was last used with are kept. */
186
+ function sessionPermissionKey(sessionId) {
187
+ return 'session:permission:' + sessionId;
188
+ }
181
189
  /** The terminal registry's key for a conversation - runs use their assignment id. */
182
190
  export function conversationTerminalKey(sessionId) {
183
191
  return 'chat:' + sessionId;
@@ -218,6 +226,18 @@ export class Assistant extends EventEmitter {
218
226
  * a blocked recipient or a channel that was switched off mid-session.
219
227
  */
220
228
  notifyProbe;
229
+ /** Takes over report-back turns so people can watch them; see `TurnRunner`. */
230
+ turnRunner;
231
+ /**
232
+ * The turn each conversation is running or waiting to run, chained: one
233
+ * conversation answers one message at a time. A report-back arriving while
234
+ * the user's own message is being answered waits its turn instead of
235
+ * talking over it - and a conversation's terminal could not take two at
236
+ * once anyway.
237
+ */
238
+ #sessionTurns = new Map();
239
+ /** Conversation terminals by session id (T1). */
240
+ #chatTerminals = new Map();
221
241
  /**
222
242
  * The last status seen for a task, by id - only so the board-watch
223
243
  * subscriber can tell a fresh landing in `failed` apart from an unrelated
@@ -250,9 +270,14 @@ export class Assistant extends EventEmitter {
250
270
  runner: (job, run, signal) => this.#runScheduled(job, run, signal),
251
271
  logger: this.log,
252
272
  timeoutMs: this.config.org.assignmentTimeoutMs,
273
+ // A run's outcome goes the one road to the user. A closure, because
274
+ // the controller is built below; no run can end before it exists.
275
+ notify: (input) => {
276
+ this.org.notifyUser(input);
277
+ },
253
278
  });
254
279
  // Before the controller: the `sleep_now` tool needs it at construction.
255
- // The promotion hook is a closure rather than `this.org.sendUserMail`
280
+ // The promotion hook is a closure rather than `this.org.notifyUser`
256
281
  // itself for exactly that reason - the controller does not exist yet
257
282
  // here, and it does by the time a night can promote anything.
258
283
  this.sleep = new SleepRunner({
@@ -260,7 +285,7 @@ export class Assistant extends EventEmitter {
260
285
  registry: this.providers,
261
286
  config: this.config,
262
287
  logger: this.log,
263
- onPromotion: (notice) => this.#announcePromotion(notice),
288
+ onPromotion: (notice) => this.announcePromotion(notice),
264
289
  });
265
290
  // Before the controller, like the night shift: the `ask_user` tool needs
266
291
  // it at construction. Its own emitter is what the Assistant re-broadcasts:
@@ -287,11 +312,12 @@ export class Assistant extends EventEmitter {
287
312
  // a channel that drops the message. Whoever hosts the runtime sets
288
313
  // `notifyProbe` to the honest test.
289
314
  canNotify: () => (this.notifyProbe ? this.notifyProbe() : this.listenerCount('notify') > 0),
290
- runAssistantMail: (input) => this.#answerMail(input.mail, input.senderLabel, input.thread),
291
315
  });
292
316
  this.cron.on('cron', (event) => this.emit('cron', event));
293
317
  this.cron.on('message', (event) => this.emit('message', event));
294
- this.cron.on('mail', (event) => this.emit('mail', event));
318
+ // Only a scheduler without the `notify` hook emits this itself; wired
319
+ // anyway so an outcome can never be written without being announced.
320
+ this.cron.on('notification', (event) => this.emit('notification', event));
295
321
  // Every client watches the brain fall asleep and wake up again.
296
322
  this.sleep.on('sleep', (event) => this.emit('sleep', event));
297
323
  // Anything an agent does is interesting to every client, not only the
@@ -302,7 +328,11 @@ export class Assistant extends EventEmitter {
302
328
  // sockets, never a blanket fan-out.
303
329
  this.org.on('assignment-log', (frame) => this.emit('assignment-log', frame));
304
330
  this.org.on('message', (event) => this.emit('message', event));
305
- this.org.on('mail', (event) => this.emit('mail', event));
331
+ // Everything that reaches the user outside a conversation, and every
332
+ // line added to a card's activity - the two carriers that replaced mail
333
+ // (docs/concepts/mail-removal-notifications-and-task-activity.md).
334
+ this.org.on('notification', (event) => this.emit('notification', event));
335
+ this.org.on('task-event', (event) => this.emit('task-event', event));
306
336
  this.org.on('task', (event) => this.emit('task', event));
307
337
  // The watcher's fast path (section 5): a task landing in `failed` or
308
338
  // `blocked` wakes it through the same event machinery a webhook or an
@@ -313,6 +343,108 @@ export class Assistant extends EventEmitter {
313
343
  // Telegram here, just an event a channel in another package can listen
314
344
  // for and act on however it likes.
315
345
  this.org.on('notify', (event) => this.emit('notify', event));
346
+ // Work handed off in the background has ended: the conversation that
347
+ // handed it off hears about it as a turn of its own (R2/R3).
348
+ this.org.on('report-back', (event) => this.#onReportBack(event));
349
+ }
350
+ /* --------------------------- report-back --------------------------- */
351
+ #onReportBack(event) {
352
+ const session = this.store.getSession(event.sessionId);
353
+ // A scheduled run has nobody reading along, and a conversation that was
354
+ // deleted has nobody at all. The ending still belongs to somebody, and
355
+ // the only one left is the user: it goes to them as a notification
356
+ // instead of a turn nobody would see - a question most of all.
357
+ if (!session || (session.kind !== 'chat' && session.kind !== 'voice')) {
358
+ const task = this.store.org.getTask(event.taskId);
359
+ if (!task)
360
+ return;
361
+ const agent = task.assigneeId ? this.store.org.getAgent(task.assigneeId) : null;
362
+ const question = task.status === 'blocked' ? this.store.org.lastTaskEvent(task.id, 'question') : null;
363
+ this.org.notifyUser({
364
+ orgId: task.orgId,
365
+ ...taskNotification(task, agent, question?.text),
366
+ ...(session ? { sessionId: session.id } : {}),
367
+ });
368
+ return;
369
+ }
370
+ // Archived while the work ran: bringing it back is better than burying
371
+ // the answer where nobody looks.
372
+ if (session.archived)
373
+ this.store.updateSession(session.id, { archived: false });
374
+ this.followUp({ sessionId: session.id, text: event.notice, taskId: event.taskId });
375
+ }
376
+ /**
377
+ * A turn in a conversation that nobody typed: Rookery telling the
378
+ * assistant something it has to pass on - today, how work it handed off
379
+ * ended. It runs like any other turn of that conversation, after whatever
380
+ * is being answered there now, and the host shows it live (`turnRunner`).
381
+ * Returns the turn id.
382
+ */
383
+ followUp(input) {
384
+ const turnId = randomUUID();
385
+ const controller = new AbortController();
386
+ const permission = this.store.getMeta(sessionPermissionKey(input.sessionId));
387
+ const events = this.#reported(this.chat({
388
+ text: input.text,
389
+ sessionId: input.sessionId,
390
+ turnId,
391
+ origin: 'system',
392
+ ...(permission ? { permission } : {}),
393
+ signal: controller.signal,
394
+ }), input);
395
+ if (this.turnRunner) {
396
+ this.turnRunner({ turnId, sessionId: input.sessionId, controller, events });
397
+ }
398
+ else {
399
+ void (async () => {
400
+ for await (const event of events)
401
+ void event;
402
+ })().catch((error) => this.log.warn('Follow-up turn failed', { error: String(error) }));
403
+ }
404
+ return turnId;
405
+ }
406
+ /** Passes a follow-up's events through and says how it ended, once, however it ends. */
407
+ async *#reported(events, input) {
408
+ let text = '';
409
+ let error;
410
+ try {
411
+ for await (const event of events) {
412
+ if (event.type === 'done')
413
+ text = event.text;
414
+ else if (event.type === 'error' && event.fatal)
415
+ error = event.message;
416
+ yield event;
417
+ }
418
+ }
419
+ catch (thrown) {
420
+ error = thrown.message;
421
+ throw thrown;
422
+ }
423
+ finally {
424
+ const done = {
425
+ sessionId: input.sessionId,
426
+ ...(input.taskId ? { taskId: input.taskId } : {}),
427
+ text,
428
+ ...(error ? { error } : {}),
429
+ };
430
+ this.emit('follow-up', done);
431
+ }
432
+ }
433
+ /** Wait for this conversation's turn; the returned function hands it on. */
434
+ async #takeTurn(sessionId) {
435
+ const previous = this.#sessionTurns.get(sessionId) ?? Promise.resolve();
436
+ let release;
437
+ const mine = new Promise((resolve) => {
438
+ release = resolve;
439
+ });
440
+ const tail = previous.then(() => mine);
441
+ this.#sessionTurns.set(sessionId, tail);
442
+ await previous;
443
+ return () => {
444
+ release();
445
+ if (this.#sessionTurns.get(sessionId) === tail)
446
+ this.#sessionTurns.delete(sessionId);
447
+ };
316
448
  }
317
449
  close() {
318
450
  // Anything still waiting on a person is settled first: an open question
@@ -607,6 +739,17 @@ export class Assistant extends EventEmitter {
607
739
  * ephemeral by nature and stay unjournalled.
608
740
  */
609
741
  async *chat(input) {
742
+ // One conversation answers one message at a time. A new conversation has
743
+ // nothing to wait for: nobody else can know its id yet.
744
+ const release = input.sessionId ? await this.#takeTurn(input.sessionId) : undefined;
745
+ try {
746
+ yield* this.#journalledChat(input);
747
+ }
748
+ finally {
749
+ release?.();
750
+ }
751
+ }
752
+ async *#journalledChat(input) {
610
753
  const turnId = input.turnId ?? randomUUID();
611
754
  const startedAt = Date.now();
612
755
  const journal = { begun: false };
@@ -717,14 +860,10 @@ export class Assistant extends EventEmitter {
717
860
  // resume the dead provider's thread rebuilds its prompt from this.
718
861
  const turnHistory = this.store.getMessages(session.id, this.config.memory.workingWindow);
719
862
  const history = resumed ? [] : turnHistory;
720
- // The company block: who works here, what is running, what arrived in
721
- // the mail. Read once per turn; the mail is then marked as read.
863
+ // The company block: who works here and what is running.
722
864
  const organization = this.org.activeOrganization();
723
865
  const snapshot = this.org.snapshot(organization.id);
724
- const mail = this.store.org.unreadMailFor(organization.id, { kind: 'assistant' });
725
866
  const project = session.projectId ? (this.store.org.getProject(session.projectId) ?? undefined) : undefined;
726
- if (mail.length)
727
- this.store.org.markMailReadFor(mail, { kind: 'assistant' });
728
867
  // Who is asking: the assistant. The tool servers and the prompt built on
729
868
  // them are per provider attempt, because each provider attaches its own.
730
869
  const who = 'assistant';
@@ -743,10 +882,38 @@ export class Assistant extends EventEmitter {
743
882
  // The journal's id, on the message (concept 9.4): it is what makes a
744
883
  // quote from this prompt locatable to this exact turn later, instead of
745
884
  // to a position counted off the transcript.
746
- this.store.addMessage({ sessionId: session.id, role: 'user', content: prompt, turnId });
747
- if (session.messageCount === 0 && session.title === 'New conversation') {
885
+ const fromSystem = input.origin === 'system';
886
+ // The rights this conversation was last used with, so a turn nobody
887
+ // typed - a report-back - runs with them rather than with the default.
888
+ if (!fromSystem && input.permission)
889
+ this.store.setMeta(sessionPermissionKey(session.id), input.permission);
890
+ this.store.addMessage({ sessionId: session.id, role: fromSystem ? 'system' : 'user', content: prompt, turnId });
891
+ if (!fromSystem && session.messageCount === 0 && session.title === 'New conversation') {
748
892
  this.store.updateSession(session.id, { title: deriveTitle(prompt) });
749
893
  }
894
+ // Chat and terminal are one process (T1): an ordinary conversation is
895
+ // answered by typing into its Claude Code terminal. Everything above -
896
+ // the recall, the stored message - is shared; what follows differs.
897
+ if (await this.#answersInTerminal(session, input, providerId)) {
898
+ yield* this.#terminalTurn({
899
+ session,
900
+ prompt,
901
+ memories,
902
+ project,
903
+ snapshotOrgId: organization.id,
904
+ providerId,
905
+ model,
906
+ effort,
907
+ input,
908
+ turnId,
909
+ recall,
910
+ ownSkills,
911
+ });
912
+ return;
913
+ }
914
+ // Answered headless this time - a voice turn, say. The terminal must not
915
+ // go on writing to the same transcript in parallel.
916
+ await this.#closeChatTerminal(session.id);
750
917
  const started = Date.now();
751
918
  let answer = '';
752
919
  const toolCalls = [];
@@ -788,7 +955,7 @@ export class Assistant extends EventEmitter {
788
955
  resumed: attempt === 1 && resumed,
789
956
  // A voice session speaks whichever surface the turn came from.
790
957
  voice: input.voice ?? session.kind === 'voice',
791
- orgBlock: assistantOrgBlock(this.config, snapshot, mail, project, this.cron.list(organization.id), this.store),
958
+ orgBlock: assistantOrgBlock(this.config, snapshot, project, this.cron.list(organization.id), this.store),
792
959
  toolHints,
793
960
  skillsIndex,
794
961
  // Lets the memory block group itself by entity.
@@ -824,8 +991,9 @@ export class Assistant extends EventEmitter {
824
991
  // assignment: it may read memory and open skills, but nothing it
825
992
  // does lands back in the bank - no extraction, no tools that write.
826
993
  // That covers every run with nobody in front of it: a session of
827
- // kind `schedule`, the mail-answer turn (`kind: 'mail'`), and a
828
- // schedule pinned to an ordinary conversation, which arrives with
994
+ // kind `schedule`, the old mail-answer turn (`kind: 'mail'`, no
995
+ // longer created), and a schedule pinned to an ordinary
996
+ // conversation, which arrives with
829
997
  // `input.scheduled` set. All three are exactly the runs that must
830
998
  // not be offered `ask_user` - there is no screen to answer on.
831
999
  scheduled: input.scheduled === true || session.kind === 'schedule' || session.kind === 'mail',
@@ -954,7 +1122,7 @@ export class Assistant extends EventEmitter {
954
1122
  memories,
955
1123
  resumed: true,
956
1124
  voice: input.voice ?? session.kind === 'voice',
957
- orgBlock: assistantOrgBlock(this.config, snapshot, [], project, this.cron.list(organization.id), this.store),
1125
+ orgBlock: assistantOrgBlock(this.config, snapshot, project, this.cron.list(organization.id), this.store),
958
1126
  toolHints: [...next.hints, dormantToolsHint(this.config, who, project?.id)].filter(Boolean),
959
1127
  skillsIndex,
960
1128
  store: this.store,
@@ -1006,14 +1174,198 @@ export class Assistant extends EventEmitter {
1006
1174
  // Scheduled runs stay out of the memory: the "user" side of that
1007
1175
  // exchange is Rookery's own boilerplate plus the job's prompt, not
1008
1176
  // something the user said today, and quoting it would file the job
1009
- // description again on every firing. Mail answers are deliberately
1010
- // still extracted - a person wrote in, and what they wrote stands.
1177
+ // description again on every firing.
1011
1178
  if (this.config.memory.enabled &&
1012
1179
  this.config.memory.autoExtract &&
1013
- session.kind !== 'schedule') {
1180
+ session.kind !== 'schedule' &&
1181
+ !fromSystem) {
1014
1182
  void this.#learn(session.id, prompt, answer, usedProvider, owner);
1015
1183
  }
1016
1184
  }
1185
+ /* ------------------------ chat in the terminal ------------------------ */
1186
+ /**
1187
+ * Whether this turn is typed into the conversation's terminal (T1, T5):
1188
+ * switched on, an ordinary conversation, not a spoken turn or the watcher,
1189
+ * a provider the model gateway can reach, and a pty on this machine.
1190
+ */
1191
+ async #answersInTerminal(session, input, providerId) {
1192
+ if (!this.config.turns.terminal)
1193
+ return false;
1194
+ if (session.kind !== 'chat' || input.voice || input.watching)
1195
+ return false;
1196
+ if (!this.providers.has('claude') || !this.providers.get('claude').openTerminal)
1197
+ return false;
1198
+ if (providerId !== 'claude' && providerId !== 'codex') {
1199
+ const profile = this.providers.profiles().find((entry) => entry.id === providerId);
1200
+ if (profile?.via !== 'direct')
1201
+ return false;
1202
+ }
1203
+ return (await loadPty()) !== null;
1204
+ }
1205
+ async *#terminalTurn(turn) {
1206
+ const { session, input } = turn;
1207
+ const started = Date.now();
1208
+ const permission = input.permission ?? this.config.defaultPermission;
1209
+ let terminal;
1210
+ try {
1211
+ // A turn nobody typed brings no settings of its own - it takes the
1212
+ // terminal as the person left it rather than restarting it onto the
1213
+ // defaults (a different model, other rights) in the middle of their work.
1214
+ const running = this.#chatTerminals.get(session.id);
1215
+ terminal =
1216
+ input.origin === 'system' && running?.handle.alive()
1217
+ ? running
1218
+ : await this.#chatTerminal(session, {
1219
+ providerId: turn.providerId,
1220
+ model: turn.model,
1221
+ effort: turn.effort,
1222
+ permission,
1223
+ });
1224
+ }
1225
+ catch (error) {
1226
+ yield { type: 'error', message: error.message, fatal: true };
1227
+ return;
1228
+ }
1229
+ // What a headless turn rebuilds into its system prompt every time goes
1230
+ // in through the prompt hook here (T2): the recall, the company as it is
1231
+ // right now, the skills that look like this message.
1232
+ const budget = this.config.memory.contextBudget;
1233
+ const snapshot = this.org.snapshot(turn.snapshotOrgId);
1234
+ const context = [
1235
+ renderMemoryBlock(turn.memories, Math.floor(budget * 0.4), 'this user', this.store),
1236
+ assistantOrgBlock(this.config, snapshot, turn.project, this.cron.list(turn.snapshotOrgId), this.store),
1237
+ renderSkillMatches(matchSkills(this.config, 'assistant', turn.ownSkills, turn.prompt)),
1238
+ 'It is now ' + formatNow() + '.',
1239
+ ]
1240
+ .filter(Boolean)
1241
+ .join('\n\n');
1242
+ const toolCalls = [];
1243
+ const turnBlocks = new TurnBlocks();
1244
+ if (turn.recall)
1245
+ turnBlocks.apply(turn.recall);
1246
+ let answer = '';
1247
+ let failure;
1248
+ let usage;
1249
+ let answeredBy = terminal.model;
1250
+ let prompt = turn.prompt;
1251
+ let promptContext = context;
1252
+ for (let pass = 1; pass <= MAX_PROVIDER_PASSES; pass += 1) {
1253
+ yield {
1254
+ type: 'session',
1255
+ sessionId: session.id,
1256
+ providerSessionId: terminal.handle.providerSessionId,
1257
+ provider: turn.providerId,
1258
+ ...(terminal.model ? { model: terminal.model } : {}),
1259
+ };
1260
+ const queue = new EventQueue();
1261
+ // The bridge token outlives the turn; its events belong to whichever
1262
+ // turn is typing into the terminal right now.
1263
+ terminal.context.emit = (event) => queue.push(event);
1264
+ // And its signal: an `assign` this turn waits on is stopped with it.
1265
+ terminal.context.signal = input.signal;
1266
+ const submitted = terminal.handle
1267
+ .submit({ prompt, context: promptContext, onEvent: (event) => queue.push(event), signal: input.signal })
1268
+ .finally(() => queue.close());
1269
+ try {
1270
+ for await (const event of queue.drain()) {
1271
+ if (event.type === 'tool') {
1272
+ toolCalls.push(event);
1273
+ turnBlocks.apply(event);
1274
+ this.emit('tool', event);
1275
+ }
1276
+ else if (event.type === 'text' || event.type === 'thinking') {
1277
+ turnBlocks.apply(event);
1278
+ }
1279
+ yield event;
1280
+ }
1281
+ }
1282
+ finally {
1283
+ terminal.context.emit = () => undefined;
1284
+ terminal.context.signal = undefined;
1285
+ }
1286
+ const result = await submitted;
1287
+ answeredBy = result.model ?? answeredBy;
1288
+ if (result.model)
1289
+ terminal.models.add(result.model);
1290
+ usage = mergeUsage(usage, result.usage);
1291
+ if (result.answer)
1292
+ answer = answer ? answer + '\n\n' + result.answer : result.answer;
1293
+ if (result.error) {
1294
+ failure = result.error;
1295
+ break;
1296
+ }
1297
+ if (result.interrupted || input.signal?.aborted || pass === MAX_PROVIDER_PASSES)
1298
+ break;
1299
+ // The continuation (T3): a tool server switched on during the turn
1300
+ // needs a process that has it attached. The terminal restarts on the
1301
+ // same session with it, and the work carries on.
1302
+ const next = toolServersFor(this.config, 'assistant', turn.providerId, session.projectId);
1303
+ const fresh = next.specs.map((spec) => spec.name).filter((name) => !terminal.servers.includes(name));
1304
+ if (!fresh.length)
1305
+ break;
1306
+ yield { type: 'status', label: 'tools', detail: fresh.join(', ') + ' attached, carrying on' };
1307
+ try {
1308
+ terminal = await this.#chatTerminal(this.store.getSession(session.id) ?? session, {
1309
+ providerId: turn.providerId,
1310
+ model: answeredBy ?? turn.model,
1311
+ effort: turn.effort,
1312
+ permission,
1313
+ });
1314
+ }
1315
+ catch (error) {
1316
+ failure = error.message;
1317
+ break;
1318
+ }
1319
+ prompt = continuePrompt(fresh);
1320
+ promptContext = undefined;
1321
+ }
1322
+ if (failure)
1323
+ yield { type: 'error', message: failure, fatal: !answer };
1324
+ turnBlocks.reconcile(answer);
1325
+ const turnUsage = { ...usage, durationMs: Date.now() - started };
1326
+ const answeredOn = this.#gatewayOwner(answeredBy, turn.providerId);
1327
+ this.store.addMessage({
1328
+ sessionId: session.id,
1329
+ role: 'assistant',
1330
+ content: answer,
1331
+ turnId: turn.turnId,
1332
+ provider: answeredOn,
1333
+ ...(answeredBy ? { model: answeredBy } : {}),
1334
+ usage: turnUsage,
1335
+ toolCalls,
1336
+ blocks: turnBlocks.blocks.length ? turnBlocks.blocks : undefined,
1337
+ });
1338
+ this.store.updateSession(session.id, {
1339
+ provider: answeredOn,
1340
+ ...(answeredBy ? { model: answeredBy } : {}),
1341
+ providerSessionId: terminal.handle.providerSessionId,
1342
+ });
1343
+ if (failure && !answer)
1344
+ return;
1345
+ yield { type: 'done', text: answer, providerSessionId: terminal.handle.providerSessionId, usage: turnUsage };
1346
+ if (this.config.memory.enabled && this.config.memory.autoExtract && input.origin !== 'system') {
1347
+ void this.#learn(session.id, turn.prompt, answer, answeredOn, ASSISTANT_MEMORY_OWNER);
1348
+ }
1349
+ }
1350
+ /** Which provider a model name belongs to, as the gateway routes it. */
1351
+ #gatewayOwner(model, fallback) {
1352
+ if (!this.#gateway || !model)
1353
+ return fallback;
1354
+ const route = this.#gateway.route(model);
1355
+ return route.kind === 'codex' ? 'codex' : route.kind === 'profile' ? route.profile.id : 'claude';
1356
+ }
1357
+ /** Ends a conversation's terminal and waits until its process is gone. */
1358
+ async #closeChatTerminal(sessionId) {
1359
+ const open = this.#chatTerminals.get(sessionId);
1360
+ if (!open)
1361
+ return;
1362
+ this.#chatTerminals.delete(sessionId);
1363
+ open.handle.close();
1364
+ const key = conversationTerminalKey(sessionId);
1365
+ for (let waited = 0; waited < 5000 && tuiSessions.info(key); waited += 100) {
1366
+ await new Promise((resolve) => setTimeout(resolve, 100));
1367
+ }
1368
+ }
1017
1369
  /**
1018
1370
  * What to say when a turn starts on a provider it did not ask for. Quota
1019
1371
  * reasons first - they are the ones the user cannot see anywhere else - and
@@ -1276,7 +1628,7 @@ export class Assistant extends EventEmitter {
1276
1628
  (job.schedule ? describeCron(job.schedule) : 'fired by an event') + '), ' + when + '. ' +
1277
1629
  'Nobody is following live: carry out the assignment now and finish with a short report ' +
1278
1630
  'for the user to read later. If carrying it out already delivers the result to the user by ' +
1279
- 'itself (for example you send_mail them the thing this job exists to send), that mail is the ' +
1631
+ 'itself (for example you notify them of the thing this job exists to send), that is the ' +
1280
1632
  'delivery - reply with exactly [SILENT] and nothing else, so a second "schedule completed" ' +
1281
1633
  'notification is not posted on top of it.\n\n' + job.prompt +
1282
1634
  // The watcher arrives knowing what it was woken for, so the turn is
@@ -1312,44 +1664,13 @@ export class Assistant extends EventEmitter {
1312
1664
  // sometimes reasons out loud first and tacks the sentinel on as its
1313
1665
  // last line instead of replying with only it, which used to defeat the
1314
1666
  // match and let the explanation (sentinel and all) straight into the
1315
- // inbox mail. Matching it as a trailing token - not anywhere in the
1667
+ // outcome notification. Matching it as a trailing token - not anywhere in the
1316
1668
  // text - still catches that case without firing on a report that
1317
1669
  // merely quotes or explains the convention somewhere in its middle.
1318
1670
  if (/\[SILENT\]\s*$/.test(text))
1319
1671
  return { status: 'done', result: '', silent: true, sessionId };
1320
1672
  return { status: 'done', result: text, sessionId };
1321
1673
  }
1322
- /**
1323
- * One assistant turn for a mail addressed to it, answered by mail.
1324
- * Same shape as a scheduled run: its own conversation, nobody watching
1325
- * live, the answer read later - except the answer goes back as a reply.
1326
- */
1327
- async #answerMail(mail, senderLabel, thread) {
1328
- // `kind: 'mail'` keeps this out of the conversations list: it is the
1329
- // transcript of one answered mail, not a thread anyone continues.
1330
- const session = this.createSession({ title: 'Mail: ' + mail.subject, kind: 'mail' });
1331
- // Subjects only: the thread can be long, and most mail is answerable
1332
- // without it. `read_mail_thread` fetches the text if this one is not.
1333
- const history = thread.length
1334
- ? 'Earlier in this thread (' + thread.length + ' mail(s)), subjects only:\n' +
1335
- thread.map((entry) => '- ' + entry.subject).join('\n') +
1336
- '\nRead the full text with read_mail_thread("' + mail.threadId + '") if the answer depends on it.\n\n'
1337
- : '';
1338
- const prompt = 'Mail ' + mail.id + ' arrived for you from ' + senderLabel + '. Nobody is following this ' +
1339
- 'conversation live: answer it now, and write the answer as the body of your reply mail - no ' +
1340
- 'chat pleasantries, no report framing. It is sent back to them as a reply automatically. Do ' +
1341
- 'not send_mail the answer to them as well: this text is the reply, and doing both delivers ' +
1342
- 'it twice. send_mail here is only for bringing somebody else in.\n\n' +
1343
- history + 'Subject: ' + mail.subject + '\n\n' + mail.body;
1344
- let text = '';
1345
- for await (const event of this.chat({ text: prompt, sessionId: session.id })) {
1346
- if (event.type === 'done')
1347
- text = event.text;
1348
- else if (event.type === 'error' && event.fatal)
1349
- throw new Error(event.message);
1350
- }
1351
- return text;
1352
- }
1353
1674
  /* ---------------------------- internals --------------------------- */
1354
1675
  /**
1355
1676
  * Whether this turn is framed for the dream. All conditions must hold
@@ -1423,7 +1744,7 @@ export class Assistant extends EventEmitter {
1423
1744
  /**
1424
1745
  * A retrieval policy went in force, so the user hears about it (S26,
1425
1746
  * concept 9.6). This is the one place that can say so: the night owns the
1426
- * promotion and knows nothing about mail, the controller owns the mail and
1747
+ * promotion and knows nothing about notifications, the controller owns them and
1427
1748
  * knows nothing about the night, and the runtime holds both.
1428
1749
  *
1429
1750
  * Everything quoted is a number, an id or the promotion's own stored
@@ -1432,9 +1753,9 @@ export class Assistant extends EventEmitter {
1432
1753
  *
1433
1754
  * A failing send costs the message, never the night: `#announcePromotion`
1434
1755
  * in sleep.ts catches whatever comes back out of here, and this catches
1435
- * first so the warning names the mail rather than the hook.
1756
+ * first so the warning names the notice rather than the hook.
1436
1757
  */
1437
- async #announcePromotion(notice) {
1758
+ async announcePromotion(notice) {
1438
1759
  const version = notice.version;
1439
1760
  const evaluation = notice.evaluation;
1440
1761
  const body = [
@@ -1457,15 +1778,19 @@ export class Assistant extends EventEmitter {
1457
1778
  'Take the whole night back: undo sleep run ' + notice.runId + '.',
1458
1779
  ].join('\n');
1459
1780
  try {
1460
- await this.org.sendUserMail({
1781
+ // A `sleep` notification, from Rookery itself. It used to be a mail
1782
+ // from the user to the user, which no push filter ever let through -
1783
+ // the promotion reached the web inbox and never the phone.
1784
+ this.org.notifyUser({
1461
1785
  orgId: this.org.activeOrganization().id,
1462
- to: ['user'],
1463
- subject: 'Retrieval policy ' + notice.slot + ' v' + version.version + ' is in force',
1786
+ kind: 'sleep',
1787
+ title: 'Retrieval policy ' + notice.slot + ' v' + version.version + ' is in force',
1464
1788
  body,
1789
+ fromKind: 'system',
1465
1790
  });
1466
1791
  }
1467
1792
  catch (error) {
1468
- this.log.warn('Could not mail the promotion notice', {
1793
+ this.log.warn('Could not post the promotion notice', {
1469
1794
  owner: notice.owner,
1470
1795
  slot: notice.slot,
1471
1796
  policy: version.id,
@@ -1587,18 +1912,11 @@ export class Assistant extends EventEmitter {
1587
1912
  }
1588
1913
  /* ------------------------- conversation terminal ------------------------ */
1589
1914
  /**
1590
- * Carries a conversation on in Claude Code's own terminal instead of the
1591
- * chat: the full TUI, typed into directly, on the same provider session a
1592
- * chat turn resumes - so switching back and forth loses nothing. Claude
1593
- * Code keeps its own context across the switch; Rookery keeps the
1594
- * conversation's history by storing every exchange the terminal reports.
1595
- *
1596
- * What a chat turn rebuilds every time is built once here: the system
1597
- * prompt, the company block, the tool servers. A terminal has one prompt
1598
- * for its whole life, so the per-turn memory recall is the one thing it
1599
- * goes without - the memories still come back on the next chat turn.
1600
- *
1601
- * Returns at once if the conversation already has an open terminal.
1915
+ * The terminal view of a conversation: the same Claude Code process every
1916
+ * chat message of it is typed into (T1), opened here if nothing has opened
1917
+ * it yet. Switching between chat and terminal loses nothing because there
1918
+ * is nothing to switch - it is one process with one transcript, and what a
1919
+ * person types into it lands in the conversation like any other message.
1602
1920
  */
1603
1921
  async openConversationTerminal(input) {
1604
1922
  const session = this.#resolveSession({
@@ -1609,18 +1927,36 @@ export class Assistant extends EventEmitter {
1609
1927
  ...(input.projectId ? { projectId: input.projectId } : {}),
1610
1928
  });
1611
1929
  const key = conversationTerminalKey(session.id);
1612
- if (tuiSessions.info(key))
1930
+ const open = this.#chatTerminals.get(session.id);
1931
+ if (open?.handle.alive())
1613
1932
  return { sessionId: session.id, key };
1614
1933
  if (input.projectId && input.projectId !== session.projectId) {
1615
1934
  this.store.updateSession(session.id, { projectId: input.projectId });
1616
1935
  session.projectId = input.projectId;
1617
1936
  }
1618
- const wanted = input.provider ?? session.provider;
1619
- const providerId = await this.providers.resolveUsable(wanted);
1937
+ const providerId = await this.providers.resolveUsable(input.provider ?? session.provider);
1620
1938
  if (!providerId)
1621
1939
  throw new Error('No AI provider is ready.');
1622
- // Always the plain Claude Code adapter: the gateway, not a profile's
1623
- // environment, decides where each model goes.
1940
+ await this.#chatTerminal(session, {
1941
+ providerId,
1942
+ model: input.model ?? session.model ?? this.config.defaultModel,
1943
+ effort: input.effort ?? this.config.defaultEffort,
1944
+ permission: input.permission ?? this.config.defaultPermission,
1945
+ });
1946
+ return { sessionId: session.id, key };
1947
+ }
1948
+ /**
1949
+ * The conversation's terminal, started as this turn needs it. A terminal
1950
+ * already running with the same model, effort, rights, project and tool
1951
+ * servers is reused; any difference ends it and starts it again on the same
1952
+ * Claude Code session (T3) - the context is in the transcript, not in the
1953
+ * process, so nothing of the conversation is lost.
1954
+ *
1955
+ * What a headless turn rebuilds every time is built once here: the system
1956
+ * prompt, the tool servers. What changes per message - the recall, the
1957
+ * company's current state - goes in through the prompt hook instead.
1958
+ */
1959
+ async #chatTerminal(session, want) {
1624
1960
  const provider = this.providers.get('claude');
1625
1961
  if (!provider.openTerminal)
1626
1962
  throw new Error(provider.displayName + ' has no terminal of its own.');
@@ -1633,7 +1969,7 @@ export class Assistant extends EventEmitter {
1633
1969
  continue;
1634
1970
  const profile = this.providers.profiles().find((entry) => entry.id === status.id);
1635
1971
  // The gateway speaks to ChatGPT and to Anthropic-compatible endpoints;
1636
- // a router-backed profile stays reachable from the chat only.
1972
+ // a router-backed profile stays reachable from headless turns only.
1637
1973
  if (status.id !== 'codex' && profile?.via !== 'direct')
1638
1974
  continue;
1639
1975
  const models = await this.providers.models(status.id).catch(() => []);
@@ -1646,22 +1982,30 @@ export class Assistant extends EventEmitter {
1646
1982
  this.#gatewayProfiles = direct;
1647
1983
  this.#gateway ??= new ModelGateway({ profiles: () => this.#gatewayProfiles });
1648
1984
  const gateway = await this.#gateway.start();
1649
- const ownerOf = (name) => {
1650
- const route = this.#gateway?.route(name) ?? { kind: 'anthropic' };
1651
- return route.kind === 'codex' ? 'codex' : route.kind === 'profile' ? route.profile.id : 'claude';
1652
- };
1653
- // One gateway serves every model, so the session resumes whichever
1654
- // provider it last ran on - Claude Code's transcript is the same format.
1655
- const resumed = Boolean(session.providerSessionId);
1656
- const requested = input.model ?? session.model ?? this.config.defaultModel;
1657
- // A name another provider owns (the chat's `sonnet` on a GPT terminal)
1985
+ // A name another provider owns (the chat's `sonnet` on a GPT turn)
1658
1986
  // becomes that provider's own default instead of silently going to Claude.
1659
- const model = requested && ownerOf(requested) === providerId ? requested : remapModel(providerId, requested);
1660
- const organization = this.org.activeOrganization();
1661
- const snapshot = this.org.snapshot(organization.id);
1987
+ const model = want.model && this.#gatewayOwner(want.model, 'claude') === want.providerId
1988
+ ? want.model
1989
+ : remapModel(want.providerId, want.model);
1662
1990
  const project = session.projectId ? (this.store.org.getProject(session.projectId) ?? undefined) : undefined;
1663
1991
  const who = 'assistant';
1664
- const extra = toolServersFor(this.config, who, providerId, project?.id);
1992
+ const extra = toolServersFor(this.config, who, want.providerId, project?.id);
1993
+ const servers = extra.specs.map((spec) => spec.name).sort();
1994
+ const signature = JSON.stringify([want.effort ?? '', want.permission, project?.id ?? '', servers]);
1995
+ const open = this.#chatTerminals.get(session.id);
1996
+ const sameModel = (entry) => !model || entry.models.has(model) || (want.model !== undefined && entry.models.has(want.model));
1997
+ if (open && open.handle.alive() && open.signature === signature && sameModel(open))
1998
+ return open;
1999
+ // Whatever a person is doing in it right now finishes first; a restart
2000
+ // must not cut off a turn somebody typed into the terminal view.
2001
+ if (open?.handle.alive())
2002
+ await open.handle.whenIdle();
2003
+ await this.#closeChatTerminal(session.id);
2004
+ // Read again: a restart must resume the session the last process wrote.
2005
+ const current = this.store.getSession(session.id) ?? session;
2006
+ const resumed = Boolean(current.providerSessionId);
2007
+ const organization = this.org.activeOrganization();
2008
+ const snapshot = this.org.snapshot(organization.id);
1665
2009
  const ownSkills = this.skills.for(who);
1666
2010
  const systemPrompt = buildSystemPrompt({
1667
2011
  config: this.config,
@@ -1670,14 +2014,15 @@ export class Assistant extends EventEmitter {
1670
2014
  history: resumed ? [] : this.store.getMessages(session.id, this.config.memory.workingWindow),
1671
2015
  resumed,
1672
2016
  voice: false,
1673
- orgBlock: assistantOrgBlock(this.config, snapshot, [], project, this.cron.list(organization.id), this.store),
2017
+ orgBlock: assistantOrgBlock(this.config, snapshot, project, this.cron.list(organization.id), this.store),
1674
2018
  toolHints: [...extra.hints, dormantToolsHint(this.config, who, project?.id)].filter(Boolean),
1675
2019
  skillsIndex: [renderSkillsIndex(ownSkills), renderExternalSkillsHint(this.config, who)].filter(Boolean).join('\n\n'),
1676
2020
  store: this.store,
1677
2021
  });
1678
2022
  // The token lives as long as the terminal: the MCP bridge answers the
1679
- // assistant's own tools for exactly that long.
1680
- const token = this.org.register({
2023
+ // assistant's own tools for exactly that long. `emit` is pointed at
2024
+ // whichever turn is typing into it at the time.
2025
+ const context = {
1681
2026
  orgId: organization.id,
1682
2027
  audience: 'assistant',
1683
2028
  agentId: undefined,
@@ -1688,93 +2033,118 @@ export class Assistant extends EventEmitter {
1688
2033
  watching: false,
1689
2034
  emit: () => undefined,
1690
2035
  signal: undefined,
1691
- });
2036
+ };
2037
+ const token = this.org.register(context);
1692
2038
  const release = () => {
1693
2039
  this.org.unregister(token);
1694
2040
  this.questions.cancelForOwner(token);
1695
2041
  };
2042
+ const key = conversationTerminalKey(session.id);
2043
+ let entry;
1696
2044
  try {
1697
2045
  const mcp = await this.org.bridge.spec(token);
1698
2046
  const opened = await provider.openTerminal({
1699
2047
  prompt: '',
1700
2048
  systemPrompt,
1701
2049
  systemPromptMode: 'replace',
1702
- ...(resumed && session.providerSessionId ? { providerSessionId: session.providerSessionId } : {}),
2050
+ ...(resumed && current.providerSessionId ? { providerSessionId: current.providerSessionId } : {}),
1703
2051
  ...(model ? { model } : {}),
1704
- effort: input.effort ?? this.config.defaultEffort,
2052
+ ...(want.effort ? { effort: want.effort } : {}),
1705
2053
  cwd: this.config.workspace,
1706
- permission: input.permission ?? this.config.defaultPermission,
2054
+ permission: want.permission,
1707
2055
  mcp,
1708
2056
  ...(extra.specs.length ? { mcpExtra: extra.specs } : {}),
1709
2057
  ...externalTurnExtras(this.config, who),
1710
2058
  gateway: { ...gateway, picker },
1711
2059
  tui: { key },
1712
2060
  }, {
1713
- onTurn: (turn) => {
1714
- if (turn.prompt)
1715
- this.store.addMessage({ sessionId: session.id, role: 'user', content: turn.prompt });
1716
- // Stored the way a chat turn stores itself: the tool calls, and
1717
- // the ordered transcript the thread renders them from - or the
1718
- // chat would show a terminal turn as bare text.
1719
- const toolCalls = [];
1720
- const turnBlocks = new TurnBlocks();
1721
- for (const event of turn.events) {
1722
- if (event.type === 'tool')
1723
- toolCalls.push(event);
1724
- turnBlocks.apply(event);
1725
- }
1726
- turnBlocks.reconcile(turn.answer);
1727
- // Whoever actually answered: `/model` in the terminal may have
1728
- // moved the conversation to another provider since it opened.
1729
- const answeredBy = turn.model ?? model;
1730
- const answeredOn = ownerOf(answeredBy);
1731
- this.store.addMessage({
1732
- sessionId: session.id,
1733
- role: 'assistant',
1734
- content: turn.answer,
1735
- provider: answeredOn,
1736
- ...(answeredBy ? { model: answeredBy } : {}),
1737
- usage: turn.usage,
1738
- toolCalls,
1739
- ...(turnBlocks.blocks.length ? { blocks: turnBlocks.blocks } : {}),
1740
- });
1741
- const current = this.store.getSession(session.id);
1742
- if (current && current.title === 'New conversation' && turn.prompt) {
1743
- this.store.updateSession(session.id, { title: deriveTitle(turn.prompt) });
1744
- }
1745
- this.store.updateSession(session.id, {
1746
- provider: answeredOn,
1747
- ...(answeredBy ? { model: answeredBy } : {}),
1748
- providerSessionId: turn.providerSessionId,
1749
- });
1750
- this.emit('changed', { kind: 'session', id: session.id });
1751
- if (this.config.memory.enabled && this.config.memory.autoExtract && turn.prompt) {
1752
- void this.#learn(session.id, turn.prompt, turn.answer, answeredOn, ASSISTANT_MEMORY_OWNER);
1753
- }
2061
+ // Something a person typed into the terminal itself. What Rookery
2062
+ // types comes back to the turn that typed it and is stored there.
2063
+ onTurn: (typed) => {
2064
+ // A model picked with `/model` in the terminal is this terminal's
2065
+ // model from now on; the chat asking for it must not restart it.
2066
+ if (entry && typed.model)
2067
+ entry.models.add(typed.model);
2068
+ this.#storeTypedTurn(session.id, typed, model);
1754
2069
  },
1755
2070
  onExit: () => {
1756
2071
  release();
2072
+ if (entry && this.#chatTerminals.get(session.id) === entry)
2073
+ this.#chatTerminals.delete(session.id);
1757
2074
  this.emit('changed', { kind: 'session', id: session.id });
1758
2075
  },
1759
2076
  });
1760
- // Stored at once, so switching back to chat resumes this very session
1761
- // even if nothing was said in the terminal yet.
1762
- this.store.updateSession(session.id, { provider: providerId, model, providerSessionId: opened.providerSessionId });
2077
+ const models = new Set([model, want.model].filter((name) => Boolean(name)));
2078
+ entry = { handle: opened.terminal, signature, models, servers, context, model };
2079
+ this.#chatTerminals.set(session.id, entry);
2080
+ // Stored at once, so the next message - or a headless turn - resumes
2081
+ // this very session even if nothing was said in the terminal yet.
2082
+ this.store.updateSession(session.id, {
2083
+ provider: want.providerId,
2084
+ ...(model ? { model } : {}),
2085
+ providerSessionId: opened.providerSessionId,
2086
+ });
1763
2087
  }
1764
2088
  catch (error) {
1765
2089
  release();
1766
2090
  throw error;
1767
2091
  }
1768
2092
  this.emit('changed', { kind: 'session', id: session.id });
1769
- return { sessionId: session.id, key };
2093
+ return entry;
2094
+ }
2095
+ /** A turn a person typed straight into the terminal, stored like a chat turn. */
2096
+ #storeTypedTurn(sessionId, turn, openedWith) {
2097
+ if (turn.prompt)
2098
+ this.store.addMessage({ sessionId, role: 'user', content: turn.prompt });
2099
+ // Stored the way a chat turn stores itself: the tool calls, and the
2100
+ // ordered transcript the thread renders them from - or the chat would
2101
+ // show a terminal turn as bare text.
2102
+ const toolCalls = [];
2103
+ const turnBlocks = new TurnBlocks();
2104
+ for (const event of turn.events) {
2105
+ if (event.type === 'tool')
2106
+ toolCalls.push(event);
2107
+ turnBlocks.apply(event);
2108
+ }
2109
+ turnBlocks.reconcile(turn.answer);
2110
+ // Whoever actually answered: `/model` in the terminal may have moved
2111
+ // the conversation to another provider since it opened.
2112
+ const answeredBy = turn.model ?? openedWith;
2113
+ const answeredOn = this.#gatewayOwner(answeredBy, 'claude');
2114
+ this.store.addMessage({
2115
+ sessionId,
2116
+ role: 'assistant',
2117
+ content: turn.answer,
2118
+ provider: answeredOn,
2119
+ ...(answeredBy ? { model: answeredBy } : {}),
2120
+ usage: turn.usage,
2121
+ toolCalls,
2122
+ ...(turnBlocks.blocks.length ? { blocks: turnBlocks.blocks } : {}),
2123
+ });
2124
+ const current = this.store.getSession(sessionId);
2125
+ if (current && current.title === 'New conversation' && turn.prompt) {
2126
+ this.store.updateSession(sessionId, { title: deriveTitle(turn.prompt) });
2127
+ }
2128
+ this.store.updateSession(sessionId, {
2129
+ provider: answeredOn,
2130
+ ...(answeredBy ? { model: answeredBy } : {}),
2131
+ providerSessionId: turn.providerSessionId,
2132
+ });
2133
+ this.emit('changed', { kind: 'session', id: sessionId });
2134
+ if (this.config.memory.enabled && this.config.memory.autoExtract && turn.prompt) {
2135
+ void this.#learn(sessionId, turn.prompt, turn.answer, answeredOn, ASSISTANT_MEMORY_OWNER);
2136
+ }
1770
2137
  }
1771
2138
  /** The model gateway conversation terminals share, started with the first one. */
1772
2139
  #gateway;
1773
2140
  /** The directly reachable profiles and their models, refreshed with every terminal. */
1774
2141
  #gatewayProfiles = [];
1775
- /** Back to chat: ends the conversation's terminal. False when it had none. */
2142
+ /** Ends the conversation's terminal. False when it had none. */
1776
2143
  closeConversationTerminal(sessionId) {
1777
- return tuiSessions.kill(conversationTerminalKey(sessionId));
2144
+ const had = this.#chatTerminals.has(sessionId) || tuiSessions.info(conversationTerminalKey(sessionId)) !== null;
2145
+ void this.#closeChatTerminal(sessionId);
2146
+ tuiSessions.kill(conversationTerminalKey(sessionId));
2147
+ return had;
1778
2148
  }
1779
2149
  #resolveSession(input) {
1780
2150
  if (input.sessionId) {