@assistant-ui/core 0.3.14 → 0.3.15
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/dist/adapters/voice.js +11 -0
- package/dist/adapters/voice.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/internal.d.ts +2 -1
- package/dist/internal.js +2 -1
- package/dist/model-context/frame/host.d.ts +1 -1
- package/dist/model-context/frame/host.d.ts.map +1 -1
- package/dist/model-context/frame/host.js +17 -3
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/frame/provider.d.ts +4 -0
- package/dist/model-context/frame/provider.d.ts.map +1 -1
- package/dist/model-context/frame/provider.js +50 -3
- package/dist/model-context/frame/provider.js.map +1 -1
- package/dist/model-context/frame/types.d.ts +4 -1
- package/dist/model-context/frame/types.d.ts.map +1 -1
- package/dist/model-context/frame/types.js.map +1 -1
- package/dist/react/client/RemoteThreadList.d.ts +1 -1
- package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
- package/dist/react/client/RemoteThreadList.js +95 -23
- package/dist/react/client/RemoteThreadList.js.map +1 -1
- package/dist/react/primitive-hooks/useActionBarCopy.js +7 -1
- package/dist/react/primitive-hooks/useActionBarCopy.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadIsEmpty.d.ts +3 -0
- package/dist/react/primitive-hooks/useThreadIsEmpty.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useThreadIsEmpty.js +3 -0
- package/dist/react/primitive-hooks/useThreadIsEmpty.js.map +1 -1
- package/dist/react/primitive-hooks/useThreadIsRunning.d.ts +3 -0
- package/dist/react/primitive-hooks/useThreadIsRunning.d.ts.map +1 -1
- package/dist/react/primitive-hooks/useThreadIsRunning.js +3 -0
- package/dist/react/primitive-hooks/useThreadIsRunning.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts +2 -0
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +6 -0
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +6 -0
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +192 -50
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadResource.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadResource.js +2 -0
- package/dist/react/runtimes/RemoteThreadResource.js.map +1 -1
- package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.d.ts.map +1 -1
- package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.js +1 -1
- package/dist/react/runtimes/assistant-transport/useAssistantTransportRuntime.js.map +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js +38 -5
- package/dist/react/runtimes/cloud/useCloudThreadListAdapter.js.map +1 -1
- package/dist/runtime/utils/message-repository.d.ts.map +1 -1
- package/dist/runtime/utils/message-repository.js +27 -18
- package/dist/runtime/utils/message-repository.js.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js +2 -0
- package/dist/runtimes/external-store/external-store-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/inert/InertThreadRuntimeCore.d.ts +102 -0
- package/dist/runtimes/inert/InertThreadRuntimeCore.d.ts.map +1 -0
- package/dist/runtimes/inert/InertThreadRuntimeCore.js +156 -0
- package/dist/runtimes/inert/InertThreadRuntimeCore.js.map +1 -0
- package/dist/runtimes/local/local-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/local/local-thread-runtime-core.js +25 -6
- package/dist/runtimes/local/local-thread-runtime-core.js.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts +12 -60
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.d.ts.map +1 -1
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js +10 -145
- package/dist/runtimes/readonly/ReadonlyThreadRuntimeCore.js.map +1 -1
- package/dist/runtimes/remote-thread-list/adapter-changed.d.ts +9 -0
- package/dist/runtimes/remote-thread-list/adapter-changed.d.ts.map +1 -0
- package/dist/runtimes/remote-thread-list/adapter-changed.js +13 -0
- package/dist/runtimes/remote-thread-list/adapter-changed.js.map +1 -0
- package/dist/runtimes/remote-thread-list/empty-thread-core.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/empty-thread-core.js +16 -155
- package/dist/runtimes/remote-thread-list/empty-thread-core.js.map +1 -1
- package/dist/runtimes/remote-thread-list/optimistic-state.d.ts +2 -0
- package/dist/runtimes/remote-thread-list/optimistic-state.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/optimistic-state.js +11 -0
- package/dist/runtimes/remote-thread-list/optimistic-state.js.map +1 -1
- package/dist/runtimes/remote-thread-list/types.d.ts +3 -0
- package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
- package/dist/store/clients/external-thread.js +1 -1
- package/dist/store/clients/external-thread.js.map +1 -1
- package/dist/store/runtime-clients/handle-runtime-action.d.ts.map +1 -1
- package/dist/store/runtime-clients/handle-runtime-action.js +2 -0
- package/dist/store/runtime-clients/handle-runtime-action.js.map +1 -1
- package/dist/types/message.d.ts +1 -1
- package/dist/types/message.js.map +1 -1
- package/dist/utils/silent-runtime-action.d.ts +6 -0
- package/dist/utils/silent-runtime-action.d.ts.map +1 -0
- package/dist/utils/silent-runtime-action.js +7 -0
- package/dist/utils/silent-runtime-action.js.map +1 -0
- package/package.json +4 -4
- package/src/adapters/voice.test.ts +66 -1
- package/src/adapters/voice.ts +8 -0
- package/src/internal.ts +1 -0
- package/src/model-context/frame/host.test.ts +64 -5
- package/src/model-context/frame/host.ts +16 -3
- package/src/model-context/frame/provider.test.ts +347 -20
- package/src/model-context/frame/provider.ts +58 -2
- package/src/model-context/frame/types.ts +5 -0
- package/src/react/client/RemoteThreadList.test.ts +196 -0
- package/src/react/client/RemoteThreadList.ts +93 -24
- package/src/react/primitive-hooks/useActionBarCopy.test.ts +15 -0
- package/src/react/primitive-hooks/useActionBarCopy.ts +13 -3
- package/src/react/primitive-hooks/useThreadIsEmpty.ts +3 -0
- package/src/react/primitive-hooks/useThreadIsRunning.ts +3 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +12 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.republish.test.ts +87 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +268 -63
- package/src/react/runtimes/RemoteThreadResource.ts +2 -0
- package/src/react/runtimes/assistant-transport/useAssistantTransportRuntime.test.tsx +58 -0
- package/src/react/runtimes/assistant-transport/useAssistantTransportRuntime.ts +3 -1
- package/src/react/runtimes/cloud/useCloudThreadListAdapter.test.tsx +98 -3
- package/src/react/runtimes/cloud/useCloudThreadListAdapter.tsx +68 -6
- package/src/react/runtimes/useLocalRuntime.test.tsx +5 -5
- package/src/runtime/utils/message-repository.ts +26 -18
- package/src/runtimes/external-store/external-store-thread-runtime-core.ts +4 -0
- package/src/runtimes/inert/InertThreadRuntimeCore.test.ts +253 -0
- package/src/runtimes/inert/InertThreadRuntimeCore.ts +232 -0
- package/src/runtimes/local/local-thread-runtime-core.test.ts +319 -0
- package/src/runtimes/local/local-thread-runtime-core.ts +38 -8
- package/src/runtimes/readonly/ReadonlyThreadRuntimeCore.ts +17 -209
- package/src/runtimes/remote-thread-list/adapter-changed.ts +10 -0
- package/src/runtimes/remote-thread-list/empty-thread-core.ts +28 -221
- package/src/runtimes/remote-thread-list/optimistic-state.test.ts +18 -0
- package/src/runtimes/remote-thread-list/optimistic-state.ts +13 -0
- package/src/runtimes/remote-thread-list/types.ts +4 -0
- package/src/store/clients/external-thread.ts +1 -1
- package/src/store/runtime-clients/handle-runtime-action.test.ts +40 -0
- package/src/store/runtime-clients/handle-runtime-action.ts +3 -0
- package/src/tests/MessageRepository.test.ts +48 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-errors.test.ts +2 -2
- package/src/tests/RemoteThreadListThreadListRuntimeCore-loadMore.test.ts +8 -6
- package/src/tests/empty-thread-core.test.ts +6 -0
- package/src/tests/external-store-thread-runtime-core-adapter.test.ts +20 -0
- package/src/tests/external-thread-isEmpty.test.tsx +100 -0
- package/src/tests/remote-thread-list-adapter-switch.test.ts +383 -0
- package/src/tests/useRemoteThreadListRuntime-controlled.test.tsx +67 -0
- package/src/types/message.ts +1 -1
- package/src/utils/silent-runtime-action.ts +6 -0
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { ThreadMessage } from "../../types/message.js";
|
|
2
|
+
import { Unsubscribe } from "../../types/unsubscribe.js";
|
|
3
|
+
import { ExportedMessageRepository } from "../../runtime/utils/message-repository.js";
|
|
4
|
+
import { ThreadRuntimeCore } from "../../runtime/interfaces/thread-runtime-core.js";
|
|
5
|
+
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
6
|
+
//#region src/runtimes/inert/InertThreadRuntimeCore.d.ts
|
|
7
|
+
declare const createInertComposer: <TIsEditing extends boolean>(error: Error, isEditing: TIsEditing) => {
|
|
8
|
+
attachments: never[];
|
|
9
|
+
attachmentAccept: string;
|
|
10
|
+
addAttachment(): Promise<never>;
|
|
11
|
+
removeAttachment(): Promise<never>;
|
|
12
|
+
isEditing: TIsEditing;
|
|
13
|
+
canCancel: boolean;
|
|
14
|
+
canSend: boolean;
|
|
15
|
+
isEmpty: boolean;
|
|
16
|
+
text: string;
|
|
17
|
+
setText(): never;
|
|
18
|
+
role: "user";
|
|
19
|
+
setRole(): never;
|
|
20
|
+
runConfig: {};
|
|
21
|
+
setRunConfig(): never;
|
|
22
|
+
reset(): Promise<void>;
|
|
23
|
+
clearAttachments(): Promise<void>;
|
|
24
|
+
send(): never;
|
|
25
|
+
cancel(): void;
|
|
26
|
+
queue: never[];
|
|
27
|
+
moveQueueItem(): void;
|
|
28
|
+
removeQueueItem(): void;
|
|
29
|
+
dictation: undefined;
|
|
30
|
+
startDictation(): never;
|
|
31
|
+
stopDictation(): void;
|
|
32
|
+
quote: undefined;
|
|
33
|
+
setQuote(): never;
|
|
34
|
+
subscribe(): () => void;
|
|
35
|
+
unstable_on(): () => void;
|
|
36
|
+
};
|
|
37
|
+
declare abstract class InertThreadRuntimeCore extends BaseSubscribable implements ThreadRuntimeCore {
|
|
38
|
+
protected abstract get error(): Error;
|
|
39
|
+
abstract readonly messages: readonly ThreadMessage[];
|
|
40
|
+
abstract readonly isLoading: boolean;
|
|
41
|
+
abstract readonly composer: ThreadRuntimeCore["composer"];
|
|
42
|
+
abstract getMessageById(messageId: string): {
|
|
43
|
+
parentId: string | null;
|
|
44
|
+
message: ThreadMessage;
|
|
45
|
+
index: number;
|
|
46
|
+
} | undefined;
|
|
47
|
+
abstract getBranches(messageId: string): readonly string[];
|
|
48
|
+
abstract export(): ExportedMessageRepository;
|
|
49
|
+
switchToBranch(): void;
|
|
50
|
+
append(): void;
|
|
51
|
+
deleteMessage(): void;
|
|
52
|
+
startRun(): void;
|
|
53
|
+
resumeRun(): void;
|
|
54
|
+
cancelRun(): void;
|
|
55
|
+
unstable_notifySessionReset(): void;
|
|
56
|
+
addToolResult(): void;
|
|
57
|
+
resumeToolCall(): void;
|
|
58
|
+
respondToToolApproval(): void;
|
|
59
|
+
speak(): void;
|
|
60
|
+
stopSpeaking(): void;
|
|
61
|
+
connectVoice(): void;
|
|
62
|
+
disconnectVoice(): void;
|
|
63
|
+
muteVoice(): void;
|
|
64
|
+
unmuteVoice(): void;
|
|
65
|
+
submitFeedback(): void;
|
|
66
|
+
exportExternalState(): void;
|
|
67
|
+
importExternalState(): void;
|
|
68
|
+
beginEdit(): void;
|
|
69
|
+
import(): void;
|
|
70
|
+
reset(): void;
|
|
71
|
+
getModelContext(): {};
|
|
72
|
+
getEditComposer(): undefined;
|
|
73
|
+
getVoiceVolume: () => number;
|
|
74
|
+
subscribeVoiceVolume: () => Unsubscribe;
|
|
75
|
+
speech: undefined;
|
|
76
|
+
voice: undefined;
|
|
77
|
+
capabilities: {
|
|
78
|
+
readonly switchToBranch: false;
|
|
79
|
+
readonly switchBranchDuringRun: false;
|
|
80
|
+
readonly edit: false;
|
|
81
|
+
readonly delete: false;
|
|
82
|
+
readonly reload: false;
|
|
83
|
+
readonly refetchThread: false;
|
|
84
|
+
readonly cancel: false;
|
|
85
|
+
readonly unstable_copy: false;
|
|
86
|
+
readonly speech: false;
|
|
87
|
+
readonly dictation: false;
|
|
88
|
+
readonly voice: false;
|
|
89
|
+
readonly attachments: false;
|
|
90
|
+
readonly feedback: false;
|
|
91
|
+
readonly queue: false;
|
|
92
|
+
};
|
|
93
|
+
isDisabled: boolean;
|
|
94
|
+
isSendDisabled: boolean;
|
|
95
|
+
state: null;
|
|
96
|
+
suggestions: never[];
|
|
97
|
+
extras: undefined;
|
|
98
|
+
unstable_on(): Unsubscribe;
|
|
99
|
+
}
|
|
100
|
+
//#endregion
|
|
101
|
+
export { InertThreadRuntimeCore, createInertComposer };
|
|
102
|
+
//# sourceMappingURL=InertThreadRuntimeCore.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InertThreadRuntimeCore.d.ts","names":[],"sources":["../../../src/runtimes/inert/InertThreadRuntimeCore.ts"],"mappings":";;;;;;cAMa,sBAAuB,4BAClC,OAAO,OACP,WAAW;EAEQ;;;;;;;;;;;;;;;;;;EA2CN;;;;;;;;;;;uBA2BO,+BACZ,4BACG;yBAEY,SAAS;oBAEd,mBAAmB;oBACnB;oBACA,UAAU;WAEnB,eAAe;IAElB;IACA,SAAS;IACT;;WAIG,YAAY;WAEZ,UAAU;EAEnB;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EAIA;EACA,4BAA2B;EAE3B;EACA;EAEA;;;;;;;;;;;;;;;;EAiBA;EACA;EAEA;EACA;EACA;EAEA,eAAe"}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { BaseSubscribable } from "../../subscribable/subscribable.js";
|
|
2
|
+
//#region src/runtimes/inert/InertThreadRuntimeCore.ts
|
|
3
|
+
const createInertComposer = (error, isEditing) => ({
|
|
4
|
+
attachments: [],
|
|
5
|
+
attachmentAccept: "*",
|
|
6
|
+
async addAttachment() {
|
|
7
|
+
throw error;
|
|
8
|
+
},
|
|
9
|
+
async removeAttachment() {
|
|
10
|
+
throw error;
|
|
11
|
+
},
|
|
12
|
+
isEditing,
|
|
13
|
+
canCancel: false,
|
|
14
|
+
canSend: false,
|
|
15
|
+
isEmpty: true,
|
|
16
|
+
text: "",
|
|
17
|
+
setText() {
|
|
18
|
+
throw error;
|
|
19
|
+
},
|
|
20
|
+
role: "user",
|
|
21
|
+
setRole() {
|
|
22
|
+
throw error;
|
|
23
|
+
},
|
|
24
|
+
runConfig: {},
|
|
25
|
+
setRunConfig() {
|
|
26
|
+
throw error;
|
|
27
|
+
},
|
|
28
|
+
async reset() {},
|
|
29
|
+
async clearAttachments() {},
|
|
30
|
+
send() {
|
|
31
|
+
throw error;
|
|
32
|
+
},
|
|
33
|
+
cancel() {},
|
|
34
|
+
queue: [],
|
|
35
|
+
moveQueueItem() {},
|
|
36
|
+
removeQueueItem() {},
|
|
37
|
+
dictation: void 0,
|
|
38
|
+
startDictation() {
|
|
39
|
+
throw error;
|
|
40
|
+
},
|
|
41
|
+
stopDictation() {},
|
|
42
|
+
quote: void 0,
|
|
43
|
+
setQuote() {
|
|
44
|
+
throw error;
|
|
45
|
+
},
|
|
46
|
+
subscribe() {
|
|
47
|
+
return () => {};
|
|
48
|
+
},
|
|
49
|
+
unstable_on() {
|
|
50
|
+
return () => {};
|
|
51
|
+
}
|
|
52
|
+
});
|
|
53
|
+
var InertThreadRuntimeCore = class extends BaseSubscribable {
|
|
54
|
+
switchToBranch() {
|
|
55
|
+
throw this.error;
|
|
56
|
+
}
|
|
57
|
+
append() {
|
|
58
|
+
throw this.error;
|
|
59
|
+
}
|
|
60
|
+
deleteMessage() {
|
|
61
|
+
throw this.error;
|
|
62
|
+
}
|
|
63
|
+
startRun() {
|
|
64
|
+
throw this.error;
|
|
65
|
+
}
|
|
66
|
+
resumeRun() {
|
|
67
|
+
throw this.error;
|
|
68
|
+
}
|
|
69
|
+
cancelRun() {
|
|
70
|
+
throw this.error;
|
|
71
|
+
}
|
|
72
|
+
unstable_notifySessionReset() {
|
|
73
|
+
throw this.error;
|
|
74
|
+
}
|
|
75
|
+
addToolResult() {
|
|
76
|
+
throw this.error;
|
|
77
|
+
}
|
|
78
|
+
resumeToolCall() {
|
|
79
|
+
throw this.error;
|
|
80
|
+
}
|
|
81
|
+
respondToToolApproval() {
|
|
82
|
+
throw this.error;
|
|
83
|
+
}
|
|
84
|
+
speak() {
|
|
85
|
+
throw this.error;
|
|
86
|
+
}
|
|
87
|
+
stopSpeaking() {
|
|
88
|
+
throw this.error;
|
|
89
|
+
}
|
|
90
|
+
connectVoice() {
|
|
91
|
+
throw this.error;
|
|
92
|
+
}
|
|
93
|
+
disconnectVoice() {
|
|
94
|
+
throw this.error;
|
|
95
|
+
}
|
|
96
|
+
muteVoice() {
|
|
97
|
+
throw this.error;
|
|
98
|
+
}
|
|
99
|
+
unmuteVoice() {
|
|
100
|
+
throw this.error;
|
|
101
|
+
}
|
|
102
|
+
submitFeedback() {
|
|
103
|
+
throw this.error;
|
|
104
|
+
}
|
|
105
|
+
exportExternalState() {
|
|
106
|
+
throw this.error;
|
|
107
|
+
}
|
|
108
|
+
importExternalState() {
|
|
109
|
+
throw this.error;
|
|
110
|
+
}
|
|
111
|
+
beginEdit() {
|
|
112
|
+
throw this.error;
|
|
113
|
+
}
|
|
114
|
+
import() {
|
|
115
|
+
throw this.error;
|
|
116
|
+
}
|
|
117
|
+
reset() {
|
|
118
|
+
throw this.error;
|
|
119
|
+
}
|
|
120
|
+
getModelContext() {
|
|
121
|
+
return {};
|
|
122
|
+
}
|
|
123
|
+
getEditComposer() {}
|
|
124
|
+
getVoiceVolume = () => 0;
|
|
125
|
+
subscribeVoiceVolume = () => () => {};
|
|
126
|
+
speech = void 0;
|
|
127
|
+
voice = void 0;
|
|
128
|
+
capabilities = {
|
|
129
|
+
switchToBranch: false,
|
|
130
|
+
switchBranchDuringRun: false,
|
|
131
|
+
edit: false,
|
|
132
|
+
delete: false,
|
|
133
|
+
reload: false,
|
|
134
|
+
refetchThread: false,
|
|
135
|
+
cancel: false,
|
|
136
|
+
unstable_copy: false,
|
|
137
|
+
speech: false,
|
|
138
|
+
dictation: false,
|
|
139
|
+
voice: false,
|
|
140
|
+
attachments: false,
|
|
141
|
+
feedback: false,
|
|
142
|
+
queue: false
|
|
143
|
+
};
|
|
144
|
+
isDisabled = false;
|
|
145
|
+
isSendDisabled = false;
|
|
146
|
+
state = null;
|
|
147
|
+
suggestions = [];
|
|
148
|
+
extras = void 0;
|
|
149
|
+
unstable_on() {
|
|
150
|
+
return () => {};
|
|
151
|
+
}
|
|
152
|
+
};
|
|
153
|
+
//#endregion
|
|
154
|
+
export { InertThreadRuntimeCore, createInertComposer };
|
|
155
|
+
|
|
156
|
+
//# sourceMappingURL=InertThreadRuntimeCore.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"InertThreadRuntimeCore.js","names":["Unsubscribe","ThreadMessage","ThreadRuntimeCore","ExportedMessageRepository","BaseSubscribable","createInertComposer","error","Error","isEditing","TIsEditing","attachments","attachmentAccept","addAttachment","removeAttachment","canCancel","canSend","isEmpty","text","setText","role","const","setRole","runConfig","setRunConfig","reset","clearAttachments","send","cancel","queue","moveQueueItem","removeQueueItem","dictation","undefined","startDictation","stopDictation","quote","setQuote","subscribe","unstable_on","InertThreadRuntimeCore","messages","isLoading","composer","getMessageById","messageId","parentId","message","index","getBranches","export","switchToBranch","append","deleteMessage","startRun","resumeRun","cancelRun","unstable_notifySessionReset","addToolResult","resumeToolCall","respondToToolApproval","speak","stopSpeaking","connectVoice","disconnectVoice","muteVoice","unmuteVoice","submitFeedback","exportExternalState","importExternalState","beginEdit","import","getModelContext","getEditComposer","getVoiceVolume","subscribeVoiceVolume","speech","voice","capabilities","switchBranchDuringRun","edit","delete","reload","refetchThread","unstable_copy","feedback","isDisabled","isSendDisabled","state","suggestions","extras"],"sources":["../../../src/runtimes/inert/InertThreadRuntimeCore.ts"],"sourcesContent":["import type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { ThreadMessage } from \"../../types/message\";\nimport type { ThreadRuntimeCore } from \"../../runtime/interfaces/thread-runtime-core\";\nimport type { ExportedMessageRepository } from \"../../runtime/utils/message-repository\";\nimport { BaseSubscribable } from \"../../subscribable/subscribable\";\n\nexport const createInertComposer = <TIsEditing extends boolean>(\n error: Error,\n isEditing: TIsEditing,\n) => ({\n attachments: [] as never[],\n attachmentAccept: \"*\",\n\n async addAttachment() {\n throw error;\n },\n\n async removeAttachment() {\n throw error;\n },\n\n isEditing,\n canCancel: false,\n canSend: false,\n isEmpty: true,\n text: \"\",\n\n setText() {\n throw error;\n },\n\n role: \"user\" as const,\n\n setRole() {\n throw error;\n },\n\n runConfig: {},\n\n setRunConfig() {\n throw error;\n },\n\n async reset() {},\n\n async clearAttachments() {},\n\n send() {\n throw error;\n },\n\n cancel() {},\n\n queue: [] as never[],\n moveQueueItem() {},\n removeQueueItem() {},\n\n dictation: undefined,\n\n startDictation() {\n throw error;\n },\n\n stopDictation() {},\n\n quote: undefined,\n\n setQuote() {\n throw error;\n },\n\n subscribe() {\n return () => {};\n },\n\n unstable_on() {\n return () => {};\n },\n});\n\nexport abstract class InertThreadRuntimeCore\n extends BaseSubscribable\n implements ThreadRuntimeCore\n{\n protected abstract get error(): Error;\n\n abstract readonly messages: readonly ThreadMessage[];\n abstract readonly isLoading: boolean;\n abstract readonly composer: ThreadRuntimeCore[\"composer\"];\n\n abstract getMessageById(messageId: string):\n | {\n parentId: string | null;\n message: ThreadMessage;\n index: number;\n }\n | undefined;\n\n abstract getBranches(messageId: string): readonly string[];\n\n abstract export(): ExportedMessageRepository;\n\n switchToBranch(): void {\n throw this.error;\n }\n\n append(): void {\n throw this.error;\n }\n\n deleteMessage(): void {\n throw this.error;\n }\n\n startRun(): void {\n throw this.error;\n }\n\n resumeRun(): void {\n throw this.error;\n }\n\n cancelRun(): void {\n throw this.error;\n }\n\n unstable_notifySessionReset(): void {\n throw this.error;\n }\n\n addToolResult(): void {\n throw this.error;\n }\n\n resumeToolCall(): void {\n throw this.error;\n }\n\n respondToToolApproval(): void {\n throw this.error;\n }\n\n speak(): void {\n throw this.error;\n }\n\n stopSpeaking(): void {\n throw this.error;\n }\n\n connectVoice(): void {\n throw this.error;\n }\n\n disconnectVoice(): void {\n throw this.error;\n }\n\n muteVoice(): void {\n throw this.error;\n }\n\n unmuteVoice(): void {\n throw this.error;\n }\n\n submitFeedback(): void {\n throw this.error;\n }\n\n exportExternalState(): void {\n throw this.error;\n }\n\n importExternalState(): void {\n throw this.error;\n }\n\n beginEdit(): void {\n throw this.error;\n }\n\n import(): void {\n throw this.error;\n }\n\n reset(): void {\n throw this.error;\n }\n\n getModelContext() {\n return {};\n }\n\n getEditComposer() {\n return undefined;\n }\n\n getVoiceVolume = () => 0;\n subscribeVoiceVolume = (): Unsubscribe => () => {};\n\n speech = undefined;\n voice = undefined;\n\n capabilities = {\n switchToBranch: false,\n switchBranchDuringRun: false,\n edit: false,\n delete: false,\n reload: false,\n refetchThread: false,\n cancel: false,\n unstable_copy: false,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n } as const;\n\n isDisabled = false;\n isSendDisabled = false;\n\n state = null;\n suggestions = [] as never[];\n extras = undefined;\n\n unstable_on(): Unsubscribe {\n return () => {};\n }\n}\n"],"mappings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KvD;CACb;CAEAwD,eAAqB;EACnB,MAAM,KAAKxD;CACb;CAEAyD,kBAAwB;EACtB,MAAM,KAAKzD;CACb;CAEA0D,YAAkB;EAChB,MAAM,KAAK1D;CACb;CAEA2D,cAAoB;EAClB,MAAM,KAAK3D;CACb;CAEA4D,iBAAuB;EACrB,MAAM,KAAK5D;CACb;CAEA6D,sBAA4B;EAC1B,MAAM,KAAK7D;CACb;CAEA8D,sBAA4B;EAC1B,MAAM,KAAK9D;CACb;CAEA+D,YAAkB;EAChB,MAAM,KAAK/D;CACb;CAEAgE,SAAe;EACb,MAAM,KAAKhE;CACb;CAEAkB,QAAc;EACZ,MAAM,KAAKlB;CACb;CAEAiE,kBAAkB;EAChB,OAAO,CAAC;CACV;CAEAC,kBAAkB,CAElB;CAEAC,uBAAuB;CACvBC,mCAAgD,CAAC;CAEjDC,SAAS3C,KAAAA;CACT4C,QAAQ5C,KAAAA;CAER6C,eAAe;EACb3B,gBAAgB;EAChB4B,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfvD,QAAQ;EACRwD,eAAe;EACfR,QAAQ;EACR5C,WAAW;EACX6C,OAAO;EACPlE,aAAa;EACb0E,UAAU;EACVxD,OAAO;CACT;CAEAyD,aAAa;CACbC,iBAAiB;CAEjBC,QAAQ;CACRC,cAAc,CAAA;CACdC,SAASzD,KAAAA;CAETM,cAA2B;EACzB,aAAa,CAAC;CAChB;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;;cAmDa,+BACH,iCACG;WAEK;;;;;;;;;;;;;;;;UAiBR;UAEA;UACA;UACA;UACA;UAEA;UAIA;UAuBA;WAYQ;WACA;UAER;MACG;UAIH;UACA;MACG,wBAAwB;MAIxB;;;;;;;;;;EAKT,YAAA,iBAAiB,sBACjB,SAAS;UAMH;UAEA;UAEA;EAED,0BAA0B;UAIzB;EAED,mCACL,kBAAkB;MAKT;EAIJ,sBAAsB,SAAS;UA6F9B;UACA;EACD,mBAAe;EAyCT,OAAO,SAAS,gBAAgB;EAkBtC,0BAA0B;EAM1B,+BAA+B;EAI/B,cAAc,qBAAqB,WAAW;EAI9C,gBAAgB;UAIf;UASM;EA4DD,cAAc,oBAAoB;EAmBxC,YAAY,WAAW,eAAe,kBAAkB;EAMxD;EAIA;EAIA;EAIM,WACT,UAAU,aAAa,gBACzB,cAAc,0BACb;UAuBW;
|
|
1
|
+
{"version":3,"file":"local-thread-runtime-core.d.ts","names":[],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"mappings":";;;;;;;;;;;;;;;;cAmDa,+BACH,iCACG;WAEK;;;;;;;;;;;;;;;;UAiBR;UAEA;UACA;UACA;UACA;UAEA;UAIA;UAuBA;WAYQ;WACA;UAER;MACG;UAIH;UACA;MACG,wBAAwB;MAIxB;;;;;;;;;;EAKT,YAAA,iBAAiB,sBACjB,SAAS;UAMH;UAEA;UAEA;EAED,0BAA0B;UAIzB;EAED,mCACL,kBAAkB;MAKT;EAIJ,sBAAsB,SAAS;UA6F9B;UACA;EACD,mBAAe;EAyCT,OAAO,SAAS,gBAAgB;EAkBtC,0BAA0B;EAM1B,+BAA+B;EAI/B,cAAc,qBAAqB,WAAW;EAI9C,gBAAgB;UAIf;UASM;EA4DD,cAAc,oBAAoB;EAmBxC,YAAY,WAAW,eAAe,kBAAkB;EAMxD;EAIA;EAIA;EAIM,WACT,UAAU,aAAa,gBACzB,cAAc,0BACb;UAuBW;UA6EA;EA8NP;EAWA;EAgBA,gBACL,WACA,YACA,QACA,SACA,YACC;EA6CI,eAAe,UAAU;EAMzB,wBACL,YACA,UACA,UACA,UACC"}
|
|
@@ -309,8 +309,9 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
309
309
|
this._suggestionsController = null;
|
|
310
310
|
this._notifySubscribers();
|
|
311
311
|
do {
|
|
312
|
-
message = await this.performRoundtrip(parentId, message, runConfig, alreadyPersisted, runCallback);
|
|
312
|
+
message = await this.performRoundtrip(parentId, message, runConfig, alreadyPersisted, run, runCallback);
|
|
313
313
|
runCallback = void 0;
|
|
314
|
+
if (this._activeRun !== run) break;
|
|
314
315
|
} while (shouldContinue(message, this._options.unstable_humanToolNames));
|
|
315
316
|
} finally {
|
|
316
317
|
this._notifyEventSubscribers("runEnd", {});
|
|
@@ -339,7 +340,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
339
340
|
})();
|
|
340
341
|
}
|
|
341
342
|
}
|
|
342
|
-
async performRoundtrip(parentId, message, runConfig, alreadyPersisted, runCallback) {
|
|
343
|
+
async performRoundtrip(parentId, message, runConfig, alreadyPersisted, run, runCallback) {
|
|
343
344
|
const messages = parentId ? this.repository.getMessages(parentId) : [];
|
|
344
345
|
this.abortController?.abort();
|
|
345
346
|
const abortController = new AbortController();
|
|
@@ -349,7 +350,22 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
349
350
|
const initialData = message.metadata?.unstable_data;
|
|
350
351
|
const initialSteps = message.metadata?.steps;
|
|
351
352
|
const initialCustom = message.metadata?.custom;
|
|
353
|
+
let hasStoredMessage = true;
|
|
354
|
+
try {
|
|
355
|
+
this.repository.getMessage(message.id);
|
|
356
|
+
} catch {
|
|
357
|
+
hasStoredMessage = false;
|
|
358
|
+
}
|
|
359
|
+
const ownsMessage = () => {
|
|
360
|
+
if (!hasStoredMessage) return this._activeRun === run;
|
|
361
|
+
try {
|
|
362
|
+
return this.repository.getMessage(message.id).message === message;
|
|
363
|
+
} catch {
|
|
364
|
+
return false;
|
|
365
|
+
}
|
|
366
|
+
};
|
|
352
367
|
const updateMessage = (m) => {
|
|
368
|
+
if (!ownsMessage()) return;
|
|
353
369
|
const newSteps = m.metadata?.steps;
|
|
354
370
|
const steps = newSteps ? [...initialSteps ?? [], ...newSteps] : void 0;
|
|
355
371
|
const newAnnotations = m.metadata?.unstable_annotations;
|
|
@@ -374,6 +390,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
374
390
|
} } : void 0
|
|
375
391
|
};
|
|
376
392
|
this.repository.addOrUpdateMessage(parentId, message);
|
|
393
|
+
hasStoredMessage = true;
|
|
377
394
|
this._notifySubscribers();
|
|
378
395
|
};
|
|
379
396
|
const maxSteps = this._options.maxSteps ?? 2;
|
|
@@ -392,6 +409,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
392
409
|
const { unstable_composerMetadata: _, ...context } = this.getModelContext();
|
|
393
410
|
runCallback = runCallback ?? this.adapters.chatModel.run.bind(this.adapters.chatModel);
|
|
394
411
|
const abortSignal = abortController.signal;
|
|
412
|
+
const shouldCancelMessage = () => abortSignal.aborted && (message.status.type === "running" || message.status.type === "requires-action" && (this._activeRun !== run || shouldContinue(message, this._options.unstable_humanToolNames)));
|
|
395
413
|
const threadId = this._getThreadId?.();
|
|
396
414
|
const promiseOrGenerator = runCallback({
|
|
397
415
|
messages,
|
|
@@ -407,7 +425,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
407
425
|
});
|
|
408
426
|
if (Symbol.asyncIterator in promiseOrGenerator) for await (const r of promiseOrGenerator) {
|
|
409
427
|
if (abortSignal.aborted) {
|
|
410
|
-
updateMessage({ status: {
|
|
428
|
+
if (shouldCancelMessage()) updateMessage({ status: {
|
|
411
429
|
type: "incomplete",
|
|
412
430
|
reason: "cancelled"
|
|
413
431
|
} });
|
|
@@ -416,10 +434,11 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
416
434
|
updateMessage(r);
|
|
417
435
|
}
|
|
418
436
|
else updateMessage(await promiseOrGenerator);
|
|
419
|
-
if (
|
|
437
|
+
if (shouldCancelMessage()) updateMessage({ status: {
|
|
420
438
|
type: "incomplete",
|
|
421
439
|
reason: "cancelled"
|
|
422
|
-
}
|
|
440
|
+
} });
|
|
441
|
+
else if (message.status.type === "running") updateMessage({ status: {
|
|
423
442
|
type: "complete",
|
|
424
443
|
reason: "unknown"
|
|
425
444
|
} });
|
|
@@ -450,7 +469,7 @@ var LocalThreadRuntimeCore = class extends BaseThreadRuntimeCore {
|
|
|
450
469
|
};
|
|
451
470
|
const isTerminal = message.status.type === "complete" || message.status.type === "incomplete";
|
|
452
471
|
const isPausing = message.status.type === "requires-action" && !shouldContinue(message, this._options.unstable_humanToolNames);
|
|
453
|
-
if (isTerminal || isPausing && history?.update) {
|
|
472
|
+
if (ownsMessage() && (isTerminal || isPausing && history?.update)) {
|
|
454
473
|
const write = alreadyPersisted && history?.update ? history.update.bind(history) : history?.append.bind(history);
|
|
455
474
|
if (write) await this._chainHistoryWrite(message.id, () => write(item));
|
|
456
475
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","MessageNotSentError","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","captureThreadRuntimeGeneration","invalidateThreadRuntime","isThreadRuntimeGenerationCurrent","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","status","type","history","_options","adapters","update","bind","item","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","undefined","previousHistory","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","messages","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadRequested","_loadPromise","length","__internal_load","error","console","promise","load","repo","repository","import","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","willRun","role","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","_rollbackAppend","messageId","deleteMessage","rawMessage","enrichAppendMetadata","newMessage","reason","addOrUpdateMessage","initPromise","notSent","cause","historyWrite","runResult","historyResult","allSettled","resetHead","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","unstable_notifySessionReset","runCallback","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","active","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","data","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","aborted","e","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","addToolResult","toolCallId","result","isError","artifact","messageData","getMessage","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig } from \"../../types/message\";\nimport { MessageNotSentError, toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport {\n captureThreadRuntimeGeneration,\n invalidateThreadRuntime,\n isThreadRuntimeGenerationCurrent,\n} from \"../../runtime/utils/thread-runtime-lifecycle\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n refetchThread: false,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n const previousHistory = this._options?.adapters.history;\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n\n if (\n this._loadRequested &&\n !this._loadPromise &&\n !previousHistory &&\n options.adapters.history &&\n this.messages.length === 0\n ) {\n void this.__internal_load().catch((error: unknown) => {\n console.error(\n \"[assistant-ui] local thread history load failed:\",\n error,\n );\n });\n }\n }\n\n private _loadPromise: Promise<void> | undefined;\n private _loadRequested = false;\n public __internal_load() {\n this._loadRequested = true;\n if (this._loadPromise) return this._loadPromise;\n if (!this.adapters.history) return Promise.resolve();\n\n const promise = this.adapters.history.load();\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private _rollbackAppend(messageId: string) {\n try {\n this.repository.deleteMessage(messageId);\n } catch {\n return;\n }\n this._notifySubscribers();\n }\n\n private async _runAppend(rawMessage: AppendMessage): Promise<void> {\n // Stamped here rather than in `append` so a queued message is gated after\n // the flush re-pointed its parentId at the current tail.\n const generation = captureThreadRuntimeGeneration(this);\n const message = this.enrichAppendMetadata(rawMessage);\n this.ensureInitialized();\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._notifySubscribers();\n\n // Initialization only gates the history write and the run; the message\n // is already on screen. A failed barrier rolls the optimistic message\n // back and rejects as an unsent message so the composer restores the\n // draft; a thread invalidated mid-wait rolls back silently.\n try {\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n } catch (error) {\n this._rollbackAppend(newMessage.id);\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n const notSent = new MessageNotSentError();\n notSent.cause = error;\n throw notSent;\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) {\n this._rollbackAppend(newMessage.id);\n return;\n }\n const historyWrite = this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n void historyWrite?.catch(() => {});\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n const [runResult, historyResult] = await Promise.allSettled([\n this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n }),\n historyWrite,\n ]);\n if (runResult.status === \"rejected\") throw runResult.reason;\n if (historyResult.status === \"rejected\") throw historyResult.reason;\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n await historyWrite;\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public unstable_notifySessionReset(): void {\n throw new Error(\"Runtime does not support resetting sessions.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n let active = false;\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n alreadyPersisted,\n runCallback,\n );\n runCallback = undefined;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n active &&\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = abortController;\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state !== undefined\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = abortController.signal;\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (message.status.type === \"running\") {\n updateMessage({\n status: abortSignal.aborted\n ? { type: \"incomplete\", reason: \"cancelled\" }\n : { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n if (e instanceof AbortError) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"error\",\n error: toAssistantError(e),\n },\n });\n\n throw e;\n }\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (isTerminal || (isPausing && history?.update)) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n invalidateThreadRuntime(this);\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (c.result === undefined) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else if (added) {\n this._persistPausedMessage(parentId, message);\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else {\n this._persistPausedMessage(parentId, message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAyCA,IAAM6B,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUrB,sBAEV;CACE,eAA+B;EAC7BuB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,WAAW;EACXC,OAAO;EACPC,aAAa;EACbC,UAAU;EACVC,OAAO;CACT;CAEA,kBAAkD;CAElD,SAAgD;CAChD,oBAA4B;CAC5B,aAAoD;CACpD,iBAAyB;CAEzB,iCAAyB,IAAIS,IAA2B;CAIxD,mBACEG,IACAC,OACe;EACf,MAAMC,QAAQ,KAAKN,eAAeO,IAAIH,EAAE,KAAKF,QAAQM,QAAQ,EAAA,CAAGC,KAC9DJ,OACAA,KACF;EACA,MAAMK,SAASJ,KAAKG,WACZ,CAAC,SACD,CAAC,CACT;EACA,KAAKT,eAAeW,IAAIP,IAAIM,MAAM;EAClC,OAAYD,WAAW;GACrB,IAAI,KAAKT,e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GR;IACHQ;IACAjB,QAAQ,EAAExH,OAAOsC,UAAU,uBAAuB;IAClDmF,SAAS;GACX;EACF,CAAC;EAEDnN,UAAU;GAAE,GAAGA;GAASqJ,SAASoE;EAAW;EAC5C,MAAM,EAAEpL,aAAa,KAAK0D,WAAWuH,WAAWtN,QAAQ4B,EAAE;EAC1D,KAAKmE,WAAWkC,mBAAmB5F,UAAUrC,OAAO;EACpD,KAAKqF,mBAAmB;EAExB,IACE,KAAKU,WAAWM,WAAWrG,QAAQ4B,MACnC1D,eAAe8B,SAAS,KAAKyC,SAAS6H,uBAAuB,GAE7D,KAAKP,SAAS1H,UAAUrC,SAAS,KAAK+C,cAAc,CAAC,CAACC,YAAY,CAAC,CAAC;OAEpE,KAAKZ,sBAAsBC,UAAUrC,OAAO;CAEhD;AACF"}
|
|
1
|
+
{"version":3,"file":"local-thread-runtime-core.js","names":["fromThreadMessageLike","generateId","ChatModelAdapter","ChatModelRunResult","shouldContinue","LocalRuntimeOptionsBase","consumeSuggestionResult","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","ThreadSuggestion","ThreadRuntimeCore","StartRunConfig","ResumeRunConfig","BaseThreadRuntimeCore","AppendMessage","ThreadAssistantMessage","RunConfig","MessageNotSentError","toAssistantError","ModelContextProvider","createMessageQueue","MessageQueueController","QueuePlacement","EMPTY_QUEUE_ITEMS","QueueItemState","captureThreadRuntimeGeneration","invalidateThreadRuntime","isThreadRuntimeGenerationCurrent","AbortError","Error","name","detach","constructor","message","LocalThreadRuntimeCore","capabilities","switchToBranch","switchBranchDuringRun","edit","delete","reload","refetchThread","cancel","unstable_copy","speech","dictation","voice","attachments","feedback","queue","abortController","AbortController","_queue","_queueRunInFlight","_activeRun","cancelled","_runGeneration","_historyWrites","Map","Promise","_chainHistoryWrite","id","write","next","get","resolve","then","stored","set","_persistPausedMessage","parentId","status","type","history","_options","adapters","update","bind","item","runConfig","_lastRunConfig","catch","isDisabled","isSendDisabled","_isLoading","isLoading","_suggestions","_suggestionsController","suggestions","contextProvider","options","__internal_setOptions","_getThreadId","__internal_setGetThreadId","getThreadId","_getInitializePromise","__internal_setGetInitializePromise","getPromise","extras","undefined","previousHistory","hasUpdates","canSpeak","canDictate","canVoice","canAttach","canFeedback","canDelete","canQueue","unstable_enableMessageQueue","run","generation","_runAppend","messages","at","finally","notifyIdle","subscribe","_notifySubscribers","_loadRequested","_loadPromise","length","__internal_load","error","console","promise","load","repo","repository","import","ensureInitialized","resume","unstable_resume","startRun","headId","sourceId","append","isTail","willRun","role","steer","adapter","enqueue","unstable_queueClearOnRewind","clear","getQueueItems","items","getSteerQueueItems","steerItems","moveQueueItem","queueItemId","placement","move","removeQueueItem","remove","_rollbackAppend","messageId","deleteMessage","rawMessage","enrichAppendMetadata","newMessage","reason","addOrUpdateMessage","initPromise","notSent","cause","historyWrite","runResult","historyResult","allSettled","resetHead","getMessages","messageIndex","findIndex","m","resumeRun","stream","startConfig","exportExternalState","importExternalState","unstable_notifySessionReset","runCallback","content","metadata","unstable_state","state","unstable_annotations","unstable_data","steps","custom","createdAt","Date","_runLoop","_notifyEventSubscribers","alreadyPersisted","active","notifyBusy","abort","performRoundtrip","unstable_humanToolNames","queueMicrotask","suggestion","signal","promiseOrGenerator","generate","onUpdate","r","initialContent","initialAnnotations","initialData","initialSteps","initialCustom","hasStoredMessage","getMessage","ownsMessage","updateMessage","Partial","newSteps","newAnnotations","newData","annotations","data","timing","maxSteps","unstable_composerMetadata","_","context","getModelContext","chatModel","abortSignal","shouldCancelMessage","aborted","threadId","unstable_assistantMessageId","unstable_threadId","unstable_parentId","unstable_getMessage","Symbol","asyncIterator","e","isTerminal","isPausing","cancelRun","unstable_queueClearOnCancel","notifyCancelled","addToolResult","toolCallId","result","isError","artifact","messageData","added","found","newContent","map","c","resumeToolCall","respondToToolApproval","approvalId","approved","optionId","findLast","some","approval","target","find","resolution","targetApproval"],"sources":["../../../src/runtimes/local/local-thread-runtime-core.ts"],"sourcesContent":["import { fromThreadMessageLike } from \"../../runtime/utils/thread-message-like\";\nimport { generateId } from \"../../utils/id\";\nimport type {\n ChatModelAdapter,\n ChatModelRunResult,\n} from \"../../runtime/utils/chat-model-adapter\";\nimport { shouldContinue } from \"./should-continue\";\nimport type { LocalRuntimeOptionsBase } from \"./local-runtime-options\";\nimport { consumeSuggestionResult } from \"../../adapters/suggestion\";\nimport type {\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n ThreadSuggestion,\n ThreadRuntimeCore,\n StartRunConfig,\n ResumeRunConfig,\n} from \"../../runtime/interfaces/thread-runtime-core\";\nimport { BaseThreadRuntimeCore } from \"../../runtime/base/base-thread-runtime-core\";\nimport type {\n AppendMessage,\n ThreadAssistantMessage,\n} from \"../../types/message\";\nimport type { RunConfig } from \"../../types/message\";\nimport { MessageNotSentError, toAssistantError } from \"../../types/error\";\nimport type { ModelContextProvider } from \"../../model-context/types\";\nimport {\n createMessageQueue,\n type MessageQueueController,\n} from \"../../runtime/queue/message-queue\";\nimport type { QueuePlacement } from \"../../runtime/queue/external-thread-queue-adapter\";\nimport {\n EMPTY_QUEUE_ITEMS,\n type QueueItemState,\n} from \"../../store/scopes/queue-item\";\nimport {\n captureThreadRuntimeGeneration,\n invalidateThreadRuntime,\n isThreadRuntimeGenerationCurrent,\n} from \"../../runtime/utils/thread-runtime-lifecycle\";\n\nclass AbortError extends Error {\n override name = \"AbortError\";\n detach: boolean;\n\n constructor(detach: boolean, message?: string) {\n super(message);\n this.detach = detach;\n }\n}\n\nexport class LocalThreadRuntimeCore\n extends BaseThreadRuntimeCore\n implements ThreadRuntimeCore\n{\n public readonly capabilities = {\n switchToBranch: true,\n switchBranchDuringRun: true,\n edit: true,\n delete: false,\n reload: true,\n refetchThread: false,\n cancel: true,\n unstable_copy: true,\n speech: false,\n dictation: false,\n voice: false,\n attachments: false,\n feedback: false,\n queue: false,\n };\n\n private abortController: AbortController | null = null;\n\n private _queue: MessageQueueController | null = null;\n private _queueRunInFlight = false;\n private _activeRun: { cancelled: boolean } | null = null;\n private _runGeneration = 0;\n\n private _historyWrites = new Map<string, Promise<void>>();\n\n // Writes for one message id must land in issue order; an earlier paused\n // snapshot arriving after the terminal write would resurrect the pause.\n private _chainHistoryWrite(\n id: string,\n write: () => Promise<void>,\n ): Promise<void> {\n const next = (this._historyWrites.get(id) ?? Promise.resolve()).then(\n write,\n write,\n );\n const stored = next.then(\n () => {},\n () => {},\n );\n this._historyWrites.set(id, stored);\n void stored.then(() => {\n if (this._historyWrites.get(id) === stored) {\n this._historyWrites.delete(id);\n }\n });\n return next;\n }\n\n // A decision recorded on a still-paused message must reach history before\n // the run resumes, or a refresh would restore the message without it.\n private _persistPausedMessage(\n parentId: string | null,\n message: ThreadAssistantMessage,\n ) {\n if (message.status?.type !== \"requires-action\") return;\n const history = this._options.adapters.history;\n if (!history?.update) return;\n const update = history.update.bind(history);\n const item = { parentId, message, runConfig: this._lastRunConfig };\n this._chainHistoryWrite(message.id, () => update(item)).catch(() => {});\n }\n\n public readonly isDisabled = false;\n public readonly isSendDisabled = false;\n\n private _isLoading = false;\n public get isLoading() {\n return this._isLoading;\n }\n\n private _suggestions: readonly ThreadSuggestion[] = [];\n private _suggestionsController: AbortController | null = null;\n public get suggestions(): readonly ThreadSuggestion[] {\n return this._suggestions;\n }\n\n public get adapters() {\n return this._options.adapters;\n }\n\n constructor(\n contextProvider: ModelContextProvider,\n options: LocalRuntimeOptionsBase,\n ) {\n super(contextProvider);\n this.__internal_setOptions(options);\n }\n\n private _options!: LocalRuntimeOptionsBase;\n\n private _lastRunConfig: RunConfig = {};\n\n private _getThreadId?: () => string | undefined;\n\n public __internal_setGetThreadId(getThreadId: () => string | undefined) {\n this._getThreadId = getThreadId;\n }\n\n private _getInitializePromise?: () => Promise<unknown> | undefined;\n\n public __internal_setGetInitializePromise(\n getPromise: () => Promise<unknown> | undefined,\n ) {\n this._getInitializePromise = getPromise;\n }\n\n public get extras() {\n return undefined;\n }\n\n public __internal_setOptions(options: LocalRuntimeOptionsBase) {\n if (this._options === options) return;\n\n const previousHistory = this._options?.adapters.history;\n this._options = options;\n\n let hasUpdates = false;\n\n const canSpeak = options.adapters?.speech !== undefined;\n if (this.capabilities.speech !== canSpeak) {\n this.capabilities.speech = canSpeak;\n hasUpdates = true;\n }\n\n const canDictate = options.adapters?.dictation !== undefined;\n if (this.capabilities.dictation !== canDictate) {\n this.capabilities.dictation = canDictate;\n hasUpdates = true;\n }\n\n const canVoice = options.adapters?.voice !== undefined;\n if (this.capabilities.voice !== canVoice) {\n this.capabilities.voice = canVoice;\n hasUpdates = true;\n }\n\n const canAttach = options.adapters?.attachments !== undefined;\n if (this.capabilities.attachments !== canAttach) {\n this.capabilities.attachments = canAttach;\n hasUpdates = true;\n }\n\n const canFeedback = options.adapters?.feedback !== undefined;\n if (this.capabilities.feedback !== canFeedback) {\n this.capabilities.feedback = canFeedback;\n hasUpdates = true;\n }\n\n const canDelete = options.adapters?.history?.delete !== undefined;\n if (this.capabilities.delete !== canDelete) {\n this.capabilities.delete = canDelete;\n hasUpdates = true;\n }\n\n const canQueue = options.unstable_enableMessageQueue === true;\n if (canQueue && !this._queue) {\n this._queue = createMessageQueue({\n run: (message) => {\n // release the queue when the dispatch settles, even if it rejects\n // before reaching startRun's finally, so a failure can't deadlock it\n this._queueRunInFlight = true;\n const generation = this._runGeneration;\n // the tail may have moved since the message was enqueued\n void this._runAppend({\n ...message,\n parentId: this.messages.at(-1)?.id ?? null,\n })\n .finally(() => {\n this._queueRunInFlight = false;\n // a dispatch that failed before starting a run settles here;\n // runs that did start release from _runLoop\n if (this._runGeneration === generation) this._queue?.notifyIdle();\n })\n .catch(() => {});\n },\n });\n this._queue.subscribe(() => this._notifySubscribers());\n } else if (!canQueue && this._queue) {\n this._queue = null;\n }\n if (this.capabilities.queue !== canQueue) {\n this.capabilities.queue = canQueue;\n hasUpdates = true;\n }\n\n if (hasUpdates) this._notifySubscribers();\n\n if (\n this._loadRequested &&\n !this._loadPromise &&\n !previousHistory &&\n options.adapters.history &&\n this.messages.length === 0\n ) {\n void this.__internal_load().catch((error: unknown) => {\n console.error(\n \"[assistant-ui] local thread history load failed:\",\n error,\n );\n });\n }\n }\n\n private _loadPromise: Promise<void> | undefined;\n private _loadRequested = false;\n public __internal_load() {\n this._loadRequested = true;\n if (this._loadPromise) return this._loadPromise;\n if (!this.adapters.history) return Promise.resolve();\n\n const promise = this.adapters.history.load();\n\n this._isLoading = true;\n this._notifySubscribers();\n\n this._loadPromise = promise\n .then((repo) => {\n if (!repo) return;\n this.repository.import(repo);\n if (repo.messages.length > 0) {\n this.ensureInitialized();\n }\n this._notifySubscribers();\n\n const resume = this.adapters.history?.resume?.bind(\n this.adapters.history,\n );\n if (repo.unstable_resume && resume) {\n this.startRun(\n {\n parentId: this.repository.headId,\n sourceId: this.repository.headId,\n runConfig: this._lastRunConfig,\n },\n resume,\n ).catch(() => {});\n }\n })\n .finally(() => {\n this._isLoading = false;\n this._notifySubscribers();\n });\n\n return this._loadPromise;\n }\n\n public async append(message: AppendMessage): Promise<void> {\n const isTail = message.parentId === (this.messages.at(-1)?.id ?? null);\n const willRun = message.startRun ?? message.role === \"user\";\n if (this._queue && willRun && isTail) {\n if (message.steer ?? this._queueRunInFlight)\n this._queue.adapter.steer(message);\n else this._queue.adapter.enqueue(message);\n return;\n }\n if (\n this._queue &&\n !isTail &&\n (this._options.unstable_queueClearOnRewind ?? true)\n )\n this._queue.clear();\n return this._runAppend(message);\n }\n\n public getQueueItems(): readonly QueueItemState[] {\n // Reads can arrive during base-thread construction, before the queue field\n // is assigned, so guard against the unset field.\n return this._queue?.adapter.items ?? EMPTY_QUEUE_ITEMS;\n }\n\n public getSteerQueueItems(): readonly QueueItemState[] {\n return this._queue?.adapter.steerItems ?? EMPTY_QUEUE_ITEMS;\n }\n\n public moveQueueItem(queueItemId: string, placement: QueuePlacement): void {\n this._queue?.adapter.move(queueItemId, placement);\n }\n\n public removeQueueItem(queueItemId: string): void {\n this._queue?.adapter.remove(queueItemId);\n }\n\n private _rollbackAppend(messageId: string) {\n try {\n this.repository.deleteMessage(messageId);\n } catch {\n return;\n }\n this._notifySubscribers();\n }\n\n private async _runAppend(rawMessage: AppendMessage): Promise<void> {\n // Stamped here rather than in `append` so a queued message is gated after\n // the flush re-pointed its parentId at the current tail.\n const generation = captureThreadRuntimeGeneration(this);\n const message = this.enrichAppendMetadata(rawMessage);\n this.ensureInitialized();\n\n const newMessage = fromThreadMessageLike(message, generateId(), {\n type: \"complete\",\n reason: \"unknown\",\n });\n this.repository.addOrUpdateMessage(message.parentId, newMessage);\n this._notifySubscribers();\n\n // Initialization only gates the history write and the run; the message\n // is already on screen. A failed barrier rolls the optimistic message\n // back and rejects as an unsent message so the composer restores the\n // draft; a thread invalidated mid-wait rolls back silently.\n try {\n const initPromise = this._getInitializePromise?.();\n if (initPromise) {\n await initPromise;\n }\n } catch (error) {\n this._rollbackAppend(newMessage.id);\n if (!isThreadRuntimeGenerationCurrent(this, generation)) return;\n const notSent = new MessageNotSentError();\n notSent.cause = error;\n throw notSent;\n }\n if (!isThreadRuntimeGenerationCurrent(this, generation)) {\n this._rollbackAppend(newMessage.id);\n return;\n }\n const historyWrite = this._options.adapters.history?.append({\n parentId: message.parentId,\n message: newMessage,\n ...(message.runConfig !== undefined && { runConfig: message.runConfig }),\n });\n void historyWrite?.catch(() => {});\n\n const startRun = message.startRun ?? message.role === \"user\";\n if (startRun) {\n const [runResult, historyResult] = await Promise.allSettled([\n this.startRun({\n parentId: newMessage.id,\n sourceId: message.sourceId,\n runConfig: message.runConfig ?? {},\n }),\n historyWrite,\n ]);\n if (runResult.status === \"rejected\") throw runResult.reason;\n if (historyResult.status === \"rejected\") throw historyResult.reason;\n } else {\n this.repository.resetHead(newMessage.id);\n this._notifySubscribers();\n await historyWrite;\n }\n }\n\n public async deleteMessage(messageId: string): Promise<void> {\n const adapter = this._options.adapters.history;\n if (!adapter?.delete)\n throw new Error(\"Runtime does not support deleting messages.\");\n\n const messages = this.repository.getMessages();\n const messageIndex = messages.findIndex((m) => m.id === messageId);\n if (messageIndex === -1) throw new Error(\"Message not found.\");\n\n const message = messages[messageIndex]!;\n const parentId = messages[messageIndex - 1]?.id ?? null;\n const items = [{ parentId, message }];\n\n await adapter.delete(items);\n\n this.repository.deleteMessage(messageId);\n this._notifySubscribers();\n }\n\n public resumeRun({ stream, ...startConfig }: ResumeRunConfig): Promise<void> {\n if (!stream)\n throw new Error(\"You must pass a stream parameter to resume runs.\");\n return this.startRun(startConfig, stream);\n }\n\n public exportExternalState(): any {\n throw new Error(\"Runtime does not support exporting external states.\");\n }\n\n public importExternalState(): void {\n throw new Error(\"Runtime does not support importing external states.\");\n }\n\n public unstable_notifySessionReset(): void {\n throw new Error(\"Runtime does not support resetting sessions.\");\n }\n\n public async startRun(\n { parentId, runConfig }: StartRunConfig,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this.ensureInitialized();\n\n // add assistant message\n const id = generateId();\n const message: ThreadAssistantMessage = {\n id,\n role: \"assistant\",\n status: { type: \"running\" },\n content: [],\n metadata: {\n unstable_state: this.state,\n unstable_annotations: [],\n unstable_data: [],\n steps: [],\n custom: {},\n },\n createdAt: new Date(),\n };\n\n return this._runLoop(parentId, message, runConfig, runCallback);\n }\n\n private async _runLoop(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n runCallback?: ChatModelAdapter[\"run\"],\n ): Promise<void> {\n this._notifyEventSubscribers(\"runStart\", {});\n\n // A run entered on a requires-action message resumes a pause an\n // update-capable adapter already holds (written at pause time or loaded).\n const alreadyPersisted =\n message.status?.type === \"requires-action\" &&\n this._options.adapters.history?.update !== undefined;\n\n const run = { cancelled: false };\n this._activeRun = run;\n this._runGeneration++;\n\n let active = false;\n try {\n // mark busy for runs not started through the queue (regenerate, resume)\n this._queue?.notifyBusy();\n this._suggestions = [];\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n this._notifySubscribers();\n\n do {\n message = await this.performRoundtrip(\n parentId,\n message,\n runConfig,\n alreadyPersisted,\n run,\n runCallback,\n );\n runCallback = undefined;\n if (this._activeRun !== run) break;\n } while (shouldContinue(message, this._options.unstable_humanToolNames));\n } finally {\n this._notifyEventSubscribers(\"runEnd\", {});\n // the settle belongs to this run only while it is still the active run\n // or was cancelled (the engine expects a cancelled run's settle); a run\n // superseded by a newer one stays silent\n active = this._activeRun === run;\n if (active) this._activeRun = null;\n if (active || run.cancelled) {\n queueMicrotask(() => this._queue?.notifyIdle());\n }\n }\n\n if (\n active &&\n this.adapters.suggestion &&\n message.status?.type !== \"requires-action\"\n ) {\n this._suggestionsController = new AbortController();\n const signal = this._suggestionsController.signal;\n const adapter = this.adapters.suggestion;\n void (async () => {\n try {\n const promiseOrGenerator = adapter.generate({\n messages: this.messages,\n signal,\n });\n await consumeSuggestionResult(promiseOrGenerator, {\n signal,\n onUpdate: (r) => {\n this._suggestions = r;\n this._notifySubscribers();\n },\n });\n } catch {}\n })();\n }\n }\n\n private async performRoundtrip(\n parentId: string | null,\n message: ThreadAssistantMessage,\n runConfig: RunConfig | undefined,\n alreadyPersisted: boolean,\n run: { cancelled: boolean },\n runCallback?: ChatModelAdapter[\"run\"],\n ) {\n const messages = parentId ? this.repository.getMessages(parentId) : [];\n\n // abort existing run\n this.abortController?.abort();\n const abortController = new AbortController();\n this.abortController = abortController;\n\n const initialContent = message.content;\n const initialAnnotations = message.metadata?.unstable_annotations;\n const initialData = message.metadata?.unstable_data;\n const initialSteps = message.metadata?.steps;\n const initialCustom = message.metadata?.custom;\n let hasStoredMessage = true;\n try {\n this.repository.getMessage(message.id);\n } catch {\n hasStoredMessage = false;\n }\n // Other writers replace the stored message object, so identity distinguishes this run from a newer owner.\n const ownsMessage = () => {\n if (!hasStoredMessage) return this._activeRun === run;\n try {\n return this.repository.getMessage(message.id).message === message;\n } catch {\n return false;\n }\n };\n const updateMessage = (m: Partial<ChatModelRunResult>) => {\n if (!ownsMessage()) return;\n const newSteps = m.metadata?.steps;\n const steps = newSteps\n ? [...(initialSteps ?? []), ...newSteps]\n : undefined;\n\n const newAnnotations = m.metadata?.unstable_annotations;\n const newData = m.metadata?.unstable_data;\n const annotations = newAnnotations\n ? [...(initialAnnotations ?? []), ...newAnnotations]\n : undefined;\n const data = newData ? [...(initialData ?? []), ...newData] : undefined;\n\n message = {\n ...message,\n ...(m.content\n ? { content: [...initialContent, ...(m.content ?? [])] }\n : undefined),\n status: m.status ?? message.status,\n ...(m.metadata\n ? {\n metadata: {\n ...message.metadata,\n ...(m.metadata.unstable_state !== undefined\n ? { unstable_state: m.metadata.unstable_state }\n : undefined),\n ...(annotations\n ? { unstable_annotations: annotations }\n : undefined),\n ...(data ? { unstable_data: data } : undefined),\n ...(steps ? { steps } : undefined),\n ...(m.metadata?.timing\n ? { timing: m.metadata.timing }\n : undefined),\n ...(m.metadata?.custom\n ? {\n custom: {\n ...(initialCustom ?? {}),\n ...m.metadata.custom,\n },\n }\n : undefined),\n },\n }\n : undefined),\n };\n this.repository.addOrUpdateMessage(parentId, message);\n hasStoredMessage = true;\n this._notifySubscribers();\n };\n\n const maxSteps = this._options.maxSteps ?? 2;\n\n try {\n const steps = message.metadata?.steps?.length ?? 0;\n if (steps >= maxSteps) {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"tool-calls\",\n },\n });\n return message;\n }\n\n updateMessage({\n status: {\n type: \"running\",\n },\n });\n\n // Switch to the new message branch right after adding it for the first time\n this.repository.resetHead(message.id);\n this._notifySubscribers();\n\n this._lastRunConfig = runConfig ?? {};\n // unstable_composerMetadata is composer-only (stamped onto the outgoing\n // message); never expose it to the chat-model adapter's run context.\n const { unstable_composerMetadata: _, ...context } =\n this.getModelContext();\n\n runCallback =\n runCallback ??\n this.adapters.chatModel.run.bind(this.adapters.chatModel);\n\n const abortSignal = abortController.signal;\n const shouldCancelMessage = () =>\n abortSignal.aborted &&\n (message.status.type === \"running\" ||\n (message.status.type === \"requires-action\" &&\n (this._activeRun !== run ||\n shouldContinue(message, this._options.unstable_humanToolNames))));\n const threadId = this._getThreadId?.();\n const promiseOrGenerator = runCallback({\n messages,\n runConfig: this._lastRunConfig,\n abortSignal,\n context,\n unstable_assistantMessageId: message.id,\n unstable_threadId: threadId,\n unstable_parentId: parentId,\n unstable_getMessage() {\n return message;\n },\n });\n\n // handle async iterator for streaming results\n if (Symbol.asyncIterator in promiseOrGenerator) {\n for await (const r of promiseOrGenerator) {\n if (abortSignal.aborted) {\n if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n }\n break;\n }\n\n updateMessage(r);\n }\n } else {\n updateMessage(await promiseOrGenerator);\n }\n\n if (shouldCancelMessage()) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (message.status.type === \"running\") {\n updateMessage({\n status: { type: \"complete\", reason: \"unknown\" },\n });\n }\n } catch (e) {\n if (e instanceof AbortError) {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else if (e instanceof Error && e.name === \"AbortError\") {\n updateMessage({\n status: { type: \"incomplete\", reason: \"cancelled\" },\n });\n } else {\n updateMessage({\n status: {\n type: \"incomplete\",\n reason: \"error\",\n error: toAssistantError(e),\n },\n });\n\n throw e;\n }\n } finally {\n if (this.abortController === abortController) {\n this.abortController = null;\n }\n\n const history = this._options.adapters.history;\n const item = {\n parentId,\n message,\n runConfig: this._lastRunConfig,\n };\n const isTerminal =\n message.status.type === \"complete\" ||\n message.status.type === \"incomplete\";\n const isPausing =\n message.status.type === \"requires-action\" &&\n !shouldContinue(message, this._options.unstable_humanToolNames);\n\n // Pauses are written only for adapters that can rewrite the entry later;\n // an append-only adapter would strand a half-finished run in history.\n if (ownsMessage() && (isTerminal || (isPausing && history?.update))) {\n const write =\n alreadyPersisted && history?.update\n ? history.update.bind(history)\n : history?.append.bind(history);\n if (write) {\n await this._chainHistoryWrite(message.id, () => write(item));\n }\n }\n }\n return message;\n }\n\n public detach() {\n invalidateThreadRuntime(this);\n // drop the queue so pending items cannot dispatch on a detached thread\n this._queue = null;\n const error = new AbortError(true);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public cancelRun() {\n if (this._queue) {\n if (this._options.unstable_queueClearOnCancel ?? true) {\n this._queue.clear();\n } else {\n this._queue.notifyCancelled();\n if (this._activeRun) this._activeRun.cancelled = true;\n }\n }\n const error = new AbortError(false);\n this.abortController?.abort(error);\n this.abortController = null;\n this._suggestionsController?.abort();\n this._suggestionsController = null;\n }\n\n public addToolResult({\n messageId,\n toolCallId,\n result,\n isError,\n artifact,\n }: AddToolResultOptions) {\n const messageData = this.repository.getMessage(messageId);\n const { parentId } = messageData;\n let { message } = messageData;\n\n if (message.role !== \"assistant\")\n throw new Error(\"Tried to add tool result to non-assistant message\");\n\n let added = false;\n let found = false;\n const newContent = message.content.map((c) => {\n if (c.type !== \"tool-call\") return c;\n if (c.toolCallId !== toolCallId) return c;\n found = true;\n if (c.result === undefined) added = true;\n return {\n ...c,\n result,\n artifact,\n isError,\n };\n });\n\n if (!found)\n throw new Error(\"Tried to add tool result to non-existing tool call\");\n\n message = {\n ...message,\n content: newContent,\n };\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n // a result may arrive mid-run or on a non-head message; the resume\n // intentionally aborts any in-flight run, unlike respondToToolApproval\n if (\n added &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else if (added) {\n this._persistPausedMessage(parentId, message);\n }\n }\n\n public resumeToolCall(_options: ResumeToolCallOptions) {\n throw new Error(\n \"Local runtime does not support resuming tool calls. For human-in-the-loop tools, list the tool in unstable_humanToolNames and complete the call with addToolResult.\",\n );\n }\n\n public respondToToolApproval({\n approvalId,\n approved,\n optionId,\n reason,\n }: RespondToToolApprovalOptions) {\n let message = this.repository\n .getMessages()\n .findLast(\n (m): m is ThreadAssistantMessage =>\n m.role === \"assistant\" &&\n m.content.some(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n ),\n );\n\n if (!message)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n\n if (this.abortController !== null)\n throw new Error(\n \"Tried to respond to a tool approval while a run is in progress\",\n );\n\n if (message.status?.type !== \"requires-action\")\n throw new Error(\n \"Tried to respond to a tool approval on a message whose status is not requires-action\",\n );\n\n const target = message.content.find(\n (c) => c.type === \"tool-call\" && c.approval?.id === approvalId,\n );\n if (target?.type !== \"tool-call\" || !target.approval)\n throw new Error(\"Tried to respond to a non-existing tool approval\");\n if (target.approval.resolution !== undefined)\n throw new Error(\n \"Tried to respond to a tool approval that was cancelled or expired\",\n );\n if (target.approval.approved !== undefined)\n throw new Error(\"Tried to respond to an already decided tool approval\");\n\n const targetApproval = target.approval;\n const newContent = message.content.map((c) => {\n if (c !== target) return c;\n const approval = {\n ...targetApproval,\n approved,\n ...(optionId != null && { optionId }),\n ...(reason != null && { reason }),\n };\n if (approved) return { ...c, approval };\n return {\n ...c,\n approval,\n result: { error: reason || \"Tool approval denied\" },\n isError: true,\n };\n });\n\n message = { ...message, content: newContent };\n const { parentId } = this.repository.getMessage(message.id);\n this.repository.addOrUpdateMessage(parentId, message);\n this._notifySubscribers();\n\n if (\n this.repository.headId === message.id &&\n shouldContinue(message, this._options.unstable_humanToolNames)\n ) {\n this._runLoop(parentId, message, this._lastRunConfig).catch(() => {});\n } else {\n this._persistPausedMessage(parentId, message);\n }\n }\n}\n"],"mappings":";;;;;;;;;;AAyCA,IAAM6B,aAAN,cAAyBC,MAAM;CAC7B,OAAgB;CAChBE;CAEAC,YAAYD,QAAiBE,SAAkB;EAC7C,MAAMA,OAAO;EACb,KAAKF,SAASA;CAChB;AACF;AAEA,IAAaG,yBAAb,cACUrB,sBAEV;CACE,eAA+B;EAC7BuB,gBAAgB;EAChBC,uBAAuB;EACvBC,MAAM;EACNC,QAAQ;EACRC,QAAQ;EACRC,eAAe;EACfC,QAAQ;EACRC,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