@jini-ai/chat 0.7.3-next.2 → 0.7.3-next.4

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 (216) hide show
  1. package/README.md +49 -0
  2. package/dist/core/accepted-input.d.ts +1 -1
  3. package/dist/core/ag-ui/event-projection.d.ts +14 -69
  4. package/dist/core/ag-ui/event-projection.js +58 -133
  5. package/dist/core/ag-ui/event-reduction.d.ts +12 -2
  6. package/dist/core/ag-ui/event-reduction.js +35 -10
  7. package/dist/core/ag-ui/resume.d.ts +110 -0
  8. package/dist/core/ag-ui/resume.js +200 -0
  9. package/dist/core/ag-ui/run-input.d.ts +23 -0
  10. package/dist/core/ag-ui/run-input.js +45 -0
  11. package/dist/core/ag-ui/server.d.ts +69 -0
  12. package/dist/core/ag-ui/server.js +71 -0
  13. package/dist/core/agent-plugin-chat-state.js +13 -11
  14. package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
  15. package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
  16. package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
  17. package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
  18. package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
  19. package/dist/core/assistant-client/ag-ui-transport.js +310 -80
  20. package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
  21. package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
  22. package/dist/core/assistant-client/durable-run-subscription.js +141 -130
  23. package/dist/core/assistant-client/entry.d.ts +2 -1
  24. package/dist/core/assistant-client/entry.js +1 -0
  25. package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
  26. package/dist/core/assistant-client/transport-prompt.js +180 -0
  27. package/dist/core/assistant-client/transport-run.d.ts +49 -0
  28. package/dist/core/assistant-client/transport-run.js +432 -0
  29. package/dist/core/assistant-client/transport-stream.d.ts +73 -0
  30. package/dist/core/assistant-client/transport-stream.js +128 -0
  31. package/dist/core/assistant-client/transport.d.ts +1 -1
  32. package/dist/core/assistant-client/transport.js +129 -835
  33. package/dist/core/assistant-content.d.ts +1 -17
  34. package/dist/core/assistant-content.js +16 -0
  35. package/dist/core/assistant-tool-metadata.d.ts +103 -0
  36. package/dist/core/assistant-tool-metadata.js +56 -0
  37. package/dist/core/checkpoint-interval.d.ts +1 -1
  38. package/dist/core/compact-events.d.ts +1 -1
  39. package/dist/core/durable-projection.d.ts +1 -1
  40. package/dist/core/durable-runs/continuation.d.ts +1 -1
  41. package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
  42. package/dist/core/durable-runs/ports.d.ts +2 -1
  43. package/dist/core/durable-runs/run-contracts.d.ts +1 -1
  44. package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
  45. package/dist/core/durable-runs/run-finalizer.js +171 -0
  46. package/dist/core/events.d.ts +4 -82
  47. package/dist/core/events.js +2 -1
  48. package/dist/core/index.d.ts +4 -1
  49. package/dist/core/index.js +2 -1
  50. package/dist/core/messages.d.ts +1 -1
  51. package/dist/core/persistence/index.d.ts +1 -1
  52. package/dist/core/persistence/index.js +1 -1
  53. package/dist/core/question-form/normalize.d.ts +9 -3
  54. package/dist/core/question-form/normalize.js +20 -20
  55. package/dist/core/question-form/scan.js +15 -19
  56. package/dist/core/run-activity.d.ts +1 -1
  57. package/dist/core/run-events/entry.d.ts +11 -63
  58. package/dist/core/run-events/entry.js +12 -7
  59. package/dist/core/todos.d.ts +1 -1
  60. package/dist/core/todos.js +8 -0
  61. package/dist/core/tool-call-detail.d.ts +8 -1
  62. package/dist/core/tool-call-detail.js +35 -12
  63. package/dist/core/tool-events.d.ts +1 -1
  64. package/dist/core/tool-output.js +2 -6
  65. package/dist/core/tools.d.ts +2 -1
  66. package/dist/core/transport.d.ts +1 -1
  67. package/dist/core/turn-usage.d.ts +1 -1
  68. package/dist/core/util/parser.js +70 -69
  69. package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
  70. package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
  71. package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
  72. package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
  73. package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
  74. package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
  75. package/dist/embed-widget/browser/lazy-loader.js +16 -12
  76. package/dist/embed-widget/browser/session-store.d.ts +19 -1
  77. package/dist/embed-widget/browser/session-store.js +48 -17
  78. package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
  79. package/dist/embed-widget/vanilla/index.js +131 -67
  80. package/dist/embed-widget/vanilla/state.js +53 -38
  81. package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
  82. package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
  83. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
  84. package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
  85. package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +32 -0
  86. package/dist/react/chat-cleanup/ChatCleanupPanel.js +34 -0
  87. package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +174 -0
  88. package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
  89. package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
  90. package/dist/react/components/ChatCleanupDialog.js +15 -0
  91. package/dist/react/components/ChatSettingsDialog.d.ts +3 -0
  92. package/dist/react/components/ChatSettingsDialog.js +3 -3
  93. package/dist/react/components/ConversationList.d.ts +19 -5
  94. package/dist/react/components/ConversationList.hooks.d.ts +1 -0
  95. package/dist/react/components/ConversationList.hooks.js +4 -2
  96. package/dist/react/components/ConversationList.js +66 -9
  97. package/dist/react/components/Icon.d.ts +1 -1
  98. package/dist/react/components/Icon.js +7 -0
  99. package/dist/react/components/Markdown.js +6 -6
  100. package/dist/react/components/MarkdownLink.d.ts +25 -0
  101. package/dist/react/components/MarkdownLink.js +17 -0
  102. package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
  103. package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
  104. package/dist/react/components/ToolCard.d.ts +4 -2
  105. package/dist/react/components/ToolCard.js +46 -4
  106. package/dist/react/components/ToolCard.rules.d.ts +5 -2
  107. package/dist/react/components/ToolCard.rules.js +12 -5
  108. package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
  109. package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
  110. package/dist/react/components/mcp-ui-surface-state.js +2 -2
  111. package/dist/react/components/own-link.d.ts +26 -0
  112. package/dist/react/components/own-link.js +36 -0
  113. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
  114. package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
  115. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
  116. package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
  117. package/dist/react/features/bridged-chat/index.d.ts +8 -0
  118. package/dist/react/features/bridged-chat/index.js +7 -0
  119. package/dist/react/features/bridged-chat/types.d.ts +49 -0
  120. package/dist/react/features/bridged-chat/types.js +2 -0
  121. package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
  122. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
  123. package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
  124. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
  125. package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
  126. package/dist/react/features/chat-pane/model-options.d.ts +3 -1
  127. package/dist/react/features/chat-pane/model-options.js +3 -3
  128. package/dist/react/features/chat-pane/rules.js +4 -3
  129. package/dist/react/features/chat-pane/styles.d.ts +1 -1
  130. package/dist/react/features/chat-pane/styles.js +16 -0
  131. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
  132. package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
  133. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
  134. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
  135. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
  136. package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
  137. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
  138. package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
  139. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
  140. package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
  141. package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
  142. package/dist/react/features/conversation-chat-pane/index.js +8 -0
  143. package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
  144. package/dist/react/features/conversation-chat-pane/rules.js +29 -0
  145. package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
  146. package/dist/react/features/conversation-chat-pane/types.js +2 -0
  147. package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
  148. package/dist/react/features/conversations/conversation-controller.js +280 -0
  149. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
  150. package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
  151. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
  152. package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
  153. package/dist/react/features/conversations/index.d.ts +9 -0
  154. package/dist/react/features/conversations/index.js +8 -0
  155. package/dist/react/features/conversations/types.d.ts +120 -0
  156. package/dist/react/features/conversations/types.js +2 -0
  157. package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
  158. package/dist/react/features/voice-input/space-hold-rules.js +48 -0
  159. package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
  160. package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
  161. package/dist/react/hooks/useConversation.js +5 -2
  162. package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
  163. package/dist/react/hooks/useRunActivity.d.ts +2 -1
  164. package/dist/react/hooks/useRunStream.d.ts +1 -1
  165. package/dist/react/hooks/useRunStream.js +1 -1
  166. package/dist/react/hooks/useSurfaceRecovery.js +3 -1
  167. package/dist/react/hooks/useToolTimeline.d.ts +2 -1
  168. package/dist/react/index.d.ts +5 -2
  169. package/dist/react/index.js +4 -2
  170. package/dist/react/message-blocks.d.ts +1 -48
  171. package/dist/react/message-blocks.js +47 -0
  172. package/dist/react/styles/chat-settings.css +42 -14
  173. package/dist/server/chat-cleanup-routes.d.ts +56 -0
  174. package/dist/server/chat-cleanup-routes.js +56 -0
  175. package/dist/server/durable-runs/recover.js +193 -171
  176. package/dist/server/run-finalizer/entry.js +133 -110
  177. package/dist/store/legacy/sqlite/conversations.js +29 -17
  178. package/dist/store/pglite/index.d.ts +1 -0
  179. package/dist/store/pglite/index.js +1 -0
  180. package/dist/store/ports.d.ts +12 -0
  181. package/dist/store/postgres/index.d.ts +1 -0
  182. package/dist/store/postgres/index.js +1 -0
  183. package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
  184. package/dist/store/runtime/attempt-base-retention.js +103 -0
  185. package/dist/store/runtime/chat-maintenance.d.ts +16 -0
  186. package/dist/store/runtime/chat-maintenance.js +19 -0
  187. package/dist/store/runtime/chat-principal.d.ts +63 -0
  188. package/dist/store/runtime/chat-principal.js +39 -0
  189. package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
  190. package/dist/store/runtime/durable-run-queries.d.ts +124 -0
  191. package/dist/store/runtime/durable-run-queries.js +122 -0
  192. package/dist/store/runtime/durable-run-store.d.ts +1 -1
  193. package/dist/store/runtime/durable-run-store.js +291 -343
  194. package/dist/store/runtime/entry.d.ts +3 -0
  195. package/dist/store/runtime/entry.js +3 -0
  196. package/dist/store/runtime/events-json.d.ts +1 -1
  197. package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
  198. package/dist/store/runtime/lazy-run-ledger.js +28 -0
  199. package/dist/store/runtime/run-ledger.d.ts +4 -1
  200. package/dist/store/runtime/run-ledger.js +256 -204
  201. package/dist/store/sql/bulk-deletion.d.ts +36 -0
  202. package/dist/store/sql/bulk-deletion.js +103 -0
  203. package/dist/store/sql/store-queries.d.ts +170 -0
  204. package/dist/store/sql/store-queries.js +212 -0
  205. package/dist/store/sql/store-rows.d.ts +106 -0
  206. package/dist/store/sql/store-rows.js +116 -0
  207. package/dist/store/sql/store-writes.d.ts +46 -0
  208. package/dist/store/sql/store-writes.js +161 -0
  209. package/dist/store/sql/store.d.ts +3 -16
  210. package/dist/store/sql/store.js +58 -428
  211. package/dist/store/sql/tables.d.ts +1 -0
  212. package/dist/store/sqlite/index.d.ts +1 -0
  213. package/dist/store/sqlite/index.js +1 -0
  214. package/dist/store/sqlite/schema.d.ts +1 -1
  215. package/dist/store/sqlite/schema.js +5 -1
  216. package/package.json +171 -20
@@ -0,0 +1,56 @@
1
+ import type { CleanupPreviewStore } from '@jini-ai/core/contracts/storage';
2
+ import type { ChatOwnerScope, ChatStore, ChatTitleSource } from '../store/ports.js';
3
+ import type { createChatBulkDeletion } from '../store/sql/bulk-deletion.js';
4
+ export interface ChatCleanupPatchDeps {
5
+ principal: string;
6
+ scope: ChatOwnerScope;
7
+ copy: {
8
+ invalidInput: string;
9
+ expired: string;
10
+ notFound: string;
11
+ };
12
+ readPatchInput: (required: {
13
+ body: unknown;
14
+ }) => {
15
+ title?: string;
16
+ pinned?: boolean;
17
+ source?: ChatTitleSource;
18
+ };
19
+ }
20
+ export type ChatCleanupPreviewDeps = Omit<ChatCleanupPatchDeps, 'readPatchInput'>;
21
+ export type ChatCleanupApplyDeps = ChatCleanupPreviewDeps;
22
+ export type ChatCleanupSelectedDeps = ChatCleanupPreviewDeps;
23
+ type BulkDeletionForScope = (required: {
24
+ principal: string;
25
+ scope: ChatOwnerScope;
26
+ }) => ReturnType<typeof createChatBulkDeletion>;
27
+ export declare function createChatCleanupRoutes({ paths, bulkDeletionFor, previewStore, store }: {
28
+ paths: {
29
+ patch: string;
30
+ preview: string;
31
+ apply: string;
32
+ deleteSelected: string;
33
+ };
34
+ bulkDeletionFor: BulkDeletionForScope;
35
+ previewStore: CleanupPreviewStore;
36
+ store: (required: {
37
+ principal: string;
38
+ scope: ChatOwnerScope;
39
+ }) => ChatStore;
40
+ }, _optional?: {}): {
41
+ patch: import("@jini-ai/core/contracts/server").JsonRouteSpec<{
42
+ id: string;
43
+ body: unknown;
44
+ }, object, ChatCleanupPatchDeps, undefined>;
45
+ preview: import("@jini-ai/core/contracts/server").JsonRouteSpec<{
46
+ body: unknown;
47
+ }, object, ChatCleanupPreviewDeps, undefined>;
48
+ apply: import("@jini-ai/core/contracts/server").JsonRouteSpec<{
49
+ body: unknown;
50
+ }, object, ChatCleanupPreviewDeps, undefined>;
51
+ deleteSelected: import("@jini-ai/core/contracts/server").JsonRouteSpec<{
52
+ body: unknown;
53
+ }, object, ChatCleanupPreviewDeps, undefined>;
54
+ };
55
+ export {};
56
+ //# sourceMappingURL=chat-cleanup-routes.d.ts.map
@@ -0,0 +1,56 @@
1
+ import { defineJsonRoute, ok, err } from '@jini-ai/core/contracts/server';
2
+ function defineCleanupApplyRoute({ path, bulkDeletionFor, previewStore }) {
3
+ return defineJsonRoute({
4
+ method: 'post', path, parse: raw => ok({ value: { body: raw.body } }),
5
+ handle: async ({ input, deps }) => {
6
+ const body = input.body;
7
+ if (body?.confirm !== true || typeof body.previewToken !== 'string')
8
+ return err({ error: { code: 'INVALID_INPUT', message: deps.copy.invalidInput } });
9
+ const taken = previewStore.take({ token: body.previewToken, principal: deps.principal, kind: 'chat-cleanup', scope: JSON.stringify(deps.scope) }, {});
10
+ if (!taken)
11
+ return err({ error: { code: 'INVALID_INPUT', message: deps.copy.expired } });
12
+ const ids = taken.payload.ids;
13
+ const before = taken.payload.before;
14
+ const result = await bulkDeletionFor(deps).apply({ ids: ids.slice(0, 500), before }, {});
15
+ if (ids.length <= 500)
16
+ return ok({ value: result });
17
+ const next = previewStore.put({ principal: deps.principal, kind: 'chat-cleanup', scope: JSON.stringify(deps.scope), payload: { ids: ids.slice(500), before, deadline: taken.deadline } }, {});
18
+ return ok({ value: { ...result, previewToken: next.token } });
19
+ },
20
+ }, { requireSameOrigin: true });
21
+ }
22
+ export function createChatCleanupRoutes({ paths, bulkDeletionFor, previewStore, store }, _optional = {}) {
23
+ return {
24
+ patch: defineJsonRoute({
25
+ method: 'patch', path: paths.patch,
26
+ parse: raw => ok({ value: { id: raw.params.id, body: raw.body } }),
27
+ handle: async ({ input, deps }) => {
28
+ const { source = 'manual', ...patch } = deps.readPatchInput({ body: input.body });
29
+ const conversation = await store(deps).updateConversation({ id: input.id, ...patch }, { source });
30
+ return conversation ? ok({ value: { conversation } }) : err({ error: { code: 'NOT_FOUND', message: deps.copy.notFound } });
31
+ },
32
+ }, { requireSameOrigin: true }),
33
+ preview: defineJsonRoute({
34
+ method: 'post', path: paths.preview, parse: raw => ok({ value: { body: raw.body } }),
35
+ handle: async ({ input, deps }) => {
36
+ const body = input.body;
37
+ if (typeof body?.before !== 'number' || !Number.isFinite(body.before))
38
+ return err({ error: { code: 'INVALID_INPUT', message: deps.copy.invalidInput } });
39
+ const preview = await bulkDeletionFor(deps).preview({ before: body.before }, {});
40
+ const token = previewStore.put({ principal: deps.principal, kind: 'chat-cleanup', scope: JSON.stringify(deps.scope), payload: preview }, {});
41
+ return ok({ value: { ...preview, previewToken: token.token } });
42
+ },
43
+ }, { requireSameOrigin: true }),
44
+ apply: defineCleanupApplyRoute({ path: paths.apply, bulkDeletionFor, previewStore }),
45
+ deleteSelected: defineJsonRoute({
46
+ method: 'post', path: paths.deleteSelected, parse: raw => ok({ value: { body: raw.body } }),
47
+ handle: async ({ input, deps }) => {
48
+ const body = input.body;
49
+ if (body?.confirm !== true || !Array.isArray(body.ids) || body.ids.length > 500 || !body.ids.every(id => typeof id === 'string'))
50
+ return err({ error: { code: 'INVALID_INPUT', message: deps.copy.invalidInput } });
51
+ return ok({ value: await bulkDeletionFor(deps).apply({ ids: body.ids }, {}) });
52
+ },
53
+ }, { requireSameOrigin: true }),
54
+ };
55
+ }
56
+ //# sourceMappingURL=chat-cleanup-routes.js.map
@@ -133,183 +133,205 @@ function savedWork({ run }, _optional = {}) {
133
133
  function continuesNow({ run, trigger, now }, _optional = {}) {
134
134
  return trigger === "attempt-failed" || now - run.attemptStartedAt >= 10_000;
135
135
  }
136
- /** Recovery coordinator behind explicit host ports. One CAS owns both the attempt and its conversation slot.
137
- * Each recovery decision reports run metadata through the host port or the safe default logger. */
138
- export function createDurableRecovery(ports, { report = createConsoleLogger({ prefix: '' }) } = {}) {
139
- /** Replay starts from attemptBase. Carry this attempt's saved launch notice into it too, so
140
- * reconnect/reload cannot replace that evidence with the daemon's shorter replay prefix.
141
- * O(e) in saved events; no additional store read, write, or polling. */
142
- function attach(run) {
143
- const events = run.message.events ?? [];
144
- const noticeIndex = lastIndexWhere({ events, match: event => event.kind === 'status' && event.code === 'run_launch_unconfirmed' });
145
- const marker = lastIndexWhere({ events, match: event => event.kind === 'status' && event.code === 'run_recovering' });
146
- if (noticeIndex <= marker) {
147
- ports.attach(run, {});
148
- return;
149
- }
150
- const notice = events[noticeIndex];
151
- const base = [...run.attemptBase];
152
- if (!base.includes(notice))
153
- base.push(notice);
154
- ports.attach({ ...run, attemptBase: base }, {});
155
- }
156
- async function finalize(run, notice, { canceled = false, detail } = {}) {
157
- await ports.cancelAttempt(run, {}).catch(() => undefined);
158
- // Persist the notice as an event: hook errors are live-only and would leave a reloaded
159
- // terminal message without its explanation. Only this coordinator decides exhaustion.
160
- const events = [...(run.message.events ?? []), { kind: "status", label: notice, ...(detail ? { detail } : {}) }];
161
- await ports.settle({ ...run, content: run.message.content, events, status: canceled ? "canceled" : "failed", endedAt: ports.now() }, {});
162
- return "finalized";
163
- }
164
- async function nativeAllowed(run) {
165
- if (!run.sessionConfirmed || !run.sessionId || !run.child)
166
- return false;
167
- if (!ports.supportsNativeResume({ agentId: run.request.agentId ?? "claude" }, {}))
168
- return false;
169
- return ports.verifyChildDead(run.child, {}).catch(() => false);
170
- }
171
- /** Persist rejection evidence but leave liveness and retry decisions to the existing probe. */
172
- async function launchNext({ run, next, native }, _optional = {}) {
173
- let stage = 'recovery launch';
174
- try {
175
- await ports.launch({ run: next, request: continuationRequest({ run: { ...run, message: next.message, transcript: next.transcript }, native }, {}) }, {});
176
- stage = 'recovery clock';
177
- await ports.store.recoveryClock({ runId: next.runId, now: ports.now(), active: false }, {});
178
- }
179
- catch (error) {
180
- // A rejected/lost start response is uncertain: the daemon may already be executing. The
181
- // same idempotent attempt is probed by the attached watcher before another CAS is possible.
182
- const diagnostic = { kind: 'status', code: 'run_launch_unconfirmed',
183
- label: 'The assistant start response was not confirmed. Checking whether this attempt is running.',
184
- detail: startupFailureMessage({ stage, error }, {
185
- notice: 'The assistant start response was not confirmed. Wait while this attempt is checked.',
186
- }) };
187
- const events = [...(next.message.events ?? []), diagnostic];
188
- // Preserve the saved answer and all prior events in the existing projection write. The
189
- // checkpoint's generation fence rejects a concurrent stop or successor attempt.
190
- await ports.checkpoint?.({ conversationId: next.conversationId, messageId: next.messageId,
191
- runId: next.runId, content: next.message.content, events }, {}).catch(() => false);
192
- return { ...next, message: { ...next.message, events } };
193
- }
194
- return next;
195
- }
196
- async function continueDead(run) {
197
- await ports.cancelAttempt(run, {}).catch(() => undefined);
198
- // A locator captured before a hard cancel can outlive its rollout. Reuse reconstruction,
199
- // including prior turns/tool outcomes, instead of retrying a known missing native session.
200
- const missingResume = run.request.agentId === 'codex' && /no rollout found for thread id/.test(attemptDiagnostics({ run }, {}));
201
- const native = !missingResume && await nativeAllowed(run);
202
- const nextRunId = ports.mintRunId();
203
- const events = recoveredRunEvents({ saved: savedWork({ run }) }, { notice: missingResume ? 'silent' : 'visible' });
204
- if (!await ports.store.advance({ run, nextRunId, now: ports.now(), events }, {}))
205
- return "superseded";
206
- const next = await ports.store.load({ messageId: run.messageId }, { includeTranscriptEvents: false });
207
- // Cancel/deletion can win while the old attempt is being fenced. Re-read after CAS and do
208
- // not launch against a removed binding or a newer generation.
209
- if (!next || next.runId !== nextRunId)
210
- return "superseded";
211
- if (next.cancelReason)
212
- return finalize(next, STOPPED_NOTICE, { canceled: true });
213
- const launched = await launchNext({ run, next, native });
214
- attach(launched);
215
- return "continued";
216
- }
217
- async function probeAttempt({ run, trigger, liveRunId }, _optional = {}) {
218
- // A terminal executor end confirms this attempt is dead even when the daemon retains its
219
- // replayable record (HTTP 200). Other triggers must obtain fresh liveness evidence.
220
- if (trigger === "attempt-failed")
221
- return "dead";
222
- return liveRunId === run.runId ? "live" : ports.probe(run, {});
223
- }
224
- async function reattach(run) {
225
- await ports.store.recoveryClock({ runId: run.runId, now: ports.now(), active: false }, {});
226
- attach(run);
227
- return "reattached";
228
- }
229
- async function finalizeFailure({ run, failure, diagnostics }, _optional = {}) {
230
- if (failure !== "permanent")
231
- return finalize(run, failure === "auth-failure" ? "Not logged in. Saved work is above." : STOPPED_NOTICE, { canceled: true });
232
- // A bridge failure shows its own reason (and stderr): the generic notice hides what needs repair.
233
- const bridgeNotice = diagnostics.match(MCP_BRIDGE_FAILURE)?.[0];
234
- return finalize(run, bridgeNotice ?? EXHAUSTED_NOTICE, { detail: bridgeNotice ? undefined : lastDiagnosticLine({ diagnostics }) });
235
- }
236
- async function decide(run, trigger, liveRunId) {
237
- if (exclusion(run))
238
- return { decision: await finalize(run, STOPPED_NOTICE, { canceled: true }) };
239
- const probe = await probeAttempt({ run, trigger, liveRunId });
240
- // HTTP/storage awaits can cross cancellation, settlement, or an attempt-generation change.
241
- // Re-read before attaching or applying diagnostics to the probed attempt.
242
- const current = await reload(run);
243
- if (typeof current === "string")
244
- return { probe, decision: current };
245
- if (probe === "live")
246
- return { probe, decision: await reattach(current) };
247
- if (probe === "uncertain") {
248
- // Transport uncertainty is not proof of death and spends no restart/time budget. The
249
- // existing watcher waits and probes again; even an expired budget cannot kill a live child.
250
- await reattach(current);
251
- return { probe, decision: "waiting" };
252
- }
253
- return decideDead(current, trigger);
254
- }
255
- async function decideDead(run, trigger) {
256
- const probe = "dead";
257
- // A pending human answer takes precedence over executor exit diagnostics.
258
- if (awaitingAnswer({ run }))
259
- return { probe, decision: await resolveMissing(run, trigger) };
260
- // Diagnostics decide only the fate of an attempt that is no longer running. Read before the
261
- // probe, raw stdout quoting a tool description ("OAuth-authenticated") canceled a live turn
262
- // as "Not logged in" (luvira, 2026-10-08).
263
- const diagnostics = attemptDiagnostics({ run });
264
- const failure = attemptFailure({ diagnostics });
265
- const decision = failure === "retryable" ? await resolveMissing(run, trigger) : await finalizeFailure({ run, failure, diagnostics });
266
- return { probe, failure, decision };
267
- }
268
- async function resolveMissing(run, trigger) {
269
- await ports.store.recoveryClock({ runId: run.runId, now: ports.now(), active: true }, {});
270
- const timed = await reload(run);
271
- return typeof timed === "string" ? timed : resolveDead(timed, trigger);
136
+ function isActive({ run }, _optional = {}) {
137
+ return run.message.runStatus === "queued" || run.message.runStatus === "running";
138
+ }
139
+ /** Pure eligibility: the outcome that ends a recovery before any probe, or null while the saved run is recoverable. */
140
+ function entryOutcome({ run, expectedRunId }, _optional = {}) {
141
+ if (!run)
142
+ return "gone";
143
+ if (!isActive({ run }))
144
+ return "terminal";
145
+ if (expectedRunId && expectedRunId !== run.runId)
146
+ return "superseded";
147
+ return null;
148
+ }
149
+ /** Pure eligibility after an await: the outcome that ends this decision, or null while `current` is still the probed attempt. */
150
+ function reloadOutcome({ run, current }, _optional = {}) {
151
+ if (!current)
152
+ return "gone";
153
+ // A probe only speaks about the generation it inspected. Never apply its dead result to
154
+ // a newer attempt committed by another caller while this one was awaiting storage/HTTP.
155
+ if (current.runId !== run.runId)
156
+ return "superseded";
157
+ return isActive({ run: current }) ? null : "terminal";
158
+ }
159
+ function failureNotice({ failure, diagnostics }, _optional = {}) {
160
+ if (failure !== "permanent")
161
+ return { notice: failure === "auth-failure" ? "Not logged in. Saved work is above." : STOPPED_NOTICE, canceled: true };
162
+ // A bridge failure shows its own reason (and stderr): the generic notice hides what needs repair.
163
+ const bridgeNotice = diagnostics.match(MCP_BRIDGE_FAILURE)?.[0];
164
+ return { notice: bridgeNotice ?? EXHAUSTED_NOTICE, canceled: false, detail: bridgeNotice ? undefined : lastDiagnosticLine({ diagnostics }) };
165
+ }
166
+ /** Replay starts from attemptBase. Carry this attempt's saved launch notice into it too, so
167
+ * reconnect/reload cannot replace that evidence with the daemon's shorter replay prefix.
168
+ * Pure: O(e) in saved events; the run to attach, unchanged when no new notice must be carried. */
169
+ function attachTarget({ run }, _optional = {}) {
170
+ const events = run.message.events ?? [];
171
+ const noticeIndex = lastIndexWhere({ events, match: event => event.kind === 'status' && event.code === 'run_launch_unconfirmed' });
172
+ const marker = lastIndexWhere({ events, match: event => event.kind === 'status' && event.code === 'run_recovering' });
173
+ if (noticeIndex <= marker)
174
+ return run;
175
+ const notice = events[noticeIndex];
176
+ const base = [...run.attemptBase];
177
+ if (!base.includes(notice))
178
+ base.push(notice);
179
+ return { ...run, attemptBase: base };
180
+ }
181
+ function launchUnconfirmed({ stage, error }, _optional = {}) {
182
+ return { kind: 'status', code: 'run_launch_unconfirmed',
183
+ label: 'The assistant start response was not confirmed. Checking whether this attempt is running.',
184
+ detail: startupFailureMessage({ stage, error }, {
185
+ notice: 'The assistant start response was not confirmed. Wait while this attempt is checked.',
186
+ }) };
187
+ }
188
+ /** Attaches the watcher to `attachTarget`; no additional store read, write, or polling. */
189
+ function attach({ ports, run }, _optional = {}) {
190
+ ports.attach(attachTarget({ run }), {});
191
+ }
192
+ async function finalize({ ports, run, notice, canceled = false, detail }, _optional = {}) {
193
+ await ports.cancelAttempt(run, {}).catch(() => undefined);
194
+ // Persist the notice as an event: hook errors are live-only and would leave a reloaded
195
+ // terminal message without its explanation. Only this coordinator decides exhaustion.
196
+ const events = [...(run.message.events ?? []), { kind: "status", label: notice, ...(detail ? { detail } : {}) }];
197
+ await ports.settle({ ...run, content: run.message.content, events, status: canceled ? "canceled" : "failed", endedAt: ports.now() }, {});
198
+ return "finalized";
199
+ }
200
+ async function nativeAllowed({ ports, run }, _optional = {}) {
201
+ if (!run.sessionConfirmed || !run.sessionId || !run.child)
202
+ return false;
203
+ if (!ports.supportsNativeResume({ agentId: run.request.agentId ?? "claude" }, {}))
204
+ return false;
205
+ return ports.verifyChildDead(run.child, {}).catch(() => false);
206
+ }
207
+ /** Persist rejection evidence but leave liveness and retry decisions to the existing probe. */
208
+ async function launchNext({ ports, run, next, native }, _optional = {}) {
209
+ let stage = 'recovery launch';
210
+ try {
211
+ await ports.launch({ run: next, request: continuationRequest({ run: { ...run, message: next.message, transcript: next.transcript }, native }, {}) }, {});
212
+ stage = 'recovery clock';
213
+ await ports.store.recoveryClock({ runId: next.runId, now: ports.now(), active: false }, {});
272
214
  }
273
- /** The saved row after an await, or the outcome that ends this decision. O(1) store reads. */
274
- async function reload(run) {
275
- const current = await ports.store.load({ messageId: run.messageId }, { includeTranscriptEvents: false });
276
- if (!current)
277
- return "gone";
278
- // A probe only speaks about the generation it inspected. Never apply its dead result to
279
- // a newer attempt committed by another caller while this one was awaiting storage/HTTP.
280
- if (current.runId !== run.runId)
281
- return "superseded";
282
- if (current.message.runStatus !== "queued" && current.message.runStatus !== "running")
283
- return "terminal";
284
- if (exclusion(current))
285
- return finalize(current, STOPPED_NOTICE, { canceled: true });
286
- return current;
215
+ catch (error) {
216
+ // A rejected/lost start response is uncertain: the daemon may already be executing. The
217
+ // same idempotent attempt is probed by the attached watcher before another CAS is possible.
218
+ const events = [...(next.message.events ?? []), launchUnconfirmed({ stage, error })];
219
+ // Preserve the saved answer and all prior events in the existing projection write. The
220
+ // checkpoint's generation fence rejects a concurrent stop or successor attempt.
221
+ await ports.checkpoint?.({ conversationId: next.conversationId, messageId: next.messageId,
222
+ runId: next.runId, content: next.message.content, events }, {}).catch(() => false);
223
+ return { ...next, message: { ...next.message, events } };
287
224
  }
288
- async function resolveDead(run, trigger) {
289
- // A dead process cannot resume its question. End this turn with the existing card intact,
290
- // rather than minting an attempt that runs preflight and asks the same question again.
291
- if (awaitingAnswer({ run }))
292
- return finalize(run, AWAITING_ANSWER_NOTICE);
293
- const notice = budgetNotice(run, ports.now());
294
- if (notice)
295
- return finalize(run, notice, { detail: notice === EXHAUSTED_NOTICE ? exhaustedDetail({ run }) : undefined });
296
- // A queued attempt may be between durable acceptance and the daemon's start transaction.
297
- // Give that idempotent launch time to appear before a 404 can advance its generation.
298
- if (continuesNow({ run, trigger, now: ports.now() }))
299
- return continueDead(run);
300
- attach(run);
301
- return "waiting";
225
+ return next;
226
+ }
227
+ async function continueDead({ ports, run }, _optional = {}) {
228
+ await ports.cancelAttempt(run, {}).catch(() => undefined);
229
+ // A locator captured before a hard cancel can outlive its rollout. Reuse reconstruction,
230
+ // including prior turns/tool outcomes, instead of retrying a known missing native session.
231
+ const missingResume = run.request.agentId === 'codex' && /no rollout found for thread id/.test(attemptDiagnostics({ run }, {}));
232
+ const native = !missingResume && await nativeAllowed({ ports, run });
233
+ const nextRunId = ports.mintRunId();
234
+ const events = recoveredRunEvents({ saved: savedWork({ run }) }, { notice: missingResume ? 'silent' : 'visible' });
235
+ if (!await ports.store.advance({ run, nextRunId, now: ports.now(), events }, {}))
236
+ return "superseded";
237
+ const next = await ports.store.load({ messageId: run.messageId }, { includeTranscriptEvents: false });
238
+ // Cancel/deletion can win while the old attempt is being fenced. Re-read after CAS and do
239
+ // not launch against a removed binding or a newer generation.
240
+ if (!next || next.runId !== nextRunId)
241
+ return "superseded";
242
+ if (next.cancelReason)
243
+ return finalize({ ports, run: next, notice: STOPPED_NOTICE, canceled: true });
244
+ const launched = await launchNext({ ports, run, next, native });
245
+ attach({ ports, run: launched });
246
+ return "continued";
247
+ }
248
+ async function probeAttempt({ ports, run, trigger, liveRunId }, _optional = {}) {
249
+ // A terminal executor end confirms this attempt is dead even when the daemon retains its
250
+ // replayable record (HTTP 200). Other triggers must obtain fresh liveness evidence.
251
+ if (trigger === "attempt-failed")
252
+ return "dead";
253
+ return liveRunId === run.runId ? "live" : ports.probe(run, {});
254
+ }
255
+ async function reattach({ ports, run }, _optional = {}) {
256
+ await ports.store.recoveryClock({ runId: run.runId, now: ports.now(), active: false }, {});
257
+ attach({ ports, run });
258
+ return "reattached";
259
+ }
260
+ async function finalizeFailure({ ports, run, failure, diagnostics }, _optional = {}) {
261
+ return finalize({ ports, run, ...failureNotice({ failure, diagnostics }) });
262
+ }
263
+ /** The saved row after an await, or the outcome that ends this decision. O(1) store reads. */
264
+ async function reload({ ports, run }, _optional = {}) {
265
+ const current = await ports.store.load({ messageId: run.messageId }, { includeTranscriptEvents: false });
266
+ const ended = reloadOutcome({ run, current });
267
+ if (ended)
268
+ return ended;
269
+ if (exclusion(current))
270
+ return finalize({ ports, run: current, notice: STOPPED_NOTICE, canceled: true });
271
+ return current;
272
+ }
273
+ async function resolveDead({ ports, run, trigger }, _optional = {}) {
274
+ // A dead process cannot resume its question. End this turn with the existing card intact,
275
+ // rather than minting an attempt that runs preflight and asks the same question again.
276
+ if (awaitingAnswer({ run }))
277
+ return finalize({ ports, run, notice: AWAITING_ANSWER_NOTICE });
278
+ const notice = budgetNotice(run, ports.now());
279
+ if (notice)
280
+ return finalize({ ports, run, notice, detail: notice === EXHAUSTED_NOTICE ? exhaustedDetail({ run }) : undefined });
281
+ // A queued attempt may be between durable acceptance and the daemon's start transaction.
282
+ // Give that idempotent launch time to appear before a 404 can advance its generation.
283
+ if (continuesNow({ run, trigger, now: ports.now() }))
284
+ return continueDead({ ports, run });
285
+ attach({ ports, run });
286
+ return "waiting";
287
+ }
288
+ async function resolveMissing({ ports, run, trigger }, _optional = {}) {
289
+ await ports.store.recoveryClock({ runId: run.runId, now: ports.now(), active: true }, {});
290
+ const timed = await reload({ ports, run });
291
+ return typeof timed === "string" ? timed : resolveDead({ ports, run: timed, trigger });
292
+ }
293
+ async function decideDead({ ports, run, trigger }, _optional = {}) {
294
+ const probe = "dead";
295
+ // A pending human answer takes precedence over executor exit diagnostics.
296
+ if (awaitingAnswer({ run }))
297
+ return { probe, decision: await resolveMissing({ ports, run, trigger }) };
298
+ // Diagnostics decide only the fate of an attempt that is no longer running. Read before the
299
+ // probe, raw stdout quoting a tool description ("OAuth-authenticated") canceled a live turn
300
+ // as "Not logged in" (luvira, 2026-10-08).
301
+ const diagnostics = attemptDiagnostics({ run });
302
+ const failure = attemptFailure({ diagnostics });
303
+ const decision = failure === "retryable" ? await resolveMissing({ ports, run, trigger }) : await finalizeFailure({ ports, run, failure, diagnostics });
304
+ return { probe, failure, decision };
305
+ }
306
+ async function decide({ ports, run, trigger, liveRunId }, _optional = {}) {
307
+ if (exclusion(run))
308
+ return { decision: await finalize({ ports, run, notice: STOPPED_NOTICE, canceled: true }) };
309
+ const probe = await probeAttempt({ ports, run, trigger, liveRunId });
310
+ // HTTP/storage awaits can cross cancellation, settlement, or an attempt-generation change.
311
+ // Re-read before attaching or applying diagnostics to the probed attempt.
312
+ const current = await reload({ ports, run });
313
+ if (typeof current === "string")
314
+ return { probe, decision: current };
315
+ if (probe === "live")
316
+ return { probe, decision: await reattach({ ports, run: current }) };
317
+ if (probe === "uncertain") {
318
+ // Transport uncertainty is not proof of death and spends no restart/time budget. The
319
+ // existing watcher waits and probes again; even an expired budget cannot kill a live child.
320
+ await reattach({ ports, run: current });
321
+ return { probe, decision: "waiting" };
302
322
  }
323
+ return decideDead({ ports, run: current, trigger });
324
+ }
325
+ /** Recovery coordinator behind explicit host ports. One CAS owns both the attempt and its conversation slot.
326
+ * Each recovery decision reports run metadata through the host port or the safe default logger. */
327
+ export function createDurableRecovery(ports, { report = createConsoleLogger({ prefix: '' }) } = {}) {
303
328
  return {
304
329
  async recover({ messageId, trigger, expectedRunId }, options) {
305
330
  const run = await ports.store.load({ messageId }, { includeTranscriptEvents: false });
306
- if (!run)
307
- return "gone";
308
- if (run.message.runStatus !== "queued" && run.message.runStatus !== "running")
309
- return "terminal";
310
- if (expectedRunId && expectedRunId !== run.runId)
311
- return "superseded";
312
- const { decision, probe, failure } = await decide(run, trigger, options.liveRunId);
331
+ const ended = entryOutcome({ run, expectedRunId });
332
+ if (ended)
333
+ return ended;
334
+ const { decision, probe, failure } = await decide({ ports, run: run, trigger, liveRunId: options.liveRunId });
313
335
  // The watcher re-confirms its own live run every resolution window; log only real recovery
314
336
  // decisions. Metadata only: diagnostics, answers and cancel reasons can hold secrets.
315
337
  if (options.liveRunId !== run.runId)