conductor-remote 1.117.0 → 1.118.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 (200) hide show
  1. package/README.md +10 -8
  2. package/dist/assets/{PierrePatch-D3_YBIAr.js → PierrePatch-Dh-08CLI.js} +1 -1
  3. package/dist/assets/index-BRzsSW8g.css +1 -0
  4. package/dist/assets/index-BpY3Jhxk.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} +43 -18
  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 +10 -10
  132. package/dist-node/src/{transcript.js → transcript/parser.js} +4 -4
  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-ByTwVInL.css +0 -1
  169. package/dist/assets/index-LAm9X7wv.js +0 -65
  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
@@ -0,0 +1,362 @@
1
+ import { estimateContextCategories, estimateTextTokens } from "../transcript/context-breakdown.js";
2
+ import { parseMessage, parseOutboxMessage, renderTranscript, toolImageAt } from "../transcript/parser.js";
3
+ import { resolveWorktree } from "./worktrees.js";
4
+ export class MessageReads {
5
+ db;
6
+ workspacesRoot;
7
+ constructor(db, workspacesRoot) {
8
+ this.db = db;
9
+ this.workspacesRoot = workspacesRoot;
10
+ }
11
+ messageOutboxAvailable = null;
12
+ messageOutboxCheckedAt = 0;
13
+ /** Session → worktree path, cached: stable for a session's lifetime and polled every tick. */
14
+ worktreeBySession = new Map();
15
+ /**
16
+ * The newest structured AskUserQuestion input, when a harness emitted one. Conductor's
17
+ * normal gstack path writes the same decision as prose, so this is deliberately a fallback
18
+ * behind `lastAssistantText`, not a second primary transcript parser.
19
+ */
20
+ lastQuestionInput(sessionId) {
21
+ const rows = this.db.query(`SELECT content FROM session_messages
22
+ WHERE session_id = ? AND content LIKE '%AskUserQuestion%'
23
+ ORDER BY rowid DESC LIMIT 40`, [sessionId]);
24
+ for (const row of rows) {
25
+ if (!row.content)
26
+ continue;
27
+ try {
28
+ const parsed = JSON.parse(row.content);
29
+ for (const block of parsed.message?.content ?? []) {
30
+ if (block.type === 'tool_use' &&
31
+ typeof block.name === 'string' &&
32
+ block.name.toLowerCase().endsWith('askuserquestion'))
33
+ return block.input ?? null;
34
+ }
35
+ }
36
+ catch {
37
+ // The LIKE is only a cheap prefilter; malformed history is skipped like parseMessage does.
38
+ }
39
+ }
40
+ return null;
41
+ }
42
+ /**
43
+ * The last thing the agent actually said in a chat — the body of a "finished"
44
+ * notification. Reads the tail rather than the whole transcript, and runs the
45
+ * same parser the phone renders with, so what lands on the lock screen is the
46
+ * text that will be at the bottom of the chat when it's opened.
47
+ */
48
+ lastAssistantText(sessionId) {
49
+ const rows = this.db.query(`SELECT rowid, id, role, content, full_message, created_at, sent_at, queue_order
50
+ FROM session_messages
51
+ WHERE session_id = ?
52
+ ORDER BY rowid DESC
53
+ LIMIT 20`, [sessionId]);
54
+ // Rows come back newest-first; the last assistant text is the first one found.
55
+ for (const row of rows) {
56
+ const entries = parseMessage(row, null);
57
+ for (let i = entries.length - 1; i >= 0; i--) {
58
+ if (entries[i].role === 'assistant' && entries[i].text.trim())
59
+ return entries[i].text.trim();
60
+ }
61
+ }
62
+ return null;
63
+ }
64
+ /**
65
+ * One image a tool returned, by the reference its transcript entry carries.
66
+ *
67
+ * The bytes sit in `session_messages.content` as base64, so this is the same read-only
68
+ * handle as everything else — nothing is written and nothing is cached to disk. The
69
+ * reference names a row and the image's position in it, and `toolImageAt` does the
70
+ * walk, because the numbering has to be the one `parseMessage` used.
71
+ */
72
+ toolImage(reference) {
73
+ const dot = reference.lastIndexOf('.');
74
+ const rowid = Number(reference.slice(0, dot));
75
+ const index = Number(reference.slice(dot + 1));
76
+ if (dot < 0 || !Number.isInteger(rowid) || !Number.isInteger(index) || index < 0)
77
+ return null;
78
+ const rows = this.db.query('SELECT content FROM session_messages WHERE rowid = ? LIMIT 1', [rowid]);
79
+ const content = rows[0]?.content;
80
+ return content ? toolImageAt(content, index) : null;
81
+ }
82
+ sessionWorktree(sessionId) {
83
+ const cached = this.worktreeBySession.get(sessionId);
84
+ if (cached !== undefined)
85
+ return cached;
86
+ const rows = this.db.query(`SELECT w.directory_name, w.branch, r.name AS repo_name, r.root_path AS repo_root
87
+ FROM sessions s
88
+ JOIN workspaces w ON w.id = s.workspace_id
89
+ LEFT JOIN repos r ON r.id = w.repository_id
90
+ WHERE s.id = ? LIMIT 1`, [sessionId]);
91
+ const r = rows[0];
92
+ const worktree = r
93
+ ? resolveWorktree(this.workspacesRoot, r.repo_name, r.directory_name, r.branch, r.repo_root)
94
+ : null;
95
+ this.worktreeBySession.set(sessionId, worktree);
96
+ return worktree;
97
+ }
98
+ /**
99
+ * The outbox arrived in Conductor migration 123. Keep older desktop builds usable,
100
+ * and re-probe occasionally so a running relay notices an in-place app migration.
101
+ */
102
+ hasMessageOutbox() {
103
+ if (this.messageOutboxAvailable === true)
104
+ return true;
105
+ const now = Date.now();
106
+ if (this.messageOutboxAvailable === false && now - this.messageOutboxCheckedAt < 60_000)
107
+ return false;
108
+ const rows = this.db.query("SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = 'session_messages_outbox' LIMIT 1");
109
+ this.messageOutboxAvailable = rows.length > 0;
110
+ this.messageOutboxCheckedAt = now;
111
+ return this.messageOutboxAvailable;
112
+ }
113
+ /** Current outbox contents. `queueOnly` is the snapshot the transcript renders. */
114
+ outboxMessages(sessionId, queueOnly) {
115
+ if (!this.hasMessageOutbox())
116
+ return [];
117
+ try {
118
+ const rows = this.db.query(`SELECT message_id, delivery_payload, created_at
119
+ FROM session_messages_outbox
120
+ WHERE session_id = ?${queueOnly ? " AND mode = 'queue'" : ''}
121
+ ORDER BY COALESCE(queue_order, 2147483647), created_at ASC`, [sessionId]);
122
+ return rows.flatMap(row => {
123
+ const entry = parseOutboxMessage(row);
124
+ return entry ? [entry] : [];
125
+ });
126
+ }
127
+ catch (error) {
128
+ // A Conductor rollback can swap the DB beneath the relay. Treat only the
129
+ // missing-table case as an older schema; every other read failure stays loud.
130
+ if (error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)) {
131
+ this.messageOutboxAvailable = false;
132
+ this.messageOutboxCheckedAt = Date.now();
133
+ return [];
134
+ }
135
+ throw error;
136
+ }
137
+ }
138
+ /** Snapshot the durable transcript cursor and pending message ids in one SQLite read. */
139
+ deliveryCursor(sessionId) {
140
+ if (!this.hasMessageOutbox()) {
141
+ const row = this.db.query('SELECT COALESCE(MAX(rowid), 0) AS rowid FROM session_messages WHERE session_id = ?', [sessionId])[0];
142
+ return { rowid: row?.rowid ?? 0, outboxIds: new Set() };
143
+ }
144
+ try {
145
+ const rows = this.db.query(`WITH transcript_cursor AS (
146
+ SELECT COALESCE(MAX(rowid), 0) AS rowid
147
+ FROM session_messages
148
+ WHERE session_id = ?
149
+ )
150
+ SELECT transcript_cursor.rowid, NULL AS message_id
151
+ FROM transcript_cursor
152
+ UNION ALL
153
+ SELECT transcript_cursor.rowid, outbox.message_id
154
+ FROM transcript_cursor
155
+ JOIN session_messages_outbox outbox ON outbox.session_id = ?`, [sessionId, sessionId]);
156
+ return {
157
+ rowid: rows[0]?.rowid ?? 0,
158
+ outboxIds: new Set(rows.flatMap(row => (row.message_id ? [row.message_id] : [])))
159
+ };
160
+ }
161
+ catch (error) {
162
+ if (!(error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)))
163
+ throw error;
164
+ this.messageOutboxAvailable = false;
165
+ this.messageOutboxCheckedAt = Date.now();
166
+ return this.deliveryCursor(sessionId);
167
+ }
168
+ }
169
+ /** Has this send created either a durable user row or a newly-owned outbox item? */
170
+ promptDeliveredSince(sessionId, text, before) {
171
+ return this.deliveryReceiptSince(sessionId, text, before) !== null;
172
+ }
173
+ deliveryMessageRows(where, params) {
174
+ const select = (turn) => `SELECT rowid, id, content, ${turn} AS turn_id
175
+ FROM session_messages
176
+ WHERE session_id = ? AND role = 'user' AND ${where}
177
+ ORDER BY rowid ASC`;
178
+ try {
179
+ return this.db.query(select('turn_id'), params);
180
+ }
181
+ catch (error) {
182
+ // turn_id predates the current outbox protocol. Preserve the tagged receipt
183
+ // on older Conductor builds, with a truthful null rather than inventing a turn.
184
+ if (!(error instanceof Error && /no such column:\s*turn_id/i.test(error.message)))
185
+ throw error;
186
+ return this.db.query(select('NULL'), params);
187
+ }
188
+ }
189
+ rawOutboxRows(sessionId, messageId) {
190
+ if (!this.hasMessageOutbox())
191
+ return [];
192
+ try {
193
+ return this.db.query(`SELECT message_id, delivery_payload
194
+ FROM session_messages_outbox
195
+ WHERE session_id = ?${messageId === undefined ? '' : ' AND message_id = ?'}
196
+ ORDER BY COALESCE(queue_order, 2147483647), created_at ASC`, messageId === undefined ? [sessionId] : [sessionId, messageId]);
197
+ }
198
+ catch (error) {
199
+ if (!(error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)))
200
+ throw error;
201
+ this.messageOutboxAvailable = false;
202
+ this.messageOutboxCheckedAt = Date.now();
203
+ return [];
204
+ }
205
+ }
206
+ outboxText(payload) {
207
+ try {
208
+ const message = JSON.parse(payload ?? '').message;
209
+ return typeof message === 'string' ? message : null;
210
+ }
211
+ catch {
212
+ return null;
213
+ }
214
+ }
215
+ /**
216
+ * Find the first positive receipt created after a pre-send cursor. Matching uses
217
+ * the private raw text inside this read-only method: parsed transcripts intentionally
218
+ * redact Workflow capabilities, which would make two rotated envelopes look equal.
219
+ * A durable row wins over a stale outbox snapshot if promotion straddles the reads.
220
+ */
221
+ deliveryReceiptSince(sessionId, text, before) {
222
+ const target = text.trim();
223
+ const durableReceipt = () => {
224
+ const durable = this.deliveryMessageRows('rowid > ?', [sessionId, before.rowid]).find(row => row.content?.trim() === target && !before.outboxIds.has(row.id));
225
+ return durable ? { kind: 'message', id: durable.id, rowid: durable.rowid, turnId: durable.turn_id ?? null } : null;
226
+ };
227
+ const durable = durableReceipt();
228
+ if (durable)
229
+ return durable;
230
+ const accepted = this.rawOutboxRows(sessionId).find(row => this.outboxText(row.delivery_payload)?.trim() === target && !before.outboxIds.has(row.message_id));
231
+ if (accepted)
232
+ return { kind: 'outbox', id: accepted.message_id };
233
+ // Promotion deletes the outbox row and inserts the durable row. If that
234
+ // transaction lands after our first query but before the outbox query, one
235
+ // final durable read closes the otherwise false-negative snapshot gap.
236
+ return durableReceipt();
237
+ }
238
+ /**
239
+ * Recover an orphaned Workflow send by its persisted non-secret correlation
240
+ * marker. Raw message text stays inside this read-only boundary; callers receive
241
+ * only the tagged receipt, and ordinary transcript surfaces still scrub the whole
242
+ * private envelope that contains the marker.
243
+ */
244
+ deliveryReceiptContainingSince(sessionId, marker, before) {
245
+ if (!marker)
246
+ return null;
247
+ const durableReceipt = () => {
248
+ const durable = this.deliveryMessageRows('rowid > ?', [sessionId, before.rowid]).find(row => row.content?.includes(marker) && !before.outboxIds.has(row.id));
249
+ return durable ? { kind: 'message', id: durable.id, rowid: durable.rowid, turnId: durable.turn_id ?? null } : null;
250
+ };
251
+ const durable = durableReceipt();
252
+ if (durable)
253
+ return durable;
254
+ const accepted = this.rawOutboxRows(sessionId).find(row => this.outboxText(row.delivery_payload)?.includes(marker) && !before.outboxIds.has(row.message_id));
255
+ return accepted ? { kind: 'outbox', id: accepted.message_id } : durableReceipt();
256
+ }
257
+ /** Follow one accepted id as Conductor promotes it from outbox to transcript. */
258
+ deliveryReceiptForId(sessionId, messageId) {
259
+ if (!this.hasMessageOutbox()) {
260
+ const durable = this.deliveryMessageRows('id = ?', [sessionId, messageId])[0];
261
+ return durable ? { kind: 'message', id: durable.id, rowid: durable.rowid, turnId: durable.turn_id ?? null } : null;
262
+ }
263
+ const select = (turn) => `
264
+ SELECT kind, id, rowid, turn_id
265
+ FROM (
266
+ SELECT 'message' AS kind, id, rowid, ${turn} AS turn_id, 0 AS preference
267
+ FROM session_messages
268
+ WHERE session_id = ? AND role = 'user' AND id = ?
269
+ UNION ALL
270
+ SELECT 'outbox' AS kind, message_id AS id, NULL AS rowid, NULL AS turn_id, 1 AS preference
271
+ FROM session_messages_outbox
272
+ WHERE session_id = ? AND message_id = ?
273
+ )
274
+ ORDER BY preference
275
+ LIMIT 1`;
276
+ let row;
277
+ try {
278
+ row = this.db.query(select('turn_id'), [sessionId, messageId, sessionId, messageId])[0];
279
+ }
280
+ catch (error) {
281
+ if (error instanceof Error && /no such column:\s*turn_id/i.test(error.message)) {
282
+ row = this.db.query(select('NULL'), [sessionId, messageId, sessionId, messageId])[0];
283
+ }
284
+ else if (error instanceof Error && /no such table:\s*session_messages_outbox/i.test(error.message)) {
285
+ this.messageOutboxAvailable = false;
286
+ this.messageOutboxCheckedAt = Date.now();
287
+ return this.deliveryReceiptForId(sessionId, messageId);
288
+ }
289
+ else {
290
+ throw error;
291
+ }
292
+ }
293
+ if (!row)
294
+ return null;
295
+ if (row.kind === 'outbox')
296
+ return { kind: 'outbox', id: row.id };
297
+ if (!Number.isSafeInteger(row.rowid))
298
+ return null;
299
+ return { kind: 'message', id: row.id, rowid: row.rowid, turnId: row.turn_id ?? null };
300
+ }
301
+ /** Incremental durable transcript fetch, without the independently replaced outbox snapshot. */
302
+ durableMessages(sessionId, afterRowid, turnId) {
303
+ const rows = this.db.query(`SELECT rowid, id, role, content, full_message, created_at, sent_at, queue_order
304
+ FROM session_messages
305
+ WHERE session_id = ? AND rowid > ?${turnId === undefined ? '' : ' AND turn_id = ?'}
306
+ ORDER BY rowid ASC`, turnId === undefined ? [sessionId, afterRowid] : [sessionId, afterRowid, turnId]);
307
+ const worktree = this.sessionWorktree(sessionId);
308
+ const entries = [];
309
+ let cursor = afterRowid;
310
+ for (const row of rows) {
311
+ cursor = row.rowid;
312
+ entries.push(...parseMessage(row, worktree));
313
+ }
314
+ return { entries, cursor };
315
+ }
316
+ /** Incremental transcript rows plus the full current queue snapshot. */
317
+ getMessages(sessionId, afterRowid = 0) {
318
+ return { ...this.durableMessages(sessionId, afterRowid), queued: this.outboxMessages(sessionId, true) };
319
+ }
320
+ /**
321
+ * The exact context total Conductor persisted, split into provider-neutral estimates.
322
+ *
323
+ * This is intentionally an on-demand read rather than another field on the two-second
324
+ * session poll: sizing the fork choices needs the full durable transcript, which can be
325
+ * tens of megabytes on a long-running chat. One query feeds both calculations so opening
326
+ * the sheet never walks that history twice.
327
+ */
328
+ getContextBreakdown(sessionId) {
329
+ const session = this.db.query(`SELECT context_token_count, context_used_percent
330
+ FROM sessions
331
+ WHERE id = ? AND COALESCE(is_hidden, 0) = 0
332
+ LIMIT 1`, [sessionId])[0];
333
+ if (!session)
334
+ return null;
335
+ const rows = this.db.query(`SELECT rowid, id, role, content, full_message, created_at, sent_at, queue_order
336
+ FROM session_messages
337
+ WHERE session_id = ?
338
+ ORDER BY rowid ASC`, [sessionId]);
339
+ const totalTokens = Math.max(0, Math.round(session.context_token_count ?? 0));
340
+ const current = estimateContextCategories(rows, totalTokens);
341
+ const worktree = this.sessionWorktree(sessionId);
342
+ const entries = rows.flatMap(row => parseMessage(row, worktree));
343
+ const forkTokens = {
344
+ concise: estimateTextTokens(renderTranscript(entries, { thinking: false, tools: false }).text),
345
+ reasoning: estimateTextTokens(renderTranscript(entries, { thinking: true, tools: false }).text),
346
+ full: estimateTextTokens(renderTranscript(entries, { thinking: true, tools: true }).text)
347
+ };
348
+ return {
349
+ totalTokens,
350
+ usedPercent: typeof session.context_used_percent === 'number' && Number.isFinite(session.context_used_percent)
351
+ ? session.context_used_percent
352
+ : null,
353
+ compacted: current.compacted,
354
+ categories: current.categories,
355
+ forkTokens
356
+ };
357
+ }
358
+ /** Exact durable frames from one Conductor turn; used to keep managed child outcomes correlated. */
359
+ getMessagesForTurn(sessionId, turnId, afterRowid = 0) {
360
+ return this.durableMessages(sessionId, afterRowid, turnId);
361
+ }
362
+ }
@@ -0,0 +1,87 @@
1
+ import { agentProcessStarts } from "./background-tasks.js";
2
+ import { MessageReads } from "./messages.js";
3
+ import { SessionReads } from "./sessions.js";
4
+ import { WorkspacesReads } from "./workspaces.js";
5
+ /** One read-only Conductor connection shared by the three focused query repositories. */
6
+ export class Reads {
7
+ workspaces;
8
+ sessions;
9
+ messages;
10
+ constructor(db, workspacesRoot, liveAgents = agentProcessStarts) {
11
+ this.workspaces = new WorkspacesReads(db, workspacesRoot);
12
+ this.sessions = new SessionReads(db, liveAgents);
13
+ this.messages = new MessageReads(db, workspacesRoot);
14
+ }
15
+ listWorkspaces() {
16
+ return this.workspaces.listWorkspaces();
17
+ }
18
+ getWorkspace(id) {
19
+ return this.workspaces.getWorkspace(id);
20
+ }
21
+ listRepos() {
22
+ return this.workspaces.listRepos();
23
+ }
24
+ searchTargets(sessionIds) {
25
+ return this.workspaces.searchTargets(sessionIds);
26
+ }
27
+ searchSessionIds(repos, includeArchived) {
28
+ return this.workspaces.searchSessionIds(repos, includeArchived);
29
+ }
30
+ findWorkspacesByName(tokens, limit = 20, repos, includeArchived = true) {
31
+ return this.workspaces.findWorkspacesByName(tokens, limit, repos, includeArchived);
32
+ }
33
+ getAnyWorkspace(id) {
34
+ return this.workspaces.getAnyWorkspace(id);
35
+ }
36
+ resolveRepoIcon(repoName) {
37
+ return this.workspaces.resolveRepoIcon(repoName);
38
+ }
39
+ sessionWorkspaceId(sessionId) {
40
+ return this.workspaces.sessionWorkspaceId(sessionId);
41
+ }
42
+ listSessions(workspaceId) {
43
+ return this.sessions.listSessions(workspaceId);
44
+ }
45
+ listClosedSessions(workspaceId) {
46
+ return this.sessions.listClosedSessions(workspaceId);
47
+ }
48
+ getSession(sessionId) {
49
+ return this.sessions.getSession(sessionId);
50
+ }
51
+ listSessionStates() {
52
+ return this.sessions.listSessionStates();
53
+ }
54
+ lastQuestionInput(sessionId) {
55
+ return this.messages.lastQuestionInput(sessionId);
56
+ }
57
+ lastAssistantText(sessionId) {
58
+ return this.messages.lastAssistantText(sessionId);
59
+ }
60
+ toolImage(reference) {
61
+ return this.messages.toolImage(reference);
62
+ }
63
+ deliveryCursor(sessionId) {
64
+ return this.messages.deliveryCursor(sessionId);
65
+ }
66
+ promptDeliveredSince(sessionId, text, before) {
67
+ return this.messages.promptDeliveredSince(sessionId, text, before);
68
+ }
69
+ deliveryReceiptSince(sessionId, text, before) {
70
+ return this.messages.deliveryReceiptSince(sessionId, text, before);
71
+ }
72
+ deliveryReceiptContainingSince(sessionId, marker, before) {
73
+ return this.messages.deliveryReceiptContainingSince(sessionId, marker, before);
74
+ }
75
+ deliveryReceiptForId(sessionId, messageId) {
76
+ return this.messages.deliveryReceiptForId(sessionId, messageId);
77
+ }
78
+ getMessages(sessionId, afterRowid = 0) {
79
+ return this.messages.getMessages(sessionId, afterRowid);
80
+ }
81
+ getContextBreakdown(sessionId) {
82
+ return this.messages.getContextBreakdown(sessionId);
83
+ }
84
+ getMessagesForTurn(sessionId, turnId, afterRowid = 0) {
85
+ return this.messages.getMessagesForTurn(sessionId, turnId, afterRowid);
86
+ }
87
+ }
@@ -0,0 +1,165 @@
1
+ import { workspaceTitle } from "../shared.js";
2
+ import { openBackgroundTasks, TASK_FRAME_FILTER } from "./background-tasks.js";
3
+ /** Keep the stable wire field in sync with whichever provider owns the chat. */
4
+ function toSessionRow(row, background_tasks) {
5
+ const { codex_thinking_level, ...session } = row;
6
+ const effort = row.agent_type === 'codex' ? codex_thinking_level : row.claude_effort_level;
7
+ return {
8
+ ...session,
9
+ // Codex calls its top level `ultra`; the relay's long-lived wire value is
10
+ // `ultracode`, which is also Claude's stored spelling and the phone's key.
11
+ claude_effort_level: effort === 'ultra' ? 'ultracode' : effort,
12
+ background_tasks
13
+ };
14
+ }
15
+ /**
16
+ * The dispatch time of the latest turn a person started.
17
+ *
18
+ * Current Conductor writes the same `turn_id` on a turn's first prompt and every
19
+ * steering message added while it runs, but stopped populating `queue_order` on
20
+ * 2026-08-31. Start with the latest user row that was actually dispatched (so a prompt
21
+ * queued behind the current answer cannot take over), then take the first dispatch in
22
+ * that turn (so steering cannot restart the clock). A self-scheduled `/loop` lap writes
23
+ * no user row, leaving this value unchanged for the notification deduper.
24
+ *
25
+ * The second arm preserves workspaces written by older Conductor builds, where
26
+ * `queue_order` identified turn heads and `turn_id` may be absent.
27
+ * `MIN(CASE …)` is deliberate: a plain `MIN(sent_at)` makes SQLite favour the
28
+ * sent-time index and walk every older turn, while the expression lets the existing
29
+ * `(session_id, role, turn_id, …)` index jump straight to this turn's few user rows.
30
+ */
31
+ const TURN_STARTED_AT_SQL = `COALESCE(
32
+ (SELECT MIN(CASE WHEN head.sent_at IS NOT NULL THEN head.sent_at END)
33
+ FROM session_messages head
34
+ WHERE head.session_id = s.id
35
+ AND head.role = 'user'
36
+ AND head.turn_id = (
37
+ SELECT latest.turn_id
38
+ FROM session_messages latest
39
+ WHERE latest.session_id = s.id
40
+ AND latest.role = 'user'
41
+ AND latest.turn_id IS NOT NULL
42
+ AND latest.sent_at IS NOT NULL
43
+ ORDER BY latest.sent_at DESC, latest.rowid DESC
44
+ LIMIT 1
45
+ )),
46
+ (SELECT MAX(legacy.sent_at)
47
+ FROM session_messages legacy
48
+ WHERE legacy.session_id = s.id
49
+ AND legacy.queue_order IS NOT NULL
50
+ AND legacy.sent_at IS NOT NULL)
51
+ )`;
52
+ export class SessionReads {
53
+ db;
54
+ liveAgents;
55
+ constructor(db, liveAgents) {
56
+ this.db = db;
57
+ this.liveAgents = liveAgents;
58
+ }
59
+ listSessions(workspaceId) {
60
+ // created_at ASC keeps tab order stable (matches the desktop app) instead of jumping on activity.
61
+ //
62
+ // `turn_started_at` is when the latest user-started turn began, which is NOT
63
+ // `last_user_message_at`: a message typed while the agent is already working is
64
+ // *steering* — it joins the running turn rather than starting one, and the phone's
65
+ // elapsed timer must not restart on it. TURN_STARTED_AT_SQL groups those messages
66
+ // by Conductor's `turn_id`, while retaining `queue_order` for older database rows.
67
+ // `sent_at` is the dispatch time, so queued messages are excluded until they run.
68
+ const rows = this.db.query(`SELECT s.id, s.status, s.title, s.model, s.permission_mode,
69
+ s.claude_effort_level, s.codex_thinking_level, s.fast_mode, s.agent_type,
70
+ s.context_used_percent, s.unread_count,
71
+ s.created_at, s.updated_at, s.last_user_message_at,
72
+ (SELECT CASE
73
+ -- Mixed-TTL writes exist, so the shorter conversation tail wins.
74
+ WHEN m.content GLOB '*"ephemeral_5m_input_tokens":[1-9]*' THEN 300000
75
+ WHEN m.content GLOB '*"ephemeral_1h_input_tokens":[1-9]*' THEN 3600000
76
+ END
77
+ FROM session_messages m
78
+ WHERE m.session_id = s.id
79
+ AND s.agent_type IN ('claude', 'anthropic')
80
+ AND (m.content GLOB '*"ephemeral_5m_input_tokens":[1-9]*'
81
+ OR m.content GLOB '*"ephemeral_1h_input_tokens":[1-9]*')
82
+ ORDER BY m.rowid DESC LIMIT 1) AS prompt_cache_ttl_ms,
83
+ ${TURN_STARTED_AT_SQL} AS turn_started_at
84
+ FROM sessions s
85
+ WHERE s.workspace_id = ? AND COALESCE(s.is_hidden, 0) = 0
86
+ ORDER BY s.created_at ASC`, [workspaceId]);
87
+ const live = this.liveAgents();
88
+ return rows.map(row => {
89
+ const started = live.get(row.id);
90
+ return toSessionRow(row, started === undefined ? [] : this.openBackgroundTasks(row.id, started));
91
+ });
92
+ }
93
+ listClosedSessions(workspaceId) {
94
+ return this.db.query(`SELECT id, title, model, agent_type, created_at, updated_at
95
+ FROM sessions
96
+ WHERE workspace_id = ? AND is_hidden = 1
97
+ ORDER BY REPLACE(REPLACE(updated_at, 'T', ' '), 'Z', '') DESC, created_at DESC, id ASC`, [workspaceId]);
98
+ }
99
+ /** One delegated child, including its provider-specific open-task guard. */
100
+ getSession(sessionId) {
101
+ const rows = this.db.query(`SELECT s.id, s.status, s.title, s.model, s.permission_mode,
102
+ s.claude_effort_level, s.codex_thinking_level, s.fast_mode, s.agent_type,
103
+ s.context_used_percent, s.unread_count,
104
+ s.created_at, s.updated_at, s.last_user_message_at,
105
+ (SELECT MAX(m.sent_at) FROM session_messages m
106
+ WHERE m.session_id = s.id AND m.queue_order IS NOT NULL AND m.sent_at IS NOT NULL) AS turn_started_at
107
+ FROM sessions s
108
+ WHERE s.id = ? AND COALESCE(s.is_hidden, 0) = 0
109
+ LIMIT 1`, [sessionId]);
110
+ const row = rows[0];
111
+ if (!row)
112
+ return null;
113
+ const started = this.liveAgents().get(row.id);
114
+ return toSessionRow(row, started === undefined ? [] : this.openBackgroundTasks(row.id, started));
115
+ }
116
+ /**
117
+ * The background tasks a chat is still waiting on (src/reads/background-tasks.ts).
118
+ *
119
+ * Only asked for a chat with a live agent process, which bounds the cost twice over:
120
+ * a handful of chats at a time, and a prefix scan measured at 4–8ms on the largest
121
+ * chats here (1,000–1,700 rows, 30–58 MB) — under the 2s sessions poll it rides on.
122
+ */
123
+ openBackgroundTasks(sessionId, processStartedAt) {
124
+ const rows = this.db.query(`SELECT created_at, content FROM session_messages
125
+ WHERE session_id = ? AND ${TASK_FRAME_FILTER}
126
+ ORDER BY rowid ASC`, [sessionId]);
127
+ return openBackgroundTasks(rows, processStartedAt);
128
+ }
129
+ /**
130
+ * Every live chat's status, across all workspaces — what the notifier watches for
131
+ * transitions. Unlike `listWorkspaces` this is not limited to the *active* session:
132
+ * a background tab finishing its turn is exactly the thing you want told about.
133
+ * `setting_up` workspaces are excluded; their chat isn't the user's turn yet.
134
+ */
135
+ listSessionStates() {
136
+ const rows = this.db.query(
137
+ // These two together are the notifier's record of whether a *person* had
138
+ // anything to do with the turn that just ended. An agent that schedules its own
139
+ // next turn (a `/loop`) writes no message at all, so both stay put while
140
+ // `status` cycles working → idle on every lap. Both are needed: `turn_started_at`
141
+ // stays at the first message when a person steers the running turn, while
142
+ // `last_user_message_at` moves. See src/notifications/notify.ts.
143
+ `SELECT s.id, s.status, s.title, s.workspace_id, s.last_user_message_at, s.updated_at,
144
+ w.workspace_name, w.pr_title, w.branch, w.directory_name,
145
+ r.name AS repo_name,
146
+ (SELECT COUNT(*) FROM sessions t WHERE t.workspace_id = w.id AND COALESCE(t.is_hidden, 0) = 0) AS tab_count,
147
+ ${TURN_STARTED_AT_SQL} AS turn_started_at
148
+ FROM sessions s
149
+ JOIN workspaces w ON w.id = s.workspace_id
150
+ LEFT JOIN repos r ON r.id = w.repository_id
151
+ WHERE w.state = 'ready' AND COALESCE(s.is_hidden, 0) = 0`);
152
+ return rows.map(r => ({
153
+ sessionId: r.id,
154
+ workspaceId: r.workspace_id,
155
+ status: r.status,
156
+ updatedAt: r.updated_at,
157
+ turnStartedAt: r.turn_started_at,
158
+ lastUserMessageAt: r.last_user_message_at,
159
+ workspaceTitle: workspaceTitle({ ...r, id: r.workspace_id }),
160
+ repoName: r.repo_name,
161
+ // A single-tab workspace's chat title is just the workspace again — only name it when it disambiguates.
162
+ sessionTitle: r.tab_count > 1 ? r.title : null
163
+ }));
164
+ }
165
+ }
@@ -0,0 +1 @@
1
+ export {};