@assistant-ui/core 0.3.17 → 0.3.18
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/attachment.d.ts.map +1 -1
- package/dist/adapters/attachment.js +5 -4
- package/dist/adapters/attachment.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/internal.d.ts +3 -2
- package/dist/internal.js +3 -2
- package/dist/model-context/frame/host.d.ts.map +1 -1
- package/dist/model-context/frame/host.js +10 -4
- package/dist/model-context/frame/host.js.map +1 -1
- package/dist/model-context/frame/provider.d.ts +2 -0
- package/dist/model-context/frame/provider.d.ts.map +1 -1
- package/dist/model-context/frame/provider.js +30 -7
- package/dist/model-context/frame/provider.js.map +1 -1
- package/dist/model-context/interactable-composer-metadata.d.ts.map +1 -1
- package/dist/model-context/interactable-composer-metadata.js +16 -9
- package/dist/model-context/interactable-composer-metadata.js.map +1 -1
- package/dist/model-context/registry.d.ts.map +1 -1
- package/dist/model-context/registry.js +3 -5
- package/dist/model-context/registry.js.map +1 -1
- package/dist/model-context/types.d.ts.map +1 -1
- package/dist/model-context/types.js +5 -4
- package/dist/model-context/types.js.map +1 -1
- package/dist/react/client/InMemoryThreadList.d.ts.map +1 -1
- package/dist/react/client/InMemoryThreadList.js +62 -56
- package/dist/react/client/InMemoryThreadList.js.map +1 -1
- package/dist/react/client/Interactables.d.ts.map +1 -1
- package/dist/react/client/Interactables.js +24 -27
- package/dist/react/client/Interactables.js.map +1 -1
- package/dist/react/client/RemoteThreadList.d.ts +1 -0
- package/dist/react/client/RemoteThreadList.d.ts.map +1 -1
- package/dist/react/client/RemoteThreadList.js +151 -141
- package/dist/react/client/RemoteThreadList.js.map +1 -1
- package/dist/react/client/Tools.d.ts.map +1 -1
- package/dist/react/client/Tools.js +18 -16
- package/dist/react/client/Tools.js.map +1 -1
- package/dist/react/interactables-legacy/Interactables.js +242 -121
- package/dist/react/interactables-legacy/Interactables.js.map +1 -1
- package/dist/react/interactables-shared/useInteractablePersistenceQueue.d.ts.map +1 -1
- package/dist/react/interactables-shared/useInteractablePersistenceQueue.js +11 -9
- package/dist/react/interactables-shared/useInteractablePersistenceQueue.js.map +1 -1
- package/dist/react/model-context/makeAssistantTool.d.ts +2 -2
- package/dist/react/model-context/makeAssistantTool.js +1 -1
- package/dist/react/model-context/makeAssistantTool.js.map +1 -1
- package/dist/react/model-context/useAssistantTool.d.ts +2 -2
- package/dist/react/model-context/useAssistantTool.js +1 -1
- package/dist/react/model-context/useAssistantTool.js.map +1 -1
- package/dist/react/model-context/useToolArgsStatus.d.ts.map +1 -1
- package/dist/react/model-context/useToolArgsStatus.js +2 -1
- package/dist/react/model-context/useToolArgsStatus.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js +16 -8
- package/dist/react/runtimes/RemoteThreadListHookInstanceManager.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts +5 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js +103 -103
- package/dist/react/runtimes/RemoteThreadListThreadListRuntimeCore.js.map +1 -1
- package/dist/react/runtimes/RemoteThreadResource.d.ts +1 -0
- package/dist/react/runtimes/RemoteThreadResource.d.ts.map +1 -1
- package/dist/react/runtimes/RemoteThreadResource.js +13 -11
- package/dist/react/runtimes/RemoteThreadResource.js.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts +4 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js +401 -34
- package/dist/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.js.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.d.ts.map +1 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js +2 -1
- package/dist/react/runtimes/cloud/createCloudThreadListAdapter.js.map +1 -1
- package/dist/react/runtimes/useExternalStoreRuntime.js +75 -46
- package/dist/react/runtimes/useExternalStoreRuntime.js.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.d.ts.map +1 -1
- package/dist/react/runtimes/useRemoteThreadListRuntime.js +63 -23
- package/dist/react/runtimes/useRemoteThreadListRuntime.js.map +1 -1
- package/dist/runtime/api/thread-list-item-runtime.d.ts +7 -3
- package/dist/runtime/api/thread-list-item-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-item-runtime.js +2 -2
- package/dist/runtime/api/thread-list-item-runtime.js.map +1 -1
- package/dist/runtime/api/thread-list-runtime.d.ts +3 -0
- package/dist/runtime/api/thread-list-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-list-runtime.js +18 -14
- package/dist/runtime/api/thread-list-runtime.js.map +1 -1
- package/dist/runtime/api/thread-runtime.d.ts +4 -0
- package/dist/runtime/api/thread-runtime.d.ts.map +1 -1
- package/dist/runtime/api/thread-runtime.js +1 -1
- package/dist/runtime/api/thread-runtime.js.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-composer-runtime-core.js +16 -12
- package/dist/runtime/base/base-composer-runtime-core.js.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.d.ts.map +1 -1
- package/dist/runtime/base/base-thread-runtime-core.js +6 -5
- package/dist/runtime/base/base-thread-runtime-core.js.map +1 -1
- package/dist/runtime/interfaces/composer-runtime-core.d.ts +12 -5
- package/dist/runtime/interfaces/composer-runtime-core.d.ts.map +1 -1
- package/dist/runtime/interfaces/thread-list-runtime-core.d.ts +4 -1
- package/dist/runtime/interfaces/thread-list-runtime-core.d.ts.map +1 -1
- package/dist/runtime/utils/external-message-conversion.js +1 -1
- package/dist/runtime/utils/external-message-conversion.js.map +1 -1
- package/dist/runtime/utils/message-repository.d.ts +1 -0
- package/dist/runtime/utils/message-repository.d.ts.map +1 -1
- package/dist/runtime/utils/message-repository.js +15 -6
- package/dist/runtime/utils/message-repository.js.map +1 -1
- package/dist/runtime/utils/thread-message-like.js +1 -1
- package/dist/runtime/utils/thread-message-like.js.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.d.ts.map +1 -1
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js +21 -27
- package/dist/runtimes/external-store/external-store-thread-list-runtime-core.js.map +1 -1
- package/dist/runtimes/internal.d.ts +2 -2
- package/dist/runtimes/internal.js +2 -2
- package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts +18 -1
- package/dist/runtimes/remote-thread-list/remote-thread-state.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/remote-thread-state.js +130 -42
- package/dist/runtimes/remote-thread-list/remote-thread-state.js.map +1 -1
- package/dist/runtimes/remote-thread-list/title-generation.d.ts +49 -0
- package/dist/runtimes/remote-thread-list/title-generation.d.ts.map +1 -0
- package/dist/runtimes/remote-thread-list/title-generation.js +197 -0
- package/dist/runtimes/remote-thread-list/title-generation.js.map +1 -0
- package/dist/runtimes/remote-thread-list/title.d.ts +3 -1
- package/dist/runtimes/remote-thread-list/title.d.ts.map +1 -1
- package/dist/runtimes/remote-thread-list/title.js +9 -1
- package/dist/runtimes/remote-thread-list/title.js.map +1 -1
- package/dist/runtimes/remote-thread-list/types.d.ts +10 -0
- package/dist/runtimes/remote-thread-list/types.d.ts.map +1 -1
- package/dist/store/clients/external-thread.d.ts.map +1 -1
- package/dist/store/clients/external-thread.js +19 -3
- package/dist/store/clients/external-thread.js.map +1 -1
- package/dist/store/clients/model-context-client.d.ts.map +1 -1
- package/dist/store/clients/model-context-client.js +2 -1
- package/dist/store/clients/model-context-client.js.map +1 -1
- package/dist/store/clients/single-thread-list.d.ts.map +1 -1
- package/dist/store/clients/single-thread-list.js +1 -0
- package/dist/store/clients/single-thread-list.js.map +1 -1
- package/dist/store/clients/suggestions.d.ts.map +1 -1
- package/dist/store/clients/suggestions.js +5 -4
- package/dist/store/clients/suggestions.js.map +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.d.ts +1 -0
- package/dist/store/runtime-clients/composer-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/composer-runtime-client.js +97 -61
- package/dist/store/runtime-clients/composer-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/message-runtime-client.d.ts +1 -0
- package/dist/store/runtime-clients/message-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/message-runtime-client.js +221 -144
- package/dist/store/runtime-clients/message-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js +1 -1
- package/dist/store/runtime-clients/thread-list-item-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-list-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-list-runtime-client.js +54 -52
- package/dist/store/runtime-clients/thread-list-runtime-client.js.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.d.ts.map +1 -1
- package/dist/store/runtime-clients/thread-runtime-client.js +193 -121
- package/dist/store/runtime-clients/thread-runtime-client.js.map +1 -1
- package/dist/store/scopes/composer.d.ts +10 -2
- package/dist/store/scopes/composer.d.ts.map +1 -1
- package/dist/store/scopes/message.d.ts +30 -1
- package/dist/store/scopes/message.d.ts.map +1 -1
- package/dist/store/scopes/thread-list-item.d.ts +2 -2
- package/dist/store/scopes/thread-list-item.d.ts.map +1 -1
- package/dist/store/scopes/thread.d.ts +8 -0
- package/dist/store/scopes/thread.d.ts.map +1 -1
- package/dist/store/scopes/threads.d.ts +1 -0
- package/dist/store/scopes/threads.d.ts.map +1 -1
- package/dist/types/attachment.d.ts +2 -1
- package/dist/types/attachment.d.ts.map +1 -1
- package/dist/types/attachment.js +2 -1
- package/dist/types/attachment.js.map +1 -1
- package/dist/utils/abortable-iterable.d.ts +19 -0
- package/dist/utils/abortable-iterable.d.ts.map +1 -0
- package/dist/utils/abortable-iterable.js +72 -0
- package/dist/utils/abortable-iterable.js.map +1 -0
- package/dist/utils/composite-context-provider.d.ts.map +1 -1
- package/dist/utils/composite-context-provider.js +20 -2
- package/dist/utils/composite-context-provider.js.map +1 -1
- package/dist/utils/record.d.ts +11 -0
- package/dist/utils/record.d.ts.map +1 -0
- package/dist/utils/record.js +12 -0
- package/dist/utils/record.js.map +1 -0
- package/package.json +10 -10
- package/src/adapters/attachment.test.ts +50 -1
- package/src/adapters/attachment.ts +7 -4
- package/src/index.ts +1 -0
- package/src/internal.ts +4 -0
- package/src/model-context/frame/host.test.ts +24 -0
- package/src/model-context/frame/host.ts +10 -4
- package/src/model-context/frame/provider.test.ts +71 -0
- package/src/model-context/frame/provider.ts +37 -7
- package/src/model-context/interactable-composer-metadata.test.ts +28 -0
- package/src/model-context/interactable-composer-metadata.ts +9 -3
- package/src/model-context/registry.test.ts +12 -0
- package/src/model-context/registry.ts +3 -2
- package/src/model-context/types.test.ts +25 -0
- package/src/model-context/types.ts +9 -4
- package/src/react/RuntimeAdapter.test.ts +34 -0
- package/src/react/client/InMemoryThreadList.ts +1 -0
- package/src/react/client/Interactables.test.ts +28 -0
- package/src/react/client/Interactables.ts +15 -13
- package/src/react/client/RemoteThreadList.background.test.ts +148 -6
- package/src/react/client/RemoteThreadList.concurrent.test.tsx +42 -1
- package/src/react/client/RemoteThreadList.test.ts +345 -3
- package/src/react/client/RemoteThreadList.ts +166 -110
- package/src/react/client/Tools.ts +22 -11
- package/src/react/interactables-legacy/Interactables.ts +16 -16
- package/src/react/interactables-shared/useInteractablePersistenceQueue.ts +9 -10
- package/src/react/model-context/makeAssistantTool.ts +2 -2
- package/src/react/model-context/useAssistantTool.ts +2 -2
- package/src/react/model-context/useToolArgsStatus.test.tsx +30 -0
- package/src/react/model-context/useToolArgsStatus.ts +2 -1
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.destroy.test.tsx +172 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.running.test.tsx +33 -0
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.test.tsx +7 -1
- package/src/react/runtimes/RemoteThreadListHookInstanceManager.tsx +28 -5
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.load-error.test.ts +132 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.switch-delete.test.ts +105 -0
- package/src/react/runtimes/RemoteThreadListThreadListRuntimeCore.tsx +136 -111
- package/src/react/runtimes/RemoteThreadResource.test.ts +9 -0
- package/src/react/runtimes/RemoteThreadResource.ts +19 -12
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.test.tsx +483 -6
- package/src/react/runtimes/cloud/AssistantCloudThreadHistoryAdapter.ts +504 -68
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.test.ts +15 -0
- package/src/react/runtimes/cloud/createCloudThreadListAdapter.ts +1 -0
- package/src/react/runtimes/useExternalStoreRuntime.lifecycle.test.tsx +41 -0
- package/src/react/runtimes/useExternalStoreRuntime.ts +10 -4
- package/src/react/runtimes/useLocalRuntime.test.tsx +20 -0
- package/src/react/runtimes/useRemoteThreadListRuntime.load-error.test.tsx +108 -0
- package/src/react/runtimes/useRemoteThreadListRuntime.ts +33 -0
- package/src/runtime/api/message-runtime.test.ts +75 -0
- package/src/runtime/api/thread-list-item-runtime.ts +10 -3
- package/src/runtime/api/thread-list-runtime.ts +21 -11
- package/src/runtime/api/thread-runtime.test.ts +78 -0
- package/src/runtime/api/thread-runtime.ts +8 -1
- package/src/runtime/base/base-composer-runtime-core.ts +36 -8
- package/src/runtime/base/base-thread-runtime-core.test.ts +55 -1
- package/src/runtime/base/base-thread-runtime-core.ts +6 -4
- package/src/runtime/interfaces/composer-runtime-core.ts +10 -5
- package/src/runtime/interfaces/thread-list-runtime-core.ts +5 -1
- package/src/runtime/utils/external-message-conversion.test.ts +68 -0
- package/src/runtime/utils/external-message-conversion.ts +1 -1
- package/src/runtime/utils/message-repository.ts +29 -17
- package/src/runtime/utils/thread-message-like.ts +1 -1
- package/src/runtimes/external-store/external-store-thread-list-runtime-core.ts +18 -13
- package/src/runtimes/internal.ts +1 -0
- package/src/runtimes/remote-thread-list/remote-thread-state.test.ts +128 -2
- package/src/runtimes/remote-thread-list/remote-thread-state.ts +182 -42
- package/src/runtimes/remote-thread-list/title-generation.test.ts +602 -0
- package/src/runtimes/remote-thread-list/title-generation.ts +329 -0
- package/src/runtimes/remote-thread-list/title.test.ts +62 -0
- package/src/runtimes/remote-thread-list/title.ts +13 -0
- package/src/runtimes/remote-thread-list/types.ts +10 -0
- package/src/store/clients/external-thread.ts +48 -3
- package/src/store/clients/model-context-client.ts +5 -1
- package/src/store/clients/single-thread-list.ts +1 -0
- package/src/store/clients/suggestions.test.ts +40 -0
- package/src/store/clients/suggestions.ts +13 -10
- package/src/store/runtime-clients/composer-runtime-client.ts +42 -9
- package/src/store/runtime-clients/message-runtime-client.ts +54 -6
- package/src/store/runtime-clients/thread-list-item-runtime-client.ts +4 -2
- package/src/store/runtime-clients/thread-list-runtime-client.ts +1 -0
- package/src/store/runtime-clients/thread-runtime-client.ts +58 -10
- package/src/store/scopes/composer.ts +16 -4
- package/src/store/scopes/message.ts +14 -0
- package/src/store/scopes/thread-list-item.ts +5 -2
- package/src/store/scopes/thread.ts +4 -0
- package/src/store/scopes/threads.ts +1 -0
- package/src/tests/MessageRepository.test.ts +116 -0
- package/src/tests/OptimisticState-list-race.test.ts +1 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-initialize-adapter-change.test.ts +38 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-load-race.test.ts +47 -0
- package/src/tests/RemoteThreadListThreadListRuntimeCore-title-race.test.ts +89 -0
- package/src/tests/attachment-adapters.test.ts +14 -0
- package/src/tests/base-composer-runtime-core.test.ts +39 -0
- package/src/tests/external-store-thread-list-runtime-core.test.ts +83 -0
- package/src/tests/external-store-thread-runtime-core-adapter.test.ts +27 -18
- package/src/tests/external-thread-attachments.test.tsx +139 -0
- package/src/tests/external-thread-parity.test.tsx +23 -0
- package/src/tests/remote-thread-list-isLoading.test.ts +1 -0
- package/src/tests/thread-list-runtime-getLoadThreadsPromise.test.ts +1 -0
- package/src/tests/thread-switch-events.test.tsx +78 -0
- package/src/tests/tools-scope-migration.test.tsx +28 -0
- package/src/types/attachment.ts +4 -0
- package/src/utils/abortable-iterable.test.ts +213 -0
- package/src/utils/abortable-iterable.ts +93 -0
- package/src/utils/composite-context-provider.test.ts +25 -0
- package/src/utils/composite-context-provider.ts +23 -2
- package/src/utils/record.test.ts +48 -0
- package/src/utils/record.ts +11 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachment.d.ts","names":[],"sources":["../../src/adapters/attachment.ts"],"mappings":";;;KAQY;EACV;EACA,IAAI;IACF,MAAM;MACJ,QAAQ,qBAAqB,eAAe;EAChD,OAAO,YAAY,aAAa;EAChC,KAAK,YAAY,oBAAoB,QAAQ;;cAGlC,wCAAwC;EAC5C;EAEM,IAAI;IAAS,MAAM;MAAS,QAAQ;EAWpC,KACX,YAAY,oBACX,QAAQ;EAaE,UAAM;;cA0BR,iBAAwB,MAAM,SAAO;cAarC,uCAAuC;EAC3C;EAGM,IAAI;IAAS,MAAM;MAAS,QAAQ;EAWpC,KACX,YAAY,oBACX,QAAQ;EAaE,UAAM;;iBAiBL,kBACd;EAAQ;EAAc;GACtB;iBAiCc,iBACd,YAAY,sBACZ,YAAY;
|
|
1
|
+
{"version":3,"file":"attachment.d.ts","names":[],"sources":["../../src/adapters/attachment.ts"],"mappings":";;;KAQY;EACV;EACA,IAAI;IACF,MAAM;MACJ,QAAQ,qBAAqB,eAAe;EAChD,OAAO,YAAY,aAAa;EAChC,KAAK,YAAY,oBAAoB,QAAQ;;cAGlC,wCAAwC;EAC5C;EAEM,IAAI;IAAS,MAAM;MAAS,QAAQ;EAWpC,KACX,YAAY,oBACX,QAAQ;EAaE,UAAM;;cA0BR,iBAAwB,MAAM,SAAO;cAarC,uCAAuC;EAC3C;EAGM,IAAI;IAAS,MAAM;MAAS,QAAQ;EAWpC,KACX,YAAY,oBACX,QAAQ;EAaE,UAAM;;iBAiBL,kBACd;EAAQ;EAAc;GACtB;iBAiCc,iBACd,YAAY,sBACZ,YAAY;iBASE,yBACd,MAAM,QAAQ;EAAyB;KACtC;iBA4Ca,iBACd,kBAAkB,0BACjB;cAUU,sCAAsC;UACzC;EAED;EAEK,YAAA,UAAU;EAgBf,IAAI;IAAS,MAAM;MAAM,QAAA,qBAAA,eAAA;EASnB,KAAK,YAAY,oBAAiB,QAAA;EAUlC,OAAO,YAAY,aAAU"}
|
|
@@ -86,10 +86,10 @@ const getFileText = async (file) => {
|
|
|
86
86
|
function fileMatchesAccept(file, acceptString) {
|
|
87
87
|
if (acceptString === "*") return true;
|
|
88
88
|
const allowedTypes = acceptString.split(",").map((type) => type.trim().toLowerCase());
|
|
89
|
-
const
|
|
89
|
+
const fileName = file.name.toLowerCase();
|
|
90
90
|
const fileMimeType = file.type.split(";", 1)[0].trim().toLowerCase();
|
|
91
91
|
for (const type of allowedTypes) {
|
|
92
|
-
if (type.startsWith(".") && type
|
|
92
|
+
if (type.startsWith(".") && fileName.endsWith(type)) return true;
|
|
93
93
|
if (type.includes("/") && type === fileMimeType) return true;
|
|
94
94
|
if (type.endsWith("/*")) {
|
|
95
95
|
const generalType = type.split("/")[0];
|
|
@@ -100,7 +100,8 @@ function fileMatchesAccept(file, acceptString) {
|
|
|
100
100
|
}
|
|
101
101
|
function attachmentsEqual(a, b) {
|
|
102
102
|
if (a.length !== b.length) return false;
|
|
103
|
-
|
|
103
|
+
for (let i = 0; i < a.length; i++) if (a[i]?.id !== b[i]?.id) return false;
|
|
104
|
+
return true;
|
|
104
105
|
}
|
|
105
106
|
function partToCompleteAttachment(part) {
|
|
106
107
|
const id = generateId();
|
|
@@ -162,7 +163,7 @@ var CompositeAttachmentAdapter = class {
|
|
|
162
163
|
}
|
|
163
164
|
async remove(attachment) {
|
|
164
165
|
const adapters = this._adapters.slice();
|
|
165
|
-
for (const adapter of adapters) if (fileMatchesAccept({
|
|
166
|
+
for (const adapter of adapters) if (fileMatchesAccept(attachment.file ?? {
|
|
166
167
|
name: attachment.name,
|
|
167
168
|
type: attachment.contentType ?? ""
|
|
168
169
|
}, adapter.accept)) return adapter.remove(attachment);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attachment.js","names":["Attachment","PendingAttachment","CompleteAttachment","ThreadUserMessagePart","generateId","AttachmentAdapter","accept","add","state","file","File","Promise","AsyncGenerator","remove","attachment","send","SimpleImageAttachmentAdapter","id","type","name","contentType","status","reason","content","image","getFileDataURL","bytesToBase64","bytes","Uint8Array","nodeBuffer","globalThis","Buffer","from","toString","encoding","binary","chunkSize","i","length","String","fromCharCode","subarray","btoa","FileReader","buffer","arrayBuffer","resolve","reject","reader","onload","result","onerror","error","readAsDataURL","SimpleTextAttachmentAdapter","text","getFileText","readAsText","fileMatchesAccept","acceptString","allowedTypes","split","map","trim","toLowerCase","fileExtension","pop","fileMimeType","startsWith","includes","endsWith","generalType","attachmentsEqual","a","b","every","att","partToCompleteAttachment","part","Exclude","filename","mimeType","audio","format","liftNonTextParts","push","CompositeAttachmentAdapter","_adapters","constructor","adapters","wildcardIdx","findIndex","Error","join","adapter","slice"],"sources":["../../src/adapters/attachment.ts"],"sourcesContent":["import type {\n Attachment,\n PendingAttachment,\n CompleteAttachment,\n} from \"../types/attachment\";\nimport type { ThreadUserMessagePart } from \"../types/message\";\nimport { generateId } from \"../utils/id\";\n\nexport type AttachmentAdapter = {\n accept: string;\n add(state: {\n file: File;\n }): Promise<PendingAttachment> | AsyncGenerator<PendingAttachment, void>;\n remove(attachment: Attachment): Promise<void>;\n send(attachment: PendingAttachment): Promise<CompleteAttachment>;\n};\n\nexport class SimpleImageAttachmentAdapter implements AttachmentAdapter {\n public accept = \"image/*\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: generateId(),\n type: \"image\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"image\",\n image: await getFileDataURL(attachment.file),\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n const nodeBuffer = (\n globalThis as {\n Buffer?: {\n from(bytes: Uint8Array): { toString(encoding: string): string };\n };\n }\n ).Buffer;\n if (nodeBuffer) {\n return nodeBuffer.from(bytes).toString(\"base64\");\n }\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n};\n\n// React Native's Blob polyfill has FileReader but not file.text()/arrayBuffer(); Node has\n// the reverse. Prefer FileReader when present, falling back to the Blob methods otherwise.\nexport const getFileDataURL = async (file: File): Promise<string> => {\n if (typeof FileReader === \"undefined\") {\n const buffer = await file.arrayBuffer();\n return `data:${file.type || \"application/octet-stream\"};base64,${bytesToBase64(new Uint8Array(buffer))}`;\n }\n return new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsDataURL(file);\n });\n};\n\nexport class SimpleTextAttachmentAdapter implements AttachmentAdapter {\n public accept =\n \"text/plain,text/html,text/markdown,text/csv,text/xml,text/json,application/json,text/css\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: generateId(),\n type: \"document\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"text\",\n text: `<attachment name=${attachment.name}>\\n${await getFileText(attachment.file)}\\n</attachment>`,\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileText = async (file: File): Promise<string> => {\n if (typeof FileReader === \"undefined\") {\n return file.text();\n }\n return new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsText(file);\n });\n};\n\nexport function fileMatchesAccept(\n file: { name: string; type: string },\n acceptString: string,\n) {\n if (acceptString === \"*\") {\n return true;\n }\n\n const allowedTypes = acceptString\n .split(\",\")\n .map((type) => type.trim().toLowerCase());\n\n const fileExtension = `.${file.name.split(\".\").pop()!.toLowerCase()}`;\n const fileMimeType = file.type.split(\";\", 1)[0]!.trim().toLowerCase();\n\n for (const type of allowedTypes) {\n if (type.startsWith(\".\") && type === fileExtension) {\n return true;\n }\n\n if (type.includes(\"/\") && type === fileMimeType) {\n return true;\n }\n\n if (type.endsWith(\"/*\")) {\n const generalType = type.split(\"/\")[0]!;\n if (fileMimeType.startsWith(`${generalType}/`)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function attachmentsEqual(\n a: readonly CompleteAttachment[],\n b: readonly CompleteAttachment[],\n): boolean {\n if (a.length !== b.length) return false;\n return a.every((att, i) => att.id === b[i]!.id);\n}\n\nexport function partToCompleteAttachment(\n part: Exclude<ThreadUserMessagePart, { type: \"text\" }>,\n): CompleteAttachment {\n const id = generateId();\n\n if (part.type === \"image\") {\n return {\n id,\n type: \"image\",\n name: part.filename ?? \"image\",\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"file\") {\n return {\n id,\n type: \"document\",\n name: part.filename ?? \"document\",\n contentType: part.mimeType,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"audio\") {\n return {\n id,\n type: \"audio\",\n name: `audio.${part.audio.format}`,\n contentType: `audio/${part.audio.format}`,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n return {\n id,\n type: \"data\",\n name: part.name,\n content: [part],\n status: { type: \"complete\" },\n };\n}\n\nexport function liftNonTextParts(\n content: readonly ThreadUserMessagePart[],\n): CompleteAttachment[] {\n const result: CompleteAttachment[] = [];\n for (const part of content) {\n if (part.type !== \"text\") {\n result.push(partToCompleteAttachment(part));\n }\n }\n return result;\n}\n\nexport class CompositeAttachmentAdapter implements AttachmentAdapter {\n private _adapters: AttachmentAdapter[];\n\n public accept: string;\n\n constructor(adapters: AttachmentAdapter[]) {\n this._adapters = adapters;\n\n const wildcardIdx = adapters.findIndex((a) => a.accept === \"*\");\n if (wildcardIdx !== -1) {\n if (wildcardIdx !== adapters.length - 1)\n throw new Error(\n \"A wildcard adapter (handling all files) can only be specified as the last adapter.\",\n );\n\n this.accept = \"*\";\n } else {\n this.accept = adapters.map((a) => a.accept).join(\",\");\n }\n }\n\n public add(state: { file: File }) {\n for (const adapter of this._adapters) {\n if (fileMatchesAccept(state.file, adapter.accept)) {\n return adapter.add(state);\n }\n }\n throw new Error(\"No matching adapter found for file\");\n }\n\n public async send(attachment: PendingAttachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.send(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n\n public async remove(attachment: Attachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (\n fileMatchesAccept(\n {\n name: attachment.name,\n type: attachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n return adapter.remove(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n}\n"],"mappings":";;AAiBA,IAAagB,+BAAb,MAAuE;CACrE,SAAgB;CAEhB,MAAaT,IAAIC,OAAmD;EAClE,OAAO;GACLS,IAAIb,WAAW;GACfc,MAAM;GACNC,MAAMX,MAAMC,KAAKU;GACjBC,aAAaZ,MAAMC,KAAKS;GACxBT,MAAMD,MA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AAKF,YAAYE;EAEjB,MAAMC,cAAcD,SAASE,WAAWlB,MAAMA,EAAEnE,WAAW,GAAG;EAC9D,IAAIoF,gBAAgB,IAAI;GACtB,IAAIA,gBAAgBD,SAASnD,SAAS,GACpC,MAAM,IAAIsD,MACR,oFACF;GAEF,KAAKtF,SAAS;EAChB,OACE,KAAKA,SAASmF,SAAS3B,KAAKW,MAAMA,EAAEnE,MAAM,CAAC,CAACuF,KAAK,GAAG;CAExD;CAEA,IAAWrF,OAAuB;EAChC,KAAK,MAAMsF,WAAW,KAAKP,WACzB,IAAI7B,kBAAkBlD,MAAMC,MAAMqF,QAAQxF,MAAM,GAC9C,OAAOwF,QAAQvF,IAAIC,KAAK;EAG5B,MAAM,IAAIoF,MAAM,oCAAoC;CACtD;CAEA,MAAa7E,KAAKD,YAA+B;EAC/C,MAAM2E,WAAW,KAAKF,UAAUQ,MAAM;EACtC,KAAK,MAAMD,WAAWL,UACpB,IAAI/B,kBAAkB5C,WAAWL,MAAMqF,QAAQxF,MAAM,GACnD,OAAOwF,QAAQ/E,KAAKD,UAAU;EAGlC,MAAM,IAAI8E,MAAM,0CAA0C;CAC5D;CAEA,MAAa/E,OAAOC,YAAwB;EAC1C,MAAM2E,WAAW,KAAKF,UAAUQ,MAAM;EACtC,KAAK,MAAMD,WAAWL,UACpB,IACE/B,kBACE;GACEvC,MAAML,WAAWK;GACjBD,MAAMJ,WAAWM,eAAe;EAClC,GACA0E,QAAQxF,MACV,GAEA,OAAOwF,QAAQjF,OAAOC,UAAU;EAGpC,MAAM,IAAI8E,MAAM,0CAA0C;CAC5D;AACF"}
|
|
1
|
+
{"version":3,"file":"attachment.js","names":["Attachment","PendingAttachment","CompleteAttachment","ThreadUserMessagePart","generateId","AttachmentAdapter","accept","add","state","file","File","Promise","AsyncGenerator","remove","attachment","send","SimpleImageAttachmentAdapter","id","type","name","contentType","status","reason","content","image","getFileDataURL","bytesToBase64","bytes","Uint8Array","nodeBuffer","globalThis","Buffer","from","toString","encoding","binary","chunkSize","i","length","String","fromCharCode","subarray","btoa","FileReader","buffer","arrayBuffer","resolve","reject","reader","onload","result","onerror","error","readAsDataURL","SimpleTextAttachmentAdapter","text","getFileText","readAsText","fileMatchesAccept","acceptString","allowedTypes","split","map","trim","toLowerCase","fileName","fileMimeType","startsWith","endsWith","includes","generalType","attachmentsEqual","a","b","partToCompleteAttachment","part","Exclude","filename","mimeType","audio","format","liftNonTextParts","push","CompositeAttachmentAdapter","_adapters","constructor","adapters","wildcardIdx","findIndex","Error","join","adapter","slice"],"sources":["../../src/adapters/attachment.ts"],"sourcesContent":["import type {\n Attachment,\n PendingAttachment,\n CompleteAttachment,\n} from \"../types/attachment\";\nimport type { ThreadUserMessagePart } from \"../types/message\";\nimport { generateId } from \"../utils/id\";\n\nexport type AttachmentAdapter = {\n accept: string;\n add(state: {\n file: File;\n }): Promise<PendingAttachment> | AsyncGenerator<PendingAttachment, void>;\n remove(attachment: Attachment): Promise<void>;\n send(attachment: PendingAttachment): Promise<CompleteAttachment>;\n};\n\nexport class SimpleImageAttachmentAdapter implements AttachmentAdapter {\n public accept = \"image/*\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: generateId(),\n type: \"image\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"image\",\n image: await getFileDataURL(attachment.file),\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst bytesToBase64 = (bytes: Uint8Array): string => {\n const nodeBuffer = (\n globalThis as {\n Buffer?: {\n from(bytes: Uint8Array): { toString(encoding: string): string };\n };\n }\n ).Buffer;\n if (nodeBuffer) {\n return nodeBuffer.from(bytes).toString(\"base64\");\n }\n let binary = \"\";\n const chunkSize = 0x8000;\n for (let i = 0; i < bytes.length; i += chunkSize) {\n binary += String.fromCharCode(...bytes.subarray(i, i + chunkSize));\n }\n return btoa(binary);\n};\n\n// React Native's Blob polyfill has FileReader but not file.text()/arrayBuffer(); Node has\n// the reverse. Prefer FileReader when present, falling back to the Blob methods otherwise.\nexport const getFileDataURL = async (file: File): Promise<string> => {\n if (typeof FileReader === \"undefined\") {\n const buffer = await file.arrayBuffer();\n return `data:${file.type || \"application/octet-stream\"};base64,${bytesToBase64(new Uint8Array(buffer))}`;\n }\n return new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsDataURL(file);\n });\n};\n\nexport class SimpleTextAttachmentAdapter implements AttachmentAdapter {\n public accept =\n \"text/plain,text/html,text/markdown,text/csv,text/xml,text/json,application/json,text/css\";\n\n public async add(state: { file: File }): Promise<PendingAttachment> {\n return {\n id: generateId(),\n type: \"document\",\n name: state.file.name,\n contentType: state.file.type,\n file: state.file,\n status: { type: \"requires-action\", reason: \"composer-send\" },\n };\n }\n\n public async send(\n attachment: PendingAttachment,\n ): Promise<CompleteAttachment> {\n return {\n ...attachment,\n status: { type: \"complete\" },\n content: [\n {\n type: \"text\",\n text: `<attachment name=${attachment.name}>\\n${await getFileText(attachment.file)}\\n</attachment>`,\n },\n ],\n };\n }\n\n public async remove() {\n // noop\n }\n}\n\nconst getFileText = async (file: File): Promise<string> => {\n if (typeof FileReader === \"undefined\") {\n return file.text();\n }\n return new Promise<string>((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = (error) => reject(error);\n reader.readAsText(file);\n });\n};\n\nexport function fileMatchesAccept(\n file: { name: string; type: string },\n acceptString: string,\n) {\n if (acceptString === \"*\") {\n return true;\n }\n\n const allowedTypes = acceptString\n .split(\",\")\n .map((type) => type.trim().toLowerCase());\n\n const fileName = file.name.toLowerCase();\n const fileMimeType = file.type.split(\";\", 1)[0]!.trim().toLowerCase();\n\n for (const type of allowedTypes) {\n if (type.startsWith(\".\") && fileName.endsWith(type)) {\n return true;\n }\n\n if (type.includes(\"/\") && type === fileMimeType) {\n return true;\n }\n\n if (type.endsWith(\"/*\")) {\n const generalType = type.split(\"/\")[0]!;\n if (fileMimeType.startsWith(`${generalType}/`)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\nexport function attachmentsEqual(\n a: readonly CompleteAttachment[],\n b: readonly CompleteAttachment[],\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i]?.id !== b[i]?.id) return false;\n }\n return true;\n}\n\nexport function partToCompleteAttachment(\n part: Exclude<ThreadUserMessagePart, { type: \"text\" }>,\n): CompleteAttachment {\n const id = generateId();\n\n if (part.type === \"image\") {\n return {\n id,\n type: \"image\",\n name: part.filename ?? \"image\",\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"file\") {\n return {\n id,\n type: \"document\",\n name: part.filename ?? \"document\",\n contentType: part.mimeType,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n if (part.type === \"audio\") {\n return {\n id,\n type: \"audio\",\n name: `audio.${part.audio.format}`,\n contentType: `audio/${part.audio.format}`,\n content: [part],\n status: { type: \"complete\" },\n };\n }\n\n return {\n id,\n type: \"data\",\n name: part.name,\n content: [part],\n status: { type: \"complete\" },\n };\n}\n\nexport function liftNonTextParts(\n content: readonly ThreadUserMessagePart[],\n): CompleteAttachment[] {\n const result: CompleteAttachment[] = [];\n for (const part of content) {\n if (part.type !== \"text\") {\n result.push(partToCompleteAttachment(part));\n }\n }\n return result;\n}\n\nexport class CompositeAttachmentAdapter implements AttachmentAdapter {\n private _adapters: AttachmentAdapter[];\n\n public accept: string;\n\n constructor(adapters: AttachmentAdapter[]) {\n this._adapters = adapters;\n\n const wildcardIdx = adapters.findIndex((a) => a.accept === \"*\");\n if (wildcardIdx !== -1) {\n if (wildcardIdx !== adapters.length - 1)\n throw new Error(\n \"A wildcard adapter (handling all files) can only be specified as the last adapter.\",\n );\n\n this.accept = \"*\";\n } else {\n this.accept = adapters.map((a) => a.accept).join(\",\");\n }\n }\n\n public add(state: { file: File }) {\n for (const adapter of this._adapters) {\n if (fileMatchesAccept(state.file, adapter.accept)) {\n return adapter.add(state);\n }\n }\n throw new Error(\"No matching adapter found for file\");\n }\n\n public async send(attachment: PendingAttachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (fileMatchesAccept(attachment.file, adapter.accept)) {\n return adapter.send(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n\n public async remove(attachment: Attachment) {\n const adapters = this._adapters.slice();\n for (const adapter of adapters) {\n if (\n fileMatchesAccept(\n attachment.file ?? {\n name: attachment.name,\n type: attachment.contentType ?? \"\",\n },\n adapter.accept,\n )\n ) {\n return adapter.remove(attachment);\n }\n }\n throw new Error(\"No matching adapter found for attachment\");\n }\n}\n"],"mappings":";;AAiBA,IAAagB,+BAAb,MAAuE;CACrE,SAAgB;CAEhB,MAAaT,IAAIC,OAAmD;EAClE,OAAO;GACLS,IAAIb,WAAW;GACfc,MAAM;GACNC,MAAMX,MAAMC,KAAKU;GACjBC,aAAaZ,MAAMC,KAAKS;GACxBT,MAAMD,MAAMC;GACZY,QAAQ;IAAEH,MAAM;IAAmBI,QAAQ;GAAgB;EAC7D;CACF;CAEA,MAAaP,KACXD,YAC6B;EAC7B,OAAO;GACL,GAAGA;GACHO,QAAQ,EAAEH,MAAM,WAAW;GAC3BK,SAAS,CACP;IACEL,MAAM;IACNM,OAAO,MAAMC,eAAeX,WAAWL,IAAI;GAC7C,CAAC;EAEL;CACF;CAEA,MAAaI,SAAS,CACpB;AAEJ;AAEA,MAAMa,iBAAiBC,UAA8B;CACnD,MAAME,aACJC,WAKAC;CACF,IAAIF,YACF,OAAOA,WAAWG,KAAKL,KAAK,CAAC,CAACM,SAAS,QAAQ;CAEjD,IAAIE,SAAS;CACb,MAAMC,YAAY;CAClB,KAAK,IAAIC,IAAI,GAAGA,IAAIV,MAAMW,QAAQD,K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,YAA+B;EAC/C,MAAMwE,WAAW,KAAKF,UAAUQ,MAAM;EACtC,KAAK,MAAMD,WAAWL,UACpB,IAAI5B,kBAAkB5C,WAAWL,MAAMkF,QAAQrF,MAAM,GACnD,OAAOqF,QAAQ5E,KAAKD,UAAU;EAGlC,MAAM,IAAI2E,MAAM,0CAA0C;CAC5D;CAEA,MAAa5E,OAAOC,YAAwB;EAC1C,MAAMwE,WAAW,KAAKF,UAAUQ,MAAM;EACtC,KAAK,MAAMD,WAAWL,UACpB,IACE5B,kBACE5C,WAAWL,QAAQ;GACjBU,MAAML,WAAWK;GACjBD,MAAMJ,WAAWM,eAAe;EAClC,GACAuE,QAAQrF,MACV,GAEA,OAAOqF,QAAQ9E,OAAOC,UAAU;EAGpC,MAAM,IAAI2E,MAAM,0CAA0C;CAC5D;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -35,7 +35,7 @@ import { ThreadListItemCoreState, ThreadListItemStatus, ThreadListRuntimeCore }
|
|
|
35
35
|
import { AssistantRuntimeCore } from "./runtime/interfaces/assistant-runtime-core.js";
|
|
36
36
|
import { generateId } from "./utils/id.js";
|
|
37
37
|
import { ThreadListItemState } from "./runtime/api/bindings.js";
|
|
38
|
-
import { ThreadListItemEventCallback, ThreadListItemEventPayload, ThreadListItemEventType, ThreadListItemRuntime } from "./runtime/api/thread-list-item-runtime.js";
|
|
38
|
+
import { ThreadListItemEventCallback, ThreadListItemEventPayload, ThreadListItemEventType, ThreadListItemGenerateTitleOptions, ThreadListItemRuntime } from "./runtime/api/thread-list-item-runtime.js";
|
|
39
39
|
import { ThreadListRuntime, ThreadListState } from "./runtime/api/thread-list-runtime.js";
|
|
40
40
|
import { AttachmentRuntime, AttachmentState } from "./runtime/api/attachment-runtime.js";
|
|
41
41
|
import { ComposerRuntime, ComposerState, EditComposerRuntime, EditComposerState, ThreadComposerRuntime, ThreadComposerState } from "./runtime/api/composer-runtime.js";
|
|
@@ -53,4 +53,4 @@ import { ExternalStoreSharedOptions, pickExternalStoreSharedOptions } from "./ru
|
|
|
53
53
|
import { MessageQueueController, MessageQueueDriver, createMessageQueue } from "./runtime/queue/message-queue.js";
|
|
54
54
|
import { InMemoryThreadListAdapter } from "./runtimes/remote-thread-list/adapter/in-memory.js";
|
|
55
55
|
import { createRequestHeaders } from "./runtimes/assistant-transport/utils.js";
|
|
56
|
-
export { type AddToolResultOptions, type AppendMessage, type Assistant, type AssistantContextConfig, type AssistantError, type AssistantErrorCode, AssistantFrameHost, AssistantFrameProvider, type AssistantInstructionsConfig, type AssistantRuntime, type AssistantRuntimeCore, type AssistantToolProps, type Attachment, type AttachmentAdapter, type AttachmentAddErrorEvent, type AttachmentAddErrorReason, type AttachmentRuntime, type AttachmentRuntimePath, type AttachmentState, type AttachmentStatus, type ChatModelAdapter, type ChatModelRunOptions, type ChatModelRunResult, type ChatModelRunUpdate, type CompleteAttachment, type CompleteAttachmentStatus, type ComposerRuntime, type ComposerRuntimeCore, type ComposerRuntimeEventCallback, type ComposerRuntimeEventPayload, type ComposerRuntimeEventType, type ComposerRuntimePath, type ComposerState, CompositeAttachmentAdapter, type CoreChatModelRunResult, type CreateAppendMessage, type CreateAttachment, type CreateResumeRunConfig, type CreateStartRunConfig, type CreateSuggestionAdapterOptions, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, type ErrorDisplay, type ErrorSeverity, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreBranchChange, type ExternalStoreMessageConverter, type ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, type ExternalThreadBranchAdapter, type ExternalThreadQueueAdapter, FRAME_MESSAGE_CHANNEL, type FeedbackAdapter, type FileMessagePart, type FrameMessage, type FrameMessageType, type GenerativeUIMessagePart, type GenerativeUINode, type GenerativeUISpec, type GenericThreadHistoryAdapter, type ImageMessagePart, InMemoryThreadListAdapter, type LanguageModelConfig, type LanguageModelV1CallSettings, type LocalRuntimeOptionsBase, MCP_APP_URI_SCHEME, type McpAppMetadata, type MessageFormatAdapter, type MessageFormatItem, type MessageFormatRepository, MessageNotSentError, type MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, type MessagePartStreamStatus, type MessageQueueController, type MessageQueueDriver, type MessageRole, type MessageRuntime, type MessageRuntimePath, type MessageState, type MessageStatus, type MessageStorageEntry, type MessageTiming, type ModelContext, type ModelContextProvider, ModelContextRegistry, type ModelContextRegistryInstructionHandle, type ModelContextRegistryProviderHandle, type ModelContextRegistryToolHandle, type PartProviderMetadata, type PendingAttachment, type PendingAttachmentStatus, type QueuePlacement, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListProviderComponent, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeAdapters, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type StreamingTimingAccessors, type StreamingTimingOptions, type StreamingTimingState, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type SuggestionAdapterGenerateOptions, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, type ThreadListItemRuntime, type ThreadListItemRuntimePath, type ThreadListItemState, type ThreadListItemStatus, type ThreadListRuntime, type ThreadListRuntimeCore, type ThreadListState, type ThreadMessage, type ThreadMessageLike, type ThreadRuntime, type ThreadRuntimeCore, type ThreadRuntimeEventCallback, type ThreadRuntimeEventPayload, type ThreadRuntimeEventType, type ThreadRuntimePath, type ThreadState, type ThreadStep, type ThreadSuggestion, type ThreadSystemMessage, type ThreadUserMessage, type ThreadUserMessagePart, type ToolApprovalDisplay, type ToolApprovalOption, type ToolApprovalOptionKind, type ToolApprovalResponse, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolCallTiming, type ToolExecutionStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_InteractableSnapshotEntry, type Unstable_InteractableVersion, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type UserCommands, type UserExternalState, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, isMessageNotSentError, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, toolApprovalAcceptsText, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
|
|
56
|
+
export { type AddToolResultOptions, type AppendMessage, type Assistant, type AssistantContextConfig, type AssistantError, type AssistantErrorCode, AssistantFrameHost, AssistantFrameProvider, type AssistantInstructionsConfig, type AssistantRuntime, type AssistantRuntimeCore, type AssistantToolProps, type Attachment, type AttachmentAdapter, type AttachmentAddErrorEvent, type AttachmentAddErrorReason, type AttachmentRuntime, type AttachmentRuntimePath, type AttachmentState, type AttachmentStatus, type ChatModelAdapter, type ChatModelRunOptions, type ChatModelRunResult, type ChatModelRunUpdate, type CompleteAttachment, type CompleteAttachmentStatus, type ComposerRuntime, type ComposerRuntimeCore, type ComposerRuntimeEventCallback, type ComposerRuntimeEventPayload, type ComposerRuntimeEventType, type ComposerRuntimePath, type ComposerState, CompositeAttachmentAdapter, type CoreChatModelRunResult, type CreateAppendMessage, type CreateAttachment, type CreateResumeRunConfig, type CreateStartRunConfig, type CreateSuggestionAdapterOptions, type DataMessagePart, type DictationAdapter, type DictationState, type EditComposerRuntime, type EditComposerRuntimeCore, type EditComposerState, type ErrorDisplay, type ErrorSeverity, ExportedMessageRepository, type ExportedMessageRepositoryItem, type ExternalStoreAdapter, type ExternalStoreBranchChange, type ExternalStoreMessageConverter, type ExternalStoreSharedOptions, type ExternalStoreThreadData, type ExternalStoreThreadListAdapter, type ExternalThreadBranchAdapter, type ExternalThreadQueueAdapter, FRAME_MESSAGE_CHANNEL, type FeedbackAdapter, type FileMessagePart, type FrameMessage, type FrameMessageType, type GenerativeUIMessagePart, type GenerativeUINode, type GenerativeUISpec, type GenericThreadHistoryAdapter, type ImageMessagePart, InMemoryThreadListAdapter, type LanguageModelConfig, type LanguageModelV1CallSettings, type LocalRuntimeOptionsBase, MCP_APP_URI_SCHEME, type McpAppMetadata, type MessageFormatAdapter, type MessageFormatItem, type MessageFormatRepository, MessageNotSentError, type MessagePartRuntime, type MessagePartRuntimePath, type MessagePartState, type MessagePartStatus, type MessagePartStreamStatus, type MessageQueueController, type MessageQueueDriver, type MessageRole, type MessageRuntime, type MessageRuntimePath, type MessageState, type MessageStatus, type MessageStorageEntry, type MessageTiming, type ModelContext, type ModelContextProvider, ModelContextRegistry, type ModelContextRegistryInstructionHandle, type ModelContextRegistryProviderHandle, type ModelContextRegistryToolHandle, type PartProviderMetadata, type PendingAttachment, type PendingAttachmentStatus, type QueuePlacement, type QuoteInfo, type RealtimeVoiceAdapter, type ReasoningMessagePart, type RemoteThreadInitializeResponse, type RemoteThreadListAdapter, type RemoteThreadListOptions, type RemoteThreadListPageOptions, type RemoteThreadListProviderComponent, type RemoteThreadListResponse, type RemoteThreadMetadata, type RespondToToolApprovalOptions, type ResumeRunConfig, type ResumeToolCallOptions, type RunConfig, type RuntimeAdapters, type RuntimeCapabilities, type SendOptions, type SerializedModelContext, type SerializedTool, SimpleImageAttachmentAdapter, SimpleTextAttachmentAdapter, type SourceMessagePart, type SourceProviderMetadata, type SpeechState, type SpeechSynthesisAdapter, type StartRunConfig, type StreamingTimingAccessors, type StreamingTimingOptions, type StreamingTimingState, type SubmitFeedbackOptions, type SubmittedFeedback, type SuggestionAdapter, type SuggestionAdapterGenerateOptions, type TextMessagePart, type ThreadAssistantMessage, type ThreadAssistantMessagePart, type ThreadComposerRuntime, type ThreadComposerRuntimeCore, type ThreadComposerState, type ThreadHistoryAdapter, type ThreadListItemCoreState, type ThreadListItemEventCallback, type ThreadListItemEventPayload, type ThreadListItemEventType, type ThreadListItemGenerateTitleOptions, type ThreadListItemRuntime, type ThreadListItemRuntimePath, type ThreadListItemState, type ThreadListItemStatus, type ThreadListRuntime, type ThreadListRuntimeCore, type ThreadListState, type ThreadMessage, type ThreadMessageLike, type ThreadRuntime, type ThreadRuntimeCore, type ThreadRuntimeEventCallback, type ThreadRuntimeEventPayload, type ThreadRuntimeEventType, type ThreadRuntimePath, type ThreadState, type ThreadStep, type ThreadSuggestion, type ThreadSystemMessage, type ThreadUserMessage, type ThreadUserMessagePart, type ToolApprovalDisplay, type ToolApprovalOption, type ToolApprovalOptionKind, type ToolApprovalResponse, type ToolCallMessagePart, type ToolCallMessagePartMcpMetadata, type ToolCallMessagePartStatus, type ToolCallTiming, type ToolExecutionStatus, type ToolModelContentPart, type Unstable_AudioMessagePart, type Unstable_DirectiveFormatter, type Unstable_DirectiveSegment, type Unstable_InteractableSnapshotEntry, type Unstable_InteractableVersion, type Unstable_TriggerAdapter, type Unstable_TriggerCategory, type Unstable_TriggerItem, type Unsubscribe, type UserCommands, type UserExternalState, type VoiceSessionControls, type VoiceSessionHelpers, type VoiceSessionState, WebSpeechDictationAdapter, WebSpeechSynthesisAdapter, bindExternalStoreMessage, createMessageQueue, createRequestHeaders, createSuggestionAdapter, createVoiceSession, fromThreadMessageLike, generateId, getExternalStoreMessages, isAssistantError, isMcpAppUri, isMessageNotSentError, mergeModelContexts, pickExternalStoreSharedOptions, stepStreamingTiming, toAssistantError, tool, toolApprovalAcceptsText, unstable_defaultDirectiveFormatter, unstable_formatInteractableSnapshot, unstable_getInteractableSnapshots, unstable_getInteractableVersions };
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["checkDuplicateCore","process","env","NODE_ENV","TextMessagePart","ReasoningMessagePart","PartProviderMetadata","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalDisplay","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","MessagePartStreamStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","toolApprovalAcceptsText","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","Assistant","UserCommands","UserExternalState","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","unstable_getInteractableSnapshots","unstable_formatInteractableSnapshot","unstable_getInteractableVersions","Unstable_InteractableSnapshotEntry","Unstable_InteractableVersion","ToolExecutionStatus","ModelContextRegistry","ModelContextRegistryToolHandle","ModelContextRegistryInstructionHandle","ModelContextRegistryProviderHandle","AssistantFrameHost","AssistantFrameProvider","SerializedTool","SerializedModelContext","FrameMessageType","FrameMessage","FRAME_MESSAGE_CHANNEL","AttachmentAdapter","SimpleImageAttachmentAdapter","SimpleTextAttachmentAdapter","CompositeAttachmentAdapter","SpeechSynthesisAdapter","DictationAdapter","WebSpeechSynthesisAdapter","WebSpeechDictationAdapter","RealtimeVoiceAdapter","createVoiceSession","VoiceSessionControls","VoiceSessionHelpers","FeedbackAdapter","SuggestionAdapter","SuggestionAdapterGenerateOptions","CreateSuggestionAdapterOptions","createSuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","ErrorSeverity","ErrorDisplay","AssistantErrorCode","AssistantError","toAssistantError","isAssistantError","MessageNotSentError","isMessageNotSentError","RuntimeCapabilities","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","SubmitFeedbackOptions","ThreadSuggestion","SpeechState","VoiceSessionState","SubmittedFeedback","ThreadRuntimeEventCallback","ThreadRuntimeEventPayload","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ThreadRuntimeCore","ThreadListItemStatus","ThreadListItemCoreState","ThreadListRuntimeCore","AssistantRuntimeCore","AssistantRuntime","CreateStartRunConfig","CreateResumeRunConfig","CreateAppendMessage","ThreadState","ThreadRuntime","ThreadListState","ThreadListRuntime","ThreadListItemEventCallback","ThreadListItemEventPayload","ThreadListItemEventType","ThreadListItemRuntime","ThreadListItemState","MessageState","MessageRuntime","MessagePartState","MessagePartRuntime","ThreadComposerState","EditComposerState","ComposerState","ComposerRuntime","ThreadComposerRuntime","EditComposerRuntime","AttachmentState","AttachmentRuntime","ChatModelRunUpdate","ChatModelRunResult","CoreChatModelRunResult","ChatModelRunOptions","ChatModelAdapter","ThreadMessageLike","fromThreadMessageLike","StreamingTimingAccessors","StreamingTimingOptions","StreamingTimingState","stepStreamingTiming","generateId","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreBranchChange","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","QueuePlacement","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RuntimeAdapters","RemoteThreadListOptions","RemoteThreadListProviderComponent","RemoteThreadInitializeResponse","RemoteThreadMetadata","RemoteThreadListResponse","RemoteThreadListPageOptions","InMemoryThreadListAdapter","createRequestHeaders"],"sources":["../src/index.ts"],"sourcesContent":["// @assistant-ui/core - Framework-agnostic core runtime (public API)\n\n/// <reference path=\"./store/scope-registration.ts\" />\n\nimport { checkDuplicateCore } from \"./internal/duplicate-detection\";\n\nif (process.env.NODE_ENV !== \"production\") {\n checkDuplicateCore();\n}\n\nexport type {\n // Message parts\n TextMessagePart,\n ReasoningMessagePart,\n PartProviderMetadata,\n SourceProviderMetadata,\n SourceMessagePart,\n ImageMessagePart,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n GenerativeUINode,\n GenerativeUISpec,\n Unstable_AudioMessagePart,\n ToolApprovalDisplay,\n ToolApprovalOption,\n ToolApprovalOptionKind,\n ToolApprovalResponse,\n ToolCallMessagePart,\n ToolCallTiming,\n ToolCallMessagePartMcpMetadata,\n McpAppMetadata,\n ToolModelContentPart,\n ThreadUserMessagePart,\n ThreadAssistantMessagePart,\n // Message status\n MessagePartStatus,\n MessagePartStreamStatus,\n ToolCallMessagePartStatus,\n MessageStatus,\n // Thread messages\n MessageTiming,\n ThreadStep,\n ThreadSystemMessage,\n ThreadUserMessage,\n ThreadAssistantMessage,\n ThreadMessage,\n MessageRole,\n // Config\n RunConfig,\n AppendMessage,\n} from \"./types/message\";\n\nexport {\n MCP_APP_URI_SCHEME,\n isMcpAppUri,\n toolApprovalAcceptsText,\n} from \"./types/message\";\n\nexport type {\n Attachment,\n PendingAttachment,\n PendingAttachmentStatus,\n CompleteAttachment,\n CompleteAttachmentStatus,\n AttachmentStatus,\n CreateAttachment,\n} from \"./types/attachment\";\n\nexport type { Unsubscribe } from \"./types/unsubscribe\";\n\nexport type {\n Assistant,\n UserCommands,\n UserExternalState,\n} from \"./types/augmentations\";\n\nexport type { QuoteInfo } from \"./types/quote\";\n\nexport type {\n Unstable_DirectiveSegment,\n Unstable_DirectiveFormatter,\n} from \"./types/directive\";\n\nexport type {\n Unstable_TriggerItem,\n Unstable_TriggerCategory,\n} from \"./types/trigger\";\n\nexport type { Unstable_TriggerAdapter } from \"./adapters/trigger\";\n\nexport type {\n // Language model settings\n LanguageModelV1CallSettings,\n LanguageModelConfig,\n // Model context\n ModelContext,\n ModelContextProvider,\n // Tool & instruction config\n AssistantToolProps,\n AssistantInstructionsConfig,\n AssistantContextConfig,\n} from \"./model-context/types\";\nexport { mergeModelContexts } from \"./model-context/types\";\n\nexport { tool } from \"./model-context/tool\";\n\nexport {\n unstable_getInteractableSnapshots,\n unstable_formatInteractableSnapshot,\n unstable_getInteractableVersions,\n type Unstable_InteractableSnapshotEntry,\n type Unstable_InteractableVersion,\n} from \"./model-context/interactable-composer-metadata\";\n\nexport type { ToolExecutionStatus } from \"./runtimes/tool-invocations/ToolInvocationTracker\";\n\nexport { ModelContextRegistry } from \"./model-context/registry\";\nexport type {\n ModelContextRegistryToolHandle,\n ModelContextRegistryInstructionHandle,\n ModelContextRegistryProviderHandle,\n} from \"./model-context/registry-handles\";\n\nexport { AssistantFrameHost } from \"./model-context/frame/host\";\nexport { AssistantFrameProvider } from \"./model-context/frame/provider\";\nexport type {\n SerializedTool,\n SerializedModelContext,\n FrameMessageType,\n FrameMessage,\n} from \"./model-context/frame/types\";\nexport { FRAME_MESSAGE_CHANNEL } from \"./model-context/frame/types\";\n\n// Attachment adapters\nexport type { AttachmentAdapter } from \"./adapters/attachment\";\nexport {\n SimpleImageAttachmentAdapter,\n SimpleTextAttachmentAdapter,\n CompositeAttachmentAdapter,\n} from \"./adapters/attachment\";\n\n// Speech adapters\nexport type {\n SpeechSynthesisAdapter,\n DictationAdapter,\n} from \"./adapters/speech\";\nexport {\n WebSpeechSynthesisAdapter,\n WebSpeechDictationAdapter,\n} from \"./adapters/speech\";\n\n// Voice adapter\nexport type { RealtimeVoiceAdapter } from \"./adapters/voice\";\nexport { createVoiceSession } from \"./adapters/voice\";\nexport type {\n VoiceSessionControls,\n VoiceSessionHelpers,\n} from \"./adapters/voice\";\n\n// Feedback adapter\nexport type { FeedbackAdapter } from \"./adapters/feedback\";\n\n// Suggestion adapter\nexport type {\n SuggestionAdapter,\n SuggestionAdapterGenerateOptions,\n CreateSuggestionAdapterOptions,\n} from \"./adapters/suggestion\";\nexport { createSuggestionAdapter } from \"./adapters/suggestion\";\n\n// Directive formatter\nexport { unstable_defaultDirectiveFormatter } from \"./adapters/directive-formatter\";\n\n// Thread history adapters\nexport type {\n ThreadHistoryAdapter,\n GenericThreadHistoryAdapter,\n MessageFormatAdapter,\n MessageFormatItem,\n MessageFormatRepository,\n MessageStorageEntry,\n} from \"./adapters/thread-history\";\n\n// Path Types\nexport type {\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n MessageRuntimePath,\n MessagePartRuntimePath,\n AttachmentRuntimePath,\n ComposerRuntimePath,\n} from \"./runtime/api/paths\";\n\n// Runtime Core Interface Types\nexport type {\n AttachmentAddErrorEvent,\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n EditComposerRuntimeCore,\n SendOptions,\n ThreadComposerRuntimeCore,\n} from \"./runtime/interfaces/composer-runtime-core\";\n\nexport type {\n ErrorSeverity,\n ErrorDisplay,\n AssistantErrorCode,\n AssistantError,\n} from \"./types/error\";\nexport { toAssistantError, isAssistantError } from \"./types/error\";\nexport { MessageNotSentError, isMessageNotSentError } from \"./types/error\";\n\nexport type {\n RuntimeCapabilities,\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n SubmitFeedbackOptions,\n ThreadSuggestion,\n SpeechState,\n VoiceSessionState,\n SubmittedFeedback,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventPayload,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n ThreadRuntimeCore,\n} from \"./runtime/interfaces/thread-runtime-core\";\n\nexport type {\n ThreadListItemStatus,\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"./runtime/interfaces/thread-list-runtime-core\";\n\nexport type { AssistantRuntimeCore } from \"./runtime/interfaces/assistant-runtime-core\";\n\n// Public Runtime Types\nexport type { AssistantRuntime } from \"./runtime/api/assistant-runtime\";\n\nexport type {\n CreateStartRunConfig,\n CreateResumeRunConfig,\n CreateAppendMessage,\n ThreadState,\n ThreadRuntime,\n} from \"./runtime/api/thread-runtime\";\n\nexport type {\n ThreadListState,\n ThreadListRuntime,\n} from \"./runtime/api/thread-list-runtime\";\n\nexport type {\n ThreadListItemEventCallback,\n ThreadListItemEventPayload,\n ThreadListItemEventType,\n ThreadListItemRuntime,\n} from \"./runtime/api/thread-list-item-runtime\";\n\nexport type { ThreadListItemState } from \"./runtime/api/bindings\";\n\nexport type {\n MessageState,\n MessageRuntime,\n} from \"./runtime/api/message-runtime\";\nexport type {\n MessagePartState,\n MessagePartRuntime,\n} from \"./runtime/api/message-part-runtime\";\n\nexport type {\n ThreadComposerState,\n EditComposerState,\n ComposerState,\n ComposerRuntime,\n ThreadComposerRuntime,\n EditComposerRuntime,\n} from \"./runtime/api/composer-runtime\";\n\nexport type {\n AttachmentState,\n AttachmentRuntime,\n} from \"./runtime/api/attachment-runtime\";\n\n// ChatModel Types\nexport type {\n ChatModelRunUpdate,\n ChatModelRunResult,\n CoreChatModelRunResult,\n ChatModelRunOptions,\n ChatModelAdapter,\n} from \"./runtime/utils/chat-model-adapter\";\n\n// ThreadMessageLike\nexport type { ThreadMessageLike } from \"./runtime/utils/thread-message-like\";\nexport { fromThreadMessageLike } from \"./runtime/utils/thread-message-like\";\n\n// Streaming timing (client-side)\nexport type {\n StreamingTimingAccessors,\n StreamingTimingOptions,\n StreamingTimingState,\n} from \"./runtime/utils/streaming-timing\";\nexport { stepStreamingTiming } from \"./runtime/utils/streaming-timing\";\n\n// ID generation\nexport { generateId } from \"./utils/id\";\n\n// External Store Message Utilities\nexport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"./runtime/utils/external-store-message\";\n\n// ExportedMessageRepository\nexport type { ExportedMessageRepositoryItem } from \"./runtime/utils/message-repository\";\nexport { ExportedMessageRepository } from \"./runtime/utils/message-repository\";\n\n// Local Runtime Options\nexport type { LocalRuntimeOptionsBase } from \"./runtimes/local/local-runtime-options\";\n\n// External Store Adapter Types (user-facing)\nexport type {\n ExternalStoreAdapter,\n ExternalStoreMessageConverter,\n ExternalStoreThreadListAdapter,\n ExternalStoreThreadData,\n ExternalStoreBranchChange,\n} from \"./runtimes/external-store/external-store-adapter\";\nexport type { ExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\nexport { pickExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\n\n// Message queue\nexport type {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"./runtime/queue/external-thread-queue-adapter\";\nexport type { ExternalThreadBranchAdapter } from \"./runtime/branch/external-thread-branch-adapter\";\nexport {\n createMessageQueue,\n type MessageQueueDriver,\n type MessageQueueController,\n} from \"./runtime/queue/message-queue\";\n\n// Remote Thread List (user-facing)\nexport type {\n RemoteThreadListAdapter,\n RuntimeAdapters,\n RemoteThreadListOptions,\n RemoteThreadListProviderComponent,\n RemoteThreadInitializeResponse,\n RemoteThreadMetadata,\n RemoteThreadListResponse,\n RemoteThreadListPageOptions,\n} from \"./runtimes/remote-thread-list/types\";\n\nexport { InMemoryThreadListAdapter } from \"./runtimes/remote-thread-list/adapter/in-memory\";\n\n// Assistant Transport Utilities\nexport { createRequestHeaders } from \"./runtimes/assistant-transport/utils\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAIC,QAAQC,IAAIC,aAAa,cAC3BH,mBAAmB"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["checkDuplicateCore","process","env","NODE_ENV","TextMessagePart","ReasoningMessagePart","PartProviderMetadata","SourceProviderMetadata","SourceMessagePart","ImageMessagePart","FileMessagePart","DataMessagePart","GenerativeUIMessagePart","GenerativeUINode","GenerativeUISpec","Unstable_AudioMessagePart","ToolApprovalDisplay","ToolApprovalOption","ToolApprovalOptionKind","ToolApprovalResponse","ToolCallMessagePart","ToolCallTiming","ToolCallMessagePartMcpMetadata","McpAppMetadata","ToolModelContentPart","ThreadUserMessagePart","ThreadAssistantMessagePart","MessagePartStatus","MessagePartStreamStatus","ToolCallMessagePartStatus","MessageStatus","MessageTiming","ThreadStep","ThreadSystemMessage","ThreadUserMessage","ThreadAssistantMessage","ThreadMessage","MessageRole","RunConfig","AppendMessage","MCP_APP_URI_SCHEME","isMcpAppUri","toolApprovalAcceptsText","Attachment","PendingAttachment","PendingAttachmentStatus","CompleteAttachment","CompleteAttachmentStatus","AttachmentStatus","CreateAttachment","Unsubscribe","Assistant","UserCommands","UserExternalState","QuoteInfo","Unstable_DirectiveSegment","Unstable_DirectiveFormatter","Unstable_TriggerItem","Unstable_TriggerCategory","Unstable_TriggerAdapter","LanguageModelV1CallSettings","LanguageModelConfig","ModelContext","ModelContextProvider","AssistantToolProps","AssistantInstructionsConfig","AssistantContextConfig","mergeModelContexts","tool","unstable_getInteractableSnapshots","unstable_formatInteractableSnapshot","unstable_getInteractableVersions","Unstable_InteractableSnapshotEntry","Unstable_InteractableVersion","ToolExecutionStatus","ModelContextRegistry","ModelContextRegistryToolHandle","ModelContextRegistryInstructionHandle","ModelContextRegistryProviderHandle","AssistantFrameHost","AssistantFrameProvider","SerializedTool","SerializedModelContext","FrameMessageType","FrameMessage","FRAME_MESSAGE_CHANNEL","AttachmentAdapter","SimpleImageAttachmentAdapter","SimpleTextAttachmentAdapter","CompositeAttachmentAdapter","SpeechSynthesisAdapter","DictationAdapter","WebSpeechSynthesisAdapter","WebSpeechDictationAdapter","RealtimeVoiceAdapter","createVoiceSession","VoiceSessionControls","VoiceSessionHelpers","FeedbackAdapter","SuggestionAdapter","SuggestionAdapterGenerateOptions","CreateSuggestionAdapterOptions","createSuggestionAdapter","unstable_defaultDirectiveFormatter","ThreadHistoryAdapter","GenericThreadHistoryAdapter","MessageFormatAdapter","MessageFormatItem","MessageFormatRepository","MessageStorageEntry","ThreadListItemRuntimePath","ThreadRuntimePath","MessageRuntimePath","MessagePartRuntimePath","AttachmentRuntimePath","ComposerRuntimePath","AttachmentAddErrorEvent","AttachmentAddErrorReason","ComposerRuntimeCore","ComposerRuntimeEventCallback","ComposerRuntimeEventPayload","ComposerRuntimeEventType","DictationState","EditComposerRuntimeCore","SendOptions","ThreadComposerRuntimeCore","ErrorSeverity","ErrorDisplay","AssistantErrorCode","AssistantError","toAssistantError","isAssistantError","MessageNotSentError","isMessageNotSentError","RuntimeCapabilities","AddToolResultOptions","ResumeToolCallOptions","RespondToToolApprovalOptions","SubmitFeedbackOptions","ThreadSuggestion","SpeechState","VoiceSessionState","SubmittedFeedback","ThreadRuntimeEventCallback","ThreadRuntimeEventPayload","ThreadRuntimeEventType","StartRunConfig","ResumeRunConfig","ThreadRuntimeCore","ThreadListItemStatus","ThreadListItemCoreState","ThreadListRuntimeCore","AssistantRuntimeCore","AssistantRuntime","CreateStartRunConfig","CreateResumeRunConfig","CreateAppendMessage","ThreadState","ThreadRuntime","ThreadListState","ThreadListRuntime","ThreadListItemEventCallback","ThreadListItemEventPayload","ThreadListItemEventType","ThreadListItemGenerateTitleOptions","ThreadListItemRuntime","ThreadListItemState","MessageState","MessageRuntime","MessagePartState","MessagePartRuntime","ThreadComposerState","EditComposerState","ComposerState","ComposerRuntime","ThreadComposerRuntime","EditComposerRuntime","AttachmentState","AttachmentRuntime","ChatModelRunUpdate","ChatModelRunResult","CoreChatModelRunResult","ChatModelRunOptions","ChatModelAdapter","ThreadMessageLike","fromThreadMessageLike","StreamingTimingAccessors","StreamingTimingOptions","StreamingTimingState","stepStreamingTiming","generateId","getExternalStoreMessages","bindExternalStoreMessage","ExportedMessageRepositoryItem","ExportedMessageRepository","LocalRuntimeOptionsBase","ExternalStoreAdapter","ExternalStoreMessageConverter","ExternalStoreThreadListAdapter","ExternalStoreThreadData","ExternalStoreBranchChange","ExternalStoreSharedOptions","pickExternalStoreSharedOptions","ExternalThreadQueueAdapter","QueuePlacement","ExternalThreadBranchAdapter","createMessageQueue","MessageQueueDriver","MessageQueueController","RemoteThreadListAdapter","RuntimeAdapters","RemoteThreadListOptions","RemoteThreadListProviderComponent","RemoteThreadInitializeResponse","RemoteThreadMetadata","RemoteThreadListResponse","RemoteThreadListPageOptions","InMemoryThreadListAdapter","createRequestHeaders"],"sources":["../src/index.ts"],"sourcesContent":["// @assistant-ui/core - Framework-agnostic core runtime (public API)\n\n/// <reference path=\"./store/scope-registration.ts\" />\n\nimport { checkDuplicateCore } from \"./internal/duplicate-detection\";\n\nif (process.env.NODE_ENV !== \"production\") {\n checkDuplicateCore();\n}\n\nexport type {\n // Message parts\n TextMessagePart,\n ReasoningMessagePart,\n PartProviderMetadata,\n SourceProviderMetadata,\n SourceMessagePart,\n ImageMessagePart,\n FileMessagePart,\n DataMessagePart,\n GenerativeUIMessagePart,\n GenerativeUINode,\n GenerativeUISpec,\n Unstable_AudioMessagePart,\n ToolApprovalDisplay,\n ToolApprovalOption,\n ToolApprovalOptionKind,\n ToolApprovalResponse,\n ToolCallMessagePart,\n ToolCallTiming,\n ToolCallMessagePartMcpMetadata,\n McpAppMetadata,\n ToolModelContentPart,\n ThreadUserMessagePart,\n ThreadAssistantMessagePart,\n // Message status\n MessagePartStatus,\n MessagePartStreamStatus,\n ToolCallMessagePartStatus,\n MessageStatus,\n // Thread messages\n MessageTiming,\n ThreadStep,\n ThreadSystemMessage,\n ThreadUserMessage,\n ThreadAssistantMessage,\n ThreadMessage,\n MessageRole,\n // Config\n RunConfig,\n AppendMessage,\n} from \"./types/message\";\n\nexport {\n MCP_APP_URI_SCHEME,\n isMcpAppUri,\n toolApprovalAcceptsText,\n} from \"./types/message\";\n\nexport type {\n Attachment,\n PendingAttachment,\n PendingAttachmentStatus,\n CompleteAttachment,\n CompleteAttachmentStatus,\n AttachmentStatus,\n CreateAttachment,\n} from \"./types/attachment\";\n\nexport type { Unsubscribe } from \"./types/unsubscribe\";\n\nexport type {\n Assistant,\n UserCommands,\n UserExternalState,\n} from \"./types/augmentations\";\n\nexport type { QuoteInfo } from \"./types/quote\";\n\nexport type {\n Unstable_DirectiveSegment,\n Unstable_DirectiveFormatter,\n} from \"./types/directive\";\n\nexport type {\n Unstable_TriggerItem,\n Unstable_TriggerCategory,\n} from \"./types/trigger\";\n\nexport type { Unstable_TriggerAdapter } from \"./adapters/trigger\";\n\nexport type {\n // Language model settings\n LanguageModelV1CallSettings,\n LanguageModelConfig,\n // Model context\n ModelContext,\n ModelContextProvider,\n // Tool & instruction config\n AssistantToolProps,\n AssistantInstructionsConfig,\n AssistantContextConfig,\n} from \"./model-context/types\";\nexport { mergeModelContexts } from \"./model-context/types\";\n\nexport { tool } from \"./model-context/tool\";\n\nexport {\n unstable_getInteractableSnapshots,\n unstable_formatInteractableSnapshot,\n unstable_getInteractableVersions,\n type Unstable_InteractableSnapshotEntry,\n type Unstable_InteractableVersion,\n} from \"./model-context/interactable-composer-metadata\";\n\nexport type { ToolExecutionStatus } from \"./runtimes/tool-invocations/ToolInvocationTracker\";\n\nexport { ModelContextRegistry } from \"./model-context/registry\";\nexport type {\n ModelContextRegistryToolHandle,\n ModelContextRegistryInstructionHandle,\n ModelContextRegistryProviderHandle,\n} from \"./model-context/registry-handles\";\n\nexport { AssistantFrameHost } from \"./model-context/frame/host\";\nexport { AssistantFrameProvider } from \"./model-context/frame/provider\";\nexport type {\n SerializedTool,\n SerializedModelContext,\n FrameMessageType,\n FrameMessage,\n} from \"./model-context/frame/types\";\nexport { FRAME_MESSAGE_CHANNEL } from \"./model-context/frame/types\";\n\n// Attachment adapters\nexport type { AttachmentAdapter } from \"./adapters/attachment\";\nexport {\n SimpleImageAttachmentAdapter,\n SimpleTextAttachmentAdapter,\n CompositeAttachmentAdapter,\n} from \"./adapters/attachment\";\n\n// Speech adapters\nexport type {\n SpeechSynthesisAdapter,\n DictationAdapter,\n} from \"./adapters/speech\";\nexport {\n WebSpeechSynthesisAdapter,\n WebSpeechDictationAdapter,\n} from \"./adapters/speech\";\n\n// Voice adapter\nexport type { RealtimeVoiceAdapter } from \"./adapters/voice\";\nexport { createVoiceSession } from \"./adapters/voice\";\nexport type {\n VoiceSessionControls,\n VoiceSessionHelpers,\n} from \"./adapters/voice\";\n\n// Feedback adapter\nexport type { FeedbackAdapter } from \"./adapters/feedback\";\n\n// Suggestion adapter\nexport type {\n SuggestionAdapter,\n SuggestionAdapterGenerateOptions,\n CreateSuggestionAdapterOptions,\n} from \"./adapters/suggestion\";\nexport { createSuggestionAdapter } from \"./adapters/suggestion\";\n\n// Directive formatter\nexport { unstable_defaultDirectiveFormatter } from \"./adapters/directive-formatter\";\n\n// Thread history adapters\nexport type {\n ThreadHistoryAdapter,\n GenericThreadHistoryAdapter,\n MessageFormatAdapter,\n MessageFormatItem,\n MessageFormatRepository,\n MessageStorageEntry,\n} from \"./adapters/thread-history\";\n\n// Path Types\nexport type {\n ThreadListItemRuntimePath,\n ThreadRuntimePath,\n MessageRuntimePath,\n MessagePartRuntimePath,\n AttachmentRuntimePath,\n ComposerRuntimePath,\n} from \"./runtime/api/paths\";\n\n// Runtime Core Interface Types\nexport type {\n AttachmentAddErrorEvent,\n AttachmentAddErrorReason,\n ComposerRuntimeCore,\n ComposerRuntimeEventCallback,\n ComposerRuntimeEventPayload,\n ComposerRuntimeEventType,\n DictationState,\n EditComposerRuntimeCore,\n SendOptions,\n ThreadComposerRuntimeCore,\n} from \"./runtime/interfaces/composer-runtime-core\";\n\nexport type {\n ErrorSeverity,\n ErrorDisplay,\n AssistantErrorCode,\n AssistantError,\n} from \"./types/error\";\nexport { toAssistantError, isAssistantError } from \"./types/error\";\nexport { MessageNotSentError, isMessageNotSentError } from \"./types/error\";\n\nexport type {\n RuntimeCapabilities,\n AddToolResultOptions,\n ResumeToolCallOptions,\n RespondToToolApprovalOptions,\n SubmitFeedbackOptions,\n ThreadSuggestion,\n SpeechState,\n VoiceSessionState,\n SubmittedFeedback,\n ThreadRuntimeEventCallback,\n ThreadRuntimeEventPayload,\n ThreadRuntimeEventType,\n StartRunConfig,\n ResumeRunConfig,\n ThreadRuntimeCore,\n} from \"./runtime/interfaces/thread-runtime-core\";\n\nexport type {\n ThreadListItemStatus,\n ThreadListItemCoreState,\n ThreadListRuntimeCore,\n} from \"./runtime/interfaces/thread-list-runtime-core\";\n\nexport type { AssistantRuntimeCore } from \"./runtime/interfaces/assistant-runtime-core\";\n\n// Public Runtime Types\nexport type { AssistantRuntime } from \"./runtime/api/assistant-runtime\";\n\nexport type {\n CreateStartRunConfig,\n CreateResumeRunConfig,\n CreateAppendMessage,\n ThreadState,\n ThreadRuntime,\n} from \"./runtime/api/thread-runtime\";\n\nexport type {\n ThreadListState,\n ThreadListRuntime,\n} from \"./runtime/api/thread-list-runtime\";\n\nexport type {\n ThreadListItemEventCallback,\n ThreadListItemEventPayload,\n ThreadListItemEventType,\n ThreadListItemGenerateTitleOptions,\n ThreadListItemRuntime,\n} from \"./runtime/api/thread-list-item-runtime\";\n\nexport type { ThreadListItemState } from \"./runtime/api/bindings\";\n\nexport type {\n MessageState,\n MessageRuntime,\n} from \"./runtime/api/message-runtime\";\nexport type {\n MessagePartState,\n MessagePartRuntime,\n} from \"./runtime/api/message-part-runtime\";\n\nexport type {\n ThreadComposerState,\n EditComposerState,\n ComposerState,\n ComposerRuntime,\n ThreadComposerRuntime,\n EditComposerRuntime,\n} from \"./runtime/api/composer-runtime\";\n\nexport type {\n AttachmentState,\n AttachmentRuntime,\n} from \"./runtime/api/attachment-runtime\";\n\n// ChatModel Types\nexport type {\n ChatModelRunUpdate,\n ChatModelRunResult,\n CoreChatModelRunResult,\n ChatModelRunOptions,\n ChatModelAdapter,\n} from \"./runtime/utils/chat-model-adapter\";\n\n// ThreadMessageLike\nexport type { ThreadMessageLike } from \"./runtime/utils/thread-message-like\";\nexport { fromThreadMessageLike } from \"./runtime/utils/thread-message-like\";\n\n// Streaming timing (client-side)\nexport type {\n StreamingTimingAccessors,\n StreamingTimingOptions,\n StreamingTimingState,\n} from \"./runtime/utils/streaming-timing\";\nexport { stepStreamingTiming } from \"./runtime/utils/streaming-timing\";\n\n// ID generation\nexport { generateId } from \"./utils/id\";\n\n// External Store Message Utilities\nexport {\n getExternalStoreMessages,\n bindExternalStoreMessage,\n} from \"./runtime/utils/external-store-message\";\n\n// ExportedMessageRepository\nexport type { ExportedMessageRepositoryItem } from \"./runtime/utils/message-repository\";\nexport { ExportedMessageRepository } from \"./runtime/utils/message-repository\";\n\n// Local Runtime Options\nexport type { LocalRuntimeOptionsBase } from \"./runtimes/local/local-runtime-options\";\n\n// External Store Adapter Types (user-facing)\nexport type {\n ExternalStoreAdapter,\n ExternalStoreMessageConverter,\n ExternalStoreThreadListAdapter,\n ExternalStoreThreadData,\n ExternalStoreBranchChange,\n} from \"./runtimes/external-store/external-store-adapter\";\nexport type { ExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\nexport { pickExternalStoreSharedOptions } from \"./runtimes/external-store/external-store-shared-options\";\n\n// Message queue\nexport type {\n ExternalThreadQueueAdapter,\n QueuePlacement,\n} from \"./runtime/queue/external-thread-queue-adapter\";\nexport type { ExternalThreadBranchAdapter } from \"./runtime/branch/external-thread-branch-adapter\";\nexport {\n createMessageQueue,\n type MessageQueueDriver,\n type MessageQueueController,\n} from \"./runtime/queue/message-queue\";\n\n// Remote Thread List (user-facing)\nexport type {\n RemoteThreadListAdapter,\n RuntimeAdapters,\n RemoteThreadListOptions,\n RemoteThreadListProviderComponent,\n RemoteThreadInitializeResponse,\n RemoteThreadMetadata,\n RemoteThreadListResponse,\n RemoteThreadListPageOptions,\n} from \"./runtimes/remote-thread-list/types\";\n\nexport { InMemoryThreadListAdapter } from \"./runtimes/remote-thread-list/adapter/in-memory\";\n\n// Assistant Transport Utilities\nexport { createRequestHeaders } from \"./runtimes/assistant-transport/utils\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAIC,QAAQC,IAAIC,aAAa,cAC3BH,mBAAmB"}
|
package/dist/internal.d.ts
CHANGED
|
@@ -15,6 +15,7 @@ import { stableStringifyToolArgs, trackToolArgsKeyOrder } from "./utils/json/sta
|
|
|
15
15
|
import { isJSONValue, isRecord } from "./utils/json/is-json.js";
|
|
16
16
|
import { FilePartSource, dataUrlMediaType, httpUrlPattern, isParsableUrl, parseDataUrl, resolveFilePartSource } from "./utils/data-url.js";
|
|
17
17
|
import { invokeUserCallback } from "./utils/invoke-user-callback.js";
|
|
18
|
+
import { abortableIterable, openAbortableIterable } from "./utils/abortable-iterable.js";
|
|
18
19
|
import { detectImageMediaType } from "./utils/image-media-type.js";
|
|
19
20
|
import { resolveFileMediaType, resolveImageMediaType, toMediaWireUrl } from "./utils/wire-media.js";
|
|
20
21
|
import { createToolCallCancellationStub, scanPendingToolCalls } from "./runtime/utils/pending-tool-calls.js";
|
|
@@ -50,8 +51,8 @@ import { ConverterCallback, ThreadMessageConverter } from "./runtimes/external-s
|
|
|
50
51
|
import { ReadonlyThreadRuntimeCore } from "./runtimes/readonly/ReadonlyThreadRuntimeCore.js";
|
|
51
52
|
import { OptimisticState } from "./runtimes/remote-thread-list/optimistic-state.js";
|
|
52
53
|
import { EMPTY_THREAD_CORE } from "./runtimes/remote-thread-list/empty-thread-core.js";
|
|
53
|
-
import { RemoteThreadData, RemoteThreadState, THREAD_MAPPING_ID, createThreadMappingId, getThreadData, updateStatusReducer } from "./runtimes/remote-thread-list/remote-thread-state.js";
|
|
54
|
+
import { RemoteThreadData, RemoteThreadState, THREAD_MAPPING_ID, createThreadMappingId, getThreadData, promoteNewThreadReducer, updateStatusReducer } from "./runtimes/remote-thread-list/remote-thread-state.js";
|
|
54
55
|
import "./runtimes/internal.js";
|
|
55
56
|
import { ThreadListItemRuntimeBinding, ThreadRuntimeCoreBinding, ThreadRuntimeImpl, getThreadState } from "./runtime/api/thread-runtime.js";
|
|
56
57
|
import { AssistantRuntimeImpl } from "./runtime/api/assistant-runtime.js";
|
|
57
|
-
export { type AbortableThreadLoadPurpose, AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, type ComposerRuntimeCoreBinding, ComposerRuntimeImpl, CompositeContextProvider, type ConverterCallback, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, type EditComposerRuntimeCoreBinding, EditComposerRuntimeImpl, type EventSubscribable, EventSubscriptionSubject, ExportedMessageRepository, type ExportedMessageRepositoryItem, ExternalStoreRuntimeCore, type ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, type FilePartSource, LazyMemoizeSubject, LocalRuntimeCore, type LocalRuntimeOptionsBase, type LocalThreadFactory, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, type MessageRepositorySession, type MessageRepositorySessionOptions, MessageRuntimeImpl, type MessageStateBinding, type NestedSubscribable, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, type RemoteThreadData, type RemoteThreadInitializeResponse, type RemoteThreadListOptions, type RemoteThreadState, SKIP_UPDATE, type SKIP_UPDATE as SKIP_UPDATE_TYPE, ShallowMemoizeSubject, type Subscribable, type SubscribableWithState, type THREAD_MAPPING_ID, ThreadComposerAttachmentRuntimeImpl, type ThreadComposerRuntimeCoreBinding, ThreadComposerRuntimeImpl, type ThreadListItemRuntimeBinding, ThreadListItemRuntimeImpl, type ThreadListItemStateBinding, type ThreadListRuntimeCoreBinding, ThreadListRuntimeImpl, ThreadMessageConverter, type ThreadRuntimeCoreBinding, ThreadRuntimeImpl, type ToolCallTreeEntry, ToolInvocationTracker, consumeSuggestionResult, createAbortableThreadLoad, createCloudThreadListAdapterCreateFallback, createMessageRepositorySession, createThreadMappingId, createToolCallCancellationStub, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, invokeUserCallback, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, iterateToolCallParts, mapToolCallPartsDeep, notifyEventListeners, parseDataUrl, resolveFileMediaType, resolveFilePartSource, resolveImageMediaType, resolveToolApprovalResponse, scanPendingToolCalls, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer, walkToolCallTree };
|
|
58
|
+
export { type AbortableThreadLoadPurpose, AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, type ComposerRuntimeCoreBinding, ComposerRuntimeImpl, CompositeContextProvider, type ConverterCallback, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, type EditComposerRuntimeCoreBinding, EditComposerRuntimeImpl, type EventSubscribable, EventSubscriptionSubject, ExportedMessageRepository, type ExportedMessageRepositoryItem, ExternalStoreRuntimeCore, type ExternalStoreThreadFactory, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, type FilePartSource, LazyMemoizeSubject, LocalRuntimeCore, type LocalRuntimeOptionsBase, type LocalThreadFactory, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, type MessageRepositorySession, type MessageRepositorySessionOptions, MessageRuntimeImpl, type MessageStateBinding, type NestedSubscribable, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, type RemoteThreadData, type RemoteThreadInitializeResponse, type RemoteThreadListOptions, type RemoteThreadState, SKIP_UPDATE, type SKIP_UPDATE as SKIP_UPDATE_TYPE, ShallowMemoizeSubject, type Subscribable, type SubscribableWithState, type THREAD_MAPPING_ID, ThreadComposerAttachmentRuntimeImpl, type ThreadComposerRuntimeCoreBinding, ThreadComposerRuntimeImpl, type ThreadListItemRuntimeBinding, ThreadListItemRuntimeImpl, type ThreadListItemStateBinding, type ThreadListRuntimeCoreBinding, ThreadListRuntimeImpl, ThreadMessageConverter, type ThreadRuntimeCoreBinding, ThreadRuntimeImpl, type ToolCallTreeEntry, ToolInvocationTracker, abortableIterable, consumeSuggestionResult, createAbortableThreadLoad, createCloudThreadListAdapterCreateFallback, createMessageRepositorySession, createThreadMappingId, createToolCallCancellationStub, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, invokeUserCallback, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, iterateToolCallParts, mapToolCallPartsDeep, notifyEventListeners, openAbortableIterable, parseDataUrl, promoteNewThreadReducer, resolveFileMediaType, resolveFilePartSource, resolveImageMediaType, resolveToolApprovalResponse, scanPendingToolCalls, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer, walkToolCallTree };
|
package/dist/internal.js
CHANGED
|
@@ -16,6 +16,7 @@ import { resolveToolApprovalResponse } from "./runtime/utils/resolveToolApproval
|
|
|
16
16
|
import { isCreateAttachment } from "./types/attachment.js";
|
|
17
17
|
import { stableStringifyToolArgs, trackToolArgsKeyOrder } from "./utils/json/stable-stringify-tool-args.js";
|
|
18
18
|
import { invokeUserCallback } from "./utils/invoke-user-callback.js";
|
|
19
|
+
import { abortableIterable, openAbortableIterable } from "./utils/abortable-iterable.js";
|
|
19
20
|
import { detectImageMediaType } from "./utils/image-media-type.js";
|
|
20
21
|
import { resolveFileMediaType, resolveImageMediaType, toMediaWireUrl } from "./utils/wire-media.js";
|
|
21
22
|
import { createToolCallCancellationStub, scanPendingToolCalls } from "./runtime/utils/pending-tool-calls.js";
|
|
@@ -48,5 +49,5 @@ import { ExternalStoreRuntimeCore } from "./runtimes/external-store/external-sto
|
|
|
48
49
|
import { ReadonlyThreadRuntimeCore } from "./runtimes/readonly/ReadonlyThreadRuntimeCore.js";
|
|
49
50
|
import { OptimisticState } from "./runtimes/remote-thread-list/optimistic-state.js";
|
|
50
51
|
import { EMPTY_THREAD_CORE } from "./runtimes/remote-thread-list/empty-thread-core.js";
|
|
51
|
-
import { createThreadMappingId, getThreadData, updateStatusReducer } from "./runtimes/remote-thread-list/remote-thread-state.js";
|
|
52
|
-
export { AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, ComposerRuntimeImpl, CompositeContextProvider, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, EditComposerRuntimeImpl, EventSubscriptionSubject, ExportedMessageRepository, ExternalStoreRuntimeCore, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LazyMemoizeSubject, LocalRuntimeCore, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, MessageRuntimeImpl, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, SKIP_UPDATE, ShallowMemoizeSubject, ThreadComposerAttachmentRuntimeImpl, ThreadComposerRuntimeImpl, ThreadListItemRuntimeImpl, ThreadListRuntimeImpl, ThreadMessageConverter, ThreadRuntimeImpl, ToolInvocationTracker, consumeSuggestionResult, createAbortableThreadLoad, createCloudThreadListAdapterCreateFallback, createMessageRepositorySession, createThreadMappingId, createToolCallCancellationStub, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, invokeUserCallback, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, iterateToolCallParts, mapToolCallPartsDeep, notifyEventListeners, parseDataUrl, resolveFileMediaType, resolveFilePartSource, resolveImageMediaType, resolveToolApprovalResponse, scanPendingToolCalls, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer, walkToolCallTree };
|
|
52
|
+
import { createThreadMappingId, getThreadData, promoteNewThreadReducer, updateStatusReducer } from "./runtimes/remote-thread-list/remote-thread-state.js";
|
|
53
|
+
export { AssistantRuntimeImpl, AttachmentRuntimeImpl, BaseAssistantRuntimeCore, BaseComposerRuntimeCore, BaseSubject, BaseSubscribable, BaseThreadRuntimeCore, ComposerRuntimeImpl, CompositeContextProvider, DefaultEditComposerRuntimeCore, DefaultThreadComposerRuntimeCore, EMPTY_THREAD_CORE, EditComposerAttachmentRuntimeImpl, EditComposerRuntimeImpl, EventSubscriptionSubject, ExportedMessageRepository, ExternalStoreRuntimeCore, ExternalStoreThreadListRuntimeCore, ExternalStoreThreadRuntimeCore, LazyMemoizeSubject, LocalRuntimeCore, LocalThreadListRuntimeCore, LocalThreadRuntimeCore, MessageAttachmentRuntimeImpl, MessagePartRuntimeImpl, MessageRepository, MessageRuntimeImpl, NestedSubscriptionSubject, OptimisticState, ReadonlyThreadRuntimeCore, SKIP_UPDATE, ShallowMemoizeSubject, ThreadComposerAttachmentRuntimeImpl, ThreadComposerRuntimeImpl, ThreadListItemRuntimeImpl, ThreadListRuntimeImpl, ThreadMessageConverter, ThreadRuntimeImpl, ToolInvocationTracker, abortableIterable, consumeSuggestionResult, createAbortableThreadLoad, createCloudThreadListAdapterCreateFallback, createMessageRepositorySession, createThreadMappingId, createToolCallCancellationStub, dataUrlMediaType, detectImageMediaType, fileMatchesAccept, fromThreadMessageLike, generateErrorMessageId, generateId, getAutoStatus, getFileDataURL, getThreadData, getThreadMessageText, getThreadState, hasUpcomingMessage, httpUrlPattern, invokeUserCallback, isAutoStatus, isCreateAttachment, isErrorMessageId, isJSONValue, isParsableUrl, isRecord, iterateToolCallParts, mapToolCallPartsDeep, notifyEventListeners, openAbortableIterable, parseDataUrl, promoteNewThreadReducer, resolveFileMediaType, resolveFilePartSource, resolveImageMediaType, resolveToolApprovalResponse, scanPendingToolCalls, shouldContinue, stableStringifyToolArgs, symbolInnerMessage, toMediaWireUrl, toMessagePartStatus, trackToolArgsKeyOrder, updateStatusReducer, walkToolCallTree };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/model-context/frame/host.ts"],"mappings":";;;cAqDa,8BAA8B;UACjC;UACA;UACA;UAOA;UACA;UACA;EAGN,YAAA,cAAc,QACd;UAWM;UA6BA;UAoBA;UAkBA;
|
|
1
|
+
{"version":3,"file":"host.d.ts","names":[],"sources":["../../../src/model-context/frame/host.ts"],"mappings":";;;cAqDa,8BAA8B;UACjC;UACA;UACA;UAOA;UACA;UACA;EAGN,YAAA,cAAc,QACd;UAWM;UA6BA;UAoBA;UAkBA;UA+DA;UAUA;UAYA;EAIR,mBAAmB;EAInB,UAAU,uBAAuB;EAKjC"}
|
|
@@ -115,10 +115,16 @@ var AssistantFrameHost = class {
|
|
|
115
115
|
}
|
|
116
116
|
}, timeout);
|
|
117
117
|
abortSignal?.addEventListener("abort", onAbort, { once: true });
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
118
|
+
try {
|
|
119
|
+
this._iframeWindow.postMessage({
|
|
120
|
+
channel: FRAME_MESSAGE_CHANNEL,
|
|
121
|
+
message
|
|
122
|
+
}, this._targetOrigin);
|
|
123
|
+
} catch (error) {
|
|
124
|
+
const pending = this._pendingRequests.get(message.id);
|
|
125
|
+
this._pendingRequests.delete(message.id);
|
|
126
|
+
pending?.reject(error);
|
|
127
|
+
}
|
|
122
128
|
});
|
|
123
129
|
}
|
|
124
130
|
cancelToolCall(id) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"host.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","notifySubscribers","notifyStateSubscribers","generateId","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","getDefaultTargetOrigin","window","location","origin","deserializeTool","serializedTool","parameters","description","disabled","undefined","type","deserializeModelContext","serialized","system","tools","Object","fromEntries","entries","map","name","tool","getAbortReason","signal","AbortSignal","reason","error","Error","AssistantFrameHost","_context","_subscribers","Set","_pendingRequests","Map","resolve","value","reject","_iframeWindow","Window","_targetOrigin","_disposed","constructor","iframeWindow","targetOrigin","handleMessage","bind","addEventListener","requestContext","event","MessageEvent","source","data","channel","message","updateContext","context","pending","get","id","result","delete","serializedContext","execute","args","abortSignal","callTool","toolName","Promise","sendRequest","T","timeout","timeoutMessage","aborted","timeoutId","ReturnType","setTimeout","onAbort","cancelToolCall","cleanup","clearTimeout","removeEventListener","set","once","postMessage","getModelContext","subscribe","callback","add","dispose","clear"],"sources":["../../../src/model-context/frame/host.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\nimport { notifySubscribers as notifyStateSubscribers } from \"../../subscribable/subscribable\";\nimport { generateId } from \"../../utils/id\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst getDefaultTargetOrigin = () => window.location.origin;\n\n/**\n * Deserializes tools from JSON Schema format back to Tool objects\n */\nconst deserializeTool = (serializedTool: SerializedTool): Tool<any, any> =>\n ({\n parameters: serializedTool.parameters,\n ...(serializedTool.description && {\n description: serializedTool.description,\n }),\n ...(serializedTool.disabled !== undefined && {\n disabled: serializedTool.disabled,\n }),\n ...(serializedTool.type && { type: serializedTool.type }),\n }) as Tool<any, any>;\n\n/**\n * Deserializes a ModelContext from transmission format\n */\nconst deserializeModelContext = (\n serialized: SerializedModelContext,\n): ModelContext => ({\n ...(serialized.system !== undefined && { system: serialized.system }),\n ...(serialized.tools && {\n tools: Object.fromEntries(\n Object.entries(serialized.tools).map(([name, tool]) => [\n name,\n deserializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getAbortReason = (signal: AbortSignal): unknown => {\n if (signal.reason !== undefined) return signal.reason;\n const error = new Error(\"Tool call was aborted\");\n error.name = \"AbortError\";\n return error;\n};\n\nexport class AssistantFrameHost implements ModelContextProvider {\n private _context: ModelContext = {};\n private _subscribers = new Set<() => void>();\n private _pendingRequests = new Map<\n string,\n {\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }\n >();\n private _iframeWindow: Window;\n private _targetOrigin: string;\n private _disposed = false;\n\n constructor(\n iframeWindow: Window,\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n this._iframeWindow = iframeWindow;\n this._targetOrigin = targetOrigin;\n\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n this.requestContext();\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== this._iframeWindow) return;\n if (event.data?.channel !== FRAME_MESSAGE_CHANNEL) return;\n\n const message = event.data.message as FrameMessage;\n\n switch (message.type) {\n case \"model-context-update\": {\n this.updateContext(message.context);\n break;\n }\n\n case \"tool-result\": {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n if (typeof message.error === \"string\") {\n pending.reject(new Error(message.error));\n } else {\n pending.resolve(message.result);\n }\n this._pendingRequests.delete(message.id);\n }\n break;\n }\n }\n }\n\n private updateContext(serializedContext: SerializedModelContext) {\n const context = deserializeModelContext(serializedContext);\n this._context = {\n ...context,\n tools:\n context.tools &&\n Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: (args: any, context: { abortSignal: AbortSignal }) =>\n this.callTool(name, args, context.abortSignal),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(\n toolName: string,\n args: any,\n abortSignal: AbortSignal,\n ): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${generateId()}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n abortSignal,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n abortSignal?: AbortSignal,\n ): Promise<any> {\n if (this._disposed) {\n return Promise.reject(new Error(\"AssistantFrameHost has been disposed\"));\n }\n if (abortSignal?.aborted) {\n return Promise.reject(getAbortReason(abortSignal));\n }\n\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n if (!abortSignal) return;\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(getAbortReason(abortSignal));\n this._pendingRequests.delete(message.id);\n }\n };\n const cleanup = () => {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n abortSignal?.removeEventListener(\"abort\", onAbort);\n };\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n cleanup();\n resolve(value);\n },\n reject: (error: any) => {\n cleanup();\n reject(error);\n },\n });\n\n timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n });\n }\n\n private cancelToolCall(id: string) {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: { type: \"tool-cancel\", id } satisfies FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private requestContext() {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: {\n type: \"model-context-request\",\n } as FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private notifySubscribers() {\n notifyStateSubscribers(this._subscribers);\n }\n\n getModelContext(): ModelContext {\n return this._context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n dispose() {\n this._disposed = true;\n window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n const error = new Error(\"AssistantFrameHost has been disposed\");\n for (const [id, pending] of this._pendingRequests) {\n this.cancelToolCall(id);\n pending.reject(error);\n }\n this._pendingRequests.clear();\n }\n}\n"],"mappings":";;;;AAYA,MAAMW,+BAA+BC,OAAOC,SAASC;;;;AAKrD,MAAMC,mBAAmBC,oBACtB;CACCC,YAAYD,eAAeC;CAC3B,GAAID,eAAeE,eAAe,EAChCA,aAAaF,eAAeE,YAC9B;CACA,GAAIF,eAAeG,aAAaC,KAAAA,KAAa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AY;EACjBtC,OAAO8E,oBAAoB,WAAW,KAAKpC,aAAa;EACxD,KAAKd,aAAa2D,MAAM;EACxB,MAAM/D,wBAAQ,IAAIC,MAAM,sCAAsC;EAC9D,KAAK,MAAM,CAAC+B,IAAIF,YAAY,KAAKxB,kBAAkB;GACjD,KAAK6C,eAAenB,EAAE;GACtBF,QAAQpB,OAAOV,KAAK;EACtB;EACA,KAAKM,iBAAiByD,MAAM;CAC9B;AACF"}
|
|
1
|
+
{"version":3,"file":"host.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","notifySubscribers","notifyStateSubscribers","generateId","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","getDefaultTargetOrigin","window","location","origin","deserializeTool","serializedTool","parameters","description","disabled","undefined","type","deserializeModelContext","serialized","system","tools","Object","fromEntries","entries","map","name","tool","getAbortReason","signal","AbortSignal","reason","error","Error","AssistantFrameHost","_context","_subscribers","Set","_pendingRequests","Map","resolve","value","reject","_iframeWindow","Window","_targetOrigin","_disposed","constructor","iframeWindow","targetOrigin","handleMessage","bind","addEventListener","requestContext","event","MessageEvent","source","data","channel","message","updateContext","context","pending","get","id","result","delete","serializedContext","execute","args","abortSignal","callTool","toolName","Promise","sendRequest","T","timeout","timeoutMessage","aborted","timeoutId","ReturnType","setTimeout","onAbort","cancelToolCall","cleanup","clearTimeout","removeEventListener","set","once","postMessage","getModelContext","subscribe","callback","add","dispose","clear"],"sources":["../../../src/model-context/frame/host.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport type { Tool } from \"assistant-stream\";\nimport { notifySubscribers as notifyStateSubscribers } from \"../../subscribable/subscribable\";\nimport { generateId } from \"../../utils/id\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst getDefaultTargetOrigin = () => window.location.origin;\n\n/**\n * Deserializes tools from JSON Schema format back to Tool objects\n */\nconst deserializeTool = (serializedTool: SerializedTool): Tool<any, any> =>\n ({\n parameters: serializedTool.parameters,\n ...(serializedTool.description && {\n description: serializedTool.description,\n }),\n ...(serializedTool.disabled !== undefined && {\n disabled: serializedTool.disabled,\n }),\n ...(serializedTool.type && { type: serializedTool.type }),\n }) as Tool<any, any>;\n\n/**\n * Deserializes a ModelContext from transmission format\n */\nconst deserializeModelContext = (\n serialized: SerializedModelContext,\n): ModelContext => ({\n ...(serialized.system !== undefined && { system: serialized.system }),\n ...(serialized.tools && {\n tools: Object.fromEntries(\n Object.entries(serialized.tools).map(([name, tool]) => [\n name,\n deserializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getAbortReason = (signal: AbortSignal): unknown => {\n if (signal.reason !== undefined) return signal.reason;\n const error = new Error(\"Tool call was aborted\");\n error.name = \"AbortError\";\n return error;\n};\n\nexport class AssistantFrameHost implements ModelContextProvider {\n private _context: ModelContext = {};\n private _subscribers = new Set<() => void>();\n private _pendingRequests = new Map<\n string,\n {\n resolve: (value: any) => void;\n reject: (error: any) => void;\n }\n >();\n private _iframeWindow: Window;\n private _targetOrigin: string;\n private _disposed = false;\n\n constructor(\n iframeWindow: Window,\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n this._iframeWindow = iframeWindow;\n this._targetOrigin = targetOrigin;\n\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n this.requestContext();\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== this._iframeWindow) return;\n if (event.data?.channel !== FRAME_MESSAGE_CHANNEL) return;\n\n const message = event.data.message as FrameMessage;\n\n switch (message.type) {\n case \"model-context-update\": {\n this.updateContext(message.context);\n break;\n }\n\n case \"tool-result\": {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n if (typeof message.error === \"string\") {\n pending.reject(new Error(message.error));\n } else {\n pending.resolve(message.result);\n }\n this._pendingRequests.delete(message.id);\n }\n break;\n }\n }\n }\n\n private updateContext(serializedContext: SerializedModelContext) {\n const context = deserializeModelContext(serializedContext);\n this._context = {\n ...context,\n tools:\n context.tools &&\n Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n {\n ...tool,\n execute: (args: any, context: { abortSignal: AbortSignal }) =>\n this.callTool(name, args, context.abortSignal),\n } as Tool<any, any>,\n ]),\n ),\n };\n this.notifySubscribers();\n }\n\n private callTool(\n toolName: string,\n args: any,\n abortSignal: AbortSignal,\n ): Promise<any> {\n return this.sendRequest(\n {\n type: \"tool-call\",\n id: `tool-${generateId()}`,\n toolName,\n args,\n },\n 30000,\n `Tool call \"${toolName}\" timed out`,\n abortSignal,\n );\n }\n\n private sendRequest<T extends FrameMessage & { id: string }>(\n message: T,\n timeout = 30000,\n timeoutMessage = \"Request timed out\",\n abortSignal?: AbortSignal,\n ): Promise<any> {\n if (this._disposed) {\n return Promise.reject(new Error(\"AssistantFrameHost has been disposed\"));\n }\n if (abortSignal?.aborted) {\n return Promise.reject(getAbortReason(abortSignal));\n }\n\n return new Promise((resolve, reject) => {\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n if (!abortSignal) return;\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(getAbortReason(abortSignal));\n this._pendingRequests.delete(message.id);\n }\n };\n const cleanup = () => {\n if (timeoutId !== undefined) clearTimeout(timeoutId);\n abortSignal?.removeEventListener(\"abort\", onAbort);\n };\n\n this._pendingRequests.set(message.id, {\n resolve: (value: any) => {\n cleanup();\n resolve(value);\n },\n reject: (error: any) => {\n cleanup();\n reject(error);\n },\n });\n\n timeoutId = setTimeout(() => {\n const pending = this._pendingRequests.get(message.id);\n if (pending) {\n this.cancelToolCall(message.id);\n pending.reject(new Error(timeoutMessage));\n this._pendingRequests.delete(message.id);\n }\n }, timeout);\n abortSignal?.addEventListener(\"abort\", onAbort, { once: true });\n\n try {\n this._iframeWindow.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n this._targetOrigin,\n );\n } catch (error) {\n const pending = this._pendingRequests.get(message.id);\n this._pendingRequests.delete(message.id);\n pending?.reject(error);\n }\n });\n }\n\n private cancelToolCall(id: string) {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: { type: \"tool-cancel\", id } satisfies FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private requestContext() {\n this._iframeWindow.postMessage(\n {\n channel: FRAME_MESSAGE_CHANNEL,\n message: {\n type: \"model-context-request\",\n } as FrameMessage,\n },\n this._targetOrigin,\n );\n }\n\n private notifySubscribers() {\n notifyStateSubscribers(this._subscribers);\n }\n\n getModelContext(): ModelContext {\n return this._context;\n }\n\n subscribe(callback: () => void): Unsubscribe {\n this._subscribers.add(callback);\n return () => this._subscribers.delete(callback);\n }\n\n dispose() {\n this._disposed = true;\n window.removeEventListener(\"message\", this.handleMessage);\n this._subscribers.clear();\n const error = new Error(\"AssistantFrameHost has been disposed\");\n for (const [id, pending] of this._pendingRequests) {\n this.cancelToolCall(id);\n pending.reject(error);\n }\n this._pendingRequests.clear();\n }\n}\n"],"mappings":";;;;AAYA,MAAMW,+BAA+BC,OAAOC,SAASC;;;;AAKrD,MAAMC,mBAAmBC,oBACtB;CACCC,YAAYD,eAAeC;CAC3B,GAAID,eAAeE,eAAe,EAChCA,aAAaF,eAAeE,YAC9B;CACA,GAAIF,eAAeG,aAAaC,KAAAA,KAAa,EAC3CD,UAAUH,eAAeG,SAC3B;CACA,GAAIH,eAAeK,QAAQ,EAAEA,MAAML,eAAeK,KAAK;AACzD;;;;AAKF,MAAMC,2BACJC,gBACkB;CAClB,GAAIA,WAAWC,WAAWJ,KAAAA,KAAa,EAAEI,QAAQD,WAAWC,OAAO;CACnE,GAAID,WAAWE,SAAS,EACtBA,OAAOC,OAAOC,YACZD,OAAOE,QAAQL,WAAWE,KAAK,CAAC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M,sCAAsC;EAC9D,KAAK,MAAM,CAAC+B,IAAIF,YAAY,KAAKxB,kBAAkB;GACjD,KAAK6C,eAAenB,EAAE;GACtBF,QAAQpB,OAAOV,KAAK;EACtB;EACA,KAAKM,iBAAiByD,MAAM;CAC9B;AACF"}
|
|
@@ -9,6 +9,8 @@ declare class AssistantFrameProvider {
|
|
|
9
9
|
private _targetOrigin;
|
|
10
10
|
private _strictRegistrations;
|
|
11
11
|
private _wildcardRegistrations;
|
|
12
|
+
private _startupTimer;
|
|
13
|
+
private _disposed;
|
|
12
14
|
private constructor();
|
|
13
15
|
private static getInstance;
|
|
14
16
|
private reconcileTargetOrigin;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.d.ts","names":[],"sources":["../../../src/model-context/frame/provider.ts"],"mappings":";;;cAiCa;iBACI;UAEP;UACA;UACA;UAQA;UACA;UACA;UAED;
|
|
1
|
+
{"version":3,"file":"provider.d.ts","names":[],"sources":["../../../src/model-context/frame/provider.ts"],"mappings":";;;cAiCa;iBACI;UAEP;UACA;UACA;UAQA;UACA;UACA;UACA;UACA;UAED;iBAWQ;UAWP;UAsBA;UA+BM;UA8DN;UAOA;UA+BA;UAOA;UAIA;UAaA;UAkBA;UAeA;SAiCD,wBACL,UAAU,sBACV,wBACC;SA+EI"}
|
|
@@ -20,11 +20,16 @@ var AssistantFrameProvider = class AssistantFrameProvider {
|
|
|
20
20
|
_targetOrigin;
|
|
21
21
|
_strictRegistrations = 0;
|
|
22
22
|
_wildcardRegistrations = 0;
|
|
23
|
+
_startupTimer;
|
|
24
|
+
_disposed = false;
|
|
23
25
|
constructor(targetOrigin = getDefaultTargetOrigin()) {
|
|
24
26
|
this._targetOrigin = targetOrigin;
|
|
25
27
|
this.handleMessage = this.handleMessage.bind(this);
|
|
26
28
|
window.addEventListener("message", this.handleMessage);
|
|
27
|
-
setTimeout(() =>
|
|
29
|
+
this._startupTimer = setTimeout(() => {
|
|
30
|
+
this._startupTimer = void 0;
|
|
31
|
+
this.broadcastUpdate();
|
|
32
|
+
}, 0);
|
|
28
33
|
}
|
|
29
34
|
static getInstance(targetOrigin) {
|
|
30
35
|
if (!AssistantFrameProvider._instance) AssistantFrameProvider._instance = new AssistantFrameProvider(targetOrigin);
|
|
@@ -57,7 +62,9 @@ var AssistantFrameProvider = class AssistantFrameProvider {
|
|
|
57
62
|
});
|
|
58
63
|
break;
|
|
59
64
|
case "tool-call":
|
|
60
|
-
this.handleToolCall(message, event)
|
|
65
|
+
this.handleToolCall(message, event).catch((error) => {
|
|
66
|
+
console.error("[assistant-ui] AssistantFrame tool call failed.", error);
|
|
67
|
+
});
|
|
61
68
|
break;
|
|
62
69
|
case "tool-cancel": this.cancelToolCall(message.id);
|
|
63
70
|
}
|
|
@@ -89,11 +96,21 @@ var AssistantFrameProvider = class AssistantFrameProvider {
|
|
|
89
96
|
}
|
|
90
97
|
if (this._activeToolCalls.get(message.id) !== activeCall) return;
|
|
91
98
|
this._activeToolCalls.delete(message.id);
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
99
|
+
try {
|
|
100
|
+
this.sendMessage(event, {
|
|
101
|
+
type: "tool-result",
|
|
102
|
+
id: message.id,
|
|
103
|
+
...error !== void 0 ? { error } : { result }
|
|
104
|
+
});
|
|
105
|
+
} catch (sendError) {
|
|
106
|
+
if (error !== void 0) throw sendError;
|
|
107
|
+
console.error("[assistant-ui] AssistantFrame tool result could not be sent.", sendError);
|
|
108
|
+
this.sendMessage(event, {
|
|
109
|
+
type: "tool-result",
|
|
110
|
+
id: message.id,
|
|
111
|
+
error: "Tool result could not be sent across the frame boundary"
|
|
112
|
+
});
|
|
113
|
+
}
|
|
97
114
|
}
|
|
98
115
|
cancelToolCall(id) {
|
|
99
116
|
const activeCall = this._activeToolCalls.get(id);
|
|
@@ -154,6 +171,7 @@ var AssistantFrameProvider = class AssistantFrameProvider {
|
|
|
154
171
|
}), {});
|
|
155
172
|
}
|
|
156
173
|
broadcastUpdate() {
|
|
174
|
+
if (this._disposed) return;
|
|
157
175
|
if (window.parent && window.parent !== window) {
|
|
158
176
|
const updateMessage = {
|
|
159
177
|
type: "model-context-update",
|
|
@@ -239,6 +257,11 @@ var AssistantFrameProvider = class AssistantFrameProvider {
|
|
|
239
257
|
static dispose() {
|
|
240
258
|
if (AssistantFrameProvider._instance) {
|
|
241
259
|
const instance = AssistantFrameProvider._instance;
|
|
260
|
+
instance._disposed = true;
|
|
261
|
+
if (instance._startupTimer !== void 0) {
|
|
262
|
+
clearTimeout(instance._startupTimer);
|
|
263
|
+
instance._startupTimer = void 0;
|
|
264
|
+
}
|
|
242
265
|
window.removeEventListener("message", instance.handleMessage);
|
|
243
266
|
let cleanupFailed = false;
|
|
244
267
|
let cleanupError;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","toJSONSchema","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","serializeTool","tool","description","parameters","undefined","disabled","type","serializeModelContext","context","system","tools","Object","fromEntries","entries","map","name","getDefaultTargetOrigin","window","location","origin","AssistantFrameProvider","_instance","_providers","Map","_providerUnsubscribes","_activeToolCalls","abortController","AbortController","event","MessageEvent","provider","_targetOrigin","_strictRegistrations","_wildcardRegistrations","constructor","targetOrigin","handleMessage","bind","addEventListener","setTimeout","broadcastUpdate","getInstance","reconcileTargetOrigin","size","Error","source","parent","data","channel","message","sendMessage","getModelContext","handleToolCall","cancelToolCall","id","Extract","resolvedTool","getTool","toolName","get","abort","activeCall","set","result","error","execute","args","toolCallId","abortSignal","signal","human","e","String","delete","cancelToolCallsForProvider","matchingCalls","Array","from","filter","sendFailed","sendError","console","postMessage","getProviders","Set","values","resolved","contexts","reduce","merged","updateMessage","removeProvider","unsubscribe","removedProvider","includes","addModelContextProvider","instance","Symbol","subscribe","cancelError","unsubscribeError","broadcastError","released","cleanupFailed","cleanupError","runCleanup","cleanup","dispose","removeEventListener","forEach","clear"],"sources":["../../../src/model-context/frame/provider.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { type Tool, toJSONSchema } from \"assistant-stream\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst serializeTool = (tool: Tool<any, any>): SerializedTool => ({\n ...(tool.description && { description: tool.description }),\n parameters: tool.parameters ? toJSONSchema(tool.parameters) : undefined,\n ...(tool.disabled !== undefined && { disabled: tool.disabled }),\n ...(tool.type && { type: tool.type }),\n});\n\nconst serializeModelContext = (\n context: ModelContext,\n): SerializedModelContext => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools && {\n tools: Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n serializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getDefaultTargetOrigin = () => window.location.origin;\n\nexport class AssistantFrameProvider {\n private static _instance: AssistantFrameProvider | null = null;\n\n private _providers = new Map<symbol, ModelContextProvider>();\n private _providerUnsubscribes = new Map<symbol, Unsubscribe | undefined>();\n private _activeToolCalls = new Map<\n string,\n {\n abortController: AbortController;\n event: MessageEvent;\n provider: ModelContextProvider | undefined;\n }\n >();\n private _targetOrigin: string;\n private _strictRegistrations = 0;\n private _wildcardRegistrations = 0;\n\n private constructor(targetOrigin: string = getDefaultTargetOrigin()) {\n this._targetOrigin = targetOrigin;\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n setTimeout(() => this.broadcastUpdate(), 0);\n }\n\n private static getInstance(targetOrigin?: string): AssistantFrameProvider {\n if (!AssistantFrameProvider._instance) {\n AssistantFrameProvider._instance = new AssistantFrameProvider(\n targetOrigin,\n );\n } else {\n AssistantFrameProvider._instance.reconcileTargetOrigin(targetOrigin);\n }\n return AssistantFrameProvider._instance;\n }\n\n private reconcileTargetOrigin(\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n if (targetOrigin === this._targetOrigin) return;\n\n if (this._providers.size === 0) {\n this._targetOrigin = targetOrigin;\n return;\n }\n\n if (targetOrigin === \"*\") return;\n\n if (this._targetOrigin === \"*\") {\n this._targetOrigin = targetOrigin;\n return;\n }\n\n throw new Error(\n `AssistantFrameProvider cannot register conflicting target origins: \"${this._targetOrigin}\" and \"${targetOrigin}\"`,\n );\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== window.parent) return;\n if (event.data?.channel !== FRAME_MESSAGE_CHANNEL) return;\n\n const message = event.data.message as FrameMessage;\n\n switch (message.type) {\n case \"model-context-request\":\n this.sendMessage(event, {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n });\n break;\n\n case \"tool-call\":\n this.handleToolCall(message, event);\n break;\n\n case \"tool-cancel\":\n this.cancelToolCall(message.id);\n break;\n }\n }\n\n private async handleToolCall(\n message: Extract<FrameMessage, { type: \"tool-call\" }>,\n event: MessageEvent,\n ) {\n const resolvedTool = this.getTool(message.toolName);\n const tool = resolvedTool?.tool;\n const abortController = new AbortController();\n this._activeToolCalls.get(message.id)?.abortController.abort();\n const activeCall = {\n abortController,\n event,\n provider: resolvedTool?.provider,\n };\n this._activeToolCalls.set(message.id, activeCall);\n\n let result: any;\n let error: string | undefined;\n\n if (!tool) {\n error = `Tool \"${message.toolName}\" not found`;\n } else {\n try {\n result = tool.execute\n ? await tool.execute(message.args, {\n toolCallId: message.id,\n abortSignal: abortController.signal,\n human: async () => {\n throw new Error(\n \"Tool human input is not supported in frame context\",\n );\n },\n })\n : undefined;\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n }\n\n if (this._activeToolCalls.get(message.id) !== activeCall) return;\n this._activeToolCalls.delete(message.id);\n\n this.sendMessage(event, {\n type: \"tool-result\",\n id: message.id,\n ...(error !== undefined ? { error } : { result }),\n });\n }\n\n private cancelToolCall(id: string) {\n const activeCall = this._activeToolCalls.get(id);\n if (!activeCall) return;\n this._activeToolCalls.delete(id);\n activeCall.abortController.abort();\n }\n\n private cancelToolCallsForProvider(provider: ModelContextProvider) {\n const matchingCalls = Array.from(this._activeToolCalls).filter(\n ([, activeCall]) => activeCall.provider === provider,\n );\n for (const [id, activeCall] of matchingCalls) {\n this._activeToolCalls.delete(id);\n activeCall.abortController.abort();\n }\n\n let sendFailed = false;\n let sendError: unknown;\n for (const [id, activeCall] of matchingCalls) {\n try {\n this.sendMessage(activeCall.event, {\n type: \"tool-result\",\n id,\n error: \"AssistantFrame tool provider has been removed\",\n });\n } catch (error) {\n if (sendFailed) {\n console.error(error);\n } else {\n sendFailed = true;\n sendError = error;\n }\n }\n }\n\n if (sendFailed) throw sendError;\n }\n\n private sendMessage(event: MessageEvent, message: FrameMessage) {\n event.source?.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n { targetOrigin: event.origin },\n );\n }\n\n private getProviders() {\n return Array.from(new Set(this._providers.values()));\n }\n\n private getTool(toolName: string) {\n let resolved:\n | { provider: ModelContextProvider; tool: Tool<any, any> }\n | undefined;\n\n for (const provider of this.getProviders()) {\n const tool = provider.getModelContext().tools?.[toolName];\n if (tool) resolved = { provider, tool };\n }\n\n return resolved;\n }\n\n private getModelContext(): ModelContext {\n const contexts = this.getProviders().map((provider) =>\n provider.getModelContext(),\n );\n\n return contexts.reduce(\n (merged, context) => ({\n system: context.system\n ? merged.system\n ? `${merged.system}\\n\\n${context.system}`\n : context.system\n : merged.system,\n tools: { ...(merged.tools || {}), ...(context.tools || {}) },\n }),\n {} as ModelContext,\n );\n }\n\n private broadcastUpdate() {\n if (window.parent && window.parent !== window) {\n const updateMessage: FrameMessage = {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n };\n\n window.parent.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message: updateMessage },\n this._targetOrigin,\n );\n }\n }\n\n private removeProvider(\n id: symbol,\n origin: string,\n ): {\n unsubscribe: Unsubscribe | undefined;\n removedProvider: ModelContextProvider | undefined;\n } {\n const provider = this._providers.get(id);\n this._providers.delete(id);\n const unsubscribe = this._providerUnsubscribes.get(id);\n this._providerUnsubscribes.delete(id);\n if (origin === \"*\") {\n this._wildcardRegistrations -= 1;\n if (\n this._wildcardRegistrations === 0 &&\n this._strictRegistrations === 0\n ) {\n this._targetOrigin = getDefaultTargetOrigin();\n }\n } else {\n this._strictRegistrations -= 1;\n if (this._strictRegistrations === 0) {\n this._targetOrigin =\n this._wildcardRegistrations > 0 ? \"*\" : getDefaultTargetOrigin();\n }\n }\n const removedProvider =\n provider && !this.getProviders().includes(provider)\n ? provider\n : undefined;\n return { unsubscribe, removedProvider };\n }\n\n static addModelContextProvider(\n provider: ModelContextProvider,\n targetOrigin?: string,\n ): Unsubscribe {\n const origin = targetOrigin ?? getDefaultTargetOrigin();\n const instance = AssistantFrameProvider.getInstance(origin);\n const id = Symbol();\n instance._providers.set(id, provider);\n if (origin === \"*\") {\n instance._wildcardRegistrations += 1;\n } else {\n instance._strictRegistrations += 1;\n }\n\n try {\n const unsubscribe = provider.subscribe?.(() =>\n instance.broadcastUpdate(),\n );\n if (unsubscribe) {\n instance._providerUnsubscribes.set(id, unsubscribe);\n }\n\n instance.broadcastUpdate();\n } catch (error) {\n const { unsubscribe, removedProvider } = instance.removeProvider(\n id,\n origin,\n );\n // Rollback failures must not replace the registration error.\n try {\n if (removedProvider) {\n instance.cancelToolCallsForProvider(removedProvider);\n }\n } catch (cancelError) {\n console.error(cancelError);\n }\n try {\n unsubscribe?.();\n } catch (unsubscribeError) {\n console.error(unsubscribeError);\n }\n try {\n instance.broadcastUpdate();\n } catch (broadcastError) {\n console.error(broadcastError);\n }\n throw error;\n }\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const { unsubscribe, removedProvider } = instance.removeProvider(\n id,\n origin,\n );\n let cleanupFailed = false;\n let cleanupError: unknown;\n const runCleanup = (cleanup: () => void) => {\n try {\n cleanup();\n } catch (error) {\n if (cleanupFailed) {\n console.error(error);\n } else {\n cleanupFailed = true;\n cleanupError = error;\n }\n }\n };\n\n if (removedProvider) {\n runCleanup(() => instance.cancelToolCallsForProvider(removedProvider));\n }\n if (unsubscribe) runCleanup(unsubscribe);\n runCleanup(() => instance.broadcastUpdate());\n\n if (cleanupFailed) throw cleanupError;\n };\n }\n\n static dispose() {\n if (AssistantFrameProvider._instance) {\n const instance = AssistantFrameProvider._instance;\n window.removeEventListener(\"message\", instance.handleMessage);\n\n let cleanupFailed = false;\n let cleanupError: unknown;\n const runCleanup = (cleanup: () => void) => {\n try {\n cleanup();\n } catch (error) {\n if (cleanupFailed) {\n console.error(error);\n } else {\n cleanupFailed = true;\n cleanupError = error;\n }\n }\n };\n\n instance._providerUnsubscribes.forEach((unsubscribe) => {\n if (unsubscribe) runCleanup(unsubscribe);\n });\n instance._providerUnsubscribes.clear();\n instance._providers.clear();\n instance._activeToolCalls.forEach(({ abortController, event }, id) => {\n runCleanup(() => {\n abortController.abort();\n instance.sendMessage(event, {\n type: \"tool-result\",\n id,\n error: \"AssistantFrameProvider has been disposed\",\n });\n });\n });\n instance._activeToolCalls.clear();\n\n AssistantFrameProvider._instance = null;\n if (cleanupFailed) throw cleanupError;\n }\n }\n}\n"],"mappings":";;;AAUA,MAAMS,iBAAiBC,UAA0C;CAC/D,GAAIA,KAAKC,eAAe,EAAEA,aAAaD,KAAKC,YAAY;CACxDC,YAAYF,KAAKE,aAAaR,aAAaM,KAAKE,UAAU,IAAIC,KAAAA;CAC9D,GAAIH,KAAKI,aAAaD,KAAAA,KAAa,EAAEC,UAAUJ,KAAKI,SAAS;CAC7D,GAAIJ,KAAKK,QAAQ,EAAEA,MAAML,KAAKK,KAAK;AACrC;AAEA,MAAMC,yBACJC,aAC4B;CAC5B,GAAIA,QAAQC,WAAWL,KAAAA,KAAa,EAAEK,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,SA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,gBAAgB,CAAC;GAE3C,IAAI+D,eAAe,MAAMC;EAC3B;CACF;CAEA,OAAOG,UAAU;EACf,IAAIvF,uBAAuBC,WAAW;GACpC,MAAM2E,WAAW5E,uBAAuBC;GACxCJ,OAAO2F,oBAAoB,WAAWZ,SAAS5D,aAAa;GAE5D,IAAImE,gBAAgB;GACpB,IAAIC;GACJ,MAAMC,cAAcC,YAAwB;IAC1C,IAAI;KACFA,QAAQ;IACV,SAAS1C,OAAO;KACd,IAAIuC,eACFtB,QAAQjB,MAAMA,KAAK;UACd;MACLuC,gBAAgB;MAChBC,eAAexC;KACjB;IACF;GACF;GAEAgC,SAASxE,sBAAsBqF,SAASjB,gBAAgB;IACtD,IAAIA,aAAaa,WAAWb,WAAW;GACzC,CAAC;GACDI,SAASxE,sBAAsBsF,MAAM;GACrCd,SAAS1E,WAAWwF,MAAM;GAC1Bd,SAASvE,iBAAiBoF,SAAS,EAAEnF,iBAAiBE,SAAS0B,OAAO;IACpEmD,iBAAiB;KACf/E,gBAAgBkC,MAAM;KACtBoC,SAAS9C,YAAYtB,OAAO;MAC1BtB,MAAM;MACNgD;MACAU,OAAO;KACT,CAAC;IACH,CAAC;GACH,CAAC;GACDgC,SAASvE,iBAAiBqF,MAAM;GAEhC1F,uBAAuBC,YAAY;GACnC,IAAIkF,eAAe,MAAMC;EAC3B;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"provider.js","names":["ModelContextProvider","ModelContext","Unsubscribe","Tool","toJSONSchema","FrameMessage","FRAME_MESSAGE_CHANNEL","SerializedModelContext","SerializedTool","serializeTool","tool","description","parameters","undefined","disabled","type","serializeModelContext","context","system","tools","Object","fromEntries","entries","map","name","getDefaultTargetOrigin","window","location","origin","AssistantFrameProvider","_instance","_providers","Map","_providerUnsubscribes","_activeToolCalls","abortController","AbortController","event","MessageEvent","provider","_targetOrigin","_strictRegistrations","_wildcardRegistrations","_startupTimer","ReturnType","setTimeout","_disposed","constructor","targetOrigin","handleMessage","bind","addEventListener","broadcastUpdate","getInstance","reconcileTargetOrigin","size","Error","source","parent","data","channel","message","sendMessage","getModelContext","handleToolCall","catch","error","console","cancelToolCall","id","Extract","resolvedTool","getTool","toolName","get","abort","activeCall","set","result","execute","args","toolCallId","abortSignal","signal","human","e","String","delete","sendError","cancelToolCallsForProvider","matchingCalls","Array","from","filter","sendFailed","postMessage","getProviders","Set","values","resolved","contexts","reduce","merged","updateMessage","removeProvider","unsubscribe","removedProvider","includes","addModelContextProvider","instance","Symbol","subscribe","cancelError","unsubscribeError","broadcastError","released","cleanupFailed","cleanupError","runCleanup","cleanup","dispose","clearTimeout","removeEventListener","forEach","clear"],"sources":["../../../src/model-context/frame/provider.ts"],"sourcesContent":["import type { ModelContextProvider, ModelContext } from \"../types\";\nimport type { Unsubscribe } from \"../../types/unsubscribe\";\nimport { type Tool, toJSONSchema } from \"assistant-stream\";\nimport {\n type FrameMessage,\n FRAME_MESSAGE_CHANNEL,\n type SerializedModelContext,\n type SerializedTool,\n} from \"./types\";\n\nconst serializeTool = (tool: Tool<any, any>): SerializedTool => ({\n ...(tool.description && { description: tool.description }),\n parameters: tool.parameters ? toJSONSchema(tool.parameters) : undefined,\n ...(tool.disabled !== undefined && { disabled: tool.disabled }),\n ...(tool.type && { type: tool.type }),\n});\n\nconst serializeModelContext = (\n context: ModelContext,\n): SerializedModelContext => ({\n ...(context.system !== undefined && { system: context.system }),\n ...(context.tools && {\n tools: Object.fromEntries(\n Object.entries(context.tools).map(([name, tool]) => [\n name,\n serializeTool(tool),\n ]),\n ),\n }),\n});\n\nconst getDefaultTargetOrigin = () => window.location.origin;\n\nexport class AssistantFrameProvider {\n private static _instance: AssistantFrameProvider | null = null;\n\n private _providers = new Map<symbol, ModelContextProvider>();\n private _providerUnsubscribes = new Map<symbol, Unsubscribe | undefined>();\n private _activeToolCalls = new Map<\n string,\n {\n abortController: AbortController;\n event: MessageEvent;\n provider: ModelContextProvider | undefined;\n }\n >();\n private _targetOrigin: string;\n private _strictRegistrations = 0;\n private _wildcardRegistrations = 0;\n private _startupTimer: ReturnType<typeof setTimeout> | undefined;\n private _disposed = false;\n\n private constructor(targetOrigin: string = getDefaultTargetOrigin()) {\n this._targetOrigin = targetOrigin;\n this.handleMessage = this.handleMessage.bind(this);\n window.addEventListener(\"message\", this.handleMessage);\n\n this._startupTimer = setTimeout(() => {\n this._startupTimer = undefined;\n this.broadcastUpdate();\n }, 0);\n }\n\n private static getInstance(targetOrigin?: string): AssistantFrameProvider {\n if (!AssistantFrameProvider._instance) {\n AssistantFrameProvider._instance = new AssistantFrameProvider(\n targetOrigin,\n );\n } else {\n AssistantFrameProvider._instance.reconcileTargetOrigin(targetOrigin);\n }\n return AssistantFrameProvider._instance;\n }\n\n private reconcileTargetOrigin(\n targetOrigin: string = getDefaultTargetOrigin(),\n ) {\n if (targetOrigin === this._targetOrigin) return;\n\n if (this._providers.size === 0) {\n this._targetOrigin = targetOrigin;\n return;\n }\n\n if (targetOrigin === \"*\") return;\n\n if (this._targetOrigin === \"*\") {\n this._targetOrigin = targetOrigin;\n return;\n }\n\n throw new Error(\n `AssistantFrameProvider cannot register conflicting target origins: \"${this._targetOrigin}\" and \"${targetOrigin}\"`,\n );\n }\n\n private handleMessage(event: MessageEvent) {\n if (this._targetOrigin !== \"*\" && event.origin !== this._targetOrigin)\n return;\n if (event.source !== window.parent) return;\n if (event.data?.channel !== FRAME_MESSAGE_CHANNEL) return;\n\n const message = event.data.message as FrameMessage;\n\n switch (message.type) {\n case \"model-context-request\":\n this.sendMessage(event, {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n });\n break;\n\n case \"tool-call\":\n void this.handleToolCall(message, event).catch((error: unknown) => {\n console.error(\n \"[assistant-ui] AssistantFrame tool call failed.\",\n error,\n );\n });\n break;\n\n case \"tool-cancel\":\n this.cancelToolCall(message.id);\n break;\n }\n }\n\n private async handleToolCall(\n message: Extract<FrameMessage, { type: \"tool-call\" }>,\n event: MessageEvent,\n ) {\n const resolvedTool = this.getTool(message.toolName);\n const tool = resolvedTool?.tool;\n const abortController = new AbortController();\n this._activeToolCalls.get(message.id)?.abortController.abort();\n const activeCall = {\n abortController,\n event,\n provider: resolvedTool?.provider,\n };\n this._activeToolCalls.set(message.id, activeCall);\n\n let result: any;\n let error: string | undefined;\n\n if (!tool) {\n error = `Tool \"${message.toolName}\" not found`;\n } else {\n try {\n result = tool.execute\n ? await tool.execute(message.args, {\n toolCallId: message.id,\n abortSignal: abortController.signal,\n human: async () => {\n throw new Error(\n \"Tool human input is not supported in frame context\",\n );\n },\n })\n : undefined;\n } catch (e) {\n error = e instanceof Error ? e.message : String(e);\n }\n }\n\n if (this._activeToolCalls.get(message.id) !== activeCall) return;\n this._activeToolCalls.delete(message.id);\n\n try {\n this.sendMessage(event, {\n type: \"tool-result\",\n id: message.id,\n ...(error !== undefined ? { error } : { result }),\n });\n } catch (sendError) {\n if (error !== undefined) throw sendError;\n\n console.error(\n \"[assistant-ui] AssistantFrame tool result could not be sent.\",\n sendError,\n );\n this.sendMessage(event, {\n type: \"tool-result\",\n id: message.id,\n error: \"Tool result could not be sent across the frame boundary\",\n });\n }\n }\n\n private cancelToolCall(id: string) {\n const activeCall = this._activeToolCalls.get(id);\n if (!activeCall) return;\n this._activeToolCalls.delete(id);\n activeCall.abortController.abort();\n }\n\n private cancelToolCallsForProvider(provider: ModelContextProvider) {\n const matchingCalls = Array.from(this._activeToolCalls).filter(\n ([, activeCall]) => activeCall.provider === provider,\n );\n for (const [id, activeCall] of matchingCalls) {\n this._activeToolCalls.delete(id);\n activeCall.abortController.abort();\n }\n\n let sendFailed = false;\n let sendError: unknown;\n for (const [id, activeCall] of matchingCalls) {\n try {\n this.sendMessage(activeCall.event, {\n type: \"tool-result\",\n id,\n error: \"AssistantFrame tool provider has been removed\",\n });\n } catch (error) {\n if (sendFailed) {\n console.error(error);\n } else {\n sendFailed = true;\n sendError = error;\n }\n }\n }\n\n if (sendFailed) throw sendError;\n }\n\n private sendMessage(event: MessageEvent, message: FrameMessage) {\n event.source?.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message },\n { targetOrigin: event.origin },\n );\n }\n\n private getProviders() {\n return Array.from(new Set(this._providers.values()));\n }\n\n private getTool(toolName: string) {\n let resolved:\n | { provider: ModelContextProvider; tool: Tool<any, any> }\n | undefined;\n\n for (const provider of this.getProviders()) {\n const tool = provider.getModelContext().tools?.[toolName];\n if (tool) resolved = { provider, tool };\n }\n\n return resolved;\n }\n\n private getModelContext(): ModelContext {\n const contexts = this.getProviders().map((provider) =>\n provider.getModelContext(),\n );\n\n return contexts.reduce(\n (merged, context) => ({\n system: context.system\n ? merged.system\n ? `${merged.system}\\n\\n${context.system}`\n : context.system\n : merged.system,\n tools: { ...(merged.tools || {}), ...(context.tools || {}) },\n }),\n {} as ModelContext,\n );\n }\n\n private broadcastUpdate() {\n if (this._disposed) return;\n if (window.parent && window.parent !== window) {\n const updateMessage: FrameMessage = {\n type: \"model-context-update\",\n context: serializeModelContext(this.getModelContext()),\n };\n\n window.parent.postMessage(\n { channel: FRAME_MESSAGE_CHANNEL, message: updateMessage },\n this._targetOrigin,\n );\n }\n }\n\n private removeProvider(\n id: symbol,\n origin: string,\n ): {\n unsubscribe: Unsubscribe | undefined;\n removedProvider: ModelContextProvider | undefined;\n } {\n const provider = this._providers.get(id);\n this._providers.delete(id);\n const unsubscribe = this._providerUnsubscribes.get(id);\n this._providerUnsubscribes.delete(id);\n if (origin === \"*\") {\n this._wildcardRegistrations -= 1;\n if (\n this._wildcardRegistrations === 0 &&\n this._strictRegistrations === 0\n ) {\n this._targetOrigin = getDefaultTargetOrigin();\n }\n } else {\n this._strictRegistrations -= 1;\n if (this._strictRegistrations === 0) {\n this._targetOrigin =\n this._wildcardRegistrations > 0 ? \"*\" : getDefaultTargetOrigin();\n }\n }\n const removedProvider =\n provider && !this.getProviders().includes(provider)\n ? provider\n : undefined;\n return { unsubscribe, removedProvider };\n }\n\n static addModelContextProvider(\n provider: ModelContextProvider,\n targetOrigin?: string,\n ): Unsubscribe {\n const origin = targetOrigin ?? getDefaultTargetOrigin();\n const instance = AssistantFrameProvider.getInstance(origin);\n const id = Symbol();\n instance._providers.set(id, provider);\n if (origin === \"*\") {\n instance._wildcardRegistrations += 1;\n } else {\n instance._strictRegistrations += 1;\n }\n\n try {\n const unsubscribe = provider.subscribe?.(() =>\n instance.broadcastUpdate(),\n );\n if (unsubscribe) {\n instance._providerUnsubscribes.set(id, unsubscribe);\n }\n\n instance.broadcastUpdate();\n } catch (error) {\n const { unsubscribe, removedProvider } = instance.removeProvider(\n id,\n origin,\n );\n // Rollback failures must not replace the registration error.\n try {\n if (removedProvider) {\n instance.cancelToolCallsForProvider(removedProvider);\n }\n } catch (cancelError) {\n console.error(cancelError);\n }\n try {\n unsubscribe?.();\n } catch (unsubscribeError) {\n console.error(unsubscribeError);\n }\n try {\n instance.broadcastUpdate();\n } catch (broadcastError) {\n console.error(broadcastError);\n }\n throw error;\n }\n\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const { unsubscribe, removedProvider } = instance.removeProvider(\n id,\n origin,\n );\n let cleanupFailed = false;\n let cleanupError: unknown;\n const runCleanup = (cleanup: () => void) => {\n try {\n cleanup();\n } catch (error) {\n if (cleanupFailed) {\n console.error(error);\n } else {\n cleanupFailed = true;\n cleanupError = error;\n }\n }\n };\n\n if (removedProvider) {\n runCleanup(() => instance.cancelToolCallsForProvider(removedProvider));\n }\n if (unsubscribe) runCleanup(unsubscribe);\n runCleanup(() => instance.broadcastUpdate());\n\n if (cleanupFailed) throw cleanupError;\n };\n }\n\n static dispose() {\n if (AssistantFrameProvider._instance) {\n const instance = AssistantFrameProvider._instance;\n instance._disposed = true;\n if (instance._startupTimer !== undefined) {\n clearTimeout(instance._startupTimer);\n instance._startupTimer = undefined;\n }\n window.removeEventListener(\"message\", instance.handleMessage);\n\n let cleanupFailed = false;\n let cleanupError: unknown;\n const runCleanup = (cleanup: () => void) => {\n try {\n cleanup();\n } catch (error) {\n if (cleanupFailed) {\n console.error(error);\n } else {\n cleanupFailed = true;\n cleanupError = error;\n }\n }\n };\n\n instance._providerUnsubscribes.forEach((unsubscribe) => {\n if (unsubscribe) runCleanup(unsubscribe);\n });\n instance._providerUnsubscribes.clear();\n instance._providers.clear();\n instance._activeToolCalls.forEach(({ abortController, event }, id) => {\n runCleanup(() => {\n abortController.abort();\n instance.sendMessage(event, {\n type: \"tool-result\",\n id,\n error: \"AssistantFrameProvider has been disposed\",\n });\n });\n });\n instance._activeToolCalls.clear();\n\n AssistantFrameProvider._instance = null;\n if (cleanupFailed) throw cleanupError;\n }\n }\n}\n"],"mappings":";;;AAUA,MAAMS,iBAAiBC,UAA0C;CAC/D,GAAIA,KAAKC,eAAe,EAAEA,aAAaD,KAAKC,YAAY;CACxDC,YAAYF,KAAKE,aAAaR,aAAaM,KAAKE,UAAU,IAAIC,KAAAA;CAC9D,GAAIH,KAAKI,aAAaD,KAAAA,KAAa,EAAEC,UAAUJ,KAAKI,SAAS;CAC7D,GAAIJ,KAAKK,QAAQ,EAAEA,MAAML,KAAKK,KAAK;AACrC;AAEA,MAAMC,yBACJC,aAC4B;CAC5B,GAAIA,QAAQC,WAAWL,KAAAA,KAAa,EAAEK,QAAQD,QAAQC,OAAO;CAC7D,GAAID,QAAQE,SAAS,EACnBA,OAAOC,OAAOC,YACZD,OAAOE,QAAQL,QAAQE,KAAK,CAAC,CAACI,KAAK,CAACC,MAAMd,UAAU,CAClDc,MACAf,cAAcC,IAAI,CAAC,CACpB,CACH,EACF;AACF;AAEA,MAAMe,+BAA+BC,OAAOC,SAASC;AAErD,IAAaC,yBAAb,MAAaA,uBAAuB;CAClC,OAAeC,YAA2C;CAE1D,6BAAqB,IAAIE,IAAkC;CAC3D,wCAAgC,IAAIA,IAAqC;CACzE,mCAA2B,IAAIA,IAO7B;CACF;CACA,uBAA+B;CAC/B,yBAAiC;CACjC;CACA,YAAoB;CAEpB,YAAoBgB,eAAuBvB,uBAAuB,GAAG;EACnE,KAAKe,gBAAgBQ;EAC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