@bastani/atomic 0.9.85-alpha.1 → 0.9.86-alpha.1

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 (125) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +25 -0
  3. package/dist/builtin/intercom/README.md +10 -9
  4. package/dist/builtin/intercom/broker/away-asks.ts +260 -0
  5. package/dist/builtin/intercom/broker/broker.ts +170 -9
  6. package/dist/builtin/intercom/broker/client.ts +5 -3
  7. package/dist/builtin/intercom/broker/held-reply-targets.ts +5 -0
  8. package/dist/builtin/intercom/broker/multinode-router.ts +16 -7
  9. package/dist/builtin/intercom/broker/paths.ts +5 -0
  10. package/dist/builtin/intercom/broker/pending-question-index.ts +119 -0
  11. package/dist/builtin/intercom/broker/released-asker-replies.ts +39 -0
  12. package/dist/builtin/intercom/broker/send-handler.ts +44 -3
  13. package/dist/builtin/intercom/broker/terminal-questions.ts +2 -0
  14. package/dist/builtin/intercom/index.bundle.mjs +799 -177
  15. package/dist/builtin/intercom/package.json +1 -1
  16. package/dist/builtin/intercom/retry-policy.ts +1 -1
  17. package/dist/builtin/intercom/skills/intercom/SKILL.md +29 -35
  18. package/dist/builtin/intercom/types.ts +7 -2
  19. package/dist/builtin/mcp/package.json +1 -1
  20. package/dist/builtin/subagents/CHANGELOG.md +20 -0
  21. package/dist/builtin/subagents/package.json +1 -1
  22. package/dist/builtin/subagents/skills/subagent/SKILL.md +1 -1
  23. package/dist/builtin/subagents/src/extension/index.bundle.mjs +2765 -2719
  24. package/dist/builtin/web-access/package.json +1 -1
  25. package/dist/builtin/workflows/CHANGELOG.md +22 -0
  26. package/dist/builtin/workflows/package.json +1 -1
  27. package/dist/builtin/workflows/src/authoring.d.ts +1 -1
  28. package/dist/builtin/workflows/src/extension/index.bundle.mjs +371 -193
  29. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +358 -181
  30. package/dist/builtin/workflows/src/index.js +356 -183
  31. package/dist/builtin/workflows/src/local-worker-entry.mjs +358 -181
  32. package/dist/builtin/workflows/src/shared/worktree-restore-outcome.d.ts +16 -0
  33. package/dist/builtin/workflows/src/workers/workspace-binding.d.ts +13 -2
  34. package/dist/core/agent-session-methods.d.ts +1 -0
  35. package/dist/core/agent-session-methods.d.ts.map +1 -1
  36. package/dist/core/agent-session-methods.js.map +1 -1
  37. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  38. package/dist/core/agent-session-prompt.js +2 -35
  39. package/dist/core/agent-session-prompt.js.map +1 -1
  40. package/dist/core/agent-session-runtime.d.ts +3 -1
  41. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  42. package/dist/core/agent-session-runtime.js +12 -5
  43. package/dist/core/agent-session-runtime.js.map +1 -1
  44. package/dist/core/agent-session-state.d.ts.map +1 -1
  45. package/dist/core/agent-session-state.js +14 -1
  46. package/dist/core/agent-session-state.js.map +1 -1
  47. package/dist/core/agent-session.d.ts +2 -0
  48. package/dist/core/agent-session.d.ts.map +1 -1
  49. package/dist/core/agent-session.js +3 -1
  50. package/dist/core/agent-session.js.map +1 -1
  51. package/dist/core/resume/index.d.ts +1 -1
  52. package/dist/core/resume/index.d.ts.map +1 -1
  53. package/dist/core/resume/index.js +1 -1
  54. package/dist/core/resume/index.js.map +1 -1
  55. package/dist/core/resume/path-mapping.d.ts +10 -0
  56. package/dist/core/resume/path-mapping.d.ts.map +1 -1
  57. package/dist/core/resume/path-mapping.js +20 -0
  58. package/dist/core/resume/path-mapping.js.map +1 -1
  59. package/dist/core/resume/session-resume.d.ts +5 -0
  60. package/dist/core/resume/session-resume.d.ts.map +1 -1
  61. package/dist/core/resume/session-resume.js +24 -9
  62. package/dist/core/resume/session-resume.js.map +1 -1
  63. package/dist/core/session-worktree-snapshots.d.ts +5 -8
  64. package/dist/core/session-worktree-snapshots.d.ts.map +1 -1
  65. package/dist/core/session-worktree-snapshots.js +34 -99
  66. package/dist/core/session-worktree-snapshots.js.map +1 -1
  67. package/dist/core/skill-catalog.d.ts +11 -0
  68. package/dist/core/skill-catalog.d.ts.map +1 -1
  69. package/dist/core/skill-catalog.js +31 -0
  70. package/dist/core/skill-catalog.js.map +1 -1
  71. package/dist/core/tasks/agent-adapter.d.ts +2 -0
  72. package/dist/core/tasks/agent-adapter.d.ts.map +1 -1
  73. package/dist/core/tasks/agent-adapter.js +5 -1
  74. package/dist/core/tasks/agent-adapter.js.map +1 -1
  75. package/dist/core/tasks/supervisor.d.ts +17 -0
  76. package/dist/core/tasks/supervisor.d.ts.map +1 -1
  77. package/dist/core/tasks/supervisor.js +12 -6
  78. package/dist/core/tasks/supervisor.js.map +1 -1
  79. package/dist/core/tasks/task-view-source.d.ts +10 -0
  80. package/dist/core/tasks/task-view-source.d.ts.map +1 -1
  81. package/dist/core/tasks/task-view-source.js +24 -1
  82. package/dist/core/tasks/task-view-source.js.map +1 -1
  83. package/dist/core/worktree-snapshot/best-restore.d.ts +45 -0
  84. package/dist/core/worktree-snapshot/best-restore.d.ts.map +1 -0
  85. package/dist/core/worktree-snapshot/best-restore.js +92 -0
  86. package/dist/core/worktree-snapshot/best-restore.js.map +1 -0
  87. package/dist/core/worktree-snapshot/git.d.ts +2 -2
  88. package/dist/core/worktree-snapshot/git.d.ts.map +1 -1
  89. package/dist/core/worktree-snapshot/git.js +2 -5
  90. package/dist/core/worktree-snapshot/git.js.map +1 -1
  91. package/dist/core/worktree-snapshot/index.d.ts +1 -0
  92. package/dist/core/worktree-snapshot/index.d.ts.map +1 -1
  93. package/dist/core/worktree-snapshot/index.js +1 -0
  94. package/dist/core/worktree-snapshot/index.js.map +1 -1
  95. package/dist/core/worktree-snapshot/restore.d.ts.map +1 -1
  96. package/dist/core/worktree-snapshot/restore.js +18 -2
  97. package/dist/core/worktree-snapshot/restore.js.map +1 -1
  98. package/dist/index.d.ts +3 -2
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +1 -0
  101. package/dist/index.js.map +1 -1
  102. package/dist/modes/interactive/chat-autocomplete.d.ts +7 -0
  103. package/dist/modes/interactive/chat-autocomplete.d.ts.map +1 -0
  104. package/dist/modes/interactive/chat-autocomplete.js +85 -0
  105. package/dist/modes/interactive/chat-autocomplete.js.map +1 -0
  106. package/dist/modes/interactive/components/task-transcript-page.d.ts.map +1 -1
  107. package/dist/modes/interactive/components/task-transcript-page.js +8 -0
  108. package/dist/modes/interactive/components/task-transcript-page.js.map +1 -1
  109. package/dist/modes/interactive/interactive-autocomplete.js +3 -79
  110. package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
  111. package/dist/modes/interactive/skill-command-autocomplete.d.ts +6 -0
  112. package/dist/modes/interactive/skill-command-autocomplete.d.ts.map +1 -1
  113. package/dist/modes/interactive/skill-command-autocomplete.js +18 -2
  114. package/dist/modes/interactive/skill-command-autocomplete.js.map +1 -1
  115. package/docs/background-tasks.md +1 -1
  116. package/docs/intercom/operations.md +4 -4
  117. package/docs/intercom/reference.md +39 -8
  118. package/docs/intercom.md +26 -9
  119. package/docs/skills.md +3 -1
  120. package/docs/subagents.md +2 -0
  121. package/docs/workflows/api-reference.md +3 -3
  122. package/docs/workflows/operations.md +2 -2
  123. package/docs/worktree-snapshots.md +10 -4
  124. package/npm-shrinkwrap.json +32 -32
  125. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -2,6 +2,58 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.9.86-alpha.1] - 2026-11-14
6
+
7
+ Intercom asks stop blocking, and partial restores keep more of your checkout.
8
+
9
+ - **Non-blocking Intercom asks.** `ask` returns once the question is delivered, waits for the reply like `bash` waits for a command, and delivers a late reply as a message, so the asking session keeps working ([#4751](https://github.com/bastani-inc/atomic/issues/4751), [#4758](https://github.com/bastani-inc/atomic/pull/4758)).
10
+ - **Fuller degraded restores.** A partial resume restore keeps worktrees that a checkout filter changes, searches every earlier snapshot for the closest commit, and shows its notice after `/resume` and `/import` too. Workflow runs and worker hosts can reuse the same restore through `restoreBestWorktree` and `withWorktreeRestoreNotices` ([#4744](https://github.com/bastani-inc/atomic/issues/4744), [#4747](https://github.com/bastani-inc/atomic/pull/4747), [#4738](https://github.com/bastani-inc/atomic/issues/4738), [#4750](https://github.com/bastani-inc/atomic/pull/4750)).
11
+ - **Autocomplete in subagent chats.** A subagent's chat opened from `/tasks` completes `/tasks`, its own `/skill:` commands, `@` file mentions and Tab paths in its working directory ([#4755](https://github.com/bastani-inc/atomic/issues/4755), [#4757](https://github.com/bastani-inc/atomic/pull/4757)).
12
+ - **Faster, safer credential stripping.** Checking a snapshot's remote URL for credentials is now linear, so a crafted long remote can no longer stall resume, and credentials containing `@` are stripped completely ([#4749](https://github.com/bastani-inc/atomic/pull/4749)).
13
+
14
+ ### Fixed
15
+
16
+ - Fixed checking a worktree snapshot's remote URL for credentials taking quadratic time, so a crafted record with a very long remote could stall resume for seconds or minutes. The check is now linear, and it also strips credentials that contain `@` completely ([#4749](https://github.com/bastani-inc/atomic/pull/4749))
17
+ - Fixed a degraded resume restore that was more limited than this machine allowed ([#4744](https://github.com/bastani-inc/atomic/issues/4744)). A partial restore whose files a checkout filter changes now keeps its worktree and names the files that differ, whatever started the partial restore; before, a missing change set or bundle combined with such a filter left the checkout out entirely. The closest-commit search now tries the commit of every earlier snapshot of the checkout, nearest first, before the branch tip, instead of only the three nearest. The notice's list of missing commits leaves out commits the restored history already holds. A checkout whose snapshot record the session lacks now gets its notice after `/resume` and `/import` in the TUI too, not only at startup.
18
+ - Fixed a subagent's chat, opened from `/tasks`, having no autocomplete. Its prompt now offers `/tasks` and the subagent's own `/skill:` commands, and completes `@` file mentions and Tab paths in the subagent's working directory, from the same completion the workflow stage chat uses. A skill command typed there reaches the subagent expanded from its own skills ([#4755](https://github.com/bastani-inc/atomic/issues/4755))
19
+ - Fixed workflow runs and worker hosts having no way to reuse a session resume's degraded restore: `restoreBestWorktree(snapshot, options)` restores a snapshot exactly, else as well as this host can, else reports that nothing could be restored. `withWorktreeRestoreNotices(notices, work)` tells every session opened in `work` which checkouts were restored only in part, in a `worktree_restore` system prompt section, and `formatDegradedRestoreNotice` and `formatUnrestoredNotice` take an optional `"workflow run"` owner for their wording ([#4738](https://github.com/bastani-inc/atomic/issues/4738))
20
+
21
+ ### Changed
22
+
23
+ - Intercom `ask` no longer blocks the asking session: it returns at delivery, and a reply that misses its `wait` (the same options as `bash`) arrives later as a message. Extensions can read the automatic wait budget an owner gives a command with `automaticWaitBudgetMs` and `AgentTaskHost.commandWaitBudgetMs` ([#4751](https://github.com/bastani-inc/atomic/issues/4751))
24
+
25
+ ## [0.9.85] - 2026-11-13
26
+
27
+ Resumed sessions always open, and `/tree` navigation now sticks.
28
+
29
+ - **Resume never strands a session.** A resume opens the full conversation even when a worktree snapshot cannot be restored exactly, restores the closest state it can reach, and says what is missing. Snapshots taken in a restored worktree keep the recorded remotes, so a later resume on another machine no longer fails with `commits-unavailable` ([#4733](https://github.com/bastani-inc/atomic/issues/4733), [#4739](https://github.com/bastani-inc/atomic/pull/4739), [#4732](https://github.com/bastani-inc/atomic/issues/4732), [#4734](https://github.com/bastani-inc/atomic/pull/4734)).
30
+ - **`/tree` moves show and stay.** The chat, tree, `/session`, and context indicator follow the selected branch at once, and the move survives quitting, resuming, and workflow forks ([#3325](https://github.com/bastani-inc/atomic/issues/3325), [#4736](https://github.com/bastani-inc/atomic/pull/4736)).
31
+ - **Fewer wasted requests, accurate usage.** Unsaved sessions skip the per-turn summary request, and the footer and `/session` count the latest summary's tokens and cost right away ([#4726](https://github.com/bastani-inc/atomic/issues/4726), [#4730](https://github.com/bastani-inc/atomic/pull/4730)).
32
+ - **Automatic retries on dropped connections.** Provider errors that report only a socket code such as `ECONNRESET` or `EPIPE` are now retried in sessions, workflows, and subagents ([#4740](https://github.com/bastani-inc/atomic/pull/4740)).
33
+ - **Smaller fixes.** `/copy` copies the right reply, `read` no longer leaves a stale image warning after switching to a vision model, huge tool results render without crashing, and `ask_user_question` fields keep readable colors after going back ([#4740](https://github.com/bastani-inc/atomic/pull/4740), [#4741](https://github.com/bastani-inc/atomic/issues/4741), [#4742](https://github.com/bastani-inc/atomic/pull/4742)).
34
+ - **Cleaner agent directories for SDK hosts.** The extension transpile cache follows each load's agent directory, and a disposed session's Intercom broker no longer writes into it ([#4728](https://github.com/bastani-inc/atomic/issues/4728), [#4731](https://github.com/bastani-inc/atomic/pull/4731), [#4727](https://github.com/bastani-inc/atomic/issues/4727), [#4737](https://github.com/bastani-inc/atomic/pull/4737)).
35
+
36
+ ### Added
37
+
38
+ - `SessionManager.recordBranch(entryId | null)` moves the leaf like `branch()` or `resetLeaf()` and saves the move, so the session reopens there, and `getSessionLeafId(entries)` returns the entry a stored session reopens at ([#3325](https://github.com/bastani-inc/atomic/issues/3325))
39
+
40
+ ### Changed
41
+
42
+ - `--no-session` and other unsaved sessions no longer generate session summaries, so they no longer send one extra model request after each turn. Summaries exist for the `/resume` picker, which never lists unsaved sessions. RPC `get_session_summary` returns `null` for an unsaved session ([#4726](https://github.com/bastani-inc/atomic/issues/4726))
43
+ - Resuming a session now always opens it with its full conversation, even when a worktree snapshot cannot be restored exactly ([#4733](https://github.com/bastani-inc/atomic/issues/4733)). Missing unpushed commits, `denied-history`, a missing or damaged snapshot blob, a change set that does not apply, an unreachable remote and an unavailable Git no longer stop the resume. Atomic restores the best state it can reach: the recorded commit with the change sets that apply (each whole or not at all), else the closest commit it can fetch (the pushed base, an earlier snapshot's commit, then the branch tip), else no checkout. In the last case the session continues in its recorded directory, or in the directory the resume started from when that is not on this machine, and nothing is ever written to either. Each such checkout gets one notice that says what was restored, what is missing and what to do next. The outcome is recorded on the session (`restore.degraded` or an `unrestored` entry) and shown by `/session snapshot`, and later snapshots record the tree the worktree actually holds. A session resume is now refused only when the session cannot be read, when a snapshot record fails the security checks, or when a restore target holds other files. Snapshot records whose remotes carry credentials, name a Git remote helper (`ext::`), or use a scheme other than `https`, `http`, `ssh`, `git` or `file` now fail with `invalid-snapshot` (`unsafe-remote`) before any Git command runs. New SDK exports: `restoreDegradedWorktree`, `isDegradableRestoreFailure`, `isRecoverableRestoreFailure`, `formatDegradedRestoreNotice` and `formatUnrestoredNotice`. `resumeSessionWorktree` gains the `cannotRestore`, `fallbackCwd` and `skipMissingRecords` options and reports `unrestored` and `missingRecords`.
44
+
45
+ ### Fixed
46
+
47
+ - Fixed the footer usage, the context indicator, and `/session` leaving out the tokens and cost of the latest session summary until a later turn or `/reload`. They now update as soon as the summary is saved, and also when a cache warm records its usage ([#4726](https://github.com/bastani-inc/atomic/issues/4726))
48
+ - Fixed `/tree` in interactive mode leaving the abandoned turns in the chat, keeping the tree cursor and `/clone` on the old leaf, and not showing a requested branch summary until the next turn. The chat, the tree, `/session` and the context indicator now follow the selected branch as soon as you navigate, and Escape while the summary is generated cancels it. Also fixed a `/tree` move without a summary being lost when you quit, resumed, continued, or the interactive engine restarted before the next turn, which put the abandoned turns back into the next request. The move is now saved in the session, so it reopens on the selected branch; `listForkPoints()` and workflow run forks use that branch too ([#3325](https://github.com/bastani-inc/atomic/issues/3325))
49
+ - Fixed the extension transpile cache staying under the first agent directory a process used: each load now caches under the agent directory in effect for it (`ATOMIC_CODING_AGENT_DIR` at that time, or the SDK session's `agentDir`), stale cache versions are pruned in every agent directory, and extension loads no longer create or recreate a missing agent directory; they skip the cache instead ([#4728](https://github.com/bastani-inc/atomic/issues/4728))
50
+ - Fixed snapshots captured in a worktree Atomic restored recording no remotes and bundling the checkout's whole history as unpushed, which made a resume on a third machine fail with `commits-unavailable` even for a fully pushed repository. A restored worktree now has the snapshot's recorded remotes (`origin`, then `origin-2`, …, credential-free as recorded, and only over the transports a restore fetches over) and remote-tracking refs under `refs/remotes/atomic/pushed/` for the commits a recorded remote is known to have, so later captures record the remotes and bundle only commits that are really unpushed. A repository without remotes restores and captures as before ([#4732](https://github.com/bastani-inc/atomic/issues/4732))
51
+ - Fixed `/copy` and RPC `get_last_assistant_text` skipping past a reply that ended normally without text and copying an earlier turn's answer instead, while still skipping empty turns that ended via abort, error, or tool calls (upstream [#12119](https://github.com/earendil-works/pi/issues/12119), [#12121](https://github.com/earendil-works/pi/pull/12121))
52
+ - Fixed provider errors that report only a Node socket error code (`ECONNRESET`, `ECONNABORTED`, `ECONNREFUSED`, `ETIMEDOUT`, `EPIPE`) not triggering automatic retries in sessions, workflows, and subagents, without matching those codes inside longer identifiers (upstream [#12128](https://github.com/earendil-works/pi/issues/12128), [#12136](https://github.com/earendil-works/pi/pull/12136))
53
+ - Fixed `read` storing a note that the current model does not support images in the tool result sent to the model, which replayed as stale text after switching to a vision model; the warning is now recorded in `details.imageUnsupportedByModel` and shown in the TUI both collapsed and expanded while `@bastani/pi-ai` still replaces unsupported images per request (upstream [#12131](https://github.com/earendil-works/pi/issues/12131), [#12139](https://github.com/earendil-works/pi/pull/12139))
54
+ - Fixed `ToolExecutionComponent` crashing with `RangeError: Maximum call stack size exceeded` when rendering a very large self-rendered tool result such as a multi-megabyte edit diff (upstream [#8036](https://github.com/earendil-works/pi/issues/8036), [#12145](https://github.com/earendil-works/pi/pull/12145))
55
+ - Fixed `ask_user_question` text fields showing the wrong color, or hiding what you typed, after you navigate back to a question with ←, Shift+Tab, or from the review tab. The "Type something." answer, "Chat about this", and notes now use the accent color while you edit them, the normal text color when they hold text without focus (so a draft stays visible on one line after you move away), and the muted color when empty. The same rule applies to answered and checked rows and to the review tab. Moving the cursor back inside a field no longer drops the color of the text after it, and reopened notes put the cursor at the end ([#4741](https://github.com/bastani-inc/atomic/issues/4741))
56
+
5
57
  ## [0.9.85-alpha.1] - 2026-11-13
6
58
 
7
59
  Resumed sessions always open, and `/tree` navigation now sticks.
@@ -4,6 +4,31 @@ All notable changes to the `pi-intercom` extension will be documented in this fi
4
4
 
5
5
  ## [Unreleased]
6
6
 
7
+ ## [0.9.86-alpha.1] - 2026-11-14
8
+
9
+ Intercom asks stop blocking, and one send can reach many sessions.
10
+
11
+ - **Non-blocking asks.** `ask` returns at delivery with the recipient's state, waits like `bash` does, and delivers a late reply, refusal or ended recipient as a message. Asks no longer expire, survive restarts on either side, and can be listed and cancelled ([#4751](https://github.com/bastani-inc/atomic/issues/4751), [#4760](https://github.com/bastani-inc/atomic/issues/4760), [#4758](https://github.com/bastani-inc/atomic/pull/4758)).
12
+ - **Send to many at once.** Name patterns such as `subagent-*` and the `subagents:*` target reach every matching session in your groups in one call, with a per-recipient result ([#4752](https://github.com/bastani-inc/atomic/issues/4752), [#4756](https://github.com/bastani-inc/atomic/pull/4756)).
13
+
14
+ ### Added
15
+
16
+ - Added name patterns and a children target to Intercom `send`: `subagent-worker-*`, `subagent-*` or `*` reaches every matching live session visible in your groups except you, and `subagents:*` (or `subagents:<runId>/*` for one run) reaches every running, released or paused subagent this session launched, foreground or background. Each recipient gets its own direct send with the usual refusals, receipts and retries, and the result lists every recipient's outcome. A glob that matches nothing is an error listing the closest names, patterns never reach outside your groups, and `ask` still needs one exact target. Workflow-stage paths are unchanged ([#4752](https://github.com/bastani-inc/atomic/issues/4752))
17
+
18
+ ### Changed
19
+
20
+ - `intercom` `ask` no longer blocks the asker. It returns once the question is delivered, with an ask ID and whether the recipient is idle or busy (and what it is running). It waits for the reply like `bash` waits for a command: up to the automatic yield (10 seconds by default), up to `wait: { kind: "foreground", budgetMs }`, or not at all with `wait: { kind: "background" }`. A reply that misses the wait arrives later as a message starting "Reply to your ask <id> from <name>" with the question quoted; it starts a turn when the asker is idle and arrives after the current tool call when it is busy. A refusal, or a recipient session that ends, arrives the same way as a failed-ask message. Asks no longer expire after 10 minutes. `pending` also lists your own pending asks, the new `cancel` action cancels one (a later reply is shown once, marked late), and restarting the asker or the recipient keeps the ask, with its reply delivered once. A reply to a background subagent or workflow stage that was released after asking wakes it, or waits until the stage reopens, and is shown once. A reply to a closed asker is held and delivered once when it resumes (the recipient sees "delivered (held for …)"), also with multi-node routing, and a recipient that ends or finishes while its asker is away (closed or released) comes back as a failed-ask message ([#4751](https://github.com/bastani-inc/atomic/issues/4751), [#4760](https://github.com/bastani-inc/atomic/issues/4760))
21
+
22
+ ## [0.9.85] - 2026-11-13
23
+
24
+ Disposed sessions leave the agent directory alone.
25
+
26
+ - **No writes after `dispose()`.** A disposed session cancels or stops the Intercom broker it started, so hosts that delete a temporary agent directory no longer see it reappear or fail with `ENOTEMPTY` ([#4727](https://github.com/bastani-inc/atomic/issues/4727), [#4737](https://github.com/bastani-inc/atomic/pull/4737)).
27
+
28
+ ### Fixed
29
+
30
+ - Fixed an Intercom broker started by a session that was then disposed writing into the agent directory after `dispose()` resolved: disposing a session now cancels a broker start it has not launched and waits for one it has (stopping it if it does not start in time), and a broker creates its `delivered-messages` files only when the first session registers, so one that exits without serving a session leaves none behind. Hosts that remove a temporary `ATOMIC_CODING_AGENT_DIR` after disposal no longer see it reappear or fail with `ENOTEMPTY` ([#4727](https://github.com/bastani-inc/atomic/issues/4727))
31
+
7
32
  ## [0.9.85-alpha.1] - 2026-11-13
8
33
 
9
34
  ### Fixed
@@ -46,7 +46,7 @@ Coordinate with other local Atomic/pi sessions on related codebases. Use `/skill
46
46
 
47
47
  **Not when:** Unrelated codebases, trivial questions, or when you can proceed independently.
48
48
 
49
- **Principle:** Prefer `send` for notifications; `ask` only when blocked waiting for input.
49
+ **Principle:** Prefer `send` for notifications; `ask` when you need an answer. `ask` never blocks: its reply arrives as a message.
50
50
  </intercom>
51
51
  ```
52
52
 
@@ -135,7 +135,7 @@ When a blocking `intercom.ask` targets a workflow stage that has already complet
135
135
 
136
136
  Noninteractive subagent children are different: after completion, failure, interruption, or cancellation they cannot reopen to answer an ask. New asks fail immediately with an explicit terminal-child error, even if a retained registration still shows `idle`; asks already admitted fail on termination unless their reply has settled. Launch a fresh child with explicit context for follow-up work. Live interactive idle sessions remain askable, and all `send` transport semantics remain unchanged.
137
137
 
138
- When a blocking ask reaches a sibling workflow stage during an active model/tool turn, the target reserves it synchronously in the open stage generation before any asynchronous foreground-owner detach handshake. Queue insertion waits inside that reservation, and stage finalization drains it before publishing the terminal snapshot. This prevents a structured-output or other terminal tool call from overtaking a mid-turn ask. If destination-side admission genuinely cannot complete, the asker receives an exact-thread actionable error instead of consuming the full 10-minute timeout.
138
+ When a blocking ask reaches a sibling workflow stage during an active model/tool turn, the target reserves it synchronously in the open stage generation before any asynchronous foreground-owner detach handshake. Queue insertion waits inside that reservation, and stage finalization drains it before publishing the terminal snapshot. This prevents a structured-output or other terminal tool call from overtaking a mid-turn ask. If destination-side admission genuinely cannot complete, the asker receives an exact-thread actionable failed-ask message instead of waiting.
139
139
 
140
140
  For delegated children, queued messages and terminal lifecycle notices are ordered per child. Intercom claims the terminal child's pre-terminal ordinary entries in FIFO order and atomically admits that prelude together with the interrupted, completed, or failed notice. A process-local companion bridge covers lazily loaded extensions whose event buses are distinct, while exact terminal-identity deduplication prevents double admission even when the successful terminal dispatch has no queued prelude. Failed dispatches remain retryable, and each terminal child identity is admitted only once. Other children's entries remain independently queued, messages are not discarded, terminal admission does not wait for a separate model turn, and correlated ask replies still bypass unrelated queued sends.
141
141
 
@@ -161,7 +161,7 @@ intercom({ action: "list" })
161
161
 
162
162
  ### The Conversation
163
163
 
164
- Here's how a typical exchange looks. The planner delegates with `send` (fire-and-forget). The worker uses `ask` for anything that needs a response — questions, discoveries, completion reports. `ask` sends the message and blocks until the planner replies, so the worker gets the answer as a tool result and continues in the same turn.
164
+ Here's how a typical exchange looks. The planner delegates with `send` (fire-and-forget). The worker uses `ask` for anything that needs a response — questions, discoveries, completion reports. `ask` returns once the question is delivered. A quick reply comes back as the tool result; otherwise the worker keeps going and the reply arrives later as a message starting "Reply to your ask <id> from planner".
165
165
 
166
166
  **Planner sends a task:**
167
167
  ```typescript
@@ -172,7 +172,7 @@ intercom({
172
172
  })
173
173
  ```
174
174
 
175
- **Worker hits an ambiguity — asks and waits:**
175
+ **Worker hits an ambiguity — asks:**
176
176
  ```typescript
177
177
  intercom({
178
178
  action: "ask",
@@ -180,8 +180,9 @@ intercom({
180
180
  message: "Should retry apply to all endpoints or just idempotent ones? Also, max retry count and backoff strategy?"
181
181
  })
182
182
 
183
- // → Reply from planner: Only GET/PUT/DELETE — never POST. Max 3 retries, exponential backoff starting at 100ms.
184
- // Worker continues implementing with the answer, same turn, full context.
183
+ // → Inline if the planner answers within the wait; otherwise later, as a message:
184
+ // Reply to your ask <id> from planner
185
+ // Only GET/PUT/DELETE — never POST. Max 3 retries, exponential backoff starting at 100ms.
185
186
  ```
186
187
 
187
188
  To coordinate two plain chat sessions without changing startup config, have each call `intercom({ action: "join", group: "NAME" })`. Joining adds a membership without changing the session ID or removing existing memberships. Calls to `list`, `send`, and `ask` can then reach any session sharing at least one membership. Use `intercom({ action: "groups" })` to discover every available name, connected-session count, and membership marker. Call `intercom({ action: "leave", group: "NAME" })` to remove one membership while keeping the others, or bare `leave` to reset to the original home group. `contact_supervisor` keeps its dedicated capability-based cross-group behavior.
@@ -221,7 +222,7 @@ intercom({
221
222
  | Pattern | Action | Why |
222
223
  |---------|--------|-----|
223
224
  | **Task Delegation** | Planner uses `send` | Fire-and-forget. Planner doesn't need to wait for an ack. |
224
- | **Clarification Request** | Worker uses `ask` | Worker needs the answer to proceed. Blocks until reply. |
225
+ | **Clarification Request** | Worker uses `ask` | Worker needs the answer to proceed. The reply arrives as a message. |
225
226
  | **Discovery Escalation** | Worker uses `ask` | Worker needs approval before changing course. |
226
227
  | **Completion Report** | Worker uses `ask` | Planner might have follow-up instructions or the next task. |
227
228
 
@@ -380,13 +381,13 @@ Only registered in sessions where `pi-subagents` supplied the required child bri
380
381
 
381
382
  **`list`** — Keeps session-listing semantics: returns the current session and every active session sharing at least one membership. Pass `group` for a read-only view of one group. A workflow invocation group (`workflow:<rootRunId>`) is visible only to its members, so peeking at one you have not joined says so and tells you to `join` it instead of listing it as empty.
382
383
 
383
- Live target lookup accepts an exact full Intercom session ID, a unique 8-hex prefix of a UUID-backed session, or an exact case-insensitive session name. Prefix matching stays inside the sender's existing authorized visibility; collisions list the matching full UUIDs and require one of them. Join `workflow:<rootRunId>` and use `intercom list` to see materialized `PENDING`/`RUNNING` workflow stages with canonical `workflow:<rootRunId>/<segment>[/<segment>...]` paths, plus possible future literals, globs, nested paths, and their queued counts. `*` matches one segment and `**` any depth. `workflow:<rootRunId>/**` reaches live stages now and remains sticky for every future stage until root termination; narrower patterns behave the same for their matches. A valid path outside the known set still queues, with no warning, and settles undeliverable at terminal only if never delivered; the result's `prediction` field says `known`, `predicted` or `unknown`, and a single `did you mean` line appears only for a likely typo. Use `ask` only on live targets. An eligible invocation member has directional list/send/live-ask control over stages in owned `workflow:<rootRunId>/...` subgroups. A subgroup stage or another workflow root cannot turn a mutable join into parent control; sibling subgroups stay isolated, and explicit `group: "default"` remains non-owned.
384
+ Live target lookup accepts an exact full Intercom session ID, a unique 8-hex prefix of a UUID-backed session, or an exact case-insensitive session name. `send` also takes a session-name glob (`subagent-worker-*`, or `*` for every visible session but yours) and `subagents:*` / `subagents:<runId>/*` for the running, released or paused subagents a session launched; each recipient gets its own direct send, the result lists every outcome, and patterns stay inside the sender's groups. `ask` needs one exact target. Prefix matching stays inside the sender's existing authorized visibility; collisions list the matching full UUIDs and require one of them. Join `workflow:<rootRunId>` and use `intercom list` to see materialized `PENDING`/`RUNNING` workflow stages with canonical `workflow:<rootRunId>/<segment>[/<segment>...]` paths, plus possible future literals, globs, nested paths, and their queued counts. `*` matches one segment and `**` any depth. `workflow:<rootRunId>/**` reaches live stages now and remains sticky for every future stage until root termination; narrower patterns behave the same for their matches. A valid path outside the known set still queues, with no warning, and settles undeliverable at terminal only if never delivered; the result's `prediction` field says `known`, `predicted` or `unknown`, and a single `did you mean` line appears only for a likely typo. Use `ask` only on live targets. An eligible invocation member has directional list/send/live-ask control over stages in owned `workflow:<rootRunId>/...` subgroups. A subgroup stage or another workflow root cannot turn a mutable join into parent control; sibling subgroups stay isolated, and explicit `group: "default"` remains non-owned.
384
385
 
385
386
  When multiple live agent stages share a name, `ask` refuses the ambiguous target and recommends an exact stage-ID path. Name-based `send` keeps sticky delivery to matching agents, even when a prompt or tool shares the same name. Custom hosts may set `recipientPurpose` to exactly `"agent"` or `"control"` on registration and workflow roster entries; omission means legacy agent behavior. Malformed values (including `null`) are rejected, and presence updates cannot change a session's registered purpose. Host roster-update completion includes a same-connection broker round trip before subsequent discovery.
386
387
 
387
388
  **`send`** — Sends through ordinary Intercom. Live workflow-stage sessions receive messages immediately and return `delivered`. Known pending invocation-owned stages queue durably and return the distinct `queued` result with its FIFO position; a main-chat session that explicitly joined the owning invocation group may use that route. Pending `group: "default"` stages remain ineligible, and an ineligible attempt is refused with `Target workflow run is in a different intercom group`. Each exact run/stage key retains at most 50 queued messages; the next send is refused rather than evicting an older one. Delivery occurs before the first model turn under **Messages received before you started**, with sender identity and `Sent:` timestamp separate from the task prompt. Resume/replay, broker restart, and stage-attempt restart preserve exactly-once delivery by logical message ID. Skipped, cancelled, and terminal-before-initialization destinations make pending messages undeliverable and notify the sender. If the sender reconnects with a new broker UUID, notification fallback requires one unique same-group match for the immutable registration-time name; mutable presence names/groups, cross-group matches, and ambiguous duplicates are rejected. The broker trusts that initial name/group as host-orchestration metadata, while the original display/provenance remains unchanged in the durable record. Live sends remain immediate by default; `confirmSend: true` still enables confirmation for non-reply sends.
388
389
 
389
- **`ask`** — Sends a message and waits for a live recipient to reply (10-minute timeout). Invocation control supports a live ask into an owned isolated subgroup, and the exact broker-recorded reply resolves the waiting tool call at the asker without opening reverse or lateral group access. Ask to an uninitialized stage remains refused with `pending_stage_ask_unsupported`; use queued `send` instead, because holding a reply waiter until a stage eventually starts would be unbounded. A recipient disconnect after live delivery fails only that peer's exact wait promptly; the timeout remains the backstop while the recipient stays connected. Up to `maxPendingAsks` blocking asks (default: 6) may run concurrently, including same-target and mixed-target fan-out. Replies resolve by exact sender and message ID, so out-of-order replies cannot cross-settle another call. When capacity is full, new asks receive a structured refusal.
390
+ **`ask`** — Sends a message to a live recipient and returns once it is delivered, with `askId`, `delivered`, and the recipient's `state` (`idle` or `busy`, with `currentAction` when known). `wait` works as in `bash`: omitted waits up to the automatic yield (default 10 seconds), `{ kind: "foreground", budgetMs }` up to a budget, and `{ kind: "background" }` not at all. A reply within the wait comes back inline; otherwise the ask stays pending with no expiry and its reply arrives as a message starting "Reply to your ask <id> from <name>". A refusal, or a recipient session that ends, arrives as a failed-ask message. `pending` lists your pending asks and `cancel` (with `askId`) cancels one; a later reply is shown once, marked late. Asker and recipient restarts keep the ask. Invocation control supports a live ask into an owned isolated subgroup, and the exact broker-recorded reply resolves the waiting tool call at the asker without opening reverse or lateral group access. Ask to an uninitialized stage remains refused with `pending_stage_ask_unsupported`; use queued `send` instead, because holding a reply waiter until a stage eventually starts would be unbounded. Up to `maxPendingAsks` calls (default: 6) may wait for a reply at once; further asks are still delivered and their replies arrive as messages. Replies resolve by exact sender and message ID, so out-of-order replies cannot cross-settle another ask.
390
391
 
391
392
  **`reply`** without selectors replies to the current intercom-triggered message, or otherwise the single unresolved inbound ask. Explicit `to` selects a pending ask from that exact name/full session ID, even during another sender's turn. If that sender has multiple asks, use `pending` and pass the exact message ID as `replyTo`. Explicit `replyTo` selects only that pending ask or the exact active ordinary message; stale, unknown, or empty IDs fail instead of falling back. When both selectors are supplied, the sender must match the selected thread. A successful reply keeps that sender/thread pair across internal retries.
392
393
 
@@ -0,0 +1,260 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { chmodSync, existsSync, mkdirSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { DatabaseSync } from "node:sqlite";
5
+ import { isMessage, isSessionInfo } from "./client-message-validation.js";
6
+ import type { Message, SessionInfo } from "../types.js";
7
+ import type { PendingQuestion } from "./pending-question-index.js";
8
+
9
+ /** Most asks, and most held messages, kept for sessions that are away; the oldest go first beyond it. */
10
+ export const AWAY_ASKS_MAX = 10_000;
11
+ /** An away session that has not come back within this long is treated as gone for good: what waits for it is dropped. */
12
+ export const AWAY_ASK_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
13
+
14
+ export { HELD_FOR_AWAY_ASKER_TARGET } from "./held-reply-targets.js";
15
+
16
+ /** A reply, or a failed-ask message, held for an asker that is closed, delivered once when it registers again. */
17
+ export interface HeldAwayMessage {
18
+ readonly askerSessionId: string;
19
+ readonly from: SessionInfo;
20
+ readonly message: Message;
21
+ }
22
+
23
+ interface Statement {
24
+ all(...params: Array<string | number>): Array<Record<string, unknown>>;
25
+ get(...params: Array<string | number>): Record<string, unknown> | undefined;
26
+ run(...params: Array<string | number>): { changes: number | bigint };
27
+ }
28
+
29
+ /**
30
+ * #4751: the asks a session sent or was sent while it is away (closed, restarting, or released between turns), and
31
+ * the replies and failed-ask messages held for an away asker. An ask has no expiry, so these outlive the session's
32
+ * connection and, when a path is given, the broker itself; they are dropped when the session ends for good or has
33
+ * been away longer than {@link AWAY_ASK_RETENTION_MS}. Held messages carry their text: the file is owner-only.
34
+ */
35
+ export class AwayAsks {
36
+ private readonly database: DatabaseSync;
37
+
38
+ constructor(
39
+ path?: string,
40
+ private readonly now: () => number = Date.now,
41
+ private readonly retentionMs: number = AWAY_ASK_RETENTION_MS,
42
+ ) {
43
+ if (path !== undefined) {
44
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
45
+ }
46
+ this.database = new DatabaseSync(path ?? ":memory:");
47
+ if (path !== undefined && process.platform !== "win32" && existsSync(path)) chmodSync(path, 0o600);
48
+ this.database.exec(`
49
+ CREATE TABLE IF NOT EXISTS away_questions (
50
+ message_id TEXT NOT NULL,
51
+ sender_session_id TEXT NOT NULL,
52
+ target_session_id TEXT NOT NULL,
53
+ sender_return_address TEXT,
54
+ kept_at INTEGER NOT NULL,
55
+ PRIMARY KEY (message_id, sender_session_id, target_session_id)
56
+ );
57
+ CREATE TABLE IF NOT EXISTS held_messages (
58
+ message_id TEXT PRIMARY KEY,
59
+ asker_session_id TEXT NOT NULL,
60
+ asker_return_address TEXT NOT NULL,
61
+ replier_session_id TEXT NOT NULL,
62
+ from_json TEXT NOT NULL,
63
+ message_json TEXT NOT NULL,
64
+ held_at INTEGER NOT NULL
65
+ );
66
+ `);
67
+ this.purge();
68
+ }
69
+
70
+ private statement(sql: string): Statement {
71
+ return this.database.prepare(sql) as unknown as Statement;
72
+ }
73
+
74
+ private purge(): void {
75
+ const cutoff = this.now() - this.retentionMs;
76
+ this.statement("DELETE FROM away_questions WHERE kept_at < ?").run(cutoff);
77
+ this.statement("DELETE FROM held_messages WHERE held_at < ?").run(cutoff);
78
+ this.statement(
79
+ `DELETE FROM away_questions WHERE rowid NOT IN (SELECT rowid FROM away_questions ORDER BY kept_at DESC LIMIT ${AWAY_ASKS_MAX})`,
80
+ ).run();
81
+ this.statement(
82
+ `DELETE FROM held_messages WHERE rowid NOT IN (SELECT rowid FROM held_messages ORDER BY held_at DESC LIMIT ${AWAY_ASKS_MAX})`,
83
+ ).run();
84
+ }
85
+
86
+ /**
87
+ * Keep questions whose asker or recipient is away until it is back. `senderReturnAddress`: the away asker's own
88
+ * session, so a reply is not held for an asker that is already back under another Intercom id.
89
+ */
90
+ keep(questions: readonly PendingQuestion[], senderReturnAddress?: string): void {
91
+ if (questions.length === 0) return;
92
+ const insert = this.statement(
93
+ "INSERT OR REPLACE INTO away_questions (message_id, sender_session_id, target_session_id, sender_return_address, kept_at) VALUES (?, ?, ?, ?, ?)",
94
+ );
95
+ const at = this.now();
96
+ for (const question of questions)
97
+ insert.run(question.messageId, question.senderSessionId, question.targetSessionId, senderReturnAddress ?? "", at);
98
+ this.purge();
99
+ }
100
+
101
+ /** The kept question `questionId` that `replierSessionId` answers, if its asker is away. */
102
+ question(
103
+ questionId: string,
104
+ replierSessionId: string,
105
+ ): (PendingQuestion & { readonly senderReturnAddress?: string }) | undefined {
106
+ const row = this.statement(
107
+ "SELECT sender_session_id, sender_return_address FROM away_questions WHERE message_id = ? AND target_session_id = ? LIMIT 1",
108
+ ).get(questionId, replierSessionId);
109
+ if (typeof row?.sender_session_id !== "string") return undefined;
110
+ const returnAddress = typeof row.sender_return_address === "string" ? row.sender_return_address : "";
111
+ return {
112
+ messageId: questionId,
113
+ senderSessionId: row.sender_session_id,
114
+ targetSessionId: replierSessionId,
115
+ ...(returnAddress === "" ? {} : { senderReturnAddress: returnAddress }),
116
+ };
117
+ }
118
+
119
+ /** A session is back under its id: its kept questions whose peers are both connected leave this table. */
120
+ restore(
121
+ sessionId: string,
122
+ returnAddress: string | undefined,
123
+ isConnected: (sessionId: string) => boolean,
124
+ ): PendingQuestion[] {
125
+ // An asker's routes come back only to the session that proves it is the asker (see `held`), under whatever id it
126
+ // registered with now; a recipient's come back to the id it is asked under.
127
+ const proven = returnAddress ?? "";
128
+ const rows = this.statement(
129
+ "SELECT message_id, sender_session_id, target_session_id, sender_return_address FROM away_questions WHERE (sender_return_address <> '' AND sender_return_address = ?) OR (sender_return_address = '' AND sender_session_id = ?) OR target_session_id = ? ORDER BY kept_at",
130
+ ).all(proven, sessionId, sessionId);
131
+ const remove = this.statement(
132
+ "DELETE FROM away_questions WHERE message_id = ? AND sender_session_id = ? AND target_session_id = ?",
133
+ );
134
+ const restored: PendingQuestion[] = [];
135
+ for (const row of rows) {
136
+ const kept = {
137
+ messageId: String(row.message_id),
138
+ senderSessionId: String(row.sender_session_id),
139
+ targetSessionId: String(row.target_session_id),
140
+ };
141
+ const askerBack = proven !== "" && row.sender_return_address === proven;
142
+ const question = askerBack ? { ...kept, senderSessionId: sessionId } : kept;
143
+ if (!isConnected(question.senderSessionId) || !isConnected(question.targetSessionId)) continue;
144
+ remove.run(kept.messageId, kept.senderSessionId, kept.targetSessionId);
145
+ restored.push(question);
146
+ }
147
+ return restored;
148
+ }
149
+
150
+ /**
151
+ * The recipient `target` ended, or can no longer answer: each kept question to it becomes a failed-ask message held
152
+ * for its away asker. Returns the questions failed.
153
+ */
154
+ failForTarget(target: SessionInfo, reason: string, idPrefix: string): PendingQuestion[] {
155
+ const rows = this.statement(
156
+ "SELECT message_id, sender_session_id, sender_return_address FROM away_questions WHERE target_session_id = ? ORDER BY kept_at",
157
+ ).all(target.id);
158
+ const failed: PendingQuestion[] = [];
159
+ for (const row of rows) {
160
+ const question = {
161
+ messageId: String(row.message_id),
162
+ senderSessionId: String(row.sender_session_id),
163
+ targetSessionId: target.id,
164
+ };
165
+ const returnAddress = typeof row.sender_return_address === "string" ? row.sender_return_address : "";
166
+ // A recipient's own asks to an away session keep no asker identity: only an away asker learns of the end.
167
+ if (returnAddress === "") continue;
168
+ failed.push(question);
169
+ this.hold({ ...question, senderReturnAddress: returnAddress }, target, {
170
+ // Unguessable, so no other session can name it.
171
+ id: `${idPrefix}:${randomUUID()}`,
172
+ timestamp: this.now(),
173
+ replyTo: question.messageId,
174
+ replyError: reason,
175
+ content: { text: reason },
176
+ });
177
+ }
178
+ this.statement("DELETE FROM away_questions WHERE target_session_id = ?").run(target.id);
179
+ return failed;
180
+ }
181
+
182
+ /** The asker that proves itself by its return address ended for good: nothing waits for it any more. */
183
+ drop(returnAddress: string | undefined): void {
184
+ if (returnAddress === undefined || returnAddress === "") return;
185
+ this.statement("DELETE FROM away_questions WHERE sender_return_address = ?").run(returnAddress);
186
+ this.statement("DELETE FROM held_messages WHERE asker_return_address = ?").run(returnAddress);
187
+ }
188
+
189
+ /**
190
+ * Hold a message for the away asker of `question`, and close the question: it has its answer (or its failure), so
191
+ * nothing later fails it again. A message already held under its id is held once.
192
+ */
193
+ hold(
194
+ question: PendingQuestion & { readonly senderReturnAddress: string },
195
+ from: SessionInfo,
196
+ message: Message,
197
+ ): void {
198
+ this.statement(
199
+ "INSERT OR IGNORE INTO held_messages (message_id, asker_session_id, asker_return_address, replier_session_id, from_json, message_json, held_at) VALUES (?, ?, ?, ?, ?, ?, ?)",
200
+ ).run(
201
+ message.id,
202
+ question.senderSessionId,
203
+ question.senderReturnAddress,
204
+ from.id,
205
+ JSON.stringify(from),
206
+ JSON.stringify(message),
207
+ this.now(),
208
+ );
209
+ this.statement(
210
+ "DELETE FROM away_questions WHERE message_id = ? AND sender_session_id = ? AND target_session_id = ?",
211
+ ).run(question.messageId, question.senderSessionId, question.targetSessionId);
212
+ this.purge();
213
+ }
214
+
215
+ /** Whether `messageId` from `replierSessionId` is already held for its asker: a retried reply is answered held again. */
216
+ isHeld(messageId: string, replierSessionId: string): boolean {
217
+ return (
218
+ this.statement("SELECT 1 FROM held_messages WHERE message_id = ? AND replier_session_id = ?").get(
219
+ messageId,
220
+ replierSessionId,
221
+ ) !== undefined
222
+ );
223
+ }
224
+
225
+ /**
226
+ * The messages held for this asker, in the order they were held: only to the session that proves it is the asker by
227
+ * the return address it registered with when it asked, the credential it reclaims its id with.
228
+ */
229
+ held(askerReturnAddress: string | undefined): HeldAwayMessage[] {
230
+ if (askerReturnAddress === undefined || askerReturnAddress === "") return [];
231
+ const rows = this.statement(
232
+ "SELECT asker_session_id, from_json, message_json FROM held_messages WHERE asker_return_address = ? ORDER BY held_at, rowid",
233
+ ).all(askerReturnAddress);
234
+ const held: HeldAwayMessage[] = [];
235
+ for (const row of rows) {
236
+ try {
237
+ const from: unknown = JSON.parse(String(row.from_json));
238
+ const message: unknown = JSON.parse(String(row.message_json));
239
+ if (isSessionInfo(from) && isMessage(message))
240
+ held.push({ askerSessionId: String(row.asker_session_id), from, message });
241
+ } catch {
242
+ // A row that cannot be read is skipped; it ages out with the retention.
243
+ }
244
+ }
245
+ return held;
246
+ }
247
+
248
+ /** The verified asker saved a held message: it is not delivered again. */
249
+ release(messageId: string, askerReturnAddress: string | undefined): void {
250
+ if (askerReturnAddress === undefined || askerReturnAddress === "") return;
251
+ this.statement("DELETE FROM held_messages WHERE message_id = ? AND asker_return_address = ?").run(
252
+ messageId,
253
+ askerReturnAddress,
254
+ );
255
+ }
256
+
257
+ close(): void {
258
+ this.database.close();
259
+ }
260
+ }