@jini-ai/chat 0.7.3-next.2 → 0.7.3-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +49 -0
- package/dist/core/accepted-input.d.ts +1 -1
- package/dist/core/ag-ui/event-projection.d.ts +14 -69
- package/dist/core/ag-ui/event-projection.js +58 -133
- package/dist/core/ag-ui/event-reduction.d.ts +12 -2
- package/dist/core/ag-ui/event-reduction.js +35 -10
- package/dist/core/ag-ui/resume.d.ts +110 -0
- package/dist/core/ag-ui/resume.js +200 -0
- package/dist/core/ag-ui/run-input.d.ts +23 -0
- package/dist/core/ag-ui/run-input.js +45 -0
- package/dist/core/ag-ui/server.d.ts +69 -0
- package/dist/core/ag-ui/server.js +71 -0
- package/dist/core/agent-plugin-chat-state.js +13 -11
- package/dist/core/assistant-client/ag-ui-approval-relay.d.ts +113 -0
- package/dist/core/assistant-client/ag-ui-approval-relay.js +287 -0
- package/dist/core/assistant-client/ag-ui-fetch-agent.d.ts +25 -10
- package/dist/core/assistant-client/ag-ui-fetch-agent.js +25 -6
- package/dist/core/assistant-client/ag-ui-transport.d.ts +86 -3
- package/dist/core/assistant-client/ag-ui-transport.js +310 -80
- package/dist/core/assistant-client/browser-durable-subscription.d.ts +25 -0
- package/dist/core/assistant-client/browser-durable-subscription.js +78 -0
- package/dist/core/assistant-client/durable-run-subscription.js +141 -130
- package/dist/core/assistant-client/entry.d.ts +2 -1
- package/dist/core/assistant-client/entry.js +1 -0
- package/dist/core/assistant-client/transport-prompt.d.ts +94 -0
- package/dist/core/assistant-client/transport-prompt.js +180 -0
- package/dist/core/assistant-client/transport-run.d.ts +49 -0
- package/dist/core/assistant-client/transport-run.js +432 -0
- package/dist/core/assistant-client/transport-stream.d.ts +73 -0
- package/dist/core/assistant-client/transport-stream.js +128 -0
- package/dist/core/assistant-client/transport.d.ts +1 -1
- package/dist/core/assistant-client/transport.js +129 -835
- package/dist/core/assistant-content.d.ts +1 -17
- package/dist/core/assistant-content.js +16 -0
- package/dist/core/assistant-tool-metadata.d.ts +103 -0
- package/dist/core/assistant-tool-metadata.js +56 -0
- package/dist/core/checkpoint-interval.d.ts +1 -1
- package/dist/core/compact-events.d.ts +1 -1
- package/dist/core/durable-projection.d.ts +1 -1
- package/dist/core/durable-runs/continuation.d.ts +1 -1
- package/dist/core/durable-runs/ledger-contracts.d.ts +4 -1
- package/dist/core/durable-runs/ports.d.ts +2 -1
- package/dist/core/durable-runs/run-contracts.d.ts +1 -1
- package/dist/core/durable-runs/run-finalizer.d.ts +145 -0
- package/dist/core/durable-runs/run-finalizer.js +171 -0
- package/dist/core/events.d.ts +4 -82
- package/dist/core/events.js +2 -1
- package/dist/core/index.d.ts +4 -1
- package/dist/core/index.js +2 -1
- package/dist/core/messages.d.ts +1 -1
- package/dist/core/persistence/index.d.ts +1 -1
- package/dist/core/persistence/index.js +1 -1
- package/dist/core/question-form/normalize.d.ts +9 -3
- package/dist/core/question-form/normalize.js +20 -20
- package/dist/core/question-form/scan.js +15 -19
- package/dist/core/run-activity.d.ts +1 -1
- package/dist/core/run-events/entry.d.ts +11 -63
- package/dist/core/run-events/entry.js +12 -7
- package/dist/core/todos.d.ts +1 -1
- package/dist/core/todos.js +8 -0
- package/dist/core/tool-call-detail.d.ts +8 -1
- package/dist/core/tool-call-detail.js +35 -12
- package/dist/core/tool-events.d.ts +1 -1
- package/dist/core/tool-output.js +2 -6
- package/dist/core/tools.d.ts +2 -1
- package/dist/core/transport.d.ts +1 -1
- package/dist/core/turn-usage.d.ts +1 -1
- package/dist/core/util/parser.js +70 -69
- package/dist/embed-widget/browser/embed-send-bridge.d.ts +44 -0
- package/dist/embed-widget/browser/embed-send-bridge.js +60 -0
- package/dist/embed-widget/browser/frontend-invocation-handler.d.ts +39 -0
- package/dist/embed-widget/browser/frontend-invocation-handler.js +151 -0
- package/dist/embed-widget/browser/frontend-session-bridge.d.ts +28 -0
- package/dist/embed-widget/browser/frontend-session-bridge.js +201 -257
- package/dist/embed-widget/browser/lazy-loader.js +16 -12
- package/dist/embed-widget/browser/session-store.d.ts +19 -1
- package/dist/embed-widget/browser/session-store.js +48 -17
- package/dist/embed-widget/transports/fetch-sse.d.ts +1 -1
- package/dist/embed-widget/vanilla/index.js +131 -67
- package/dist/embed-widget/vanilla/state.js +53 -38
- package/dist/react/admin-execution/ai-agent-presentation.d.ts +35 -0
- package/dist/react/admin-execution/ai-agent-presentation.js +39 -0
- package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.d.ts +22 -0
- package/dist/react/admin-execution/hooks/use-ai-agent-presentation.hooks.js +25 -0
- package/dist/react/chat-cleanup/ChatCleanupPanel.d.ts +15 -0
- package/dist/react/chat-cleanup/ChatCleanupPanel.js +17 -0
- package/dist/react/chat-cleanup/chat-cleanup.hooks.d.ts +168 -0
- package/dist/react/chat-cleanup/chat-cleanup.hooks.js +83 -0
- package/dist/react/components/ChatCleanupDialog.d.ts +38 -0
- package/dist/react/components/ChatCleanupDialog.js +12 -0
- package/dist/react/components/ConversationList.d.ts +14 -5
- package/dist/react/components/ConversationList.hooks.d.ts +1 -0
- package/dist/react/components/ConversationList.hooks.js +4 -2
- package/dist/react/components/ConversationList.js +41 -5
- package/dist/react/components/Icon.d.ts +1 -1
- package/dist/react/components/Icon.js +2 -0
- package/dist/react/components/Markdown.js +6 -6
- package/dist/react/components/MarkdownLink.d.ts +25 -0
- package/dist/react/components/MarkdownLink.js +17 -0
- package/dist/react/components/RoutedA2uiSurfaceCard.d.ts +80 -0
- package/dist/react/components/RoutedA2uiSurfaceCard.js +15 -0
- package/dist/react/components/ToolCard.d.ts +4 -2
- package/dist/react/components/ToolCard.js +46 -4
- package/dist/react/components/ToolCard.rules.d.ts +5 -2
- package/dist/react/components/ToolCard.rules.js +12 -5
- package/dist/react/components/mcp-ui-question-input.d.ts +1 -1
- package/dist/react/components/mcp-ui-surface-state.d.ts +3 -1
- package/dist/react/components/mcp-ui-surface-state.js +2 -2
- package/dist/react/components/own-link.d.ts +26 -0
- package/dist/react/components/own-link.js +36 -0
- package/dist/react/features/bridged-chat/create-staged-attachment-uploader.d.ts +7 -0
- package/dist/react/features/bridged-chat/create-staged-attachment-uploader.js +26 -0
- package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.d.ts +12 -0
- package/dist/react/features/bridged-chat/hooks/useBridgedChatTransport.hooks.js +60 -0
- package/dist/react/features/bridged-chat/index.d.ts +8 -0
- package/dist/react/features/bridged-chat/index.js +7 -0
- package/dist/react/features/bridged-chat/types.d.ts +49 -0
- package/dist/react/features/bridged-chat/types.js +2 -0
- package/dist/react/features/chat-pane/components/RuntimeDropUp.js +1 -1
- package/dist/react/features/chat-pane/create-daemon-attachment-uploader.d.ts +6 -0
- package/dist/react/features/chat-pane/create-daemon-attachment-uploader.js +101 -59
- package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.d.ts +3 -0
- package/dist/react/features/chat-pane/hooks/useChatPaneNewTabLinks.hooks.js +26 -16
- package/dist/react/features/chat-pane/model-options.d.ts +3 -1
- package/dist/react/features/chat-pane/model-options.js +3 -3
- package/dist/react/features/chat-pane/rules.js +4 -3
- package/dist/react/features/chat-pane/styles.d.ts +1 -1
- package/dist/react/features/chat-pane/styles.js +16 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.d.ts +10 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPane.js +19 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.d.ts +12 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneChat.js +21 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.d.ts +13 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationChatPaneHeader.js +9 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.d.ts +12 -0
- package/dist/react/features/conversation-chat-pane/components/ConversationDeleteConfirm.js +12 -0
- package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.d.ts +7 -0
- package/dist/react/features/conversation-chat-pane/hooks/useConversationChatPane.hooks.js +43 -0
- package/dist/react/features/conversation-chat-pane/index.d.ts +9 -0
- package/dist/react/features/conversation-chat-pane/index.js +8 -0
- package/dist/react/features/conversation-chat-pane/rules.d.ts +25 -0
- package/dist/react/features/conversation-chat-pane/rules.js +29 -0
- package/dist/react/features/conversation-chat-pane/types.d.ts +139 -0
- package/dist/react/features/conversation-chat-pane/types.js +2 -0
- package/dist/react/features/conversations/conversation-controller.d.ts +16 -0
- package/dist/react/features/conversations/conversation-controller.js +280 -0
- package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.d.ts +15 -0
- package/dist/react/features/conversations/hooks/useConversationDeleteConfirmation.hooks.js +33 -0
- package/dist/react/features/conversations/hooks/useStoredConversations.hooks.d.ts +16 -0
- package/dist/react/features/conversations/hooks/useStoredConversations.hooks.js +36 -0
- package/dist/react/features/conversations/index.d.ts +9 -0
- package/dist/react/features/conversations/index.js +8 -0
- package/dist/react/features/conversations/types.d.ts +120 -0
- package/dist/react/features/conversations/types.js +2 -0
- package/dist/react/features/voice-input/space-hold-rules.d.ts +65 -0
- package/dist/react/features/voice-input/space-hold-rules.js +48 -0
- package/dist/react/hooks/testing/fake-transport.d.ts +1 -1
- package/dist/react/hooks/useAnsweredCards.d.ts +2 -1
- package/dist/react/hooks/useConversation.js +5 -2
- package/dist/react/hooks/useExtEventGroups.d.ts +1 -1
- package/dist/react/hooks/useRunActivity.d.ts +2 -1
- package/dist/react/hooks/useRunStream.d.ts +1 -1
- package/dist/react/hooks/useRunStream.js +1 -1
- package/dist/react/hooks/useSurfaceRecovery.js +3 -1
- package/dist/react/hooks/useToolTimeline.d.ts +2 -1
- package/dist/react/index.d.ts +5 -2
- package/dist/react/index.js +4 -2
- package/dist/react/message-blocks.d.ts +1 -48
- package/dist/react/message-blocks.js +47 -0
- package/dist/react/styles/chat-settings.css +14 -14
- package/dist/server/chat-cleanup-routes.d.ts +56 -0
- package/dist/server/chat-cleanup-routes.js +56 -0
- package/dist/server/durable-runs/recover.js +193 -171
- package/dist/server/run-finalizer/entry.js +133 -110
- package/dist/store/legacy/sqlite/conversations.js +29 -17
- package/dist/store/pglite/index.d.ts +1 -0
- package/dist/store/pglite/index.js +1 -0
- package/dist/store/ports.d.ts +12 -0
- package/dist/store/postgres/index.d.ts +1 -0
- package/dist/store/postgres/index.js +1 -0
- package/dist/store/runtime/attempt-base-retention.d.ts +57 -0
- package/dist/store/runtime/attempt-base-retention.js +103 -0
- package/dist/store/runtime/chat-maintenance.d.ts +16 -0
- package/dist/store/runtime/chat-maintenance.js +19 -0
- package/dist/store/runtime/chat-principal.d.ts +63 -0
- package/dist/store/runtime/chat-principal.js +39 -0
- package/dist/store/runtime/checkpoint-delta.d.ts +1 -1
- package/dist/store/runtime/durable-run-queries.d.ts +124 -0
- package/dist/store/runtime/durable-run-queries.js +122 -0
- package/dist/store/runtime/durable-run-store.d.ts +1 -1
- package/dist/store/runtime/durable-run-store.js +291 -343
- package/dist/store/runtime/entry.d.ts +3 -0
- package/dist/store/runtime/entry.js +3 -0
- package/dist/store/runtime/events-json.d.ts +1 -1
- package/dist/store/runtime/lazy-run-ledger.d.ts +19 -0
- package/dist/store/runtime/lazy-run-ledger.js +28 -0
- package/dist/store/runtime/run-ledger.d.ts +4 -1
- package/dist/store/runtime/run-ledger.js +256 -204
- package/dist/store/sql/bulk-deletion.d.ts +36 -0
- package/dist/store/sql/bulk-deletion.js +103 -0
- package/dist/store/sql/store-queries.d.ts +170 -0
- package/dist/store/sql/store-queries.js +212 -0
- package/dist/store/sql/store-rows.d.ts +106 -0
- package/dist/store/sql/store-rows.js +116 -0
- package/dist/store/sql/store-writes.d.ts +46 -0
- package/dist/store/sql/store-writes.js +161 -0
- package/dist/store/sql/store.d.ts +3 -16
- package/dist/store/sql/store.js +58 -428
- package/dist/store/sql/tables.d.ts +1 -0
- package/dist/store/sqlite/index.d.ts +1 -0
- package/dist/store/sqlite/index.js +1 -0
- package/dist/store/sqlite/schema.d.ts +1 -1
- package/dist/store/sqlite/schema.js +5 -1
- package/package.json +171 -20
|
@@ -1,144 +1,155 @@
|
|
|
1
1
|
import { createConsoleLogger } from '@jini-ai/core/primitives';
|
|
2
2
|
import { translateRunFrame } from "../run-events/entry.js";
|
|
3
|
-
/**
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
3
|
+
/** Each stream is torn down exactly once: a dropped stream is closed on disconnect, and a later reopen or stop must not close it again. */
|
|
4
|
+
function closeStream({ s }) {
|
|
5
|
+
const close = s.stopStream;
|
|
6
|
+
s.stopStream = undefined;
|
|
7
|
+
close?.();
|
|
8
|
+
}
|
|
9
|
+
function stopFollowing(ctx) {
|
|
10
|
+
const { s, env } = ctx;
|
|
11
|
+
s.stopped = true;
|
|
12
|
+
s.streamEpoch += 1;
|
|
13
|
+
closeStream(ctx);
|
|
14
|
+
s.stopTimer?.();
|
|
15
|
+
env.signal?.removeEventListener("abort", s.abortListener);
|
|
16
|
+
}
|
|
17
|
+
function finish(ctx, message) {
|
|
18
|
+
const { handlers } = ctx.env;
|
|
19
|
+
stopFollowing(ctx);
|
|
20
|
+
handlers.onCheckpoint?.(message);
|
|
21
|
+
if (message.runStatus === "failed" && !handlers.onCheckpoint)
|
|
22
|
+
handlers.onError(new Error("The assistant could not finish this answer. Saved work is above."));
|
|
23
|
+
handlers.onDone(message.events ?? []);
|
|
24
|
+
}
|
|
25
|
+
function openStream(ctx) {
|
|
26
|
+
const { s, env } = ctx;
|
|
27
|
+
s.streamEpoch += 1;
|
|
28
|
+
const epoch = s.streamEpoch;
|
|
29
|
+
s.dropped = false;
|
|
30
|
+
closeStream(ctx);
|
|
31
|
+
s.stopStream = env.ports.stream({ runId: s.runId, cursor: s.cursor,
|
|
32
|
+
frame: (...args) => { if (epoch === s.streamEpoch)
|
|
33
|
+
deliverFrame(ctx, ...args); },
|
|
34
|
+
dropped: () => { if (epoch === s.streamEpoch)
|
|
35
|
+
onDisconnected(ctx); },
|
|
36
|
+
}, {});
|
|
37
|
+
}
|
|
38
|
+
/** One timer owns reconnects, including faults during a checkpoint read. No cursor reset. */
|
|
39
|
+
function onDisconnected(ctx) {
|
|
40
|
+
const { s, env } = ctx;
|
|
41
|
+
if (s.stopped || s.dropped)
|
|
42
|
+
return;
|
|
43
|
+
s.dropped = true;
|
|
44
|
+
s.streamEpoch += 1;
|
|
45
|
+
s.recoveryPending = true;
|
|
46
|
+
s.reconnectDelayMs = Math.min(30_000, Math.max(1_000, s.reconnectDelayMs * 2));
|
|
47
|
+
// Metadata only: neither frame contents nor saved user messages belong in transport logs.
|
|
48
|
+
env.report.info({ message: "[durable-subscription] Stream disconnected; retrying." }, { meta: { runId: s.runId, cursor: s.cursor, retryDelayMs: s.reconnectDelayMs } });
|
|
49
|
+
closeStream(ctx);
|
|
50
|
+
if (!s.reading)
|
|
51
|
+
scheduleRead(ctx);
|
|
52
|
+
}
|
|
53
|
+
function scheduleRead(ctx) {
|
|
54
|
+
const { s, env } = ctx;
|
|
55
|
+
s.stopTimer?.();
|
|
56
|
+
s.stopTimer = env.ports.schedule({ work: () => void readSaved(ctx).catch(() => undefined), delayMs: s.dropped ? s.reconnectDelayMs : 1_000 }, {});
|
|
57
|
+
}
|
|
58
|
+
function deliverFrame(ctx, kind, data, nextCursor) {
|
|
59
|
+
const { s, env } = ctx;
|
|
60
|
+
if (s.stopped)
|
|
61
|
+
return;
|
|
62
|
+
if (nextCursor) {
|
|
63
|
+
if (nextCursor !== s.cursor)
|
|
64
|
+
s.reconnectDelayMs = 0;
|
|
65
|
+
s.cursor = nextCursor;
|
|
57
66
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
67
|
+
const outcome = translateRunFrame({ kind, raw: data, notices: env.notices }, {});
|
|
68
|
+
// An attempt's error/end may be followed by a continuation. Only the row can finalize it.
|
|
69
|
+
if (outcome.terminal || outcome.error) {
|
|
70
|
+
s.recoveryPending = true;
|
|
71
|
+
void readSaved(ctx).catch(() => undefined);
|
|
72
|
+
return;
|
|
61
73
|
}
|
|
62
|
-
|
|
63
|
-
|
|
74
|
+
// With the checkpoint-capable hook, render only durable projections. Replaying a daemon
|
|
75
|
+
// prefix into a seeded bubble would duplicate its text; the server folds those deltas once.
|
|
76
|
+
if (env.handlers.onCheckpoint)
|
|
77
|
+
return;
|
|
78
|
+
for (const event of outcome.events)
|
|
79
|
+
env.handlers.onEvent(event);
|
|
80
|
+
}
|
|
81
|
+
async function readSaved(ctx) {
|
|
82
|
+
const { s, env } = ctx;
|
|
83
|
+
if (s.stopped || s.reading)
|
|
84
|
+
return;
|
|
85
|
+
s.reading = true;
|
|
86
|
+
s.stopTimer?.();
|
|
87
|
+
s.stopTimer = undefined;
|
|
88
|
+
const recover = s.recoveryPending;
|
|
89
|
+
let retryRecovery = recover;
|
|
90
|
+
// Consume only when a read starts: faults during its await latch one follow-up recovery.
|
|
91
|
+
s.recoveryPending = false;
|
|
92
|
+
try {
|
|
93
|
+
const message = await env.ports.read({ runId: s.runId, ...(s.messageId ? { messageId: s.messageId } : {}) }, { recover });
|
|
94
|
+
if (s.stopped || !message)
|
|
64
95
|
return;
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
const outcome = translateRunFrame({ kind, raw: data, notices }, {});
|
|
71
|
-
// An attempt's error/end may be followed by a continuation. Only the row can finalize it.
|
|
72
|
-
if (outcome.terminal || outcome.error) {
|
|
73
|
-
recoveryPending = true;
|
|
74
|
-
void read().catch(() => undefined);
|
|
96
|
+
retryRecovery = false;
|
|
97
|
+
if (message === "gone") {
|
|
98
|
+
stopFollowing(ctx);
|
|
99
|
+
env.handlers.onDone([]);
|
|
75
100
|
return;
|
|
76
101
|
}
|
|
77
|
-
|
|
78
|
-
// prefix into a seeded bubble would duplicate its text; the server folds those deltas once.
|
|
79
|
-
if (handlers.onCheckpoint)
|
|
80
|
-
return;
|
|
81
|
-
for (const event of outcome.events)
|
|
82
|
-
handlers.onEvent(event);
|
|
102
|
+
applySavedMessage(ctx, message);
|
|
83
103
|
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
recoveryPending = false;
|
|
94
|
-
try {
|
|
95
|
-
const message = await ports.read({ runId, ...(messageId ? { messageId } : {}) }, { recover });
|
|
96
|
-
if (stopped || !message)
|
|
97
|
-
return;
|
|
98
|
-
retryRecovery = false;
|
|
99
|
-
if (message === "gone") {
|
|
100
|
-
stop();
|
|
101
|
-
handlers.onDone([]);
|
|
102
|
-
return;
|
|
103
|
-
}
|
|
104
|
-
applySavedMessage(message);
|
|
105
|
-
}
|
|
106
|
-
finally {
|
|
107
|
-
// Recovery must return a body before conditional polls resume: a failed recovery followed
|
|
108
|
-
// by unchanged (304) polls would otherwise leave a quiet run's dropped stream closed.
|
|
109
|
-
if (retryRecovery)
|
|
110
|
-
recoveryPending = true;
|
|
111
|
-
reading = false;
|
|
112
|
-
if (!stopped) {
|
|
113
|
-
// Always schedule: an error arriving during read must not create a tight recovery loop.
|
|
114
|
-
scheduleRead();
|
|
115
|
-
}
|
|
104
|
+
finally {
|
|
105
|
+
// Recovery must return a body before conditional polls resume: a failed recovery followed
|
|
106
|
+
// by unchanged (304) polls would otherwise leave a quiet run's dropped stream closed.
|
|
107
|
+
if (retryRecovery)
|
|
108
|
+
s.recoveryPending = true;
|
|
109
|
+
s.reading = false;
|
|
110
|
+
if (!s.stopped) {
|
|
111
|
+
// Always schedule: an error arriving during read must not create a tight recovery loop.
|
|
112
|
+
scheduleRead(ctx);
|
|
116
113
|
}
|
|
117
114
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
115
|
+
}
|
|
116
|
+
function applySavedMessage(ctx, message) {
|
|
117
|
+
const { s, env } = ctx;
|
|
118
|
+
s.messageId = message.id;
|
|
119
|
+
if (["succeeded", "failed", "canceled"].includes(message.runStatus ?? "")) {
|
|
120
|
+
finish(ctx, message);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
env.handlers.onCheckpoint?.(message);
|
|
124
|
+
if (message.runId && message.runId !== s.runId) {
|
|
125
|
+
s.runId = message.runId;
|
|
126
|
+
s.cursor = "";
|
|
127
|
+
s.reconnectDelayMs = 0;
|
|
128
|
+
if (env.binding)
|
|
129
|
+
env.bindings.set(s.runId, env.binding);
|
|
130
|
+
s.dropped = true;
|
|
131
|
+
}
|
|
132
|
+
if (s.dropped)
|
|
133
|
+
openStream(ctx);
|
|
134
|
+
}
|
|
135
|
+
/** SSE is a view of one attempt. The saved message owns terminal state and can point at a new
|
|
136
|
+
* attempt after recovery; neither a browser 404 nor a closed stream may fail the logical run.
|
|
137
|
+
* An explicit "gone" result ends observation and releases the caller's streaming state. */
|
|
138
|
+
export function followDurableRun({ runId: initialRunId, handlers, signal, binding, ports, notices, bindings }, { report = createConsoleLogger({ prefix: '' }) } = {}) {
|
|
139
|
+
const s = {
|
|
140
|
+
streamEpoch: 0, runId: initialRunId, cursor: "", stopped: false, reading: false, recoveryPending: true,
|
|
141
|
+
dropped: false, reconnectDelayMs: 0, stopStream: undefined, stopTimer: undefined, messageId: binding?.messageId,
|
|
142
|
+
abortListener: () => { },
|
|
143
|
+
};
|
|
144
|
+
const ctx = { s, env: { handlers, signal, binding, ports, notices, bindings, report } };
|
|
145
|
+
const stop = () => stopFollowing(ctx);
|
|
146
|
+
s.abortListener = stop;
|
|
147
|
+
if (!signal?.aborted) {
|
|
148
|
+
signal?.addEventListener("abort", stop);
|
|
149
|
+
openStream(ctx);
|
|
150
|
+
// Polling also covers an attempt that dies before a first frame/connection error arrives.
|
|
151
|
+
s.stopTimer = ports.schedule({ work: () => void readSaved(ctx).catch(() => undefined), delayMs: 1_000 }, {});
|
|
135
152
|
}
|
|
136
|
-
if (signal?.aborted)
|
|
137
|
-
return stop;
|
|
138
|
-
signal?.addEventListener("abort", stop);
|
|
139
|
-
open();
|
|
140
|
-
// Polling also covers an attempt that dies before a first frame/connection error arrives.
|
|
141
|
-
stopTimer = ports.schedule({ work: () => void read().catch(() => undefined), delayMs: 1_000 }, {});
|
|
142
153
|
return stop;
|
|
143
154
|
}
|
|
144
155
|
//# sourceMappingURL=durable-run-subscription.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Daemon/BYOK/AG-UI chat client lifecycles. Host routes, identity and authenticated I/O are ports. */
|
|
2
2
|
export { createAssistantTransportClient } from "./transport.js";
|
|
3
3
|
export type { AssistantTransportPorts, AssistantTransportOptions, AssistantTransportClient, ByokFrameContext, ByokStreamContext } from "./transport.js";
|
|
4
|
-
export type { AgUiClient, AgUiClientPorts, AgUiRunClient, AgUiEventContext } from "./ag-ui-transport.js";
|
|
4
|
+
export type { AgUiClient, AgUiClientPorts, AgUiRunClient, AgUiEventContext, AgUiDurableLocalCliBinding, AgUiDurableStart, AcceptedAgUiRun, LocalRunLaunch } from "./ag-ui-transport.js";
|
|
5
5
|
export { followDurableRun } from "./durable-run-subscription.js";
|
|
6
6
|
export type { DurableRunBinding, DurableSubscriptionPorts } from "./durable-run-subscription.js";
|
|
7
7
|
export { activeRunStub, messageWriteKey, persistableMessages, createConditionalHistoryRead } from "./messages.js";
|
|
@@ -10,4 +10,5 @@ export { createChatAttachmentValidator } from "./attachment-liveness.js";
|
|
|
10
10
|
export type { ChatAttachmentValidatorInput, ChatAttachmentValidatorOptions } from "./attachment-liveness.js";
|
|
11
11
|
export { createA2uiActionPoster } from "./a2ui-action-poster.js";
|
|
12
12
|
export type { A2uiActionPosterInput, CreateA2uiActionPosterOptions, A2uiActionDeliveryOutcome } from "./a2ui-action-poster.js";
|
|
13
|
+
export { browserDurableSubscriptionPorts, browserTimeoutSchedule } from "./browser-durable-subscription.js";
|
|
13
14
|
//# sourceMappingURL=entry.d.ts.map
|
|
@@ -4,4 +4,5 @@ export { followDurableRun } from "./durable-run-subscription.js";
|
|
|
4
4
|
export { activeRunStub, messageWriteKey, persistableMessages, createConditionalHistoryRead } from "./messages.js";
|
|
5
5
|
export { createChatAttachmentValidator } from "./attachment-liveness.js";
|
|
6
6
|
export { createA2uiActionPoster } from "./a2ui-action-poster.js";
|
|
7
|
+
export { browserDurableSubscriptionPorts, browserTimeoutSchedule } from "./browser-durable-subscription.js";
|
|
7
8
|
//# sourceMappingURL=entry.js.map
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { ChatMessage } from "../messages.js";
|
|
2
|
+
import type { StartRunInput } from "../transport.js";
|
|
3
|
+
/**
|
|
4
|
+
* The prompt for one run: the whole conversation so far, not just the newest message.
|
|
5
|
+
*
|
|
6
|
+
* This used to send only the latest user turn, which is why the assistant appeared to have no
|
|
7
|
+
* memory — ask it something, then ask a follow-up, and the second run had never seen the first.
|
|
8
|
+
* That looked like a missing capability and was not: `ChatPane` hands the full history to every
|
|
9
|
+
* `startRun`, and it was being discarded here, in the browser, before the request was even built.
|
|
10
|
+
* Nothing server-side had to change.
|
|
11
|
+
*
|
|
12
|
+
* `buildTranscript` rather than a hand-rolled join, because flattening a transcript has more edges
|
|
13
|
+
* than it first appears: it truncates any single oversized message, escapes `## user`/`## assistant`
|
|
14
|
+
* inside message bodies so a user cannot forge a turn boundary by pasting one, summarizes persisted
|
|
15
|
+
* artifacts instead of replaying them, and prepends a warning when prior-run telemetry shows the
|
|
16
|
+
* context was already large. Every admin turn cold-boots a fresh CLI subprocess, so the transcript
|
|
17
|
+
* IS the memory — and the same property makes an unbounded one expensive.
|
|
18
|
+
*
|
|
19
|
+
* Bounded deliberately: each run is billed, and an unbounded transcript grows the input cost of
|
|
20
|
+
* every subsequent turn in a conversation that has no natural end. {@link MAX_TRANSCRIPT_TURNS}
|
|
21
|
+
* keeps a long-running chat from silently becoming the most expensive thing in the product.
|
|
22
|
+
* Failed turns are labeled outcomes so another agent can explain and recover from them.
|
|
23
|
+
*/
|
|
24
|
+
export declare function runPrompt({ history }: {
|
|
25
|
+
history: StartRunInput["history"];
|
|
26
|
+
}, _optional?: Record<string, never>): string;
|
|
27
|
+
/**
|
|
28
|
+
* The history a transcript may be built from: every user turn, and only those assistant turns the
|
|
29
|
+
* agent actually answered.
|
|
30
|
+
*
|
|
31
|
+
* Defect 3 of the 2026-09-11 chat-lifecycle repair. `ai_chat_messages` in
|
|
32
|
+
* the investigated host's `chat.db` holds assistant rows with `run_status='failed'` and
|
|
33
|
+
* `length(content)=0` — the durable trace of a run that died before writing a token. Replayed
|
|
34
|
+
* through `buildTranscript` they become a `## assistant` block with nothing under it: the next run
|
|
35
|
+
* is told the agent replied when what actually happened is that it died, and a failure the user can
|
|
36
|
+
* see in the pane is laundered into an empty answer in the model's context.
|
|
37
|
+
*
|
|
38
|
+
* The rows themselves are deliberately NOT deleted, and this is the fix instead: their
|
|
39
|
+
* `events_json` carries the only surviving record of why the run failed (exit code, signal, the
|
|
40
|
+
* CLI's own stderr), the daemon's event log is in-memory and gone, and the pane renders that notice
|
|
41
|
+
* on reload. Partial output from a failed run stays stored as partial output for the same reason —
|
|
42
|
+
* it is visible to the user, and it is not the agent's answer, so it does not go back into a prompt.
|
|
43
|
+
*
|
|
44
|
+
* @param history - The pane's transcript, oldest first.
|
|
45
|
+
* @returns A new array; the input is never mutated.
|
|
46
|
+
* @complexity O(n) in history length, one pass, no allocation per message.
|
|
47
|
+
*/
|
|
48
|
+
export declare function historyForTranscript({ history }: {
|
|
49
|
+
history: readonly ChatMessage[];
|
|
50
|
+
}, _optional?: Record<string, never>): ChatMessage[];
|
|
51
|
+
/**
|
|
52
|
+
* The user text a run must carry when the agent carries its own conversation memory: every user
|
|
53
|
+
* turn since the last one the agent actually answered, not only the newest.
|
|
54
|
+
*
|
|
55
|
+
* Defect 2 of the 2026-09-11 chat-lifecycle repair, and the half of it that was actually lossy. In
|
|
56
|
+
* the investigated host's `chat.db` conversation `9289701c-…`, position 5's user text is present in
|
|
57
|
+
* `ai_chat_messages` and absent from every agent-session transcript: the run meant to answer it
|
|
58
|
+
* failed 140 ms after start, so no CLI ever read it — and because
|
|
59
|
+
* {@link resolveLocalCliPrompt} sends only the NEWEST user turn to a resume-capable agent, no later
|
|
60
|
+
* turn ever carried it either. The message was durable the whole time and still lost, permanently,
|
|
61
|
+
* with nothing anywhere saying so.
|
|
62
|
+
*
|
|
63
|
+
* Re-delivering costs a duplicate whenever the CLI did read the prompt before dying, which the
|
|
64
|
+
* agent can reconcile from its own session. Not re-delivering costs the user a message with no
|
|
65
|
+
* trace. The two are not symmetric, so this errs toward the duplicate.
|
|
66
|
+
*
|
|
67
|
+
* @param history - The pane's transcript, oldest first.
|
|
68
|
+
* @returns The prompt text — the bare newest turn in the ordinary case (the previous turn was
|
|
69
|
+
* answered), or the unanswered turns joined oldest-first behind {@link UNDELIVERED_TURNS_NOTE}.
|
|
70
|
+
* Falls back to the newest user turn when the history ends in an answered assistant turn and
|
|
71
|
+
* there is therefore nothing pending.
|
|
72
|
+
* @complexity O(n) in history length — one forward scan for the boundary plus one slice/filter over
|
|
73
|
+
* the tail. A backwards scan with an early exit would be O(1) in practice but needs `break`, and
|
|
74
|
+
* `n` here is bounded by one conversation's transcript; this is not a hot path (once per turn).
|
|
75
|
+
* The result is capped at {@link MAX_TRANSCRIPT_TURNS} for the pathological case of a
|
|
76
|
+
* conversation whose every run has failed.
|
|
77
|
+
*/
|
|
78
|
+
export declare function undeliveredUserPrompt({ history }: {
|
|
79
|
+
history: readonly ChatMessage[];
|
|
80
|
+
}, _optional?: Record<string, never>): string;
|
|
81
|
+
/** Send a resumed agent only its unseen conversation tail, retaining other agents' outcomes.
|
|
82
|
+
* Legacy rows without agent identity retain the existing unanswered-user delivery contract.
|
|
83
|
+
* @complexity O(n) to find the last answered turn; transcript rendering is capped at 40 turns.
|
|
84
|
+
*/
|
|
85
|
+
export declare function resolveLocalCliPrompt({ input, resumeCapableAgentIds }: {
|
|
86
|
+
input: StartRunInput;
|
|
87
|
+
resumeCapableAgentIds: ReadonlySet<string> | undefined;
|
|
88
|
+
}, _optional?: Record<string, never>): string;
|
|
89
|
+
/** The newest `role: "user"` message in a history, or `undefined` when it has none.
|
|
90
|
+
* @complexity O(n) in history length. */
|
|
91
|
+
export declare function newestUserMessage({ history }: {
|
|
92
|
+
history: readonly ChatMessage[];
|
|
93
|
+
}, _optional: Record<string, never>): ChatMessage | undefined;
|
|
94
|
+
//# sourceMappingURL=transport-prompt.d.ts.map
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { buildTranscript, latestUserPromptFromHistory } from "../transcript.js";
|
|
2
|
+
/**
|
|
3
|
+
* How many trailing messages of a conversation go to the agent.
|
|
4
|
+
*
|
|
5
|
+
* A cap rather than none: each turn cold-boots a fresh subprocess and pays for its whole input, so
|
|
6
|
+
* an uncapped transcript makes every message in a long chat more expensive than the last. 40 is
|
|
7
|
+
* roughly 20 exchanges — beyond what a working session usually needs to stay coherent, and far
|
|
8
|
+
* short of where input cost starts to dominate. `buildTranscript` separately truncates any single
|
|
9
|
+
* oversized message, so this bounds the number of turns, not their size.
|
|
10
|
+
*/
|
|
11
|
+
const MAX_TRANSCRIPT_TURNS = 40;
|
|
12
|
+
/**
|
|
13
|
+
* The prompt for one run: the whole conversation so far, not just the newest message.
|
|
14
|
+
*
|
|
15
|
+
* This used to send only the latest user turn, which is why the assistant appeared to have no
|
|
16
|
+
* memory — ask it something, then ask a follow-up, and the second run had never seen the first.
|
|
17
|
+
* That looked like a missing capability and was not: `ChatPane` hands the full history to every
|
|
18
|
+
* `startRun`, and it was being discarded here, in the browser, before the request was even built.
|
|
19
|
+
* Nothing server-side had to change.
|
|
20
|
+
*
|
|
21
|
+
* `buildTranscript` rather than a hand-rolled join, because flattening a transcript has more edges
|
|
22
|
+
* than it first appears: it truncates any single oversized message, escapes `## user`/`## assistant`
|
|
23
|
+
* inside message bodies so a user cannot forge a turn boundary by pasting one, summarizes persisted
|
|
24
|
+
* artifacts instead of replaying them, and prepends a warning when prior-run telemetry shows the
|
|
25
|
+
* context was already large. Every admin turn cold-boots a fresh CLI subprocess, so the transcript
|
|
26
|
+
* IS the memory — and the same property makes an unbounded one expensive.
|
|
27
|
+
*
|
|
28
|
+
* Bounded deliberately: each run is billed, and an unbounded transcript grows the input cost of
|
|
29
|
+
* every subsequent turn in a conversation that has no natural end. {@link MAX_TRANSCRIPT_TURNS}
|
|
30
|
+
* keeps a long-running chat from silently becoming the most expensive thing in the product.
|
|
31
|
+
* Failed turns are labeled outcomes so another agent can explain and recover from them.
|
|
32
|
+
*/
|
|
33
|
+
export function runPrompt({ history }, _optional = {}) {
|
|
34
|
+
const recent = history.slice(-MAX_TRANSCRIPT_TURNS).map(message => {
|
|
35
|
+
if (message.role !== 'assistant' || isAnsweredAssistantTurn(message))
|
|
36
|
+
return message;
|
|
37
|
+
const detail = message.events?.filter(event => event.kind === 'status')
|
|
38
|
+
.map(event => [event.label, event.detail].filter(Boolean).join(': ')).join('\n').slice(-4000);
|
|
39
|
+
// Reserve space for the failure reason even when partial output fills the transcript cap.
|
|
40
|
+
const outcome = [message.content.slice(0, 6000), detail].filter(Boolean).join('\n\n');
|
|
41
|
+
return { ...message, content: `[${message.agentName ?? message.agentId ?? 'Assistant'} run ${message.runStatus}; not a completed answer]\n${outcome || 'No assistant reply was produced.'}` };
|
|
42
|
+
});
|
|
43
|
+
return buildTranscript({ history: recent });
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Whether an assistant message represents a turn the agent actually answered — the single
|
|
47
|
+
* definition both {@link historyForTranscript} and {@link undeliveredUserPrompt} key off.
|
|
48
|
+
*
|
|
49
|
+
* `undefined` counts as answered: rows written before `ai_chat_messages.run_status` existed carry
|
|
50
|
+
* no status at all, and treating those as unanswered would re-send the whole history of every
|
|
51
|
+
* legacy conversation on its next turn. Every non-`succeeded` status counts as unanswered —
|
|
52
|
+
* `failed` and `canceled` obviously, and `queued`/`running` because a run killed mid-flight (a
|
|
53
|
+
* daemon respawn, see `daemon-supervisor.ts`) never reaches a terminal status at all and leaves
|
|
54
|
+
* exactly such a row behind.
|
|
55
|
+
*
|
|
56
|
+
* Do not "simplify" this away by deleting the failed rows at the source instead. That was the first
|
|
57
|
+
* shape proposed for this fix and it is the wrong trade: `run_status='failed'` was ALREADY the
|
|
58
|
+
* explicit failed state, and the only thing missing was somewhere that skips it. The row's
|
|
59
|
+
* `events_json` is the sole durable record of why a run died (exit code, signal, the CLI's own
|
|
60
|
+
* stderr) once the daemon's in-memory event log is gone, and the pane renders it on reload — so
|
|
61
|
+
* dropping the row trades a history bug for a forensics hole. The skip belongs here, on the read
|
|
62
|
+
* side. The transcript's hidden-tool mode likewise filters only recovered tool failures and keeps
|
|
63
|
+
* unrecovered failures behind a compact disclosure; it never deletes this durable evidence.
|
|
64
|
+
* See {@link historyForTranscript} and `assistant-chats.ts`'s `persistableMessages`.
|
|
65
|
+
*/
|
|
66
|
+
function isAnsweredAssistantTurn(message) {
|
|
67
|
+
return message.runStatus === undefined || message.runStatus === "succeeded";
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The history a transcript may be built from: every user turn, and only those assistant turns the
|
|
71
|
+
* agent actually answered.
|
|
72
|
+
*
|
|
73
|
+
* Defect 3 of the 2026-09-11 chat-lifecycle repair. `ai_chat_messages` in
|
|
74
|
+
* the investigated host's `chat.db` holds assistant rows with `run_status='failed'` and
|
|
75
|
+
* `length(content)=0` — the durable trace of a run that died before writing a token. Replayed
|
|
76
|
+
* through `buildTranscript` they become a `## assistant` block with nothing under it: the next run
|
|
77
|
+
* is told the agent replied when what actually happened is that it died, and a failure the user can
|
|
78
|
+
* see in the pane is laundered into an empty answer in the model's context.
|
|
79
|
+
*
|
|
80
|
+
* The rows themselves are deliberately NOT deleted, and this is the fix instead: their
|
|
81
|
+
* `events_json` carries the only surviving record of why the run failed (exit code, signal, the
|
|
82
|
+
* CLI's own stderr), the daemon's event log is in-memory and gone, and the pane renders that notice
|
|
83
|
+
* on reload. Partial output from a failed run stays stored as partial output for the same reason —
|
|
84
|
+
* it is visible to the user, and it is not the agent's answer, so it does not go back into a prompt.
|
|
85
|
+
*
|
|
86
|
+
* @param history - The pane's transcript, oldest first.
|
|
87
|
+
* @returns A new array; the input is never mutated.
|
|
88
|
+
* @complexity O(n) in history length, one pass, no allocation per message.
|
|
89
|
+
*/
|
|
90
|
+
export function historyForTranscript({ history }, _optional = {}) {
|
|
91
|
+
return history.filter((message) => message.role !== "assistant" || isAnsweredAssistantTurn(message));
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Prepended when more than one user turn is being sent at once, so the agent is not told the user
|
|
95
|
+
* typed all of it just now. Deliberately absent from the single-turn case — a note on every
|
|
96
|
+
* ordinary message would be a standing lie in the prompt of every turn in every conversation.
|
|
97
|
+
*/
|
|
98
|
+
const UNDELIVERED_TURNS_NOTE = "[Some of the messages below never reached you: the run that should have answered them failed before it could. Treat them as the user's own words, in order, and answer all of them.]";
|
|
99
|
+
/**
|
|
100
|
+
* The user text a run must carry when the agent carries its own conversation memory: every user
|
|
101
|
+
* turn since the last one the agent actually answered, not only the newest.
|
|
102
|
+
*
|
|
103
|
+
* Defect 2 of the 2026-09-11 chat-lifecycle repair, and the half of it that was actually lossy. In
|
|
104
|
+
* the investigated host's `chat.db` conversation `9289701c-…`, position 5's user text is present in
|
|
105
|
+
* `ai_chat_messages` and absent from every agent-session transcript: the run meant to answer it
|
|
106
|
+
* failed 140 ms after start, so no CLI ever read it — and because
|
|
107
|
+
* {@link resolveLocalCliPrompt} sends only the NEWEST user turn to a resume-capable agent, no later
|
|
108
|
+
* turn ever carried it either. The message was durable the whole time and still lost, permanently,
|
|
109
|
+
* with nothing anywhere saying so.
|
|
110
|
+
*
|
|
111
|
+
* Re-delivering costs a duplicate whenever the CLI did read the prompt before dying, which the
|
|
112
|
+
* agent can reconcile from its own session. Not re-delivering costs the user a message with no
|
|
113
|
+
* trace. The two are not symmetric, so this errs toward the duplicate.
|
|
114
|
+
*
|
|
115
|
+
* @param history - The pane's transcript, oldest first.
|
|
116
|
+
* @returns The prompt text — the bare newest turn in the ordinary case (the previous turn was
|
|
117
|
+
* answered), or the unanswered turns joined oldest-first behind {@link UNDELIVERED_TURNS_NOTE}.
|
|
118
|
+
* Falls back to the newest user turn when the history ends in an answered assistant turn and
|
|
119
|
+
* there is therefore nothing pending.
|
|
120
|
+
* @complexity O(n) in history length — one forward scan for the boundary plus one slice/filter over
|
|
121
|
+
* the tail. A backwards scan with an early exit would be O(1) in practice but needs `break`, and
|
|
122
|
+
* `n` here is bounded by one conversation's transcript; this is not a hot path (once per turn).
|
|
123
|
+
* The result is capped at {@link MAX_TRANSCRIPT_TURNS} for the pathological case of a
|
|
124
|
+
* conversation whose every run has failed.
|
|
125
|
+
*/
|
|
126
|
+
export function undeliveredUserPrompt({ history }, _optional = {}) {
|
|
127
|
+
// `Array.prototype.findLastIndex` would say this in one call, but it is ES2023 and the
|
|
128
|
+
// supported target is ES2022, so the index is accumulated instead.
|
|
129
|
+
let lastAnsweredIndex = -1;
|
|
130
|
+
history.forEach((message, position) => {
|
|
131
|
+
if (message.role === "assistant" && isAnsweredAssistantTurn(message))
|
|
132
|
+
lastAnsweredIndex = position;
|
|
133
|
+
});
|
|
134
|
+
const pending = history
|
|
135
|
+
.slice(lastAnsweredIndex + 1)
|
|
136
|
+
.filter((message) => message.role === "user")
|
|
137
|
+
.slice(-MAX_TRANSCRIPT_TURNS);
|
|
138
|
+
if (pending.length === 0)
|
|
139
|
+
return latestUserPromptFromHistory({ history: history });
|
|
140
|
+
const newest = pending[pending.length - 1];
|
|
141
|
+
const newestText = newest.content.trim();
|
|
142
|
+
const newestAttachmentRefs = JSON.stringify((newest.attachments ?? []).map((attachment) => attachment.path));
|
|
143
|
+
// Collapse resends of the newest text with matching attachment refs: a retry is one request.
|
|
144
|
+
const distinct = pending.filter((message, index) => index === pending.length - 1
|
|
145
|
+
|| message.content.trim() !== newestText
|
|
146
|
+
|| JSON.stringify((message.attachments ?? []).map((attachment) => attachment.path)) !== newestAttachmentRefs)
|
|
147
|
+
.map((message) => message.content);
|
|
148
|
+
if (distinct.length === 1)
|
|
149
|
+
return distinct[0];
|
|
150
|
+
return `${UNDELIVERED_TURNS_NOTE}\n\n${distinct.join("\n\n")}`;
|
|
151
|
+
}
|
|
152
|
+
/** Send a resumed agent only its unseen conversation tail, retaining other agents' outcomes.
|
|
153
|
+
* Legacy rows without agent identity retain the existing unanswered-user delivery contract.
|
|
154
|
+
* @complexity O(n) to find the last answered turn; transcript rendering is capped at 40 turns.
|
|
155
|
+
*/
|
|
156
|
+
export function resolveLocalCliPrompt({ input, resumeCapableAgentIds }, _optional = {}) {
|
|
157
|
+
const carriesOwnMemory = input.agentId !== undefined && resumeCapableAgentIds?.has(input.agentId) === true;
|
|
158
|
+
if (!carriesOwnMemory)
|
|
159
|
+
return runPrompt({ history: input.history });
|
|
160
|
+
let lastOwnAnswer = -1;
|
|
161
|
+
input.history.forEach((message, index) => {
|
|
162
|
+
if (message.role === 'assistant' && (!message.agentId || message.agentId === input.agentId) && isAnsweredAssistantTurn(message))
|
|
163
|
+
lastOwnAnswer = index;
|
|
164
|
+
});
|
|
165
|
+
const unseen = input.history.slice(lastOwnAnswer + 1);
|
|
166
|
+
const crossedAgents = unseen.some(message => message.role === 'assistant' && message.agentId && message.agentId !== input.agentId);
|
|
167
|
+
// BEHAVIOR CHANGE (2026-09-11, Defect 2): the resume-capable branch was `latestUserPrompt` — the
|
|
168
|
+
// single newest user turn, on the assumption that everything before it is already inside the
|
|
169
|
+
// CLI's own session. That assumption holds only for turns the agent actually answered; a turn
|
|
170
|
+
// whose run died before the CLI read its prompt is in neither place, and nothing ever sent it
|
|
171
|
+
// again. `undeliveredUserPrompt` returns the identical single string in the ordinary case and
|
|
172
|
+
// differs only when there is genuinely something unanswered to catch up on.
|
|
173
|
+
return crossedAgents ? runPrompt({ history: unseen }) : undeliveredUserPrompt({ history: input.history });
|
|
174
|
+
}
|
|
175
|
+
/** The newest `role: "user"` message in a history, or `undefined` when it has none.
|
|
176
|
+
* @complexity O(n) in history length. */
|
|
177
|
+
export function newestUserMessage({ history }, _optional) {
|
|
178
|
+
return [...history].reverse().find((message) => message.role === "user");
|
|
179
|
+
}
|
|
180
|
+
//# sourceMappingURL=transport-prompt.js.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { RunHandlers, StartRunInput } from "../transport.js";
|
|
2
|
+
import { type TransportCtx } from "./transport-stream.js";
|
|
3
|
+
import type { AssistantTransportOptions } from "./transport.js";
|
|
4
|
+
/**
|
|
5
|
+
* The error for a refused request: `<action> (<status>)`, plus up to 300 characters of the
|
|
6
|
+
* response body when it has one — shared by the BYOK start, Local CLI start and cancel refusals.
|
|
7
|
+
*/
|
|
8
|
+
export declare function refusalError({ action, response }: {
|
|
9
|
+
action: string;
|
|
10
|
+
response: Response;
|
|
11
|
+
}, _optional: Record<string, never>): Promise<Error>;
|
|
12
|
+
/**
|
|
13
|
+
* Assembles the Local CLI path's `contextRef` — everything `startRun`'s daemon branch sends besides
|
|
14
|
+
* `agentId` itself. Pulled out of `startRun` (2026-08-06, complexity pass, second pass) as its own
|
|
15
|
+
* pure function, then split again (2026-09-04, complexity pass) into one pure field-helper per
|
|
16
|
+
* optional field, each above: six independent, unrelated fields, none sharing state or order
|
|
17
|
+
* dependence, each read from `input` by name and included only when present (see each helper's own
|
|
18
|
+
* doc for why). Kept as six separate functions rather than grouped, on purpose — the fields have no
|
|
19
|
+
* conceptual relationship to group them by (identity, execution config, and content all mixed
|
|
20
|
+
* together), and inventing a grouping would obscure the very independence each field's own doc
|
|
21
|
+
* argues for. A plain object in, a plain object out — directly testable with a `StartRunInput`
|
|
22
|
+
* fixture, no `fetch`/`EventSource` involved.
|
|
23
|
+
*
|
|
24
|
+
* @param prompt - The already-built transcript string ({@link runPrompt}'s result) — this function
|
|
25
|
+
* only decides which of the six OPTIONAL fields ride alongside it, not how the prompt itself is
|
|
26
|
+
* built.
|
|
27
|
+
* @param resolvedConversationId - {@link resolveRunConversationId}'s answer, when `startRun` had to
|
|
28
|
+
* adopt a conversation because `input.context` named none (the first turn of a chat). Omitted by
|
|
29
|
+
* every caller that already has an id on `input.context`, and by this function's own unit tests —
|
|
30
|
+
* in which case the `context` field is read exactly as before.
|
|
31
|
+
* The bounded `coldStartContext` is the complete prompt, including the current request. The
|
|
32
|
+
* daemon selects it instead of the resume tail when native resume is unavailable.
|
|
33
|
+
*/
|
|
34
|
+
export declare function buildLocalCliContextRef({ transport, input, prompt, resolvedConversationId }: {
|
|
35
|
+
transport: TransportCtx;
|
|
36
|
+
input: StartRunInput;
|
|
37
|
+
prompt: string;
|
|
38
|
+
resolvedConversationId?: string | undefined;
|
|
39
|
+
}, _optional?: Record<string, never>): Record<string, unknown>;
|
|
40
|
+
export declare function startTransportRun({ transport, input: startInput, handlers }: {
|
|
41
|
+
transport: TransportCtx;
|
|
42
|
+
input: StartRunInput;
|
|
43
|
+
handlers: RunHandlers;
|
|
44
|
+
}, { options }?: {
|
|
45
|
+
options?: AssistantTransportOptions;
|
|
46
|
+
}): Promise<{
|
|
47
|
+
runId: string;
|
|
48
|
+
}>;
|
|
49
|
+
//# sourceMappingURL=transport-run.d.ts.map
|