conductor-remote 1.116.0 → 1.118.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (200) hide show
  1. package/README.md +10 -8
  2. package/dist/assets/{PierrePatch-BPp5Cf-p.js → PierrePatch-D4YbKD8Q.js} +1 -1
  3. package/dist/assets/index-BRzsSW8g.css +1 -0
  4. package/dist/assets/index-BaS6qXUW.js +65 -0
  5. package/dist/index.html +2 -2
  6. package/dist/push-sw.js +2 -2
  7. package/dist/sw.js +1 -1
  8. package/dist-node/scripts/nosleep-setup.js +2 -2
  9. package/dist-node/scripts/nosleep.js +3 -3
  10. package/dist-node/scripts/service/commands.js +32 -0
  11. package/dist-node/scripts/service/configuration.js +205 -0
  12. package/dist-node/scripts/service/environment.js +59 -0
  13. package/dist-node/scripts/service/flags.js +45 -0
  14. package/dist-node/scripts/service/installation.js +91 -0
  15. package/dist-node/scripts/service/launch-agent.js +134 -0
  16. package/dist-node/scripts/service/network.js +244 -0
  17. package/dist-node/scripts/service/presentation.js +101 -0
  18. package/dist-node/scripts/service/voice.js +113 -0
  19. package/dist-node/scripts/service.js +5 -980
  20. package/dist-node/src/{agent-config.js → agents/agent-config.js} +1 -1
  21. package/dist-node/src/{model-cache.js → agents/model-cache.js} +1 -1
  22. package/dist-node/src/{roles.js → agents/roles.js} +3 -3
  23. package/dist-node/src/db.js +1 -1
  24. package/dist-node/src/{parked.js → delivery/parked.js} +1 -1
  25. package/dist-node/src/{dev-server.js → dev-server/controller.js} +8 -291
  26. package/dist-node/src/dev-server/ports.js +63 -0
  27. package/dist-node/src/dev-server/processes.js +73 -0
  28. package/dist-node/src/dev-server/proxy.js +158 -0
  29. package/dist-node/src/{run-activity.js → dev-server/run-activity.js} +2 -2
  30. package/dist-node/src/dev-server/types.js +1 -0
  31. package/dist-node/src/{file-preview.js → files/file-preview.js} +1 -1
  32. package/dist-node/src/{change-stats.js → git/change-stats.js} +1 -1
  33. package/dist-node/src/{git.js → git/diff.js} +1 -1
  34. package/dist-node/src/{autoupdate.js → host/autoupdate.js} +1 -1
  35. package/dist-node/src/{funnel-watchdog.js → host/funnel-watchdog.js} +4 -4
  36. package/dist-node/src/{logbuf.js → host/logbuf.js} +1 -1
  37. package/dist-node/src/{nosleep-helper.js → host/nosleep-helper.js} +1 -1
  38. package/dist-node/src/{tailscale.js → host/tailscale.js} +1 -1
  39. package/dist-node/src/http/router-types.js +2 -0
  40. package/dist-node/src/http/router.js +78 -0
  41. package/dist-node/src/http/routes/create-workspace.js +90 -0
  42. package/dist-node/src/http/routes/files.js +53 -0
  43. package/dist-node/src/http/routes/prompts.js +363 -0
  44. package/dist-node/src/http/routes/sessions.js +279 -0
  45. package/dist-node/src/http/routes/state.js +186 -0
  46. package/dist-node/src/http/routes/system.js +220 -0
  47. package/dist-node/src/http/routes/voice.js +117 -0
  48. package/dist-node/src/http/routes/workflows.js +248 -0
  49. package/dist-node/src/http/routes/workspaces.js +267 -0
  50. package/dist-node/src/http/services/base.js +252 -0
  51. package/dist-node/src/http/services/delegations.js +301 -0
  52. package/dist-node/src/http/services/delivery.js +433 -0
  53. package/dist-node/src/http/services/files.js +199 -0
  54. package/dist-node/src/http/services/mcp.js +94 -0
  55. package/dist-node/src/http/services/responses.js +120 -0
  56. package/dist-node/src/http/services/voice.js +147 -0
  57. package/dist-node/src/http/services/workflow-probes.js +215 -0
  58. package/dist-node/src/http/services/workflow-state.js +195 -0
  59. package/dist-node/src/http/services/workflow.js +366 -0
  60. package/dist-node/src/http/services.js +35 -0
  61. package/dist-node/src/mcp/arguments.js +14 -0
  62. package/dist-node/src/mcp/dispatcher.js +56 -0
  63. package/dist-node/src/mcp/formatters.js +110 -0
  64. package/dist-node/src/mcp/protocol.js +7 -0
  65. package/dist-node/src/mcp/registry.js +66 -0
  66. package/dist-node/src/mcp/tools/agent-options.js +122 -0
  67. package/dist-node/src/mcp/tools/chat-actions.js +194 -0
  68. package/dist-node/src/mcp/tools/chats.js +194 -0
  69. package/dist-node/src/mcp/tools/delegation.js +135 -0
  70. package/dist-node/src/mcp/tools/system.js +135 -0
  71. package/dist-node/src/mcp/tools/voice.js +136 -0
  72. package/dist-node/src/mcp/tools/workspaces.js +259 -0
  73. package/dist-node/src/mcp/types.js +1 -0
  74. package/dist-node/src/mcp.js +6 -4
  75. package/dist-node/src/{notify.js → notifications/notify.js} +5 -5
  76. package/dist-node/src/{webpush.js → notifications/webpush.js} +1 -1
  77. package/dist-node/src/orchestration/delegation/codec.js +201 -0
  78. package/dist-node/src/{delegation-intake.js → orchestration/delegation/intake.js} +2 -2
  79. package/dist-node/src/{delegation-prompt.js → orchestration/delegation/prompt.js} +1 -1
  80. package/dist-node/src/orchestration/delegation/queue.js +255 -0
  81. package/dist-node/src/orchestration/delegation/store.js +111 -0
  82. package/dist-node/src/orchestration/delegation/types.js +2 -0
  83. package/dist-node/src/orchestration/persistence/capabilities.js +109 -0
  84. package/dist-node/src/orchestration/persistence/codecs.js +148 -0
  85. package/dist-node/src/orchestration/persistence/connection.js +205 -0
  86. package/dist-node/src/orchestration/persistence/db.js +101 -0
  87. package/dist-node/src/orchestration/persistence/effect-recovery.js +227 -0
  88. package/dist-node/src/orchestration/persistence/effect-transitions.js +157 -0
  89. package/dist-node/src/orchestration/persistence/effects.js +109 -0
  90. package/dist-node/src/orchestration/persistence/errors.js +39 -0
  91. package/dist-node/src/orchestration/persistence/events.js +29 -0
  92. package/dist-node/src/orchestration/persistence/idempotency.js +82 -0
  93. package/dist-node/src/orchestration/persistence/job-attempts.js +114 -0
  94. package/dist-node/src/orchestration/persistence/jobs.js +159 -0
  95. package/dist-node/src/orchestration/persistence/projections.js +190 -0
  96. package/dist-node/src/orchestration/persistence/quarantine.js +46 -0
  97. package/dist-node/src/orchestration/persistence/records.js +115 -0
  98. package/dist-node/src/orchestration/persistence/relays.js +78 -0
  99. package/dist-node/src/orchestration/persistence/runs.js +156 -0
  100. package/dist-node/src/{orchestration-schema.js → orchestration/persistence/schema.js} +1 -1
  101. package/dist-node/src/orchestration/persistence/types.js +1 -0
  102. package/dist-node/src/orchestration/persistence/ui-lease.js +197 -0
  103. package/dist-node/src/orchestration/persistence/values.js +114 -0
  104. package/dist-node/src/orchestration/workflow/commands.js +309 -0
  105. package/dist-node/src/orchestration/workflow/coordinator.js +28 -0
  106. package/dist-node/src/orchestration/workflow/effect-recovery.js +125 -0
  107. package/dist-node/src/orchestration/workflow/effects.js +307 -0
  108. package/dist-node/src/orchestration/workflow/errors.js +13 -0
  109. package/dist-node/src/orchestration/workflow/helpers.js +154 -0
  110. package/dist-node/src/orchestration/workflow/job-dispatch.js +312 -0
  111. package/dist-node/src/orchestration/workflow/job-results.js +280 -0
  112. package/dist-node/src/{workflow.js → orchestration/workflow/prompts.js} +2 -2
  113. package/dist-node/src/orchestration/workflow/root.js +293 -0
  114. package/dist-node/src/orchestration/workflow/start.js +99 -0
  115. package/dist-node/src/orchestration/workflow/state.js +105 -0
  116. package/dist-node/src/orchestration/workflow/types.js +1 -0
  117. package/dist-node/src/orchestration/workflow/wake.js +164 -0
  118. package/dist-node/src/prefs.js +1 -1
  119. package/dist-node/src/{background-tasks.js → reads/background-tasks.js} +1 -1
  120. package/dist-node/src/reads/messages.js +362 -0
  121. package/dist-node/src/reads/repository.js +87 -0
  122. package/dist-node/src/reads/sessions.js +165 -0
  123. package/dist-node/src/reads/types.js +1 -0
  124. package/dist-node/src/reads/workspaces.js +230 -0
  125. package/dist-node/src/reads/worktrees.js +45 -0
  126. package/dist-node/src/routes.js +5 -5
  127. package/dist-node/src/{search.js → search/coordinator.js} +4 -4
  128. package/dist-node/src/{search-worker.js → search/worker.js} +3 -3
  129. package/dist-node/src/server.js +14 -3930
  130. package/dist-node/src/settings.js +1 -1
  131. package/dist-node/src/shared.js +130 -9
  132. package/dist-node/src/{transcript.js → transcript/parser.js} +4 -124
  133. package/dist-node/src/{tool-usage-worker.js → usage/tool-usage-worker.js} +1 -1
  134. package/dist-node/src/{tool-usage.js → usage/tool-usage.js} +1 -1
  135. package/dist-node/src/voice/brief.js +22 -50
  136. package/dist-node/src/voice/context.js +1 -1
  137. package/dist-node/src/voice/dates.js +38 -0
  138. package/dist-node/src/voice/history.js +14 -5
  139. package/dist-node/src/voice/prompt.js +10 -9
  140. package/dist-node/src/voice/recall.js +115 -0
  141. package/dist-node/src/{speech.js → voice/speech.js} +1 -1
  142. package/dist-node/src/voice/tools.js +92 -3
  143. package/dist-node/src/voice/webrtc.js +1 -1
  144. package/dist-node/src/wire.js +2 -2
  145. package/dist-node/src/writes/actuator.js +124 -0
  146. package/dist-node/src/writes/agent-options.js +151 -0
  147. package/dist-node/src/writes/applescript/agent-options.applescript +334 -0
  148. package/dist-node/src/writes/applescript/chat-targeting.applescript +149 -0
  149. package/dist-node/src/writes/applescript/composer.applescript +195 -0
  150. package/dist-node/src/writes/applescript/hotspot.applescript +155 -0
  151. package/dist-node/src/writes/applescript/lifecycle.applescript +266 -0
  152. package/dist-node/src/writes/applescript/run-tasks.applescript +208 -0
  153. package/dist-node/src/writes/applescript/source.js +52 -0
  154. package/dist-node/src/writes/applescript/window.applescript +436 -0
  155. package/dist-node/src/writes/applescript/workspace-status.applescript +177 -0
  156. package/dist-node/src/writes/applescript/workspace-targeting.applescript +359 -0
  157. package/dist-node/src/writes/chats.js +160 -0
  158. package/dist-node/src/writes/guards.js +77 -0
  159. package/dist-node/src/writes/runner.js +67 -0
  160. package/dist-node/src/{sidecar.js → writes/sidecar.js} +1 -1
  161. package/dist-node/src/writes/system.js +81 -0
  162. package/dist-node/src/writes/targeting.js +121 -0
  163. package/dist-node/src/writes/types.js +1 -0
  164. package/dist-node/src/writes/ui-lock.js +229 -0
  165. package/dist-node/src/writes/workspaces.js +233 -0
  166. package/docs/voice-setup.md +34 -12
  167. package/package.json +2 -2
  168. package/dist/assets/index-DNLdIfZ2.css +0 -1
  169. package/dist/assets/index-QJR7tn2I.js +0 -61
  170. package/dist-node/src/conductor.applescript +0 -2279
  171. package/dist-node/src/delegations.js +0 -557
  172. package/dist-node/src/mcp-tools.js +0 -1319
  173. package/dist-node/src/orchestration-db.js +0 -2186
  174. package/dist-node/src/reads.js +0 -787
  175. package/dist-node/src/workflow-coordinator.js +0 -2119
  176. package/dist-node/src/writes.js +0 -1223
  177. /package/dist-node/src/{conductor-settings.js → agents/conductor-settings.js} +0 -0
  178. /package/dist-node/src/{firstprompt.js → delivery/firstprompt.js} +0 -0
  179. /package/dist-node/src/{sendonce.js → delivery/sendonce.js} +0 -0
  180. /package/dist-node/src/{preview-urls.js → dev-server/preview-urls.js} +0 -0
  181. /package/dist-node/src/{run-configs.js → dev-server/run-configs.js} +0 -0
  182. /package/dist-node/src/{attachments.js → files/attachments.js} +0 -0
  183. /package/dist-node/src/{icons.js → files/icons.js} +0 -0
  184. /package/dist-node/src/{staged-attachments.js → files/staged-attachments.js} +0 -0
  185. /package/dist-node/src/{fork-workspace.js → git/fork-workspace.js} +0 -0
  186. /package/dist-node/src/{merge.js → git/merge.js} +0 -0
  187. /package/dist-node/src/{pr.js → git/pr.js} +0 -0
  188. /package/dist-node/src/{nosleep.js → host/nosleep.js} +0 -0
  189. /package/dist-node/src/{relay-processes.js → host/relay-processes.js} +0 -0
  190. /package/dist-node/src/{ui-lease-watchdog.js → host/ui-lease-watchdog.js} +0 -0
  191. /package/dist-node/src/{wifi.js → host/wifi.js} +0 -0
  192. /package/dist-node/src/{orchestration-schema.generated.js → orchestration/persistence/schema.generated.js} +0 -0
  193. /package/dist-node/src/{workflow-effect-runner.js → orchestration/workflow/effect-runner.js} +0 -0
  194. /package/dist-node/src/{workflow-http.js → orchestration/workflow/http.js} +0 -0
  195. /package/dist-node/src/{workflow-machine.js → orchestration/workflow/machine.js} +0 -0
  196. /package/dist-node/src/{session-poller.js → reads/session-poller.js} +0 -0
  197. /package/dist-node/src/{context-breakdown.js → transcript/context-breakdown.js} +0 -0
  198. /package/dist-node/src/{chat-cursor.js → transcript/cursor.js} +0 -0
  199. /package/dist-node/src/{plan-usage.js → usage/plan-usage.js} +0 -0
  200. /package/dist-node/src/{tool-usage-service.js → usage/tool-usage-service.js} +0 -0
@@ -1,787 +0,0 @@
1
- import { execFileSync } from 'node:child_process';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { agentProcessStarts, openBackgroundTasks, TASK_FRAME_FILTER } from "./background-tasks.js";
5
- import { estimateContextCategories, estimateTextTokens } from "./context-breakdown.js";
6
- import { describeRepoIcon, resolveRepoIcon } from "./icons.js";
7
- import { workspaceTitle } from "./shared.js";
8
- import { parseMessage, parseOutboxMessage, renderTranscript, toolImageAt } from "./transcript.js";
9
- /** Keep the stable wire field in sync with whichever provider owns the chat. */
10
- function toSessionRow(row, background_tasks) {
11
- const { codex_thinking_level, ...session } = row;
12
- const effort = row.agent_type === 'codex' ? codex_thinking_level : row.claude_effort_level;
13
- return {
14
- ...session,
15
- // Codex calls its top level `ultra`; the relay's long-lived wire value is
16
- // `ultracode`, which is also Claude's stored spelling and the phone's key.
17
- claude_effort_level: effort === 'ultra' ? 'ultracode' : effort,
18
- background_tasks
19
- };
20
- }
21
- const worktreeCache = new Map();
22
- /**
23
- * The dispatch time of the latest turn a person started.
24
- *
25
- * Current Conductor writes the same `turn_id` on a turn's first prompt and every
26
- * steering message added while it runs, but stopped populating `queue_order` on
27
- * 2026-08-31. Start with the latest user row that was actually dispatched (so a prompt
28
- * queued behind the current answer cannot take over), then take the first dispatch in
29
- * that turn (so steering cannot restart the clock). A self-scheduled `/loop` lap writes
30
- * no user row, leaving this value unchanged for the notification deduper.
31
- *
32
- * The second arm preserves workspaces written by older Conductor builds, where
33
- * `queue_order` identified turn heads and `turn_id` may be absent.
34
- * `MIN(CASE …)` is deliberate: a plain `MIN(sent_at)` makes SQLite favour the
35
- * sent-time index and walk every older turn, while the expression lets the existing
36
- * `(session_id, role, turn_id, …)` index jump straight to this turn's few user rows.
37
- */
38
- const TURN_STARTED_AT_SQL = `COALESCE(
39
- (SELECT MIN(CASE WHEN head.sent_at IS NOT NULL THEN head.sent_at END)
40
- FROM session_messages head
41
- WHERE head.session_id = s.id
42
- AND head.role = 'user'
43
- AND head.turn_id = (
44
- SELECT latest.turn_id
45
- FROM session_messages latest
46
- WHERE latest.session_id = s.id
47
- AND latest.role = 'user'
48
- AND latest.turn_id IS NOT NULL
49
- AND latest.sent_at IS NOT NULL
50
- ORDER BY latest.sent_at DESC, latest.rowid DESC
51
- LIMIT 1
52
- )),
53
- (SELECT MAX(legacy.sent_at)
54
- FROM session_messages legacy
55
- WHERE legacy.session_id = s.id
56
- AND legacy.queue_order IS NOT NULL
57
- AND legacy.sent_at IS NOT NULL)
58
- )`;
59
- /**
60
- * Neutralize LIKE's own wildcards in a user's search word. `queryTokens` already
61
- * strips everything but letters, digits and `_` — and `_` is LIKE's single-character
62
- * wildcard, so "add_set" would quietly also match "addaset" without this.
63
- */
64
- function escapeLike(s) {
65
- return s.replace(/[\\%_]/g, m => `\\${m}`);
66
- }
67
- /** Shared row → `SearchWorkspace` shape for the two search reads below. */
68
- function toSearchWorkspace(r) {
69
- return {
70
- id: r.id,
71
- workspace_name: r.workspace_name,
72
- pr_title: r.pr_title,
73
- branch: r.branch,
74
- directory_name: r.directory_name,
75
- state: r.state,
76
- updated_at: r.updated_at,
77
- repo_name: r.repo_name,
78
- icon: describeRepoIcon({ icon: r.repo_icon, repoRoot: r.repo_root, remoteUrl: r.remote_url }),
79
- archived: r.state === 'archived'
80
- };
81
- }
82
- /**
83
- * Resolve a workspace's worktree path. Conductor lays worktrees out as
84
- * `<workspacesRoot>/<repoName>/<directoryName>`, but we verify against
85
- * `git worktree list` (matched by branch) so a layout change can't silently
86
- * point us at the wrong tree.
87
- */
88
- function resolveWorktree(workspacesRoot, repoName, directoryName, branch, repoRoot) {
89
- if (repoName && directoryName) {
90
- const guess = path.join(workspacesRoot, repoName, directoryName);
91
- if (fs.existsSync(path.join(guess, '.git')))
92
- return guess;
93
- }
94
- if (!(repoRoot && branch))
95
- return null;
96
- const cacheKey = repoRoot;
97
- let listing = worktreeCache.get(cacheKey);
98
- if (listing === undefined) {
99
- try {
100
- listing = execFileSync('git', ['-C', repoRoot, 'worktree', 'list', '--porcelain'], {
101
- encoding: 'utf8',
102
- timeout: 5000
103
- });
104
- }
105
- catch {
106
- listing = null;
107
- }
108
- worktreeCache.set(cacheKey, listing);
109
- }
110
- if (!listing)
111
- return null;
112
- // Porcelain: blocks of "worktree <path>" / "branch refs/heads/<name>"
113
- const blocks = listing.split('\n\n');
114
- for (const block of blocks) {
115
- if (block.includes(`refs/heads/${branch}`)) {
116
- const m = block.match(/^worktree (.+)$/m);
117
- if (m)
118
- return m[1];
119
- }
120
- }
121
- return null;
122
- }
123
- export class Reads {
124
- db;
125
- workspacesRoot;
126
- /** Chats with a live agent process, and its start — the gate on `background_tasks`. */
127
- liveAgents;
128
- messageOutboxAvailable = null;
129
- messageOutboxCheckedAt = 0;
130
- constructor(db, workspacesRoot, liveAgents = agentProcessStarts) {
131
- this.db = db;
132
- this.workspacesRoot = workspacesRoot;
133
- this.liveAgents = liveAgents;
134
- }
135
- /**
136
- * Unread chats, grouped by workspace. `workspaces.unread` is a **dead column** —
137
- * Conductor still declares it (and its migration still says "when 1, the workspace
138
- * should be marked visually as unread") but writes 0 on every row: 0 of 1691 are
139
- * non-zero on this Mac, which is why the sidebar's bold/badge never once fired.
140
- * The live flag is per session, and it *is* a flag — `unread_count` is only ever
141
- * 0 or 1 — so what's worth counting is how many chats have news, not the column.
142
- */
143
- unreadSessions() {
144
- const rows = this.db.query(`SELECT workspace_id, id, updated_at
145
- FROM sessions
146
- WHERE COALESCE(unread_count, 0) > 0 AND COALESCE(is_hidden, 0) = 0`);
147
- const byWorkspace = new Map();
148
- for (const r of rows) {
149
- if (!r.workspace_id)
150
- continue;
151
- const list = byWorkspace.get(r.workspace_id);
152
- if (list)
153
- list.push({ id: r.id, at: r.updated_at });
154
- else
155
- byWorkspace.set(r.workspace_id, [{ id: r.id, at: r.updated_at }]);
156
- }
157
- return byWorkspace;
158
- }
159
- listWorkspaces() {
160
- const rows = this.db.query(`SELECT w.id, w.directory_name, w.workspace_name, w.branch, w.pr_title, w.derived_status, w.manual_status,
161
- w.state, w.created_at, w.updated_at, w.pinned_at, w.active_session_id, w.intended_target_branch,
162
- r.name AS repo_name, r.root_path AS repo_root, r.icon AS repo_icon,
163
- r.remote_url AS remote_url, r.default_branch AS default_branch,
164
- s.status AS session_status, s.title AS session_title, s.model AS model,
165
- s.agent_type AS agent_type
166
- FROM workspaces w
167
- LEFT JOIN repos r ON r.id = w.repository_id
168
- LEFT JOIN sessions s ON s.id = w.active_session_id
169
- WHERE w.state IN ('ready', 'setting_up')
170
- ORDER BY (w.pinned_at IS NULL), w.updated_at DESC`);
171
- const unread = this.unreadSessions();
172
- return rows.map(r => ({
173
- ...r,
174
- unread_sessions: unread.get(r.id) ?? [],
175
- worktree: resolveWorktree(this.workspacesRoot, r.repo_name, r.directory_name, r.branch, r.repo_root),
176
- baseBranch: r.intended_target_branch || r.default_branch || 'main',
177
- icon: describeRepoIcon({ icon: r.repo_icon, repoRoot: r.repo_root, remoteUrl: r.remote_url })
178
- }));
179
- }
180
- getWorkspace(id) {
181
- return this.listWorkspaces().find(w => w.id === id) ?? null;
182
- }
183
- /**
184
- * The repos Conductor knows about, most recently used first. `root_path` is
185
- * what a `conductor://…&path=` deep link needs to pick the target repo — with
186
- * no path Conductor silently falls back to the *first* repo.
187
- *
188
- * "Used" is the newest workspace in the repo, never `repos.updated_at`: that
189
- * column moves when the repo's *settings* change, so the repo worked in every
190
- * day here reads as last touched six weeks ago. Repos with no workspace at all
191
- * keep Conductor's own sidebar order, behind every repo that has one.
192
- *
193
- * The `replace()`s are load-bearing: `created_at` is always `YYYY-MM-DD HH:MM:SS`
194
- * while `updated_at` is written both that way (306 rows) and as ISO with a `Z`
195
- * (1,819), and 'T' sorts after ' ', so an untouched string compare can rank an
196
- * earlier ISO row above a later plain one on the same day.
197
- */
198
- listRepos() {
199
- const rows = this.db.query(`SELECT r.name, r.root_path, r.default_branch, r.icon, r.remote_url
200
- FROM repos r
201
- LEFT JOIN workspaces w ON w.repository_id = r.id
202
- WHERE COALESCE(r.hidden, 0) = 0
203
- GROUP BY r.id
204
- ORDER BY (MAX(MAX(REPLACE(REPLACE(w.updated_at, 'T', ' '), 'Z', ''), w.created_at)) IS NULL),
205
- MAX(MAX(REPLACE(REPLACE(w.updated_at, 'T', ' '), 'Z', ''), w.created_at)) DESC,
206
- (r.display_order IS NULL), r.display_order, r.name`);
207
- return rows.map(r => ({
208
- name: r.name,
209
- root_path: r.root_path,
210
- default_branch: r.default_branch,
211
- icon: describeRepoIcon({ icon: r.icon, repoRoot: r.root_path, remoteUrl: r.remote_url })
212
- }));
213
- }
214
- /**
215
- * Map chat ids to the workspace that owns them, archived included.
216
- *
217
- * `listWorkspaces` filters to `state IN ('ready','setting_up')`, which is right for
218
- * the sidebar and wrong for search: the whole point of searching the transcript is
219
- * to reach work you finished and put away. One query for the whole hit set, because
220
- * a search fans out over up to 300 chunks and a per-chat lookup would be 300 of them.
221
- */
222
- searchTargets(sessionIds) {
223
- const out = new Map();
224
- if (!sessionIds.length)
225
- return out;
226
- const holes = sessionIds.map(() => '?').join(',');
227
- const rows = this.db.query(`SELECT s.id AS session_id, s.title AS session_title,
228
- w.id, w.workspace_name, w.pr_title, w.branch, w.directory_name, w.state, w.updated_at,
229
- r.name AS repo_name, r.icon AS repo_icon, r.root_path AS repo_root, r.remote_url AS remote_url
230
- FROM sessions s
231
- JOIN workspaces w ON w.id = s.workspace_id
232
- LEFT JOIN repos r ON r.id = w.repository_id
233
- WHERE s.id IN (${holes})`, sessionIds);
234
- for (const r of rows)
235
- out.set(r.session_id, { sessionTitle: r.session_title, workspace: toSearchWorkspace(r) });
236
- return out;
237
- }
238
- /**
239
- * Every chat in the requested search scope. The index only carries chat ids, so
240
- * repo and archive filters have to be resolved here before ranking. Names, not repo
241
- * ids, because names are what the phone's picker and `list_repos` hold.
242
- */
243
- searchSessionIds(repos, includeArchived) {
244
- if (repos && !repos.length)
245
- return [];
246
- const scope = [
247
- ...(repos ? [`r.name IN (${repos.map(() => '?').join(',')})`] : []),
248
- ...(!includeArchived ? ["w.state IS NOT 'archived'"] : [])
249
- ];
250
- return this.db
251
- .query(`SELECT s.id FROM sessions s
252
- JOIN workspaces w ON w.id = s.workspace_id
253
- LEFT JOIN repos r ON r.id = w.repository_id
254
- ${scope.length ? ` WHERE ${scope.join(' AND ')}` : ''}`, repos ?? [])
255
- .map(r => r.id);
256
- }
257
- /**
258
- * Workspaces whose own identity matches every token — name, PR title, branch,
259
- * worktree codename or repo. Archived are included by default, for the same reason
260
- * as `searchTargets`; `includeArchived` lets the phone narrow the search to current
261
- * work. `repos` narrows to those repos by name; an empty list matches nothing.
262
- *
263
- * This is the half of search the transcript index cannot do. A workspace named for
264
- * the thing you are looking for may never have said those words in its chat, and
265
- * one whose chat is empty has no chunks at all.
266
- */
267
- findWorkspacesByName(tokens, limit = 20, repos, includeArchived = true) {
268
- if (!tokens.length)
269
- return [];
270
- if (repos && !repos.length)
271
- return [];
272
- const fields = ['w.workspace_name', 'w.pr_title', 'w.branch', 'w.directory_name', 'r.name'];
273
- // AND across tokens, OR across fields: "auk lamp" should find the lamp workspace in
274
- // the auk repo, where no single column holds both words.
275
- const byToken = tokens.map(() => `(${fields.map(f => `${f} LIKE ? ESCAPE '\\'`).join(' OR ')})`);
276
- const scope = [
277
- ...(repos ? [`r.name IN (${repos.map(() => '?').join(',')})`] : []),
278
- ...(!includeArchived ? ["w.state IS NOT 'archived'"] : [])
279
- ];
280
- const where = [...byToken, ...scope].join(' AND ');
281
- const params = [...tokens.flatMap(t => fields.map(() => `%${escapeLike(t)}%`)), ...(repos ?? [])];
282
- const rows = this.db.query(`SELECT w.id, w.workspace_name, w.pr_title, w.branch, w.directory_name, w.state, w.updated_at,
283
- r.name AS repo_name, r.icon AS repo_icon, r.root_path AS repo_root, r.remote_url AS remote_url
284
- FROM workspaces w
285
- LEFT JOIN repos r ON r.id = w.repository_id
286
- WHERE ${where}
287
- ORDER BY (w.state = 'archived'), w.updated_at DESC
288
- LIMIT ?`, [...params, limit]);
289
- return rows.map(toSearchWorkspace);
290
- }
291
- /**
292
- * One workspace by id, whatever state it is in — the read behind opening an archived
293
- * chat (`GET /api/workspaces/:id`).
294
- *
295
- * `getWorkspace` above is the *live* one: it resolves a worktree and a base branch,
296
- * and returns null for the 1,846 archived workspaces here, which is right for every
297
- * write (there is nothing to focus and nothing to diff) and wrong for reading. The
298
- * transcript survives archiving — Conductor deletes the worktree, not the chat — so
299
- * this returns the same `SearchWorkspace` a search result carries, with no worktree
300
- * and no git, and `listSessions`/`getMessages` do the rest by id.
301
- */
302
- getAnyWorkspace(id) {
303
- const rows = this.db.query(`SELECT w.id, w.workspace_name, w.pr_title, w.branch, w.directory_name, w.state, w.updated_at,
304
- r.name AS repo_name, r.icon AS repo_icon, r.root_path AS repo_root, r.remote_url AS remote_url
305
- FROM workspaces w
306
- LEFT JOIN repos r ON r.id = w.repository_id
307
- WHERE w.id = ?
308
- LIMIT 1`, [id]);
309
- return rows[0] ? toSearchWorkspace(rows[0]) : null;
310
- }
311
- /** Resolve a repo's icon by its name (the sidebar avatar) — null if the repo or icon is unknown. */
312
- resolveRepoIcon(repoName) {
313
- const rows = this.db.query('SELECT root_path FROM repos WHERE name = ? LIMIT 1', [
314
- repoName
315
- ]);
316
- const root = rows[0]?.root_path;
317
- return root ? resolveRepoIcon(root) : null;
318
- }
319
- listSessions(workspaceId) {
320
- // created_at ASC keeps tab order stable (matches the desktop app) instead of jumping on activity.
321
- //
322
- // `turn_started_at` is when the latest user-started turn began, which is NOT
323
- // `last_user_message_at`: a message typed while the agent is already working is
324
- // *steering* — it joins the running turn rather than starting one, and the phone's
325
- // elapsed timer must not restart on it. TURN_STARTED_AT_SQL groups those messages
326
- // by Conductor's `turn_id`, while retaining `queue_order` for older database rows.
327
- // `sent_at` is the dispatch time, so queued messages are excluded until they run.
328
- const rows = this.db.query(`SELECT s.id, s.status, s.title, s.model, s.permission_mode,
329
- s.claude_effort_level, s.codex_thinking_level, s.fast_mode, s.agent_type,
330
- s.context_used_percent, s.unread_count,
331
- s.created_at, s.updated_at, s.last_user_message_at,
332
- (SELECT CASE
333
- -- Mixed-TTL writes exist, so the shorter conversation tail wins.
334
- WHEN m.content GLOB '*"ephemeral_5m_input_tokens":[1-9]*' THEN 300000
335
- WHEN m.content GLOB '*"ephemeral_1h_input_tokens":[1-9]*' THEN 3600000
336
- END
337
- FROM session_messages m
338
- WHERE m.session_id = s.id
339
- AND s.agent_type IN ('claude', 'anthropic')
340
- AND (m.content GLOB '*"ephemeral_5m_input_tokens":[1-9]*'
341
- OR m.content GLOB '*"ephemeral_1h_input_tokens":[1-9]*')
342
- ORDER BY m.rowid DESC LIMIT 1) AS prompt_cache_ttl_ms,
343
- ${TURN_STARTED_AT_SQL} AS turn_started_at
344
- FROM sessions s
345
- WHERE s.workspace_id = ? AND COALESCE(s.is_hidden, 0) = 0
346
- ORDER BY s.created_at ASC`, [workspaceId]);
347
- const live = this.liveAgents();
348
- return rows.map(row => {
349
- const started = live.get(row.id);
350
- return toSessionRow(row, started === undefined ? [] : this.openBackgroundTasks(row.id, started));
351
- });
352
- }
353
- listClosedSessions(workspaceId) {
354
- return this.db.query(`SELECT id, title, model, agent_type, created_at, updated_at
355
- FROM sessions
356
- WHERE workspace_id = ? AND is_hidden = 1
357
- ORDER BY REPLACE(REPLACE(updated_at, 'T', ' '), 'Z', '') DESC, created_at DESC, id ASC`, [workspaceId]);
358
- }
359
- /** One delegated child, including its provider-specific open-task guard. */
360
- getSession(sessionId) {
361
- const rows = this.db.query(`SELECT s.id, s.status, s.title, s.model, s.permission_mode,
362
- s.claude_effort_level, s.codex_thinking_level, s.fast_mode, s.agent_type,
363
- s.context_used_percent, s.unread_count,
364
- s.created_at, s.updated_at, s.last_user_message_at,
365
- (SELECT MAX(m.sent_at) FROM session_messages m
366
- WHERE m.session_id = s.id AND m.queue_order IS NOT NULL AND m.sent_at IS NOT NULL) AS turn_started_at
367
- FROM sessions s
368
- WHERE s.id = ? AND COALESCE(s.is_hidden, 0) = 0
369
- LIMIT 1`, [sessionId]);
370
- const row = rows[0];
371
- if (!row)
372
- return null;
373
- const started = this.liveAgents().get(row.id);
374
- return toSessionRow(row, started === undefined ? [] : this.openBackgroundTasks(row.id, started));
375
- }
376
- /**
377
- * The background tasks a chat is still waiting on (src/background-tasks.ts).
378
- *
379
- * Only asked for a chat with a live agent process, which bounds the cost twice over:
380
- * a handful of chats at a time, and a prefix scan measured at 4–8ms on the largest
381
- * chats here (1,000–1,700 rows, 30–58 MB) — under the 2s sessions poll it rides on.
382
- */
383
- openBackgroundTasks(sessionId, processStartedAt) {
384
- const rows = this.db.query(`SELECT created_at, content FROM session_messages
385
- WHERE session_id = ? AND ${TASK_FRAME_FILTER}
386
- ORDER BY rowid ASC`, [sessionId]);
387
- return openBackgroundTasks(rows, processStartedAt);
388
- }
389
- /**
390
- * Every live chat's status, across all workspaces — what the notifier watches for
391
- * transitions. Unlike `listWorkspaces` this is not limited to the *active* session:
392
- * a background tab finishing its turn is exactly the thing you want told about.
393
- * `setting_up` workspaces are excluded; their chat isn't the user's turn yet.
394
- */
395
- listSessionStates() {
396
- const rows = this.db.query(
397
- // These two together are the notifier's record of whether a *person* had
398
- // anything to do with the turn that just ended. An agent that schedules its own
399
- // next turn (a `/loop`) writes no message at all, so both stay put while
400
- // `status` cycles working → idle on every lap. Both are needed: `turn_started_at`
401
- // stays at the first message when a person steers the running turn, while
402
- // `last_user_message_at` moves. See src/notify.ts.
403
- `SELECT s.id, s.status, s.title, s.workspace_id, s.last_user_message_at, s.updated_at,
404
- w.workspace_name, w.pr_title, w.branch, w.directory_name,
405
- r.name AS repo_name,
406
- (SELECT COUNT(*) FROM sessions t WHERE t.workspace_id = w.id AND COALESCE(t.is_hidden, 0) = 0) AS tab_count,
407
- ${TURN_STARTED_AT_SQL} AS turn_started_at
408
- FROM sessions s
409
- JOIN workspaces w ON w.id = s.workspace_id
410
- LEFT JOIN repos r ON r.id = w.repository_id
411
- WHERE w.state = 'ready' AND COALESCE(s.is_hidden, 0) = 0`);
412
- return rows.map(r => ({
413
- sessionId: r.id,
414
- workspaceId: r.workspace_id,
415
- status: r.status,
416
- updatedAt: r.updated_at,
417
- turnStartedAt: r.turn_started_at,
418
- lastUserMessageAt: r.last_user_message_at,
419
- workspaceTitle: workspaceTitle({ ...r, id: r.workspace_id }),
420
- repoName: r.repo_name,
421
- // A single-tab workspace's chat title is just the workspace again — only name it when it disambiguates.
422
- sessionTitle: r.tab_count > 1 ? r.title : null
423
- }));
424
- }
425
- /**
426
- * The newest structured AskUserQuestion input, when a harness emitted one. Conductor's
427
- * normal gstack path writes the same decision as prose, so this is deliberately a fallback
428
- * behind `lastAssistantText`, not a second primary transcript parser.
429
- */
430
- lastQuestionInput(sessionId) {
431
- const rows = this.db.query(`SELECT content FROM session_messages
432
- WHERE session_id = ? AND content LIKE '%AskUserQuestion%'
433
- ORDER BY rowid DESC LIMIT 40`, [sessionId]);
434
- for (const row of rows) {
435
- if (!row.content)
436
- continue;
437
- try {
438
- const parsed = JSON.parse(row.content);
439
- for (const block of parsed.message?.content ?? []) {
440
- if (block.type === 'tool_use' &&
441
- typeof block.name === 'string' &&
442
- block.name.toLowerCase().endsWith('askuserquestion'))
443
- return block.input ?? null;
444
- }
445
- }
446
- catch {
447
- // The LIKE is only a cheap prefilter; malformed history is skipped like parseMessage does.
448
- }
449
- }
450
- return null;
451
- }
452
- /**
453
- * The last thing the agent actually said in a chat — the body of a "finished"
454
- * notification. Reads the tail rather than the whole transcript, and runs the
455
- * same parser the phone renders with, so what lands on the lock screen is the
456
- * text that will be at the bottom of the chat when it's opened.
457
- */
458
- lastAssistantText(sessionId) {
459
- const rows = this.db.query(`SELECT rowid, id, role, content, full_message, created_at, sent_at, queue_order
460
- FROM session_messages
461
- WHERE session_id = ?
462
- ORDER BY rowid DESC
463
- LIMIT 20`, [sessionId]);
464
- // Rows come back newest-first; the last assistant text is the first one found.
465
- for (const row of rows) {
466
- const entries = parseMessage(row, null);
467
- for (let i = entries.length - 1; i >= 0; i--) {
468
- if (entries[i].role === 'assistant' && entries[i].text.trim())
469
- return entries[i].text.trim();
470
- }
471
- }
472
- return null;
473
- }
474
- /**
475
- * One image a tool returned, by the reference its transcript entry carries.
476
- *
477
- * The bytes sit in `session_messages.content` as base64, so this is the same read-only
478
- * handle as everything else — nothing is written and nothing is cached to disk. The
479
- * reference names a row and the image's position in it, and `toolImageAt` does the
480
- * walk, because the numbering has to be the one `parseMessage` used.
481
- */
482
- toolImage(reference) {
483
- const dot = reference.lastIndexOf('.');
484
- const rowid = Number(reference.slice(0, dot));
485
- const index = Number(reference.slice(dot + 1));
486
- if (dot < 0 || !Number.isInteger(rowid) || !Number.isInteger(index) || index < 0)
487
- return null;
488
- const rows = this.db.query('SELECT content FROM session_messages WHERE rowid = ? LIMIT 1', [rowid]);
489
- const content = rows[0]?.content;
490
- return content ? toolImageAt(content, index) : null;
491
- }
492
- /**
493
- * Which workspace a chat belongs to.
494
- *
495
- * Every other route resolves this by matching `active_session_id`, which only ever
496
- * finds the tab that is currently on screen. That is fine for a phone, where the
497
- * chat you are looking at is the chat you are sending to. It is wrong for anything
498
- * addressing a chat by id — a background tab has a workspace too, and `sessions`
499
- * has carried `workspace_id` all along.
500
- */
501
- sessionWorkspaceId(sessionId) {
502
- const rows = this.db.query(`SELECT workspace_id FROM sessions WHERE id = ? LIMIT 1`, [sessionId]);
503
- return rows[0]?.workspace_id ?? null;
504
- }
505
- /** Session → worktree path, cached: it's stable for a session's lifetime and polled every tick. */
506
- worktreeBySession = new Map();
507
- sessionWorktree(sessionId) {
508
- const cached = this.worktreeBySession.get(sessionId);
509
- if (cached !== undefined)
510
- return cached;
511
- const rows = this.db.query(`SELECT w.directory_name, w.branch, r.name AS repo_name, r.root_path AS repo_root
512
- FROM sessions s
513
- JOIN workspaces w ON w.id = s.workspace_id
514
- LEFT JOIN repos r ON r.id = w.repository_id
515
- WHERE s.id = ? LIMIT 1`, [sessionId]);
516
- const r = rows[0];
517
- const worktree = r
518
- ? resolveWorktree(this.workspacesRoot, r.repo_name, r.directory_name, r.branch, r.repo_root)
519
- : null;
520
- this.worktreeBySession.set(sessionId, worktree);
521
- return worktree;
522
- }
523
- /**
524
- * The outbox arrived in Conductor migration 123. Keep older desktop builds usable,
525
- * and re-probe occasionally so a running relay notices an in-place app migration.
526
- */
527
- hasMessageOutbox() {
528
- if (this.messageOutboxAvailable === true)
529
- return true;
530
- const now = Date.now();
531
- if (this.messageOutboxAvailable === false && now - this.messageOutboxCheckedAt < 60_000)
532
- return false;
533
- const rows = this.db.query("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'session_messages_outbox' LIMIT 1");
534
- this.messageOutboxAvailable = rows.length > 0;
535
- this.messageOutboxCheckedAt = now;
536
- return this.messageOutboxAvailable;
537
- }
538
- /** Current outbox contents. `queueOnly` is the snapshot the transcript renders. */
539
- outboxMessages(sessionId, queueOnly) {
540
- if (!this.hasMessageOutbox())
541
- return [];
542
- try {
543
- const rows = this.db.query(`SELECT message_id, delivery_payload, created_at
544
- FROM session_messages_outbox
545
- WHERE session_id = ?${queueOnly ? " AND mode = 'queue'" : ''}
546
- ORDER BY COALESCE(queue_order, 2147483647), created_at ASC`, [sessionId]);
547
- return rows.flatMap(row => {
548
- const entry = parseOutboxMessage(row);
549
- return entry ? [entry] : [];
550
- });
551
- }
552
- catch (error) {
553
- // A Conductor rollback can swap the DB beneath the relay. Treat only the
554
- // missing-table case as an older schema; every other read failure stays loud.
555
- if (error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)) {
556
- this.messageOutboxAvailable = false;
557
- this.messageOutboxCheckedAt = Date.now();
558
- return [];
559
- }
560
- throw error;
561
- }
562
- }
563
- /** Snapshot the durable transcript cursor and pending message ids in one SQLite read. */
564
- deliveryCursor(sessionId) {
565
- if (!this.hasMessageOutbox()) {
566
- const row = this.db.query('SELECT COALESCE(MAX(rowid), 0) AS rowid FROM session_messages WHERE session_id = ?', [sessionId])[0];
567
- return { rowid: row?.rowid ?? 0, outboxIds: new Set() };
568
- }
569
- try {
570
- const rows = this.db.query(`WITH transcript_cursor AS (
571
- SELECT COALESCE(MAX(rowid), 0) AS rowid
572
- FROM session_messages
573
- WHERE session_id = ?
574
- )
575
- SELECT transcript_cursor.rowid, NULL AS message_id
576
- FROM transcript_cursor
577
- UNION ALL
578
- SELECT transcript_cursor.rowid, outbox.message_id
579
- FROM transcript_cursor
580
- JOIN session_messages_outbox outbox ON outbox.session_id = ?`, [sessionId, sessionId]);
581
- return {
582
- rowid: rows[0]?.rowid ?? 0,
583
- outboxIds: new Set(rows.flatMap(row => (row.message_id ? [row.message_id] : [])))
584
- };
585
- }
586
- catch (error) {
587
- if (!(error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)))
588
- throw error;
589
- this.messageOutboxAvailable = false;
590
- this.messageOutboxCheckedAt = Date.now();
591
- return this.deliveryCursor(sessionId);
592
- }
593
- }
594
- /** Has this send created either a durable user row or a newly-owned outbox item? */
595
- promptDeliveredSince(sessionId, text, before) {
596
- return this.deliveryReceiptSince(sessionId, text, before) !== null;
597
- }
598
- deliveryMessageRows(where, params) {
599
- const select = (turn) => `SELECT rowid, id, content, ${turn} AS turn_id
600
- FROM session_messages
601
- WHERE session_id = ? AND role = 'user' AND ${where}
602
- ORDER BY rowid ASC`;
603
- try {
604
- return this.db.query(select('turn_id'), params);
605
- }
606
- catch (error) {
607
- // turn_id predates the current outbox protocol. Preserve the tagged receipt
608
- // on older Conductor builds, with a truthful null rather than inventing a turn.
609
- if (!(error instanceof Error && /no such column:\s*turn_id/i.test(error.message)))
610
- throw error;
611
- return this.db.query(select('NULL'), params);
612
- }
613
- }
614
- rawOutboxRows(sessionId, messageId) {
615
- if (!this.hasMessageOutbox())
616
- return [];
617
- try {
618
- return this.db.query(`SELECT message_id, delivery_payload
619
- FROM session_messages_outbox
620
- WHERE session_id = ?${messageId === undefined ? '' : ' AND message_id = ?'}
621
- ORDER BY COALESCE(queue_order, 2147483647), created_at ASC`, messageId === undefined ? [sessionId] : [sessionId, messageId]);
622
- }
623
- catch (error) {
624
- if (!(error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)))
625
- throw error;
626
- this.messageOutboxAvailable = false;
627
- this.messageOutboxCheckedAt = Date.now();
628
- return [];
629
- }
630
- }
631
- outboxText(payload) {
632
- try {
633
- const message = JSON.parse(payload ?? '').message;
634
- return typeof message === 'string' ? message : null;
635
- }
636
- catch {
637
- return null;
638
- }
639
- }
640
- /**
641
- * Find the first positive receipt created after a pre-send cursor. Matching uses
642
- * the private raw text inside this read-only method: parsed transcripts intentionally
643
- * redact Workflow capabilities, which would make two rotated envelopes look equal.
644
- * A durable row wins over a stale outbox snapshot if promotion straddles the reads.
645
- */
646
- deliveryReceiptSince(sessionId, text, before) {
647
- const target = text.trim();
648
- const durableReceipt = () => {
649
- const durable = this.deliveryMessageRows('rowid > ?', [sessionId, before.rowid]).find(row => row.content?.trim() === target && !before.outboxIds.has(row.id));
650
- return durable ? { kind: 'message', id: durable.id, rowid: durable.rowid, turnId: durable.turn_id ?? null } : null;
651
- };
652
- const durable = durableReceipt();
653
- if (durable)
654
- return durable;
655
- const accepted = this.rawOutboxRows(sessionId).find(row => this.outboxText(row.delivery_payload)?.trim() === target && !before.outboxIds.has(row.message_id));
656
- if (accepted)
657
- return { kind: 'outbox', id: accepted.message_id };
658
- // Promotion deletes the outbox row and inserts the durable row. If that
659
- // transaction lands after our first query but before the outbox query, one
660
- // final durable read closes the otherwise false-negative snapshot gap.
661
- return durableReceipt();
662
- }
663
- /**
664
- * Recover an orphaned Workflow send by its persisted non-secret correlation
665
- * marker. Raw message text stays inside this read-only boundary; callers receive
666
- * only the tagged receipt, and ordinary transcript surfaces still scrub the whole
667
- * private envelope that contains the marker.
668
- */
669
- deliveryReceiptContainingSince(sessionId, marker, before) {
670
- if (!marker)
671
- return null;
672
- const durableReceipt = () => {
673
- const durable = this.deliveryMessageRows('rowid > ?', [sessionId, before.rowid]).find(row => row.content?.includes(marker) && !before.outboxIds.has(row.id));
674
- return durable ? { kind: 'message', id: durable.id, rowid: durable.rowid, turnId: durable.turn_id ?? null } : null;
675
- };
676
- const durable = durableReceipt();
677
- if (durable)
678
- return durable;
679
- const accepted = this.rawOutboxRows(sessionId).find(row => this.outboxText(row.delivery_payload)?.includes(marker) && !before.outboxIds.has(row.message_id));
680
- return accepted ? { kind: 'outbox', id: accepted.message_id } : durableReceipt();
681
- }
682
- /** Follow one accepted id as Conductor promotes it from outbox to transcript. */
683
- deliveryReceiptForId(sessionId, messageId) {
684
- if (!this.hasMessageOutbox()) {
685
- const durable = this.deliveryMessageRows('id = ?', [sessionId, messageId])[0];
686
- return durable ? { kind: 'message', id: durable.id, rowid: durable.rowid, turnId: durable.turn_id ?? null } : null;
687
- }
688
- const select = (turn) => `
689
- SELECT kind, id, rowid, turn_id
690
- FROM (
691
- SELECT 'message' AS kind, id, rowid, ${turn} AS turn_id, 0 AS preference
692
- FROM session_messages
693
- WHERE session_id = ? AND role = 'user' AND id = ?
694
- UNION ALL
695
- SELECT 'outbox' AS kind, message_id AS id, NULL AS rowid, NULL AS turn_id, 1 AS preference
696
- FROM session_messages_outbox
697
- WHERE session_id = ? AND message_id = ?
698
- )
699
- ORDER BY preference
700
- LIMIT 1`;
701
- let row;
702
- try {
703
- row = this.db.query(select('turn_id'), [sessionId, messageId, sessionId, messageId])[0];
704
- }
705
- catch (error) {
706
- if (error instanceof Error && /no such column:\s*turn_id/i.test(error.message)) {
707
- row = this.db.query(select('NULL'), [sessionId, messageId, sessionId, messageId])[0];
708
- }
709
- else if (error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)) {
710
- this.messageOutboxAvailable = false;
711
- this.messageOutboxCheckedAt = Date.now();
712
- return this.deliveryReceiptForId(sessionId, messageId);
713
- }
714
- else {
715
- throw error;
716
- }
717
- }
718
- if (!row)
719
- return null;
720
- if (row.kind === 'outbox')
721
- return { kind: 'outbox', id: row.id };
722
- if (!Number.isSafeInteger(row.rowid))
723
- return null;
724
- return { kind: 'message', id: row.id, rowid: row.rowid, turnId: row.turn_id ?? null };
725
- }
726
- /** Incremental durable transcript fetch, without the independently replaced outbox snapshot. */
727
- durableMessages(sessionId, afterRowid, turnId) {
728
- const rows = this.db.query(`SELECT rowid, id, role, content, full_message, created_at, sent_at, queue_order
729
- FROM session_messages
730
- WHERE session_id = ? AND rowid > ?${turnId === undefined ? '' : ' AND turn_id = ?'}
731
- ORDER BY rowid ASC`, turnId === undefined ? [sessionId, afterRowid] : [sessionId, afterRowid, turnId]);
732
- const worktree = this.sessionWorktree(sessionId);
733
- const entries = [];
734
- let cursor = afterRowid;
735
- for (const row of rows) {
736
- cursor = row.rowid;
737
- entries.push(...parseMessage(row, worktree));
738
- }
739
- return { entries, cursor };
740
- }
741
- /** Incremental transcript rows plus the full current queue snapshot. */
742
- getMessages(sessionId, afterRowid = 0) {
743
- return { ...this.durableMessages(sessionId, afterRowid), queued: this.outboxMessages(sessionId, true) };
744
- }
745
- /**
746
- * The exact context total Conductor persisted, split into provider-neutral estimates.
747
- *
748
- * This is intentionally an on-demand read rather than another field on the two-second
749
- * session poll: sizing the fork choices needs the full durable transcript, which can be
750
- * tens of megabytes on a long-running chat. One query feeds both calculations so opening
751
- * the sheet never walks that history twice.
752
- */
753
- getContextBreakdown(sessionId) {
754
- const session = this.db.query(`SELECT context_token_count, context_used_percent
755
- FROM sessions
756
- WHERE id = ? AND COALESCE(is_hidden, 0) = 0
757
- LIMIT 1`, [sessionId])[0];
758
- if (!session)
759
- return null;
760
- const rows = this.db.query(`SELECT rowid, id, role, content, full_message, created_at, sent_at, queue_order
761
- FROM session_messages
762
- WHERE session_id = ?
763
- ORDER BY rowid ASC`, [sessionId]);
764
- const totalTokens = Math.max(0, Math.round(session.context_token_count ?? 0));
765
- const current = estimateContextCategories(rows, totalTokens);
766
- const worktree = this.sessionWorktree(sessionId);
767
- const entries = rows.flatMap(row => parseMessage(row, worktree));
768
- const forkTokens = {
769
- concise: estimateTextTokens(renderTranscript(entries, { thinking: false, tools: false }).text),
770
- reasoning: estimateTextTokens(renderTranscript(entries, { thinking: true, tools: false }).text),
771
- full: estimateTextTokens(renderTranscript(entries, { thinking: true, tools: true }).text)
772
- };
773
- return {
774
- totalTokens,
775
- usedPercent: typeof session.context_used_percent === 'number' && Number.isFinite(session.context_used_percent)
776
- ? session.context_used_percent
777
- : null,
778
- compacted: current.compacted,
779
- categories: current.categories,
780
- forkTokens
781
- };
782
- }
783
- /** Exact durable frames from one Conductor turn; used to keep managed child outcomes correlated. */
784
- getMessagesForTurn(sessionId, turnId, afterRowid = 0) {
785
- return this.durableMessages(sessionId, afterRowid, turnId);
786
- }
787
- }