@skillcdn/console 0.6.1 → 0.6.3

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 (230) hide show
  1. package/README.md +14 -7
  2. package/SKILLCDN.md +3 -2
  3. package/dist/agent-page.d.ts +2 -0
  4. package/dist/agent-page.d.ts.map +1 -1
  5. package/dist/agent-page.js +77 -30
  6. package/dist/agent-page.js.map +1 -1
  7. package/dist/agent-state.d.ts +9 -0
  8. package/dist/agent-state.d.ts.map +1 -0
  9. package/dist/agent-state.js +28 -0
  10. package/dist/agent-state.js.map +1 -0
  11. package/dist/agent-usage.d.ts +9 -6
  12. package/dist/agent-usage.d.ts.map +1 -1
  13. package/dist/agent-usage.js +38 -8
  14. package/dist/agent-usage.js.map +1 -1
  15. package/dist/api.d.ts +4 -3
  16. package/dist/api.d.ts.map +1 -1
  17. package/dist/api.js +4 -3
  18. package/dist/api.js.map +1 -1
  19. package/dist/cli/cli.d.ts +2 -0
  20. package/dist/cli/cli.d.ts.map +1 -1
  21. package/dist/cli/cli.js +369 -130
  22. package/dist/cli/cli.js.map +1 -1
  23. package/dist/cli/format.d.ts +13 -4
  24. package/dist/cli/format.d.ts.map +1 -1
  25. package/dist/cli/format.js +43 -9
  26. package/dist/cli/format.js.map +1 -1
  27. package/dist/cli/help.d.ts +82 -9
  28. package/dist/cli/help.d.ts.map +1 -1
  29. package/dist/cli/help.js +780 -318
  30. package/dist/cli/help.js.map +1 -1
  31. package/dist/cli/pack.d.ts +2 -2
  32. package/dist/cli/pack.d.ts.map +1 -1
  33. package/dist/cli/pack.js +6 -4
  34. package/dist/cli/pack.js.map +1 -1
  35. package/dist/cli/runner-files.d.ts +16 -0
  36. package/dist/cli/runner-files.d.ts.map +1 -0
  37. package/dist/cli/runner-files.js +110 -0
  38. package/dist/cli/runner-files.js.map +1 -0
  39. package/dist/cli/runner-host.d.ts +7 -0
  40. package/dist/cli/runner-host.d.ts.map +1 -1
  41. package/dist/cli/runner-host.js +40 -2
  42. package/dist/cli/runner-host.js.map +1 -1
  43. package/dist/client.d.ts +22 -1
  44. package/dist/client.d.ts.map +1 -1
  45. package/dist/client.js +7 -1
  46. package/dist/client.js.map +1 -1
  47. package/dist/components/agent-page.d.ts +61 -11
  48. package/dist/components/agent-page.d.ts.map +1 -1
  49. package/dist/components/agent-page.js +146 -35
  50. package/dist/components/agent-page.js.map +1 -1
  51. package/dist/components/agents.d.ts +3 -2
  52. package/dist/components/agents.d.ts.map +1 -1
  53. package/dist/components/agents.js +9 -3
  54. package/dist/components/agents.js.map +1 -1
  55. package/dist/components/calendar.d.ts +24 -4
  56. package/dist/components/calendar.d.ts.map +1 -1
  57. package/dist/components/calendar.js +78 -35
  58. package/dist/components/calendar.js.map +1 -1
  59. package/dist/console.d.ts.map +1 -1
  60. package/dist/console.js +40 -12
  61. package/dist/console.js.map +1 -1
  62. package/dist/data.d.ts +2 -0
  63. package/dist/data.d.ts.map +1 -1
  64. package/dist/data.js +4 -0
  65. package/dist/data.js.map +1 -1
  66. package/dist/desk-page.js +5 -5
  67. package/dist/desk-page.js.map +1 -1
  68. package/dist/feed-words.d.ts.map +1 -1
  69. package/dist/feed-words.js +18 -1
  70. package/dist/feed-words.js.map +1 -1
  71. package/dist/i18n/en.d.ts +51 -1
  72. package/dist/i18n/en.d.ts.map +1 -1
  73. package/dist/i18n/en.js +44 -2
  74. package/dist/i18n/en.js.map +1 -1
  75. package/dist/i18n/ko.d.ts.map +1 -1
  76. package/dist/i18n/ko.js +52 -17
  77. package/dist/i18n/ko.js.map +1 -1
  78. package/dist/index.d.ts +1 -1
  79. package/dist/index.d.ts.map +1 -1
  80. package/dist/index.js +1 -1
  81. package/dist/index.js.map +1 -1
  82. package/dist/limits.d.ts +10 -0
  83. package/dist/limits.d.ts.map +1 -1
  84. package/dist/limits.js +10 -0
  85. package/dist/limits.js.map +1 -1
  86. package/dist/plugin/capabilities.d.ts +1 -1
  87. package/dist/plugin/capabilities.d.ts.map +1 -1
  88. package/dist/plugin/capabilities.js +6 -1
  89. package/dist/plugin/capabilities.js.map +1 -1
  90. package/dist/plugin/context.d.ts +101 -8
  91. package/dist/plugin/context.d.ts.map +1 -1
  92. package/dist/plugin/limits.d.ts +7 -0
  93. package/dist/plugin/limits.d.ts.map +1 -1
  94. package/dist/plugin/limits.js +7 -0
  95. package/dist/plugin/limits.js.map +1 -1
  96. package/dist/plugin/testing.d.ts +2 -0
  97. package/dist/plugin/testing.d.ts.map +1 -1
  98. package/dist/plugin/testing.js +2 -0
  99. package/dist/plugin/testing.js.map +1 -1
  100. package/dist/rules.js +1 -1
  101. package/dist/rules.js.map +1 -1
  102. package/dist/runner/acp.d.ts.map +1 -1
  103. package/dist/runner/acp.js +9 -3
  104. package/dist/runner/acp.js.map +1 -1
  105. package/dist/runner/claude.d.ts.map +1 -1
  106. package/dist/runner/claude.js +143 -10
  107. package/dist/runner/claude.js.map +1 -1
  108. package/dist/runner/codex.d.ts.map +1 -1
  109. package/dist/runner/codex.js +14 -2
  110. package/dist/runner/codex.js.map +1 -1
  111. package/dist/runner/config.d.ts +18 -0
  112. package/dist/runner/config.d.ts.map +1 -1
  113. package/dist/runner/config.js +77 -1
  114. package/dist/runner/config.js.map +1 -1
  115. package/dist/runner/desk.d.ts +7 -0
  116. package/dist/runner/desk.d.ts.map +1 -1
  117. package/dist/runner/desk.js +20 -4
  118. package/dist/runner/desk.js.map +1 -1
  119. package/dist/runner/message.d.ts +26 -2
  120. package/dist/runner/message.d.ts.map +1 -1
  121. package/dist/runner/message.js +120 -32
  122. package/dist/runner/message.js.map +1 -1
  123. package/dist/runner/runner.d.ts +40 -2
  124. package/dist/runner/runner.d.ts.map +1 -1
  125. package/dist/runner/runner.js +533 -32
  126. package/dist/runner/runner.js.map +1 -1
  127. package/dist/runner/slack-status.d.ts +19 -0
  128. package/dist/runner/slack-status.d.ts.map +1 -0
  129. package/dist/runner/slack-status.js +332 -0
  130. package/dist/runner/slack-status.js.map +1 -0
  131. package/dist/runner/slack.d.ts +17 -11
  132. package/dist/runner/slack.d.ts.map +1 -1
  133. package/dist/runner/slack.js +1199 -109
  134. package/dist/runner/slack.js.map +1 -1
  135. package/dist/runner/types.d.ts +205 -6
  136. package/dist/runner/types.d.ts.map +1 -1
  137. package/dist/runner/types.js.map +1 -1
  138. package/dist/runner/usage.d.ts +6 -1
  139. package/dist/runner/usage.d.ts.map +1 -1
  140. package/dist/runner/usage.js +9 -2
  141. package/dist/runner/usage.js.map +1 -1
  142. package/dist/runner.d.ts +4 -4
  143. package/dist/runner.d.ts.map +1 -1
  144. package/dist/runner.js +3 -3
  145. package/dist/runner.js.map +1 -1
  146. package/dist/schemas.d.ts +263 -1
  147. package/dist/schemas.d.ts.map +1 -1
  148. package/dist/schemas.js +137 -5
  149. package/dist/schemas.js.map +1 -1
  150. package/dist/vocabulary.d.ts +7 -0
  151. package/dist/vocabulary.d.ts.map +1 -1
  152. package/dist/vocabulary.js +6 -0
  153. package/dist/vocabulary.js.map +1 -1
  154. package/dist/wake-text.d.ts +43 -0
  155. package/dist/wake-text.d.ts.map +1 -0
  156. package/dist/wake-text.js +115 -0
  157. package/dist/wake-text.js.map +1 -0
  158. package/docs/specs/cli.md +21 -12
  159. package/docs/specs/plugins.md +12 -7
  160. package/docs/specs/rest.md +14 -5
  161. package/docs/specs/runner.md +133 -26
  162. package/docs/start.md +26 -5
  163. package/package.json +3 -3
  164. package/skills/building-a-plugin/SKILL.md +3 -3
  165. package/skills/deploying-a-console/SKILL.md +3 -3
  166. package/skills/deploying-a-console/references/access.md +15 -1
  167. package/skills/deploying-a-console/references/resources.md +2 -2
  168. package/skills/deploying-a-console/scripts/github-app.mjs +593 -0
  169. package/skills/planning-the-board/references/setting-up.md +1 -1
  170. package/skills/running-an-agent/SKILL.md +18 -72
  171. package/skills/running-an-agent/references/preparing-the-machine.md +17 -0
  172. package/skills/running-an-agent/references/several-tasks.md +1 -1
  173. package/skills/running-an-agent/references/slack-app.md +55 -8
  174. package/skills/running-an-agent/references/the-account-and-the-invitation.md +5 -0
  175. package/skills/running-an-agent/references/what-was-not-seen-run-yet.md +3 -0
  176. package/skills/running-an-agent/references/when-the-agent-could-not-go-on.md +16 -0
  177. package/skills/running-an-agent/references/your-first-task.md +19 -0
  178. package/skills/trying-a-console/SKILL.md +136 -0
  179. package/skills/trying-a-console/references/when-it-does-not-go.md +30 -0
  180. package/skills/working-the-board/SKILL.md +11 -15
  181. package/skills/working-the-board/references/a-pack-skills-questions.md +3 -0
  182. package/skills/working-the-board/references/a-plugins-commands.md +3 -0
  183. package/skills/working-the-board/references/a-review.md +3 -0
  184. package/skills/working-the-board/references/an-open-run.md +3 -0
  185. package/skills/working-the-board/references/requirements.md +7 -0
  186. package/skills/working-the-board/references/the-pack.md +3 -3
  187. package/skills/working-the-board/references/what-they-were-told.md +3 -0
  188. package/skills/working-the-board/references/work-given-in-chat.md +5 -0
  189. package/src/agent-page.tsx +133 -41
  190. package/src/agent-state.ts +33 -0
  191. package/src/agent-usage.ts +55 -12
  192. package/src/api.ts +23 -0
  193. package/src/cli/cli.ts +443 -137
  194. package/src/cli/format.ts +49 -9
  195. package/src/cli/help.ts +904 -359
  196. package/src/cli/pack.ts +6 -4
  197. package/src/cli/runner-files.ts +120 -0
  198. package/src/cli/runner-host.ts +48 -2
  199. package/src/client.ts +64 -0
  200. package/src/components/agent-page.tsx +264 -39
  201. package/src/components/agents.tsx +20 -5
  202. package/src/components/calendar.tsx +92 -36
  203. package/src/console.tsx +47 -10
  204. package/src/data.ts +6 -0
  205. package/src/desk-page.tsx +5 -5
  206. package/src/feed-words.ts +20 -1
  207. package/src/i18n/en.ts +50 -2
  208. package/src/i18n/ko.ts +62 -17
  209. package/src/index.ts +2 -0
  210. package/src/limits.ts +10 -0
  211. package/src/plugin/capabilities.ts +8 -1
  212. package/src/plugin/context.ts +103 -7
  213. package/src/plugin/limits.ts +7 -0
  214. package/src/plugin/testing.ts +4 -0
  215. package/src/rules.ts +1 -1
  216. package/src/runner/acp.ts +9 -3
  217. package/src/runner/claude.ts +159 -10
  218. package/src/runner/codex.ts +14 -2
  219. package/src/runner/config.ts +114 -1
  220. package/src/runner/desk.ts +23 -4
  221. package/src/runner/message.ts +144 -35
  222. package/src/runner/runner.ts +658 -35
  223. package/src/runner/slack-status.ts +423 -0
  224. package/src/runner/slack.ts +1509 -128
  225. package/src/runner/types.ts +200 -5
  226. package/src/runner/usage.ts +16 -3
  227. package/src/runner.ts +20 -1
  228. package/src/schemas.ts +161 -3
  229. package/src/vocabulary.ts +9 -0
  230. package/src/wake-text.ts +133 -0
@@ -13,7 +13,7 @@ import {
13
13
  import { type RestSignal, type RestTranscriptEventInput, RUNNER_CHOICE } from "../schemas.js";
14
14
  import { hasForbiddenCodePoint } from "../text.js";
15
15
  import type { AgentStateReason, TranscriptKind } from "../vocabulary.js";
16
- import type { RunnerConfig } from "./config.js";
16
+ import { type RunnerConfig, STATUS_AFTER } from "./config.js";
17
17
  import {
18
18
  type Attached,
19
19
  composeSignals,
@@ -23,9 +23,11 @@ import {
23
23
  makeMark,
24
24
  type Slept,
25
25
  sleptOf,
26
+ wakeTextOf,
26
27
  } from "./message.js";
27
28
  import { cutShown, cutShownEnd, type Redactor, redactorOf } from "./redact.js";
28
29
  import type {
30
+ AgentStatus,
29
31
  Driver,
30
32
  DriverEvent,
31
33
  DriverSession,
@@ -62,6 +64,15 @@ import {
62
64
  // numbered and kept for the next batch as it arrives, so that nothing of a session is left
63
65
  // behind when the session ends.
64
66
 
67
+ /** How long a wake a source raised is waited for on the stream before the source is shown nothing of it. */
68
+ const RAISED_MS = 60_000;
69
+ /** From how far away a moment is said with its day in a status. */
70
+ const FAR_MS = 20 * 60 * 60_000;
71
+ /** How long the runner's end waits for the wake sources to take back what they showed. */
72
+ const SHOWN_END_MS = 3000;
73
+ /** What the wake sources are said as the runner ends. */
74
+ const LAST_STATUS: AgentStatus = { state: "idle", last: true };
75
+
65
76
  /** How often the runner says it is there. */
66
77
  export const HEARTBEAT_MS = 30_000;
67
78
  /** How often what the product did is sent, while there is something to send. */
@@ -69,6 +80,18 @@ export const BATCH_MS = 1000;
69
80
  /** How long what arrives by itself waits after the agent could not go on: at first, and at most, twice as long after each try that ends the same way. */
70
81
  export const COOL_DOWN_MS = 15 * 60_000;
71
82
  export const MAX_COOL_DOWN_MS = 4 * 60 * 60_000;
83
+ /**
84
+ * How long the runner holds an ending that waits for the agent's turn, a model chosen, the
85
+ * account's own reset, an update or a `runner.json` that changed, for the sub-agents at work
86
+ * in the background of the session (ADR-0162): counted from when it first held one for them.
87
+ */
88
+ export const SUBAGENTS_MS = 60 * 60_000;
89
+ /**
90
+ * How long a session that had sub-agents in the background is not taken for idle after one
91
+ * ended or a turn did: the product hands the agent a sub-agent's report in a turn it starts
92
+ * itself, a moment after.
93
+ */
94
+ export const REPORT_MS = 10_000;
72
95
  /** How long the runner waits before it asks for its stream of signals again. */
73
96
  export const RECONNECT_MS = 5000;
74
97
  /** What an autosave's commit says: the runner's, and never the agent's own words. */
@@ -92,6 +115,12 @@ const SOURCE_HELD_MS = 60_000;
92
115
  const SLEPT_MS = 60_000;
93
116
  /** The kinds of event that are the agent's own answer: what it said, thought or called. */
94
117
  const ANSWERS: ReadonlySet<TranscriptKind> = new Set(["assistant", "thinking", "tool_call"]);
118
+ /**
119
+ * How long before its wake is on the record a message may have been written (ADR-0166): what a
120
+ * wake source reads for a wake, and the wakes ahead of it, are waited for half a minute at the
121
+ * most, and the messenger's clock and the console's differ by less than the rest.
122
+ */
123
+ const RAISED_AFTER_MS = 60_000;
95
124
  /** How many signals the runner writes down as kept for the agent beside what the record sends again. */
96
125
  const MAX_KEPT = 50;
97
126
  /** How long before its moment a timer may ring: a delivery asked for at a moment is taken within it. */
@@ -142,7 +171,9 @@ export type RunnerClient = Pick<
142
171
  | "secret"
143
172
  | "readSignalFile"
144
173
  | "raiseWake"
145
- >;
174
+ > &
175
+ // Who wrote at a messenger (ADR-0164): asked where the client has it, by a wake source.
176
+ Partial<Pick<ConsoleClient, "writers">>;
146
177
 
147
178
  /** What the runner keeps between its own restarts. No secret is in it. */
148
179
  export interface RunnerState {
@@ -173,8 +204,18 @@ export interface RunnerState {
173
204
  * runner started meanwhile takes them from the stream once more.
174
205
  */
175
206
  readonly kept?: readonly number[] | undefined;
207
+ /**
208
+ * When the conversation the agent goes on with began, in milliseconds since the epoch
209
+ * (ADR-0166): what it was handed before, it holds no more, and a wake source counts nothing
210
+ * from before as brought. Left out by a runner of before, whose conversation is taken to hold
211
+ * all it was handed.
212
+ */
213
+ readonly began?: number | undefined;
176
214
  }
177
215
 
216
+ /** What a wake source keeps, as it is written down: each name with what stands under it, the oldest first. */
217
+ export type KeptBySource = readonly (readonly [string, string])[];
218
+
178
219
  export interface RunnerOptions {
179
220
  readonly client: RunnerClient;
180
221
  readonly driver: Driver;
@@ -244,8 +285,25 @@ export interface RunnerOptions {
244
285
  readonly sources: readonly WakeSource[];
245
286
  readonly fetch: WakeHost["fetch"];
246
287
  readonly socket: WakeHost["socket"];
288
+ /**
289
+ * Where what a wake source keeps (`WakeHost.kept`) outlasts the runner (ADR-0166): read
290
+ * when the source is started, and written when it changed, a source at a time by its
291
+ * name. Left out, a runner started again begins with nothing kept.
292
+ */
293
+ readonly kept?:
294
+ | {
295
+ load(source: string): Promise<KeptBySource | undefined>;
296
+ save(source: string, kept: KeptBySource): Promise<void>;
297
+ }
298
+ | undefined;
247
299
  }
248
300
  | undefined;
301
+ /**
302
+ * The language of the workspace, where whoever starts the runner knows it: what a wake source
303
+ * shows of the agent to the people at its messenger is in it, where the source has the words
304
+ * (ADR-0170). Left out, the source's own.
305
+ */
306
+ readonly language?: string | undefined;
249
307
  /**
250
308
  * How the desk's `runner.json` stands against the one this runner was started with (ADR-0144):
251
309
  * the same, another that reads, or one that does not read, with what is wrong with it in a few
@@ -265,6 +323,8 @@ export interface RunnerOptions {
265
323
  holdMs: number;
266
324
  maxHoldMs: number;
267
325
  resetMarginMs: number;
326
+ subagentsMs: number;
327
+ reportMs: number;
268
328
  }>;
269
329
  /** The bounds, for a test to lower. */
270
330
  readonly bounds?: Partial<{ outboxBytes: number }>;
@@ -298,6 +358,12 @@ interface Outgoing {
298
358
  gone?: number;
299
359
  }
300
360
 
361
+ /** What an ending is for, as the record says it of one that waits for sub-agents (ADR-0162). */
362
+ const FOR_UPDATE = "for an update of the command the runner runs from";
363
+ const FOR_CHANGE = "for the desk's runner.json, which changed";
364
+ const FOR_CHOICE = "for the model or the effort chosen";
365
+ const FOR_RESET = "for the account's own reset";
366
+
301
367
  /** What an event takes of a batch as the console counts one: its JSON, and the ids of its pictures. */
302
368
  const sentBytes = (event: Outgoing): number =>
303
369
  Buffer.byteLength(
@@ -353,8 +419,30 @@ interface OpenSession {
353
419
  */
354
420
  taken: (readonly RestSignal[])[];
355
421
  unread: number;
422
+ /**
423
+ * The signals the product took before it put the conversation in fewer words (ADR-0166), by
424
+ * number: the conversation holds a summary of them at best, so a usage limit met afterwards
425
+ * has them said whole again, and not named.
426
+ */
427
+ readonly summarized: Set<number>;
356
428
  /** Whether the agent was handed word that it is back from a usage limit, and has not answered since. */
357
429
  returning: boolean;
430
+ /** How many sub-agents are at work in its background, as the driver said last (ADR-0162). */
431
+ background: number;
432
+ /**
433
+ * Whether the product said it began a turn that did not end since. With no turn of the
434
+ * runner's under way, it is one the product started itself, as it does to hand the agent the
435
+ * report of a sub-agent that ended.
436
+ */
437
+ own: boolean;
438
+ /** Until when the product is left to start such a turn: 0 in a session that had no sub-agent in the background. */
439
+ reportBy: number;
440
+ /**
441
+ * Since when the runner holds an ending for what goes on with no turn of its own under way
442
+ * (ADR-0162), and whether the record says that it waits and that it waited in vain.
443
+ */
444
+ heldSince?: number | undefined;
445
+ heldSaid?: "waits" | "over" | undefined;
358
446
  /** The number of the last event of it. */
359
447
  n: number;
360
448
  /** What the product did and the console has not been sent yet, and what that holds of memory. */
@@ -386,6 +474,8 @@ type Message =
386
474
  | { readonly t: "answered"; readonly session: OpenSession }
387
475
  | { readonly t: "deliver" }
388
476
  | { readonly t: "flush" }
477
+ /** A wake source raised something, or what it raised was not taken: how the agent stands to it is looked at again. */
478
+ | { readonly t: "shown" }
389
479
  | { readonly t: "heartbeat" }
390
480
  | { readonly t: "stop" };
391
481
 
@@ -450,6 +540,22 @@ const lineOf = (value: string | null | undefined): string | null => {
450
540
  return line.length === 0 || hasForbiddenCodePoint(line) ? null : line;
451
541
  };
452
542
 
543
+ /** What a wake source keeps, which says whether it changed since it was last written down. */
544
+ class Kept extends Map<string, string> {
545
+ changed = false;
546
+
547
+ override set(name: string, value: string): this {
548
+ this.changed = true;
549
+ return super.set(name, value);
550
+ }
551
+
552
+ override delete(name: string): boolean {
553
+ const had = super.delete(name);
554
+ this.changed ||= had;
555
+ return had;
556
+ }
557
+ }
558
+
453
559
  export function createRunner(options: RunnerOptions): Runner {
454
560
  const { client, driver, config, log } = options;
455
561
  const timing = {
@@ -462,6 +568,8 @@ export function createRunner(options: RunnerOptions): Runner {
462
568
  holdMs: HOLD_MS,
463
569
  maxHoldMs: MAX_HOLD_MS,
464
570
  resetMarginMs: RESET_MARGIN_MS,
571
+ subagentsMs: SUBAGENTS_MS,
572
+ reportMs: REPORT_MS,
465
573
  ...options.timing,
466
574
  };
467
575
  /** How long what an hour's bound refused is held back: the first time, and twice as long each time after. */
@@ -527,9 +635,38 @@ export function createRunner(options: RunnerOptions): Runner {
527
635
  let received = 0;
528
636
  let handled = 0;
529
637
  let conversation: string | undefined;
530
- let stands: { state: "running" | "stopped" | "refused" | "failed"; reason: AgentStateReason } = {
638
+ /**
639
+ * When the conversation the agent goes on with began (ADR-0166), 0 where nothing says, and
640
+ * whether that moment is of a conversation no session has begun yet: the session that begins
641
+ * it then leaves the moment as it stands.
642
+ */
643
+ let began = 0;
644
+ let renewed = false;
645
+ /**
646
+ * The signals the conversation holds already, by number (ADR-0166): the product of the open
647
+ * session took them there as a usage limit was reached, its driver vouching that what it
648
+ * took stands (`can.holdsTaken`), and the agent never answered. Handed over again in that
649
+ * session, they are named and not said a second time. Until a turn completes, the
650
+ * conversation is let go or put in fewer words, or the session ends: nothing says before a
651
+ * session's first message whether its product went on with the conversation, so a session
652
+ * begun after is said them whole.
653
+ */
654
+ const above = new Set<number>();
655
+ /** What each wake source keeps, by its name, and whether it changed since it was last written. */
656
+ const keeps = new Map<string, Kept>();
657
+ /**
658
+ * How the agent stands and why, with when the runner said so (`at`): the console is told that
659
+ * moment with the reason, since a reason is said again the same under a state that stays, a
660
+ * turn that completed after another say, and nothing else tells the two apart.
661
+ */
662
+ let stands: {
663
+ state: "running" | "stopped" | "refused" | "failed";
664
+ reason: AgentStateReason;
665
+ at: number;
666
+ } = {
531
667
  state: "running",
532
668
  reason: "started",
669
+ at: options.now(),
533
670
  };
534
671
  let said = "";
535
672
  let settings: { model: string | null; effort: string | null } = { model: null, effort: null };
@@ -612,6 +749,28 @@ export function createRunner(options: RunnerOptions): Runner {
612
749
  string,
613
750
  { state: "connected" | "waiting" | "failing"; since: number; why: string | undefined }
614
751
  >();
752
+ /**
753
+ * The wake sources that show how the agent stands (ADR-0170), by name: the host each runs
754
+ * with, and what it was last said and when.
755
+ */
756
+ const shows = new Map<
757
+ string,
758
+ { readonly source: WakeSource; readonly host: WakeHost; said: string; at: number }
759
+ >();
760
+ /**
761
+ * What `runner.json` says of how the agent stands is shown: `false` for not at all, and the
762
+ * sources' own way where it says nothing, a desk of before and a config put together by hand
763
+ * among them.
764
+ */
765
+ const shownAs: NonNullable<RunnerConfig["status"]> = config.status ?? {};
766
+ /** Since when the agent is at work without a pause: a turn under way, or something that goes on in its session with none. */
767
+ let atWorkSince: number | undefined;
768
+ /**
769
+ * What each wake source raised that the stream has not brought back yet: when it was raised,
770
+ * and its number once the console took it. A message that reached the runner is on its way
771
+ * to the agent from then on, which its source shows.
772
+ */
773
+ const raising = new Map<string, Set<{ readonly at: number; number: number | undefined }>>();
615
774
  /**
616
775
  * The signals a product was handed and never took, since it did not start or was not signed
617
776
  * in, which are kept to be sent again; and, of those, the ones a reset gave one more try: a
@@ -650,14 +809,114 @@ export function createRunner(options: RunnerOptions): Runner {
650
809
  ? {}
651
810
  : { limited: { since: limited.since, until: limited.until } }),
652
811
  ...(kept.length === 0 ? {} : { kept }),
812
+ ...(began === 0 ? {} : { began }),
653
813
  });
654
814
  } catch {
655
815
  log("the runner's state could not be written; it goes on from the console's record");
656
816
  }
657
817
  };
658
818
 
819
+ /**
820
+ * When a conversation that begins now is taken to have begun (ADR-0166): now, or, where wakes
821
+ * of a wake source wait to be handed over, a little before the oldest of them was raised.
822
+ * They are handed over in the new conversation, which holds them from then on: counted as
823
+ * from before it, their messages would be carried once more with the next wake. `handed` is
824
+ * what the conversation holds beside what waits: what a session was handed in it already,
825
+ * where the moment is set once the session is under way.
826
+ */
827
+ const beginsAt = (handed: readonly RestSignal[] = []): number => {
828
+ let at = options.now();
829
+ for (const signal of [...pending, ...handed]) {
830
+ const raised = signal.source === "messenger" ? Date.parse(signal.at) : Number.NaN;
831
+ if (Number.isFinite(raised)) {
832
+ at = Math.min(at, raised - RAISED_AFTER_MS);
833
+ }
834
+ }
835
+ return at;
836
+ };
837
+
838
+ /**
839
+ * The driver named the conversation its session runs in. Where it began one in place of the
840
+ * one it was asked to go on with (`anew`), the agent's conversation began with the session
841
+ * (ADR-0166): it holds what the session was handed, and nothing from before.
842
+ */
843
+ const converses = (
844
+ target: OpenSession,
845
+ event: Extract<DriverEvent, { type: "conversation" }>,
846
+ ): void => {
847
+ conversation = event.id;
848
+ if (event.anew === true) {
849
+ began = beginsAt([...target.sent, ...target.handed.flatMap((message) => message.signals)]);
850
+ above.clear();
851
+ }
852
+ };
853
+
854
+ /**
855
+ * The product put the conversation in fewer words (ADR-0166): what the agent was handed
856
+ * before is a summary at best, so what a wake source brought before counts no more, and what
857
+ * the product took is not named as standing there. What it was handed and has not taken yet
858
+ * it reads after, whole: the conversation is taken to hold that.
859
+ */
860
+ const summarized = (target: OpenSession): void => {
861
+ began = beginsAt(target.handed.flatMap((message) => message.signals));
862
+ above.clear();
863
+ for (const signal of target.taken.flat()) {
864
+ target.summarized.add(signal.number);
865
+ }
866
+ };
867
+
868
+ /**
869
+ * When the agent's conversation began, as a wake source is told it (ADR-0166): never after
870
+ * now. A moment ahead of the clock, kept by a runner whose machine's clock ran ahead or set
871
+ * back since, is none a message was written before: counted from, every wake of a place
872
+ * would carry again what the last one carried, for as long as the clock is behind it. It is
873
+ * taken as now, and kept so.
874
+ */
875
+ const beganBy = (): number => {
876
+ const now = options.now();
877
+ if (began > now) {
878
+ began = now;
879
+ void persist();
880
+ }
881
+ return began;
882
+ };
883
+
884
+ /**
885
+ * Lets go of the conversation kept: the next session begins a new one, which holds nothing
886
+ * the agent was handed before this moment (ADR-0166), but for what waits to be handed over.
887
+ */
888
+ const letGo = (): void => {
889
+ conversation = undefined;
890
+ began = beginsAt();
891
+ renewed = true;
892
+ above.clear();
893
+ };
894
+
895
+ /** Writes what the wake sources keep where it changed since it was last written. */
896
+ const keepKept = async (): Promise<void> => {
897
+ const store = options.wakes?.kept;
898
+ if (store === undefined) {
899
+ return;
900
+ }
901
+ for (const [name, kept] of keeps) {
902
+ if (!kept.changed) {
903
+ continue;
904
+ }
905
+ kept.changed = false;
906
+ try {
907
+ await store.save(name, [...kept]);
908
+ } catch {
909
+ // Kept in memory still, and written with the next change.
910
+ sayOnce(
911
+ `kept ${name}`,
912
+ `what the wake source ${name} keeps could not be written; it is kept while the runner runs`,
913
+ );
914
+ }
915
+ }
916
+ };
917
+
659
918
  const setState = (state: typeof stands.state, reason: AgentStateReason): void => {
660
- stands = { state, reason };
919
+ stands = { state, reason, at: options.now() };
661
920
  push({ t: "heartbeat" });
662
921
  };
663
922
 
@@ -928,6 +1187,56 @@ export function createRunner(options: RunnerOptions): Runner {
928
1187
  }
929
1188
  };
930
1189
 
1190
+ /** Whether something goes on in a session with no turn of the runner's under way: sub-agents in the background, or a turn the product started or is about to. */
1191
+ const goesOn = (target: OpenSession): boolean =>
1192
+ target.background > 0 || target.own || options.now() < target.reportBy;
1193
+
1194
+ /**
1195
+ * Whether an ending is held still for what goes on in the session (ADR-0162): for as long as
1196
+ * the runner waits for it, counted from when it first held an ending so, and said on the
1197
+ * record once where sub-agents are what it waits for, and once more where it waited in vain.
1198
+ */
1199
+ const within = (target: OpenSession, why: string): boolean => {
1200
+ const now = options.now();
1201
+ target.heldSince ??= now;
1202
+ const waits = now - target.heldSince < timing.subagentsMs;
1203
+ const word = waits ? "waits" : "over";
1204
+ if (target.background > 0 && target.heldSaid !== word) {
1205
+ target.heldSaid = word;
1206
+ const many = `${target.background} ${target.background === 1 ? "sub-agent" : "sub-agents"} at work in the background`;
1207
+ const most = `${Math.round(timing.subagentsMs / 60_000)} minutes`;
1208
+ record(
1209
+ target,
1210
+ "status",
1211
+ waits
1212
+ ? `The session is to end ${why}, with ${many}: the runner waits until none is at work, ${most} at most.`
1213
+ : `The runner waited ${most} for the sub-agents in the background, and waits no longer: the session ends ${why}, with ${many}.`,
1214
+ );
1215
+ log(
1216
+ `session ${target.id} is to end ${why}, with ${many}: the runner ${waits ? "waits for them" : "waited for long enough"}`,
1217
+ );
1218
+ }
1219
+ return waits;
1220
+ };
1221
+
1222
+ /**
1223
+ * Whether a session is at work, for an ending that waits until it is not: a turn is under
1224
+ * way, or sub-agents work on in the background, or the product started a turn of its own,
1225
+ * the last two for as long as the runner waits for them. What a supervisor ends, a stop, a
1226
+ * restart or a reset, asks nothing of it.
1227
+ */
1228
+ const busy = (target: OpenSession | undefined, why: string): boolean =>
1229
+ target !== undefined && (target.turn || (goesOn(target) && within(target, why)));
1230
+
1231
+ /**
1232
+ * Whether the runner is to end for an update and hands nothing more over (ADR-0101). Not
1233
+ * while it waits for sub-agents in the background: that may take an hour, in which the agent
1234
+ * goes on reading what it is sent.
1235
+ */
1236
+ const closing = (): boolean =>
1237
+ updatedTo !== undefined &&
1238
+ !(session !== undefined && session.background > 0 && within(session, FOR_UPDATE));
1239
+
931
1240
  /** Reads what the product does: the blocks are numbered and kept as they arrive, its own words go to the queue. */
932
1241
  const pump = async (target: OpenSession): Promise<void> => {
933
1242
  try {
@@ -943,7 +1252,13 @@ export function createRunner(options: RunnerOptions): Runner {
943
1252
  }
944
1253
  }
945
1254
  record(target, event.kind, event.text, event.data, event.pictures);
1255
+ } else if (event.type === "background") {
1256
+ target.background = event.agents;
1257
+ target.reportBy = options.now() + timing.reportMs;
1258
+ } else if (event.type === "turn_started") {
1259
+ target.own = true;
946
1260
  } else if (event.type === "cannot_go_on") {
1261
+ target.own = false;
947
1262
  // Counted here, in the order the product wrote: the queue is behind what is read.
948
1263
  push({ t: "driver", session: target, event, unread: target.unread });
949
1264
  } else {
@@ -951,6 +1266,11 @@ export function createRunner(options: RunnerOptions): Runner {
951
1266
  target.unread += 1;
952
1267
  } else if (event.type === "turn_completed") {
953
1268
  target.unread = 0;
1269
+ target.own = false;
1270
+ // A report that came while the turn was under way is read in the next.
1271
+ if (target.reportBy > 0) {
1272
+ target.reportBy = options.now() + timing.reportMs;
1273
+ }
954
1274
  }
955
1275
  push({ t: "driver", session: target, event });
956
1276
  }
@@ -1042,7 +1362,11 @@ export function createRunner(options: RunnerOptions): Runner {
1042
1362
  took: false,
1043
1363
  taken: [],
1044
1364
  unread: 0,
1365
+ summarized: new Set(),
1045
1366
  returning: false,
1367
+ background: 0,
1368
+ own: false,
1369
+ reportBy: 0,
1046
1370
  n: 0,
1047
1371
  outbox: [],
1048
1372
  waiting: 0,
@@ -1054,6 +1378,16 @@ export function createRunner(options: RunnerOptions): Runner {
1054
1378
  started.pumped = pump(started);
1055
1379
  session = started;
1056
1380
  renew = false;
1381
+ if (resume === undefined) {
1382
+ // A conversation of its own: it holds nothing the agent was handed before (ADR-0166).
1383
+ // Where it was let go a moment ago, at a reset say, it began then, and what was kept
1384
+ // for it since is handed over in it.
1385
+ if (!renewed) {
1386
+ began = beginsAt();
1387
+ }
1388
+ above.clear();
1389
+ }
1390
+ renewed = false;
1057
1391
  log(
1058
1392
  `session ${started.id} began${resume === undefined ? "" : ", going on with the conversation before"}`,
1059
1393
  );
@@ -1076,6 +1410,9 @@ export function createRunner(options: RunnerOptions): Runner {
1076
1410
  }
1077
1411
  await target.pumped;
1078
1412
  await hearLast(target);
1413
+ // What was named as standing in the conversation was taken by this session's product: a
1414
+ // session begun after is said it whole (ADR-0166).
1415
+ above.clear();
1079
1416
  // What the product was handed and never took is sent again, by the console where the
1080
1417
  // runner itself ends and by the runner where the product had not started; else it is on
1081
1418
  // the record as never read.
@@ -1180,7 +1517,7 @@ export function createRunner(options: RunnerOptions): Runner {
1180
1517
  deliverAt = undefined;
1181
1518
  // Nothing more is handed over once the runner is to end for an update: what waits is sent
1182
1519
  // again by the console, in order, to the runner started after.
1183
- if (held || updatedTo !== undefined) {
1520
+ if (held || closing()) {
1184
1521
  return;
1185
1522
  }
1186
1523
  // An agent its usage limit stopped is brought back by the runner itself, with nothing to
@@ -1217,9 +1554,16 @@ export function createRunner(options: RunnerOptions): Runner {
1217
1554
  );
1218
1555
  // An agent that is back from a usage limit goes on in the conversation it was stopped in:
1219
1556
  // what it was doing is there, and the day after begins the next one.
1220
- if (anew && session?.turn !== true && limited === undefined) {
1557
+ // Not with sub-agents at work in its background either (ADR-0162): the conversation they
1558
+ // report to goes on, as it does under a turn.
1559
+ if (
1560
+ anew &&
1561
+ session?.turn !== true &&
1562
+ (session === undefined || !goesOn(session)) &&
1563
+ limited === undefined
1564
+ ) {
1221
1565
  await end("restarted");
1222
- conversation = undefined;
1566
+ letGo();
1223
1567
  }
1224
1568
  const target = session ?? (await begin());
1225
1569
  if (target === undefined) {
@@ -1253,6 +1597,11 @@ export function createRunner(options: RunnerOptions): Runner {
1253
1597
  // what the driver says of its product.
1254
1598
  const takesPictures = target.driver.images?.() ?? driver.can.images;
1255
1599
  for (const signal of batch) {
1600
+ // What is only named is handed over with nothing: its files stand in the desk and its
1601
+ // pictures in the conversation, with the message the product took (ADR-0166).
1602
+ if (above.has(signal.number)) {
1603
+ continue;
1604
+ }
1256
1605
  const taken = new Set<string>();
1257
1606
  for (const file of signal.attachments) {
1258
1607
  const picture = PICTURE_TYPES.has(file.contentType);
@@ -1299,10 +1648,15 @@ export function createRunner(options: RunnerOptions): Runner {
1299
1648
  ]);
1300
1649
  }
1301
1650
  }
1651
+ // What the conversation holds already, the product having taken it there as the limit was
1652
+ // reached, is named and not said again (ADR-0166).
1653
+ const named = batch.filter((signal) => above.has(signal.number)).length;
1302
1654
  const composed = composeSignals(batch, {
1303
1655
  mark: target.mark,
1304
1656
  time: options.time,
1305
1657
  attached: (signal) => attached.get(signal.number) ?? [],
1658
+ own: options.account,
1659
+ above: (signal) => above.has(signal.number),
1306
1660
  });
1307
1661
  const intro = target.first ? introOf(target.mark, resetBy) : undefined;
1308
1662
  // What the runner says of its own goes ahead of the signals, under its own header: that
@@ -1318,7 +1672,13 @@ export function createRunner(options: RunnerOptions): Runner {
1318
1672
  ? undefined
1319
1673
  : runnerSays(
1320
1674
  target.mark,
1321
- limitWords(returned, { now: options.now(), moment, follow: batch.length, early }),
1675
+ limitWords(returned, {
1676
+ now: options.now(),
1677
+ moment,
1678
+ follow: batch.length - named,
1679
+ above: named,
1680
+ early,
1681
+ }),
1322
1682
  ),
1323
1683
  told === undefined ? undefined : sleptOf(told, { mark: target.mark, moment }),
1324
1684
  composed.text,
@@ -1452,7 +1812,9 @@ export function createRunner(options: RunnerOptions): Runner {
1452
1812
  * Hears what the product said as its session was ended. Its words wait in the queue behind
1453
1813
  * whatever ended the session, and are let go there once the session is no longer the open
1454
1814
  * one: a message it said it took then is taken, and not sent again, and the conversation it
1455
- * named is the one to go on with, where that message is.
1815
+ * named is the one to go on with, where that message is. That it began that conversation
1816
+ * anew, or put it in fewer words, moves the moment the conversation began as it does in a
1817
+ * session that goes on (ADR-0166): the next session goes on with what was said here.
1456
1818
  */
1457
1819
  const hearLast = async (target: OpenSession): Promise<void> => {
1458
1820
  let named = false;
@@ -1462,7 +1824,10 @@ export function createRunner(options: RunnerOptions): Runner {
1462
1824
  }
1463
1825
  const { event } = message;
1464
1826
  if (event.type === "conversation") {
1465
- conversation = event.id;
1827
+ converses(target, event);
1828
+ named = true;
1829
+ } else if (event.type === "compacted") {
1830
+ summarized(target);
1466
1831
  named = true;
1467
1832
  } else if (event.type === "taken") {
1468
1833
  await take(target);
@@ -1681,7 +2046,7 @@ export function createRunner(options: RunnerOptions): Runner {
1681
2046
  limited = undefined;
1682
2047
  await end(signal.kind === "reset" ? "reset" : "restarted");
1683
2048
  if (signal.kind === "reset") {
1684
- conversation = undefined;
2049
+ letGo();
1685
2050
  resetBy = { by, ...(signal.text.trim().length > 0 ? { number: signal.number } : {}) };
1686
2051
  // What a product was handed and never took is tried once more, in the new
1687
2052
  // conversation: a product that does not start with it again is not sent it a
@@ -1711,9 +2076,9 @@ export function createRunner(options: RunnerOptions): Runner {
1711
2076
  }
1712
2077
  await account(signal);
1713
2078
  if (session !== undefined && !(await session.driver.set(settings))) {
1714
- // Taken when the product starts: the session ends when no turn is under way, and the next has it.
2079
+ // Taken when the product starts: the session ends when it is not at work, and the next has it.
1715
2080
  renew = true;
1716
- if (!session.turn) {
2081
+ if (!busy(session, FOR_CHOICE)) {
1717
2082
  await end("restarted");
1718
2083
  }
1719
2084
  }
@@ -1732,7 +2097,7 @@ export function createRunner(options: RunnerOptions): Runner {
1732
2097
  }
1733
2098
  // Nothing is handed over once the runner is to end for an update: the turn is
1734
2099
  // stopped all the same, and what waits is sent again to the runner started after.
1735
- if (pending.length > 0 && updatedTo === undefined) {
2100
+ if (pending.length > 0 && !closing()) {
1736
2101
  if (stops) {
1737
2102
  await deliver("now");
1738
2103
  } else {
@@ -1745,7 +2110,7 @@ export function createRunner(options: RunnerOptions): Runner {
1745
2110
  return;
1746
2111
  }
1747
2112
  pending.push(signal);
1748
- if (stops && updatedTo !== undefined && session !== undefined) {
2113
+ if (stops && closing() && session !== undefined) {
1749
2114
  // Its words are not handed to a runner that is to end: the turn is stopped, the
1750
2115
  // runner ends for the update, and the console sends them again to the one after.
1751
2116
  await stopTurn(session);
@@ -1787,6 +2152,17 @@ export function createRunner(options: RunnerOptions): Runner {
1787
2152
  for (const signal of untaken) {
1788
2153
  owed.delete(signal.number);
1789
2154
  }
2155
+ // What the product took stands in the conversation, which the agent goes on in: handed
2156
+ // over again in this session, it is named and not said a second time (ADR-0166). Only
2157
+ // where the driver vouches that what it said was taken stands there, and not for what was
2158
+ // taken before the product put the conversation in fewer words.
2159
+ if (driver.can.holdsTaken === true) {
2160
+ for (const signal of unanswered) {
2161
+ if (!target.summarized.has(signal.number)) {
2162
+ above.add(signal.number);
2163
+ }
2164
+ }
2165
+ }
1790
2166
  target.taken = [];
1791
2167
  target.sent = [];
1792
2168
  target.returning = false;
@@ -1916,7 +2292,7 @@ export function createRunner(options: RunnerOptions): Runner {
1916
2292
  return;
1917
2293
  }
1918
2294
  await end("reset");
1919
- conversation = undefined;
2295
+ letGo();
1920
2296
  // Where a supervisor reset the agent meanwhile, the first message says so: the account's
1921
2297
  // words are read under their own header all the same.
1922
2298
  resetBy ??= {
@@ -1946,7 +2322,7 @@ export function createRunner(options: RunnerOptions): Runner {
1946
2322
  return;
1947
2323
  }
1948
2324
  case "conversation": {
1949
- conversation = event.id;
2325
+ converses(target, event);
1950
2326
  await persist();
1951
2327
  return;
1952
2328
  }
@@ -1966,6 +2342,8 @@ export function createRunner(options: RunnerOptions): Runner {
1966
2342
  }
1967
2343
  target.sent = [];
1968
2344
  target.returning = false;
2345
+ // The agent is done with all it was handed: nothing of it is owed a second saying.
2346
+ above.clear();
1969
2347
  if (limited !== undefined) {
1970
2348
  // A turn completed: whatever stopped the agent is over.
1971
2349
  limited = undefined;
@@ -1975,7 +2353,7 @@ export function createRunner(options: RunnerOptions): Runner {
1975
2353
  waits = undefined;
1976
2354
  setState("running", "completed");
1977
2355
  }
1978
- if (renew) {
2356
+ if (renew && !busy(target, FOR_CHOICE)) {
1979
2357
  await end("restarted");
1980
2358
  }
1981
2359
  if (pending.length > 0) {
@@ -1983,6 +2361,11 @@ export function createRunner(options: RunnerOptions): Runner {
1983
2361
  }
1984
2362
  return;
1985
2363
  }
2364
+ case "compacted": {
2365
+ summarized(target);
2366
+ await persist();
2367
+ return;
2368
+ }
1986
2369
  case "usage": {
1987
2370
  noteUsage(usageSeen, event.windows, options.now());
1988
2371
  await onUsage(target, event.windows);
@@ -2155,22 +2538,166 @@ export function createRunner(options: RunnerOptions): Runner {
2155
2538
  }
2156
2539
  };
2157
2540
 
2541
+ /**
2542
+ * Whether the agent is thinking over what a wake source raised (ADR-0170): the turn a wake
2543
+ * of that source's was handed over in is under way, or one is on its way to the agent,
2544
+ * raised and not back on the stream yet or waiting to be handed over. What waits is nothing
2545
+ * the agent thinks over while nothing is handed over at all, a supervisor's stop standing
2546
+ * or the agent unable to go on.
2547
+ */
2548
+ const thinksOf = (name: string, now: number): boolean => {
2549
+ const own = (signal: RestSignal): boolean =>
2550
+ signal.kind === "wake" &&
2551
+ signal.source === "messenger" &&
2552
+ signal.key?.startsWith(`${name}:`) === true;
2553
+ if (session?.turn === true && session.sent.some(own)) {
2554
+ return true;
2555
+ }
2556
+ if (held || waits !== undefined) {
2557
+ return false;
2558
+ }
2559
+ const raised = raising.get(name);
2560
+ for (const one of raised ?? []) {
2561
+ // Back on the stream, and among what waits from then on; or never to come, for all the
2562
+ // runner waits for it.
2563
+ if ((one.number !== undefined && one.number <= handled) || now - one.at >= RAISED_MS) {
2564
+ raised?.delete(one);
2565
+ }
2566
+ }
2567
+ return (raised?.size ?? 0) > 0 || pending.some(own);
2568
+ };
2569
+
2570
+ /**
2571
+ * How the agent stands to whoever waits for it at a wake source (ADR-0170). Its usage limit
2572
+ * first, until the moment the product named where it named one: nothing is answered before
2573
+ * it, whatever else goes on, and past it the runner brings the agent back in a turn as any
2574
+ * other. Then that it has been at work for longer than `runner.json` gives a turn, whatever
2575
+ * woke it; then that it thinks over what this source raised.
2576
+ */
2577
+ const statusFor = (name: string, now: number): AgentStatus => {
2578
+ if (limited !== undefined && (limited.until === undefined || now < limited.until)) {
2579
+ return limited.until === undefined
2580
+ ? { state: "limited" }
2581
+ : { state: "limited", until: limited.until };
2582
+ }
2583
+ if (
2584
+ atWorkSince !== undefined &&
2585
+ shownAs !== false &&
2586
+ now - atWorkSince >= (shownAs.after ?? STATUS_AFTER) * 1000
2587
+ ) {
2588
+ return { state: "working" };
2589
+ }
2590
+ return { state: thinksOf(name, now) ? "thinking" : "idle" };
2591
+ };
2592
+
2593
+ /**
2594
+ * A moment as a status says one: the hour and the minute in the workspace's zone, and with
2595
+ * its day where it is most of a day away, as the command writes a moment's.
2596
+ */
2597
+ const statusTime = (at: number): string => {
2598
+ const iso = new Date(at).toISOString();
2599
+ const written = moment(iso);
2600
+ const day = /^\d{4}-(\d{2}-\d{2})T(\d{2}:\d{2})/.exec(written);
2601
+ return at - options.now() < FAR_MS || day === null
2602
+ ? options.time(iso)
2603
+ : `${day[1]} ${day[2]}${written.endsWith("Z") ? " UTC" : ""}`;
2604
+ };
2605
+
2606
+ /** Says to a wake source how the agent stands. What the source cannot show costs the agent nothing. */
2607
+ const say = (
2608
+ one: { readonly source: WakeSource; readonly host: WakeHost },
2609
+ status: AgentStatus,
2610
+ signal: AbortSignal,
2611
+ ): Promise<void> =>
2612
+ Promise.resolve()
2613
+ .then(() =>
2614
+ one.source.show?.(one.host, status, {
2615
+ words: shownAs === false ? {} : shownAs,
2616
+ language: options.language,
2617
+ now: options.now,
2618
+ time: statusTime,
2619
+ signal,
2620
+ }),
2621
+ )
2622
+ .catch((error: unknown) => {
2623
+ sayOnce(
2624
+ `status ${one.source.name}`,
2625
+ `the wake source ${one.source.name} could not show how the agent stands (${codeOf(error)})`,
2626
+ );
2627
+ });
2628
+
2629
+ /**
2630
+ * Has the wake sources show how the agent stands (ADR-0170): each is said when that changed,
2631
+ * and again every heartbeat while it stands, so that a source keeps what it shows from
2632
+ * lapsing. Nothing is said where `runner.json` turned it off.
2633
+ */
2634
+ const showStatus = (): void => {
2635
+ if (shownAs === false) {
2636
+ return;
2637
+ }
2638
+ const now = options.now();
2639
+ const active = session !== undefined && (session.turn || goesOn(session));
2640
+ atWorkSince = active ? (atWorkSince ?? now) : undefined;
2641
+ for (const [name, one] of shows) {
2642
+ const status = statusFor(name, now);
2643
+ const word = `${status.state} ${status.state === "limited" ? (status.until ?? "") : ""}`;
2644
+ if (word === one.said && now - one.at < timing.heartbeatMs) {
2645
+ continue;
2646
+ }
2647
+ one.said = word;
2648
+ one.at = now;
2649
+ void say(one, status, abort.signal);
2650
+ }
2651
+ };
2652
+
2653
+ /**
2654
+ * The last thing the sources are said: nothing to show, as the runner ends, so that what they
2655
+ * showed is taken back. Waited for a few seconds and no longer: a messenger that does not
2656
+ * answer holds no runner's end, and what stays there ends by itself.
2657
+ */
2658
+ const showLast = async (): Promise<void> => {
2659
+ if (shownAs === false || shows.size === 0) {
2660
+ return;
2661
+ }
2662
+ const ending = new AbortController();
2663
+ const over = new Promise<void>((resolve) => {
2664
+ ending.signal.addEventListener("abort", () => resolve(), { once: true });
2665
+ });
2666
+ const timer = setTimeout(() => ending.abort(), SHOWN_END_MS);
2667
+ await Promise.race([
2668
+ Promise.all([...shows.values()].map((one) => say(one, LAST_STATUS, ending.signal))),
2669
+ over,
2670
+ ]);
2671
+ clearTimeout(timer);
2672
+ ending.abort();
2673
+ };
2674
+
2158
2675
  /**
2159
2676
  * Why the agent stands as it does, and until when where the runner knows: when its usage
2160
2677
  * limit resets. A console of before the word `usage_limit` refuses a heartbeat that says it,
2161
2678
  * and with it everything else the heartbeat carries: such a console is said `crashed`, the
2162
- * nearest word it takes, and no moment.
2679
+ * nearest word it takes, and no moment. With it, when the runner said so, which a console of
2680
+ * before reads past.
2163
2681
  */
2164
- const saidOfState = (): { reason: AgentStateReason; until?: string | null } => {
2682
+ const saidOfState = (): {
2683
+ reason: AgentStateReason;
2684
+ until?: string | null;
2685
+ reasonAt: string;
2686
+ } => {
2687
+ // A moment kept by a runner before this one is taken as it reads; one that is no moment is now.
2688
+ const at =
2689
+ Number.isFinite(stands.at) && Math.abs(stands.at) <= 8.64e15 ? stands.at : options.now();
2690
+ const reasonAt = new Date(at).toISOString();
2165
2691
  if (stands.reason !== "usage_limit") {
2166
- return { reason: stands.reason };
2692
+ return { reason: stands.reason, reasonAt };
2167
2693
  }
2168
2694
  if (plainWords) {
2169
- return { reason: "crashed" };
2695
+ return { reason: "crashed", reasonAt };
2170
2696
  }
2171
2697
  return {
2172
2698
  reason: stands.reason,
2173
2699
  until: limited?.until === undefined ? null : new Date(limited.until).toISOString(),
2700
+ reasonAt,
2174
2701
  };
2175
2702
  };
2176
2703
 
@@ -2225,7 +2752,7 @@ export function createRunner(options: RunnerOptions): Runner {
2225
2752
  if (answer.state === "stopped" && !held && answer.latest <= handled) {
2226
2753
  held = true;
2227
2754
  await end("stopped");
2228
- stands = { state: "stopped", reason: "stop" };
2755
+ stands = { state: "stopped", reason: "stop", at: options.now() };
2229
2756
  }
2230
2757
  } catch (error) {
2231
2758
  if (stopped) {
@@ -2391,6 +2918,19 @@ export function createRunner(options: RunnerOptions): Runner {
2391
2918
  if (source.run === undefined || wakes === undefined) {
2392
2919
  return;
2393
2920
  }
2921
+ // What the source kept under a runner before this one, where the machine keeps it
2922
+ // (ADR-0166): the ids and the moments of what it brought, so that a runner started again
2923
+ // says nothing a second time. What does not read is nothing kept.
2924
+ const kept = new Kept();
2925
+ try {
2926
+ for (const [name, value] of (await wakes.kept?.load(source.name)) ?? []) {
2927
+ kept.set(name, value);
2928
+ }
2929
+ } catch {
2930
+ log(`what the wake source ${source.name} kept could not be read; it begins with nothing`);
2931
+ }
2932
+ kept.changed = false;
2933
+ keeps.set(source.name, kept);
2394
2934
  const host: WakeHost = {
2395
2935
  secret: async (name) => secretValues.get(name),
2396
2936
  channels: options.config.channels ?? [],
@@ -2399,11 +2939,28 @@ export function createRunner(options: RunnerOptions): Runner {
2399
2939
  // past that, what the sources raise is let go for a while, longer each time, and said
2400
2940
  // once, so that a source that repeats itself costs the console nothing more.
2401
2941
  if (wakesHeld !== undefined && options.now() < wakesHeld.until) {
2402
- return;
2942
+ return false;
2403
2943
  }
2944
+ // Written in parts whatever the source handed over (ADR-0163): its own lines apart from
2945
+ // what someone else wrote, and a text with no line of the source's as words whole, so
2946
+ // that no word of a message reads as a line of the source's when the signal returns.
2947
+ const text = wakeTextOf("parts" in raised ? raised.parts : [{ words: raised.text }]);
2948
+ // On its way to the agent from here, which the source shows (ADR-0170): until the
2949
+ // stream brings it back, or the console did not take it.
2950
+ const underWay: { readonly at: number; number: number | undefined } = {
2951
+ at: options.now(),
2952
+ number: undefined,
2953
+ };
2954
+ const others = raising.get(source.name) ?? new Set();
2955
+ raising.set(source.name, others.add(underWay));
2956
+ push({ t: "shown" });
2404
2957
  try {
2405
- await client.raiseWake({ source: "messenger", key: raised.key, text: raised.text });
2958
+ underWay.number = (
2959
+ await client.raiseWake({ source: "messenger", key: raised.key, text })
2960
+ ).number;
2406
2961
  } catch (error) {
2962
+ others.delete(underWay);
2963
+ push({ t: "shown" });
2407
2964
  if (codeOf(error) !== "signal.too_many") {
2408
2965
  throw error;
2409
2966
  }
@@ -2413,23 +2970,39 @@ export function createRunner(options: RunnerOptions): Runner {
2413
2970
  "wakes",
2414
2971
  "the console takes no more wakes of this runner's within the hour (signal.too_many); what its wake sources raise is let go for a while",
2415
2972
  );
2416
- return;
2973
+ return false;
2417
2974
  }
2418
2975
  if (wakesHeld !== undefined) {
2419
2976
  wakesHeld = undefined;
2420
2977
  sayOver("wakes", "the console takes the wakes of this runner's wake sources again");
2421
2978
  }
2979
+ return true;
2422
2980
  },
2981
+ kept,
2982
+ began: beganBy,
2423
2983
  log,
2424
2984
  stands: (state, why) => sourceStands(source.name, state, why),
2425
2985
  fetch: wakes.fetch,
2426
2986
  socket: wakes.socket,
2427
2987
  wait: pause,
2988
+ // Who wrote, as the console answers the account's own sign-in (ADR-0164), of the
2989
+ // messenger the source is named for. A console that does not know the question, or does
2990
+ // not answer, says nothing, and the source says of an account what the messenger does.
2991
+ ...(client.writers === undefined
2992
+ ? {}
2993
+ : {
2994
+ writers: async (accounts, signal) =>
2995
+ (await client.writers?.({ messenger: source.name, accounts: [...accounts] }, signal))
2996
+ ?.items ?? [],
2997
+ }),
2428
2998
  };
2429
2999
  sourceStands(source.name, "waiting");
3000
+ if (source.show !== undefined) {
3001
+ shows.set(source.name, { source, host, said: "", at: 0 });
3002
+ }
2430
3003
  let wait = timing.reconnectMs;
2431
3004
  while (!stopped) {
2432
- const began = options.now();
3005
+ const startedAt = options.now();
2433
3006
  try {
2434
3007
  await source.run(host, abort.signal);
2435
3008
  // Ended with no error, a connection the other side closed say: it listens no more
@@ -2444,7 +3017,7 @@ export function createRunner(options: RunnerOptions): Runner {
2444
3017
  }
2445
3018
  }
2446
3019
  wait =
2447
- options.now() - began >= SOURCE_HELD_MS
3020
+ options.now() - startedAt >= SOURCE_HELD_MS
2448
3021
  ? timing.reconnectMs
2449
3022
  : Math.min(wait * 2, MAX_SOURCE_PAUSE_MS);
2450
3023
  await pause(wait);
@@ -2492,10 +3065,13 @@ export function createRunner(options: RunnerOptions): Runner {
2492
3065
  const kept = await options.state.load().catch(() => undefined);
2493
3066
  delivered = kept?.delivered ?? 0;
2494
3067
  conversation = kept?.conversation;
3068
+ // A moment after now is none the conversation began at: held to the clock here, and
3069
+ // wherever a wake source asks.
3070
+ began = Math.min(kept?.began ?? 0, options.now());
2495
3071
  if (conversation !== undefined && kept?.driver !== undefined && kept.driver !== driver.name) {
2496
3072
  // Another product's conversation is nothing this one can go on with: asked to, it fails
2497
3073
  // at every turn until a supervisor resets it.
2498
- conversation = undefined;
3074
+ letGo();
2499
3075
  log(
2500
3076
  `the conversation kept was begun under the driver ${kept.driver}: a new one begins under ${driver.name}`,
2501
3077
  );
@@ -2520,11 +3096,16 @@ export function createRunner(options: RunnerOptions): Runner {
2520
3096
  tries: 1,
2521
3097
  until: known === undefined ? now + timing.coolDownMs : known + timing.resetMarginMs,
2522
3098
  };
2523
- stands = { state: "failed", reason: "usage_limit" };
3099
+ // Said as of when the limit was reached, which the runner before this one kept.
3100
+ stands = { state: "failed", reason: "usage_limit", at: kept.limited.since };
2524
3101
  log(
2525
3102
  `the product's usage limit stopped the agent before this runner started: tried again at ${new Date(waits.until).toISOString()}`,
2526
3103
  );
2527
3104
  }
3105
+ if ((kept?.began ?? 0) > began) {
3106
+ // Kept as it is taken, once everything else the file said is in place again.
3107
+ await persist();
3108
+ }
2528
3109
  probe = await driver.probe();
2529
3110
  const left =
2530
3111
  probe.models.length +
@@ -2555,7 +3136,7 @@ export function createRunner(options: RunnerOptions): Runner {
2555
3136
  delivered = Math.max(delivered, first.delivered);
2556
3137
  if (first.state === "stopped") {
2557
3138
  held = true;
2558
- stands = { state: "stopped", reason: "stop" };
3139
+ stands = { state: "stopped", reason: "stop", at: options.now() };
2559
3140
  }
2560
3141
  break;
2561
3142
  } catch (error) {
@@ -2599,8 +3180,12 @@ export function createRunner(options: RunnerOptions): Runner {
2599
3180
  try {
2600
3181
  for (;;) {
2601
3182
  // An update is taken between two turns, and at once where none is under way; so is
2602
- // a runner.json that changed.
2603
- if ((updatedTo !== undefined || reconfigure) && session?.turn !== true) {
3183
+ // a runner.json that changed. Neither while sub-agents work on in the background of
3184
+ // the session, for as long as the runner waits for them (ADR-0162).
3185
+ if (
3186
+ (updatedTo !== undefined || reconfigure) &&
3187
+ !busy(session, updatedTo !== undefined ? FOR_UPDATE : FOR_CHANGE)
3188
+ ) {
2604
3189
  how = updatedTo !== undefined ? "updated" : "changed";
2605
3190
  if (session !== undefined) {
2606
3191
  record(
@@ -2633,6 +3218,9 @@ export function createRunner(options: RunnerOptions): Runner {
2633
3218
  if (session !== undefined) {
2634
3219
  await flush(session);
2635
3220
  }
3221
+ await keepKept();
3222
+ } else if (message.t === "shown") {
3223
+ // Looked at below, as after anything else.
2636
3224
  } else {
2637
3225
  // A timer counts no time the machine sleeps in, and rings late by as much: what
2638
3226
  // was to be handed over at a moment is looked for by the clock at every heartbeat.
@@ -2654,15 +3242,44 @@ export function createRunner(options: RunnerOptions): Runner {
2654
3242
  // and the reset is taken once a turn completed again.
2655
3243
  if (
2656
3244
  ownReset !== undefined &&
2657
- session?.turn !== true &&
2658
3245
  waits === undefined &&
2659
- limited === undefined
3246
+ limited === undefined &&
3247
+ !busy(session, FOR_RESET)
2660
3248
  ) {
2661
3249
  await beginAnew(ownReset);
2662
3250
  }
3251
+ // A model or an effort the product takes only when it starts, held for what went
3252
+ // on in the session: it ends once nothing does. Not where the agent could not go
3253
+ // on, which keeps its session as it does under a turn.
3254
+ if (
3255
+ renew &&
3256
+ session !== undefined &&
3257
+ stands.state === "running" &&
3258
+ !busy(session, FOR_CHOICE)
3259
+ ) {
3260
+ await end("restarted");
3261
+ if (pending.length > 0) {
3262
+ scheduleDeliver();
3263
+ }
3264
+ }
3265
+ // Nothing waits to end the session: the next thing that does counts from its own
3266
+ // moment how long it waits for the sub-agents.
3267
+ if (
3268
+ session !== undefined &&
3269
+ !renew &&
3270
+ ownReset === undefined &&
3271
+ updatedTo === undefined &&
3272
+ !reconfigure
3273
+ ) {
3274
+ session.heldSince = undefined;
3275
+ session.heldSaid = undefined;
3276
+ }
2663
3277
  } catch (error) {
2664
3278
  log(`the runner could not do what it was about to (${codeOf(error)}); it goes on`);
2665
3279
  }
3280
+ // Whatever was done may have changed how the agent stands to whoever waits for it,
3281
+ // and so does the time that passed: looked at once a second at the least.
3282
+ showStatus();
2666
3283
  }
2667
3284
  } finally {
2668
3285
  stopped = true;
@@ -2671,12 +3288,18 @@ export function createRunner(options: RunnerOptions): Runner {
2671
3288
  for (const timer of timers) {
2672
3289
  clearTimeout(timer);
2673
3290
  }
3291
+ // What the wake sources showed of the agent is taken back while its session ends
3292
+ // (ADR-0170): a runner that is gone shows nothing.
3293
+ const shown = showLast();
2674
3294
  // A session ended for an update goes on, in the runner started after, as one a
2675
3295
  // supervisor restarted does: with the same conversation.
2676
3296
  await end(how === "stopped" ? "exited" : "restarted");
3297
+ await shown;
2677
3298
  abort.abort();
2678
3299
  await listening;
2679
3300
  await Promise.all(sourcing);
3301
+ // What the sources raised as they ended is kept too.
3302
+ await keepKept();
2680
3303
  log(
2681
3304
  how === "updated"
2682
3305
  ? "the runner ended, for the update"