@legit-sdk/assistant-ui 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +131 -0
- package/README.md +1 -0
- package/dist/index.d.ts +131 -0
- package/dist/index.js +5 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +5 -0
- package/package.json +59 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
# PolyForm Noncommercial License 1.0.0
|
|
2
|
+
|
|
3
|
+
<https://polyformproject.org/licenses/noncommercial/1.0.0>
|
|
4
|
+
|
|
5
|
+
## Acceptance
|
|
6
|
+
|
|
7
|
+
In order to get any license under these terms, you must agree
|
|
8
|
+
to them as both strict obligations and conditions to all
|
|
9
|
+
your licenses.
|
|
10
|
+
|
|
11
|
+
## Copyright License
|
|
12
|
+
|
|
13
|
+
The licensor grants you a copyright license for the
|
|
14
|
+
software to do everything you might do with the software
|
|
15
|
+
that would otherwise infringe the licensor's copyright
|
|
16
|
+
in it for any permitted purpose. However, you may
|
|
17
|
+
only distribute the software according to [Distribution
|
|
18
|
+
License](#distribution-license) and make changes or new works
|
|
19
|
+
based on the software according to [Changes and New Works
|
|
20
|
+
License](#changes-and-new-works-license).
|
|
21
|
+
|
|
22
|
+
## Distribution License
|
|
23
|
+
|
|
24
|
+
The licensor grants you an additional copyright license
|
|
25
|
+
to distribute copies of the software. Your license
|
|
26
|
+
to distribute covers distributing the software with
|
|
27
|
+
changes and new works permitted by [Changes and New Works
|
|
28
|
+
License](#changes-and-new-works-license).
|
|
29
|
+
|
|
30
|
+
## Notices
|
|
31
|
+
|
|
32
|
+
You must ensure that anyone who gets a copy of any part of
|
|
33
|
+
the software from you also gets a copy of these terms or the
|
|
34
|
+
URL for them above, as well as copies of any plain-text lines
|
|
35
|
+
beginning with `Required Notice:` that the licensor provided
|
|
36
|
+
with the software. For example:
|
|
37
|
+
|
|
38
|
+
> Required Notice: Copyright Yoyodyne, Inc. (http://example.com)
|
|
39
|
+
|
|
40
|
+
## Changes and New Works License
|
|
41
|
+
|
|
42
|
+
The licensor grants you an additional copyright license to
|
|
43
|
+
make changes and new works based on the software for any
|
|
44
|
+
permitted purpose.
|
|
45
|
+
|
|
46
|
+
## Patent License
|
|
47
|
+
|
|
48
|
+
The licensor grants you a patent license for the software that
|
|
49
|
+
covers patent claims the licensor can license, or becomes able
|
|
50
|
+
to license, that you would infringe by using the software.
|
|
51
|
+
|
|
52
|
+
## Noncommercial Purposes
|
|
53
|
+
|
|
54
|
+
Any noncommercial purpose is a permitted purpose.
|
|
55
|
+
|
|
56
|
+
## Personal Uses
|
|
57
|
+
|
|
58
|
+
Personal use for research, experiment, and testing for
|
|
59
|
+
the benefit of public knowledge, personal study, private
|
|
60
|
+
entertainment, hobby projects, amateur pursuits, or religious
|
|
61
|
+
observance, without any anticipated commercial application,
|
|
62
|
+
is use for a permitted purpose.
|
|
63
|
+
|
|
64
|
+
## Noncommercial Organizations
|
|
65
|
+
|
|
66
|
+
Use by any charitable organization, educational institution,
|
|
67
|
+
public research organization, public safety or health
|
|
68
|
+
organization, environmental protection organization,
|
|
69
|
+
or government institution is use for a permitted purpose
|
|
70
|
+
regardless of the source of funding or obligations resulting
|
|
71
|
+
from the funding.
|
|
72
|
+
|
|
73
|
+
## Fair Use
|
|
74
|
+
|
|
75
|
+
You may have "fair use" rights for the software under the
|
|
76
|
+
law. These terms do not limit them.
|
|
77
|
+
|
|
78
|
+
## No Other Rights
|
|
79
|
+
|
|
80
|
+
These terms do not allow you to sublicense or transfer any of
|
|
81
|
+
your licenses to anyone else, or prevent the licensor from
|
|
82
|
+
granting licenses to anyone else. These terms do not imply
|
|
83
|
+
any other licenses.
|
|
84
|
+
|
|
85
|
+
## Patent Defense
|
|
86
|
+
|
|
87
|
+
If you make any written claim that the software infringes or
|
|
88
|
+
contributes to infringement of any patent, your patent license
|
|
89
|
+
for the software granted under these terms ends immediately. If
|
|
90
|
+
your company makes such a claim, your patent license ends
|
|
91
|
+
immediately for work on behalf of your company.
|
|
92
|
+
|
|
93
|
+
## Violations
|
|
94
|
+
|
|
95
|
+
The first time you are notified in writing that you have
|
|
96
|
+
violated any of these terms, or done anything with the software
|
|
97
|
+
not covered by your licenses, your licenses can nonetheless
|
|
98
|
+
continue if you come into full compliance with these terms,
|
|
99
|
+
and take practical steps to correct past violations, within
|
|
100
|
+
32 days of receiving notice. Otherwise, all your licenses
|
|
101
|
+
end immediately.
|
|
102
|
+
|
|
103
|
+
## No Liability
|
|
104
|
+
|
|
105
|
+
***As far as the law allows, the software comes as is, without
|
|
106
|
+
any warranty or condition, and the licensor will not be liable
|
|
107
|
+
to you for any damages arising out of these terms or the use
|
|
108
|
+
or nature of the software, under any kind of legal claim.***
|
|
109
|
+
|
|
110
|
+
## Definitions
|
|
111
|
+
|
|
112
|
+
The **licensor** is the individual or entity offering these
|
|
113
|
+
terms, and the **software** is the software the licensor makes
|
|
114
|
+
available under these terms.
|
|
115
|
+
|
|
116
|
+
**You** refers to the individual or entity agreeing to these
|
|
117
|
+
terms.
|
|
118
|
+
|
|
119
|
+
**Your company** is any legal entity, sole proprietorship,
|
|
120
|
+
or other kind of organization that you work for, plus all
|
|
121
|
+
organizations that have control over, are under the control of,
|
|
122
|
+
or are under common control with that organization. **Control**
|
|
123
|
+
means ownership of substantially all the assets of an entity,
|
|
124
|
+
or the power to direct its management and policies by vote,
|
|
125
|
+
contract, or otherwise. Control can be direct or indirect.
|
|
126
|
+
|
|
127
|
+
**Your licenses** are all the licenses granted to you for the
|
|
128
|
+
software under these terms.
|
|
129
|
+
|
|
130
|
+
**Use** means anything you do with the software requiring one
|
|
131
|
+
of your licenses.
|
package/README.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# @legit-sdk/assistant-ui
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { AssistantCloud } from 'assistant-cloud';
|
|
2
|
+
import { AssistantRuntime, ExportedMessageRepository, ThreadMessageLike } from '@assistant-ui/react';
|
|
3
|
+
import { initLegitFs } from '@legit-sdk/core';
|
|
4
|
+
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
5
|
+
import { ReactNode } from 'react';
|
|
6
|
+
import { ModelMessage, StreamTextResult } from 'ai';
|
|
7
|
+
|
|
8
|
+
type LegitFsInstance = Awaited<ReturnType<typeof initLegitFs>>;
|
|
9
|
+
type AssistantCloudConfig = {
|
|
10
|
+
baseUrl: string;
|
|
11
|
+
authToken: () => Promise<string | null>;
|
|
12
|
+
legitFs: LegitFsInstance;
|
|
13
|
+
};
|
|
14
|
+
type MetadataLike = {
|
|
15
|
+
custom?: unknown;
|
|
16
|
+
[key: string]: unknown;
|
|
17
|
+
};
|
|
18
|
+
type CloudMessage = {
|
|
19
|
+
id: string;
|
|
20
|
+
parent_id: string | null;
|
|
21
|
+
height: number;
|
|
22
|
+
created_at: Date;
|
|
23
|
+
updated_at: Date;
|
|
24
|
+
format: string;
|
|
25
|
+
content: Record<string, unknown>;
|
|
26
|
+
metadata?: MetadataLike;
|
|
27
|
+
};
|
|
28
|
+
type AssistantCloudThreadMessageListQuery = {
|
|
29
|
+
format?: string;
|
|
30
|
+
};
|
|
31
|
+
type AssistantCloudThreadMessageListResponse = {
|
|
32
|
+
messages: CloudMessage[];
|
|
33
|
+
};
|
|
34
|
+
type AssistantCloudThreadMessageCreateBody = {
|
|
35
|
+
parent_id: string | null;
|
|
36
|
+
format: string;
|
|
37
|
+
content: Record<string, unknown>;
|
|
38
|
+
};
|
|
39
|
+
type AssistantCloudMessageCreateResponse = {
|
|
40
|
+
message_id: string;
|
|
41
|
+
};
|
|
42
|
+
type CloudThread = {
|
|
43
|
+
id: string;
|
|
44
|
+
title: string;
|
|
45
|
+
last_message_at: Date;
|
|
46
|
+
metadata: unknown;
|
|
47
|
+
external_id: string | null;
|
|
48
|
+
project_id: string;
|
|
49
|
+
created_at: Date;
|
|
50
|
+
updated_at: Date;
|
|
51
|
+
workspace_id: string;
|
|
52
|
+
is_archived: boolean;
|
|
53
|
+
};
|
|
54
|
+
type AssistantCloudThreadsListQuery = {
|
|
55
|
+
is_archived?: boolean;
|
|
56
|
+
limit?: number;
|
|
57
|
+
after?: string;
|
|
58
|
+
};
|
|
59
|
+
type AssistantCloudThreadsListResponse = {
|
|
60
|
+
threads: CloudThread[];
|
|
61
|
+
};
|
|
62
|
+
type AssistantCloudThreadsCreateBody = {
|
|
63
|
+
title?: string;
|
|
64
|
+
last_message_at?: Date;
|
|
65
|
+
metadata?: unknown;
|
|
66
|
+
external_id?: string | null;
|
|
67
|
+
};
|
|
68
|
+
type AssistantCloudThreadsCreateResponse = {
|
|
69
|
+
thread_id: string;
|
|
70
|
+
};
|
|
71
|
+
type AssistantCloudThreadsUpdateBody = {
|
|
72
|
+
title?: string;
|
|
73
|
+
last_message_at?: Date;
|
|
74
|
+
metadata?: unknown;
|
|
75
|
+
is_archived?: boolean;
|
|
76
|
+
};
|
|
77
|
+
type CloudMessageWithoutId = Omit<CloudMessage, 'id' | 'height' | 'parent_id'>;
|
|
78
|
+
|
|
79
|
+
declare class LegitLocal extends AssistantCloud {
|
|
80
|
+
runtime?: AssistantRuntime;
|
|
81
|
+
legitFs: LegitFsInstance | null;
|
|
82
|
+
constructor(config: AssistantCloudConfig);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
type SaveDataFn = (path: string, data: Parameters<LegitFsInstance['promises']['writeFile']>[1]) => Promise<void>;
|
|
86
|
+
type GetMessageDiffFn = (messageId: string) => Promise<{
|
|
87
|
+
newOid: string;
|
|
88
|
+
oldOid: string;
|
|
89
|
+
} | undefined>;
|
|
90
|
+
type RollbackFn = (messageId: string) => Promise<string | undefined>;
|
|
91
|
+
type GetPastStateFn = (oid: string, pathToFile: string) => Promise<string | undefined>;
|
|
92
|
+
type LegitFsContextValue = {
|
|
93
|
+
legitFs: LegitFsInstance | null;
|
|
94
|
+
loading: boolean;
|
|
95
|
+
error: Error | null;
|
|
96
|
+
saveData: SaveDataFn;
|
|
97
|
+
getMessageDiff: GetMessageDiffFn;
|
|
98
|
+
getPastState: GetPastStateFn;
|
|
99
|
+
rollback: RollbackFn;
|
|
100
|
+
threadId: string;
|
|
101
|
+
resolvePath: (path: string) => string;
|
|
102
|
+
};
|
|
103
|
+
declare function LegitFsProvider({ children }: {
|
|
104
|
+
children: ReactNode;
|
|
105
|
+
}): react_jsx_runtime.JSX.Element;
|
|
106
|
+
declare function useLegitFs(): LegitFsContextValue;
|
|
107
|
+
|
|
108
|
+
type SyncOptions = {
|
|
109
|
+
threadId: string;
|
|
110
|
+
threadApi: {
|
|
111
|
+
import: (repository: ReturnType<typeof ExportedMessageRepository.fromArray>) => void;
|
|
112
|
+
reset?: (initialMessages?: readonly ThreadMessageLike[]) => void;
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
declare function syncThreadFromLegitFs({ threadId, threadApi, }: SyncOptions): Promise<void>;
|
|
116
|
+
|
|
117
|
+
type UIMessageContent = Record<string, unknown>;
|
|
118
|
+
type UIMessage = {
|
|
119
|
+
role: string;
|
|
120
|
+
content?: UIMessageContent[];
|
|
121
|
+
};
|
|
122
|
+
declare const convertMessagesToModelMessages: (messages: UIMessage[]) => ModelMessage[];
|
|
123
|
+
/**
|
|
124
|
+
* Converts a streamText result to a Data Stream Response for use with useDataStreamRuntime
|
|
125
|
+
*/
|
|
126
|
+
declare function streamTextToDataStreamResponse(result: StreamTextResult<any, never>): Promise<Response>;
|
|
127
|
+
|
|
128
|
+
declare function LegitFsHeadPoller(): null;
|
|
129
|
+
|
|
130
|
+
export { LegitFsHeadPoller, LegitFsProvider, LegitLocal, convertMessagesToModelMessages, streamTextToDataStreamResponse, syncThreadFromLegitFs, useLegitFs };
|
|
131
|
+
export type { AssistantCloudConfig, AssistantCloudMessageCreateResponse, AssistantCloudThreadMessageCreateBody, AssistantCloudThreadMessageListQuery, AssistantCloudThreadMessageListResponse, AssistantCloudThreadsCreateBody, AssistantCloudThreadsCreateResponse, AssistantCloudThreadsListQuery, AssistantCloudThreadsListResponse, AssistantCloudThreadsUpdateBody, CloudMessage, CloudMessageWithoutId, CloudThread, LegitFsInstance, MetadataLike, UIMessage, UIMessageContent };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @legit-sdk/assistant-ui bundle (ESM)
|
|
2
|
+
// Generated by esbuild
|
|
3
|
+
|
|
4
|
+
var ve=Object.defineProperty;var Ee=r=>{throw TypeError(r)};var lt=(r,e,t)=>e in r?ve(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var a=(r,e)=>ve(r,"name",{value:e,configurable:!0});var u=(r,e,t)=>lt(r,typeof e!="symbol"?e+"":e,t),Me=(r,e,t)=>e.has(r)||Ee("Cannot "+t);var G=(r,e,t)=>(Me(r,e,"read from private field"),t?t.call(r):e.get(r)),K=(r,e,t)=>e.has(r)?Ee("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(r):e.set(r,t),V=(r,e,t,o)=>(Me(r,e,"write to private field"),o?o.call(r,t):e.set(r,t),t);var Oe=a(r=>{try{let t=r.split(".")[1];if(!t)throw new Error("Invalid JWT format");let o=t.replace(/-/g,"+").replace(/_/g,"/");for(;o.length%4!==0;)o+="=";let s=atob(o),i=JSON.parse(s).exp;if(!i||typeof i!="number")throw new Error('JWT does not contain a valid "exp" field');return i*1e3}catch(e){throw new Error("Unable to determine the token expiry: "+e)}},"getJwtExpiry"),Q,C,ge=(C=class{constructor(e){u(this,"strategy","jwt");u(this,"cachedToken",null);u(this,"tokenExpiry",null);K(this,Q);V(this,Q,e)}async getAuthHeaders(){let e=Date.now();if(this.cachedToken&&this.tokenExpiry&&this.tokenExpiry-e>30*1e3)return{Authorization:`Bearer ${this.cachedToken}`};let t=await G(this,Q).call(this);return t?(this.cachedToken=t,this.tokenExpiry=Oe(t),{Authorization:`Bearer ${t}`}):!1}readAuthHeaders(e){let t=e.get("Authorization");if(!t)return;let[o,s]=t.split(" ");if(o!=="Bearer"||!s)throw new Error("Invalid auth header received");this.cachedToken=s,this.tokenExpiry=Oe(s)}},Q=new WeakMap,a(C,"AssistantCloudJWTAuthStrategy"),C),X,Y,Z,A,Fe=(A=class{constructor(e,t,o){u(this,"strategy","api-key");K(this,X);K(this,Y);K(this,Z);V(this,X,e),V(this,Y,t),V(this,Z,o)}async getAuthHeaders(){return{Authorization:`Bearer ${G(this,X)}`,"Aui-User-Id":G(this,Y),"Aui-Workspace-Id":G(this,Z)}}readAuthHeaders(){}},X=new WeakMap,Y=new WeakMap,Z=new WeakMap,a(A,"AssistantCloudAPIKeyAuthStrategy"),A),oe="aui:refresh_token",S,De=(S=class{constructor(e){u(this,"strategy","anon");u(this,"baseUrl");u(this,"jwtStrategy");this.baseUrl=e,this.jwtStrategy=new ge(async()=>{let t=Date.now(),o=localStorage.getItem(oe),s=o?JSON.parse(o):void 0;if(s)if(new Date(s.expires_at).getTime()-t>30*1e3){let T=await fetch(`${this.baseUrl}/v1/auth/tokens/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:s.token})});if(T.ok){let z=await T.json(),{access_token:m,refresh_token:h}=z;return h&&localStorage.setItem(oe,JSON.stringify(h)),m}}else localStorage.removeItem(oe);let l=await fetch(`${this.baseUrl}/v1/auth/tokens/anonymous`,{method:"POST"});if(!l.ok)return null;let i=await l.json(),{access_token:n,refresh_token:c}=i;return!n||!c?null:(localStorage.setItem(oe,JSON.stringify(c)),n)})}async getAuthHeaders(){return this.jwtStrategy.getAuthHeaders()}readAuthHeaders(e){this.jwtStrategy.readAuthHeaders(e)}},a(S,"AssistantCloudAnonymousAuthStrategy"),S);var _,ct=(_=class extends Error{constructor(e){super(e),this.name="APIError"}},a(_,"CloudAPIError"),_),b,qe=(b=class{constructor(e){u(this,"_auth");u(this,"_baseUrl");if("authToken"in e)this._baseUrl=e.baseUrl,this._auth=new ge(e.authToken);else if("apiKey"in e)this._baseUrl="https://backend.assistant-api.com",this._auth=new Fe(e.apiKey,e.userId,e.workspaceId);else if("anonymous"in e)this._baseUrl=e.baseUrl,this._auth=new De(e.baseUrl);else throw new Error("Invalid configuration: Must provide authToken, apiKey, or anonymous configuration")}async initializeAuth(){return!!this._auth.getAuthHeaders()}async makeRawRequest(e,t={}){let o=await this._auth.getAuthHeaders();if(!o)throw new Error("Authorization failed");let s={...o,...t.headers,"Content-Type":"application/json"},l=new URLSearchParams;if(t.query)for(let[c,d]of Object.entries(t.query))d!==!1&&(d===!0?l.set(c,"true"):l.set(c,d.toString()));let i=new URL(`${this._baseUrl}/v1${e}`);i.search=l.toString();let n=await fetch(i,{method:t.method??"GET",headers:s,body:t.body?JSON.stringify(t.body):null});if(this._auth.readAuthHeaders(n.headers),!n.ok){let c=await n.text();try{let d=JSON.parse(c);throw new ct(d.message)}catch{throw new Error(`Request failed with status ${n.status}, ${c}`)}}return n}async makeRequest(e,t={}){return(await this.makeRawRequest(e,t)).json()}},a(b,"AssistantCloudAPI"),b);var R,Le=(R=class{constructor(e){this.cloud=e}async create(){return this.cloud.makeRequest("/auth/tokens",{method:"POST"})}},a(R,"AssistantCloudAuthTokens"),R);var g={toResponse(r,e){return new Response(g.toByteStream(r,e),{headers:e.headers??{}})},fromResponse(r,e){return g.fromByteStream(r.body,e)},toByteStream(r,e){return r.pipeThrough(e)},fromByteStream(r,e){return r.pipeThrough(e)}};var ne=a(function(){let r,e,t=new Promise((o,s)=>{r=o,e=s});if(!r||!e)throw new Error("Failed to create promise");return{promise:t,resolve:r,reject:e}},"promiseWithResolvers");var Ne=a(()=>{let r=[],e=!1,t,o,s=a(i=>{i.promise||(i.promise=i.reader.read().then(({done:n,value:c})=>{i.promise=void 0,n?(r.splice(r.indexOf(i),1),e&&r.length===0&&t.close()):t.enqueue(c),o?.resolve(),o=void 0}).catch(n=>{console.error(n),r.forEach(c=>{c.reader.cancel()}),r.length=0,t.error(n),o?.reject(n),o=void 0}))},"handlePull");return{readable:new ReadableStream({start(i){t=i},pull(){return o=ne(),r.forEach(i=>{s(i)}),o.promise},cancel(){r.forEach(i=>{i.reader.cancel()}),r.length=0}}),isSealed(){return e},seal(){e=!0,r.length===0&&t.close()},addStream(i){if(e)throw new Error("Cannot add streams after the run callback has settled.");let n={reader:i.getReader()};r.push(n),s(n)},enqueue(i){this.addStream(new ReadableStream({start(n){n.enqueue(i),n.close()}}))}}},"createMergeStream");var k,Ue=(k=class{constructor(e){u(this,"_controller");u(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},a(k,"TextStreamControllerImpl"),k),ye=a(r=>new ReadableStream({start(e){return r.start?.(new Ue(e))},pull(e){return r.pull?.(new Ue(e))},cancel(e){return r.cancel?.(e)}}),"createTextStream"),we=a(()=>{let r;return[ye({start(t){r=t}}),r]},"createTextStreamController");var P,$e=(P=class{constructor(e){u(this,"_isClosed",!1);u(this,"_mergeTask");u(this,"_argsTextController");this._controller=e;let t=ye({start:a(s=>{this._argsTextController=s},"start")}),o=!1;this._mergeTask=t.pipeTo(new WritableStream({write:a(s=>{switch(s.type){case"text-delta":o=!0,this._controller.enqueue(s);break;case"part-finish":o||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${s.type}`)}},"write")}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},a(P,"ToolCallStreamControllerImpl"),P),ut=a(r=>new ReadableStream({start(e){return r.start?.(new $e(e))},pull(e){return r.pull?.(new $e(e))},cancel(e){return r.cancel?.(e)}}),"createToolCallStream"),He=a(()=>{let r;return[ut({start(t){r=t}}),r]},"createToolCallStreamController");var I,ie=(I=class{constructor(){u(this,"value",-1)}up(){return++this.value}},a(I,"Counter"),I);var v,Je=(v=class extends TransformStream{constructor(e){super({transform(t,o){o.enqueue({...t,path:[e,...t.path]})}})}},a(v,"PathAppendEncoder"),v),E,er=(E=class extends TransformStream{constructor(e){super({transform(t,o){let{path:[s,...l]}=t;if(e!==s)throw new Error(`Path mismatch: expected ${e}, got ${s}`);o.enqueue({...t,path:l})}})}},a(E,"PathAppendDecoder"),E),M,je=(M=class extends TransformStream{constructor(e){let t=new ie,o=new Map;super({transform(s,l){s.type==="part-start"&&s.path.length===0&&o.set(t.up(),e.up());let[i,...n]=s.path;if(i===void 0){l.enqueue(s);return}let c=o.get(i);if(c===void 0)throw new Error("Path not found");l.enqueue({...s,path:[c,...n]})}})}},a(M,"PathMergeEncoder"),M);var O,Be=(O=class extends TransformStream{constructor(e,t,o){let[s,l]=ee(),i;super({start(n){return i=s.pipeTo(new WritableStream({write(c){n.enqueue(c)},abort(c){n.error(c)},close(){n.terminate()}})).catch(c=>{n.error(c)}),e.start?.(l)},transform(n){return e.transform?.(n,l)},async flush(){await e.flush?.(l),l.close(),await i}},t,o)}},a(O,"AssistantTransformStream"),O);var F,le=(F=class extends TransformStream{constructor(e){super();let t=e(super.readable);Object.defineProperty(this,"readable",{value:t,writable:!1})}},a(F,"PipeableTransformStream"),F);var p=(r=>(r.TextDelta="0",r.Data="2",r.Error="3",r.Annotation="8",r.ToolCall="9",r.ToolCallResult="a",r.StartToolCall="b",r.ToolCallArgsTextDelta="c",r.FinishMessage="d",r.FinishStep="e",r.StartStep="f",r.ReasoningDelta="g",r.Source="h",r.RedactedReasoning="i",r.ReasoningSignature="j",r.File="k",r.AuiUpdateStateOperations="aui-state",r.AuiTextDelta="aui-text-delta",r.AuiReasoningDelta="aui-reasoning-delta",r))(p||{});var D,We=(D=class extends TransformStream{constructor(){super({transform:a((e,t)=>{t.enqueue(`${e.type}:${JSON.stringify(e.value)}
|
|
5
|
+
`)},"transform")})}},a(D,"DataStreamChunkEncoder"),D),q,pt=(q=class extends TransformStream{constructor(){super({transform:a((e,t)=>{let o=e.indexOf(":");if(o===-1)throw new Error("Invalid stream part");t.enqueue({type:e.slice(0,o),value:JSON.parse(e.slice(o+1))})},"transform")})}},a(q,"DataStreamChunkDecoder"),q);var L,ze=(L=class extends TransformStream{constructor(){let e=[];super({transform(t,o){if(t.type==="part-start"){if(t.path.length!==0){o.error(new Error("Nested parts are not supported"));return}e.push(t.part),o.enqueue(t);return}if(t.type==="text-delta"||t.type==="result"||t.type==="part-finish"||t.type==="tool-call-args-text-finish"){if(t.path.length!==1){o.error(new Error(`${t.type} chunks must have a path of length 1`));return}let s=t.path[0];if(s<0||s>=e.length){o.error(new Error(`Invalid path index: ${s}`));return}let l=e[s];o.enqueue({...t,meta:l});return}o.enqueue(t)}})}},a(L,"AssistantMetaTransformStream"),L);var N,Te=(N=class extends le{constructor(){super(t=>{let o=new TransformStream({transform(s,l){let i=s.type;switch(i){case"part-start":{let n=s.part;if(n.type==="tool-call"){let{type:c,...d}=n;l.enqueue({type:p.StartToolCall,value:d})}if(n.type==="source"){let{type:c,...d}=n;l.enqueue({type:p.Source,value:d})}break}case"text-delta":{let n=s.meta;switch(n.type){case"text":{n.parentId?l.enqueue({type:p.AuiTextDelta,value:{textDelta:s.textDelta,parentId:n.parentId}}):l.enqueue({type:p.TextDelta,value:s.textDelta});break}case"reasoning":{n.parentId?l.enqueue({type:p.AuiReasoningDelta,value:{reasoningDelta:s.textDelta,parentId:n.parentId}}):l.enqueue({type:p.ReasoningDelta,value:s.textDelta});break}case"tool-call":{l.enqueue({type:p.ToolCallArgsTextDelta,value:{toolCallId:n.toolCallId,argsTextDelta:s.textDelta}});break}default:throw new Error(`Unsupported part type for text-delta: ${n.type}`)}break}case"result":{let n=s.meta;if(n.type!=="tool-call")throw new Error(`Result chunk on non-tool-call part not supported: ${n.type}`);l.enqueue({type:p.ToolCallResult,value:{toolCallId:n.toolCallId,result:s.result,artifact:s.artifact,...s.isError?{isError:s.isError}:{}}});break}case"step-start":{let{type:n,...c}=s;l.enqueue({type:p.StartStep,value:c});break}case"step-finish":{let{type:n,...c}=s;l.enqueue({type:p.FinishStep,value:c});break}case"message-finish":{let{type:n,...c}=s;l.enqueue({type:p.FinishMessage,value:c});break}case"error":{l.enqueue({type:p.Error,value:s.error});break}case"annotations":{l.enqueue({type:p.Annotation,value:s.annotations});break}case"data":{l.enqueue({type:p.Data,value:s.data});break}case"update-state":{l.enqueue({type:p.AuiUpdateStateOperations,value:s.operations});break}case"tool-call-args-text-finish":case"part-finish":break;default:{let n=i;throw new Error(`Unsupported chunk type: ${n}`)}}}});return t.pipeThrough(new ze).pipeThrough(o).pipeThrough(new We).pipeThrough(new TextEncoderStream)});u(this,"headers",new Headers({"Content-Type":"text/plain; charset=utf-8","x-vercel-ai-data-stream":"v1"}))}},a(N,"DataStreamEncoder"),N),yr=[p.StartToolCall,p.ToolCall,p.TextDelta,p.ReasoningDelta,p.Source,p.Error,p.FinishStep,p.FinishMessage,p.AuiTextDelta,p.AuiReasoningDelta];var Ge=a((r,e=21)=>(t=e)=>{let o="",s=t|0;for(;s--;)o+=r[Math.random()*r.length|0];return o},"customAlphabet");var Ke=Ge("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);var x,dt=(x=class{constructor(e){u(this,"_state");u(this,"_parentId");this._state=e||{merger:Ne(),contentCounter:new ie}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(e){this._state.closeSubscriber=e}_addPart(e,t){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:e,path:[]}),this._state.merger.addStream(t.pipeThrough(new Je(this._state.contentCounter.value)))}merge(e){this._state.merger.addStream(e.pipeThrough(new je(this._state.contentCounter)))}appendText(e){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(e)}addTextPart(){let[e,t]=we();return this._addPart({type:"text"},e),t}addReasoningPart(){let[e,t]=we();return this._addPart({type:"reasoning"},e),t}addToolCallPart(e){let t=typeof e=="string"?{toolName:e}:e,o=t.toolName,s=t.toolCallId??Ke(),[l,i]=He();return this._addPart({type:"tool-call",toolName:o,toolCallId:s,...this._parentId&&{parentId:this._parentId}},l),t.argsText!==void 0&&(i.argsText.append(t.argsText),i.argsText.close()),t.args!==void 0&&(i.argsText.append(JSON.stringify(t.args)),i.argsText.close()),t.response!==void 0&&i.setResponse(t.response),i}appendSource(e){this._addPart({...e,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}appendFile(e){this._addPart(e,new ReadableStream({start(t){t.enqueue({type:"part-finish",path:[]}),t.close()}}))}enqueue(e){this._state.merger.enqueue(e),e.type==="part-start"&&e.path.length===0&&this._state.contentCounter.up()}withParentId(e){let t=new x(this._state);return t._parentId=e,t}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}},a(x,"_AssistantStreamControllerImpl"),x);function Ve(r){let e=new dt;return a(async()=>{try{await r(e)}catch(o){throw e.__internal_isClosed||e.enqueue({type:"error",path:[],error:String(o)}),o}finally{e.__internal_isClosed||e.close()}},"runTask")(),e.__internal_getReadable()}a(Ve,"createAssistantStream");function ee(){let{resolve:r,promise:e}=ne(),t;return[Ve(s=>(t=s,t.__internal_subscribeToClose(r),e)),t]}a(ee,"createAssistantStreamController");var U,te=(U=class extends le{constructor(){super(e=>{let t=new Be({transform(o,s){s.appendText(o)}});return e.pipeThrough(new TextDecoderStream).pipeThrough(t)})}},a(U,"PlainTextDecoder"),U);var $,Qe=($=class{constructor(e){this.cloud=e}__internal_getAssistantOptions(e){return{api:this.cloud._baseUrl+"/v1/runs/stream",headers:a(async()=>{let t=await this.cloud._auth.getAuthHeaders();if(!t)throw new Error("Authorization failed");return{...t,Accept:"text/plain"}},"headers"),body:{assistant_id:e,response_format:"vercel-ai-data-stream/v1",thread_id:"unstable_todo"}}}async stream(e){let t=await this.cloud.makeRawRequest("/runs/stream",{method:"POST",headers:{Accept:"text/plain"},body:e});return g.fromResponse(t,new te)}},a($,"AssistantCloudRuns"),$);var H,Xe=(H=class{constructor(e){this.cloud=e}async list(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{query:t})}async create(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}/messages`,{method:"POST",body:t})}},a(H,"AssistantCloudThreadMessages"),H);var J,Ye=(J=class{constructor(e){u(this,"messages");this.cloud=e,this.messages=new Xe(e)}async list(e){return this.cloud.makeRequest("/threads",{query:e})}async create(e){return this.cloud.makeRequest("/threads",{method:"POST",body:e})}async update(e,t){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"PUT",body:t})}async delete(e){return this.cloud.makeRequest(`/threads/${encodeURIComponent(e)}`,{method:"DELETE"})}},a(J,"AssistantCloudThreads"),J);var j,Ze=(j=class{constructor(e){this.cloud=e}async pdfToImages(e){return this.cloud.makeRequest("/files/pdf-to-images",{method:"POST",body:e})}async generatePresignedUploadUrl(e){return this.cloud.makeRequest("/files/attachments/generate-presigned-upload-url",{method:"POST",body:e})}},a(j,"AssistantCloudFiles"),j);var B,xe=(B=class{constructor(e){u(this,"threads");u(this,"auth");u(this,"runs");u(this,"files");let t=new qe(e);this.threads=new Ye(t),this.auth={tokens:new Le(t)},this.runs=new Qe(t),this.files=new Ze(t)}},a(B,"AssistantCloud"),B);import{initLegitFs as xt}from"@legit-sdk/core";import Ct from"memfs";import{createContext as mt,useContext as ht,useEffect as ft,useMemo as gt,useState as Ce,useCallback as ce}from"react";import{jsx as Tt}from"react/jsx-runtime";var re="main",y="/.legit/branches",tt="/.legit/commits",et=a(r=>(r.startsWith("/")&&(r=r.slice(1)),`${y}/${re}/${r}`),"resolveThreadPath"),yt=a(r=>r instanceof Error?r:new Error(String(r??"Unknown error")),"normalizeError"),rt=mt(void 0);function wt({children:r}){let[e,t]=Ce(null),[o,s]=Ce(!0),[l,i]=Ce(null);ft(()=>{let m=!1,h=a(async()=>{try{let f=await w();m||(t(f),i(null),s(!1))}catch(f){if(!m){let ae=yt(f);t(null),i(ae),s(!1)}}},"load");return s(!0),i(null),h(),()=>{m=!0}},[]);let n=ce(async(m,h)=>{if(e){let f=et(m);await e.promises.writeFile(f,h)}},[e]),c=ce(async m=>{if(e){let h=await W(re);if(!h)return;let f=h.find(fe=>fe.oid===m),ae=h.find(fe=>fe.oid===f?.parentOids[0]);if(!f||!ae)return;let Pe=f?.parentOids[1],Ie=ae?.originBranchOid;return!Pe||!Ie?void 0:{newOid:Pe,oldOid:Ie}}},[e]),d=ce(async(m,h)=>{if(e)return await at(m,h)},[e]),T=ce(async m=>(e&&(console.log("rollback",m),await st(re,m)),await ue(re)),[e]),z=gt(()=>({legitFs:e,loading:o,error:l,saveData:n,getMessageDiff:c,getPastState:d,rollback:T,threadId:re,resolvePath:et}),[e,o,l,n]);return Tt(rt.Provider,{value:z,children:r})}a(wt,"LegitFsProvider");function Ae(){let r=ht(rt);if(r===void 0)throw new Error("useLegitFs must be used within a LegitFsProvider");return r}a(Ae,"useLegitFs");var pe=null;async function w(){return pe||(pe=xt(Ct,"/"),window&&(window.legitFs=await pe)),pe}a(w,"getLegitFs");async function ot(){let r=await w();try{return(await r.promises.readdir(y)).filter(t=>!t.startsWith("."))}catch(e){if(e.code==="ENOENT")return await r.promises.mkdir(y,{recursive:!0}),[];throw e}}a(ot,"listBranches");async function ue(r){try{return await(await w()).promises.readFile(`${y}/${r}/.legit/head`,"utf8")}catch(e){throw console.error("Error reading head from path:",r,e),e}}a(ue,"readHead");async function st(r,e){try{await(await w()).promises.writeFile(`${y}/${r}/.legit/operationHead`,e,"utf8")}catch(t){throw console.error("Error writing head to path:",r,t),t}}a(st,"writeOperationHead");async function nt(r,e){try{await(await w()).promises.writeFile(`${y}/${r}/.legit/operation`,e,"utf8")}catch(t){throw console.error("Error writing operation to path:",r,t),t}}a(nt,"writeOperation");async function W(r){try{let t=await(await w()).promises.readFile(`${y}/${r}/.legit/operationHistory`,"utf8");return t.length>0?JSON.parse(t):JSON.parse("[]")}catch(e){throw console.error("Error reading operation history from path:",r,e),e}}a(W,"readOperationHistory");async function at(r,e){try{e.startsWith("/")&&(e=e.slice(1));let t=await w(),o=`${tt}/${r.slice(0,2)}/${r.slice(2)}/${e}`;return await t.promises.readFile(o,"utf8")}catch(t){throw console.error("Error reading past state from path:",r,t),t}}a(at,"readPastState");var de=a(async r=>{let e=[];for(let t of r){let o,s;try{o=JSON.parse(t.message),s={id:t.oid,height:e.length,parent_id:t.parentOids[0]===t.parentOids[1]?null:t.parentOids[0],metadata:{custom:{depending_branch_commit_id:t.originBranchOid??null}},...o},e.unshift(s)}catch{console.log("Skipping operation with invalid JSON message:",t);continue}}return e},"createUIMessages");var Se=class Se{async list(e,t){let o=await W(e);return{messages:(await de(o)).map((i,n)=>({...i,height:n,created_at:new Date(i.created_at),updated_at:new Date(i.updated_at)}))}}async create(e,t){let o=`msg-${Date.now()}-${Math.random().toString(36).slice(2)}`,s={created_at:new Date,updated_at:new Date,format:t.format,content:t.content};return await nt(e,JSON.stringify(s)),{message_id:o}}};a(Se,"LegitThreadMessages");var me=Se;var _e=class _e{constructor(){u(this,"messages",new me)}async list(e){return{threads:(await ot()).map(o=>({id:o,title:o,last_message_at:new Date,metadata:{},external_id:null,project_id:"",created_at:new Date,updated_at:new Date,workspace_id:"local-workspace",is_archived:!1}))}}async create(e){return{thread_id:"main"}}async update(e,t){}async delete(e){}};a(_e,"LegitThreads");var he=_e;var Re=class Re extends xe{constructor(t){super(t);u(this,"runtime");u(this,"legitFs",null);this.legitFs=t.legitFs,this.threads=new he;let o=this.runs.stream;this.runs.stream=async s=>{if(!this.runtime)throw new Error("LegitLocal runtime not set");let n=this.runtime.thread.__internal_threadBinding?.getState?.()?.adapters?.chatModel?.options??{},c=new Headers;c.set("Content-Type","application/json");try{let d=await fetch(n.api??"/api/chat",{method:"POST",headers:c,credentials:n.credentials??"same-origin",body:JSON.stringify({messages:s.messages,system:s.system,tools:s.tools,runConfig:n.runConfig??{}})});if(!d.ok)throw new Error(`Request failed with status ${d.status}`);return g.fromResponse(d,new te)}catch(d){return console.error("LegitLocal stream failed, falling back to default handler.",d),o.call(this.runs,s)}}}};a(Re,"LegitLocal");var be=Re;import{ExportedMessageRepository as At}from"@assistant-ui/react";var St=a(r=>{if(r&&typeof r=="object"){let e=r,t=e.custom&&typeof e.custom=="object"?e.custom:{};return{...e,custom:t}}return{custom:{}}},"normalizeMetadata"),_t="aui/v0";function bt(r){if(r.format!==_t)return null;let e=r.content;if(!e||typeof e!="object")return null;let t=e.role;if(t!=="assistant"&&t!=="user"&&t!=="system")return null;let o=e.content??[],s=typeof o=="string"||Array.isArray(o)?o:[],l=e.createdAt instanceof Date?e.createdAt:e.createdAt?new Date(e.createdAt):new Date(r.created_at),i=St(r.metadata);return{...e,role:t,content:s,id:e.id??r.id,createdAt:l,metadata:i}}a(bt,"toThreadMessageLike");async function ke({threadId:r,threadApi:e}){console.log("sync initiated");let t=await W(r),s=(await de(t)).map(bt).filter(l=>l!==null);e?.reset?.(s),e.import(At.fromArray(s))}a(ke,"syncThreadFromLegitFs");var it=a(r=>{if(typeof r=="string")return r;if(r===void 0)return"";try{return JSON.stringify(r)}catch{return""}},"serializeStructuredData");var se=a(r=>r==null?null:typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:Array.isArray(r)?r.map(e=>se(e)):typeof r=="object"?Object.fromEntries(Object.entries(r).map(([e,t])=>[e,se(t)])):JSON.stringify(r),"toJsonValue"),Rt=a((r,e)=>e?typeof r=="string"?{type:"error-text",value:r}:{type:"error-json",value:se(r)}:typeof r=="string"?{type:"text",value:r}:{type:"json",value:se(r)},"buildToolResultOutput"),kt=a(r=>{switch(r.type){case"text":return{type:"text",text:typeof r.text=="string"?r.text:""};case"tool-call":return{type:"tool-call",toolCallId:typeof r.toolCallId=="string"?r.toolCallId:`unknown-${Date.now()}`,toolName:typeof r.toolName=="string"?r.toolName:"unknown",input:se(r.args??r.input??{})};default:return null}},"mapAssistantContentPart"),Pt=a(r=>r.type!=="tool-result"?null:{type:"tool-result",toolCallId:typeof r.toolCallId=="string"?r.toolCallId:`unknown-${Date.now()}`,toolName:typeof r.toolName=="string"?r.toolName:"unknown",output:Rt(r.result??r.output,!!r.isError)},"mapToolContentPart"),js=a(r=>r.map(e=>{let t=Array.isArray(e.content)?e.content:[];switch(e.role){case"system":return{role:"system",content:t.map(s=>s.type==="text"&&typeof s.text=="string"?s.text:"").join("")};case"user":return{role:"user",content:t.map(s=>{switch(s.type){case"text":return{type:"text",text:typeof s.text=="string"?s.text:""};default:return null}}).filter(Boolean)};case"assistant":return{role:"assistant",content:t.map(s=>kt(s)).filter(Boolean)};case"tool":{let o=t.map(s=>Pt(s)).filter(Boolean);return o.length>0?{role:"tool",content:o}:null}default:return null}}).filter(e=>e!==null),"convertMessagesToModelMessages");async function Bs(r){let[e,t]=ee();(async()=>{try{let s=null,l=new Map;for await(let i of r.fullStream)switch(i.type){case"text-start":s=t.addTextPart();break;case"text-delta":s||(s=t.addTextPart()),s.append(i.text);break;case"text-end":s?.close(),s=null;break;case"tool-input-start":{let n=i.id;if(!l.has(n)){let c=t.addToolCallPart({toolCallId:n,toolName:i.toolName});l.set(n,c)}break}case"tool-input-delta":{let n=i.id,c=l.get(n);c&&c.argsText.append(i.delta);break}case"tool-input-end":{let n=i.id,c=l.get(n);c&&c.argsText.close();break}case"tool-call":{let n=i.toolCallId;if(!l.get(n)){let d=t.addToolCallPart({toolCallId:n,toolName:i.toolName,args:i.input});l.set(n,d)}break}case"tool-result":{let n=i.toolCallId,c=l.get(n);c&&c.setResponse({result:it(i.output),isError:!1});break}case"tool-error":{let n=i.toolCallId,c=l.get(n);c&&c.setResponse({result:it(i.error),isError:!0});break}case"start-step":{let n=`msg-${Date.now()}-${Math.random().toString(36).slice(2)}`;t.enqueue({type:"step-start",path:[],messageId:n});break}case"finish-step":{let n=i.usage;t.enqueue({type:"step-finish",path:[],finishReason:i.finishReason,usage:{promptTokens:n.promptTokens??n.prompt?.tokens??0,completionTokens:n.completionTokens??n.completion?.tokens??0},isContinued:!1});break}case"finish":{let n=i.totalUsage;t.enqueue({type:"message-finish",path:[],finishReason:i.finishReason,usage:{promptTokens:n.promptTokens??n.prompt?.tokens??0,completionTokens:n.completionTokens??n.completion?.tokens??0}});break}case"error":{t.enqueue({type:"error",path:[],error:i.error instanceof Error?i.error.message:typeof i.error=="string"?i.error:"Unknown error"});break}case"start":case"abort":case"raw":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"source":case"file":break}s?.close(),l.forEach(i=>i.close()),t.close()}catch(s){t.enqueue({type:"error",path:[],error:s instanceof Error?s.message:typeof s=="string"?s:"Unknown error"}),t.close()}})();let o=new Te;return g.toResponse(e,o)}a(Bs,"streamTextToDataStreamResponse");import{useEffect as It}from"react";import{useAssistantApi as vt}from"@assistant-ui/react";var Et=100;function Ys(){let{legitFs:r,threadId:e}=Ae(),o=vt().thread();return It(()=>{if(!r||!e)return;let s=!1,l,i=null,n=a(()=>{s||(l=setTimeout(c,Et))},"scheduleNext"),c=a(async()=>{try{let d=await ue(e);if(s||d===i)return;let{isRunning:T,isLoading:z}=o.getState();if(T||z)return;setTimeout(async()=>{await ke({threadId:e,threadApi:o}),i=d},100)}catch(d){d.code!=="ENOENT"&&console.error("Failed to poll Legit head",d)}finally{n()}},"tick");return n(),()=>{s=!0,l!==void 0&&clearTimeout(l)}},[r,o,e]),null}a(Ys,"LegitFsHeadPoller");export{Ys as LegitFsHeadPoller,wt as LegitFsProvider,be as LegitLocal,js as convertMessagesToModelMessages,Bs as streamTextToDataStreamResponse,ke as syncThreadFromLegitFs,Ae as useLegitFs};
|
package/dist/server.d.ts
ADDED
package/dist/server.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// @legit-sdk/assistant-ui bundle (ESM)
|
|
2
|
+
// Generated by esbuild
|
|
3
|
+
|
|
4
|
+
var M=Object.defineProperty;var H=(t,e,r)=>e in t?M(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var l=(t,e)=>M(t,"name",{value:e,configurable:!0});var u=(t,e,r)=>H(t,typeof e!="symbol"?e+"":e,r);var I={toResponse(t,e){return new Response(I.toByteStream(t,e),{headers:e.headers??{}})},fromResponse(t,e){return I.fromByteStream(t.body,e)},toByteStream(t,e){return t.pipeThrough(e)},fromByteStream(t,e){return t.pipeThrough(e)}};var A=l(function(){let t,e,r=new Promise((n,a)=>{t=n,e=a});if(!t||!e)throw new Error("Failed to create promise");return{promise:r,resolve:t,reject:e}},"promiseWithResolvers");var k=l(()=>{let t=[],e=!1,r,n,a=l(s=>{s.promise||(s.promise=s.reader.read().then(({done:o,value:p})=>{s.promise=void 0,o?(t.splice(t.indexOf(s),1),e&&t.length===0&&r.close()):r.enqueue(p),n?.resolve(),n=void 0}).catch(o=>{console.error(o),t.forEach(p=>{p.reader.cancel()}),t.length=0,r.error(o),n?.reject(o),n=void 0}))},"handlePull");return{readable:new ReadableStream({start(s){r=s},pull(){return n=A(),t.forEach(s=>{a(s)}),n.promise},cancel(){t.forEach(s=>{s.reader.cancel()}),t.length=0}}),isSealed(){return e},seal(){e=!0,t.length===0&&r.close()},addStream(s){if(e)throw new Error("Cannot add streams after the run callback has settled.");let o={reader:s.getReader()};t.push(o),a(o)},enqueue(s){this.addStream(new ReadableStream({start(o){o.enqueue(s),o.close()}}))}}},"createMergeStream");var m,N=(m=class{constructor(e){u(this,"_controller");u(this,"_isClosed",!1);this._controller=e}append(e){return this._controller.enqueue({type:"text-delta",path:[],textDelta:e}),this}close(){this._isClosed||(this._isClosed=!0,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},l(m,"TextStreamControllerImpl"),m),P=l(t=>new ReadableStream({start(e){return t.start?.(new N(e))},pull(e){return t.pull?.(new N(e))},cancel(e){return t.cancel?.(e)}}),"createTextStream"),E=l(()=>{let t;return[P({start(r){t=r}}),t]},"createTextStreamController");var f,O=(f=class{constructor(e){u(this,"_isClosed",!1);u(this,"_mergeTask");u(this,"_argsTextController");this._controller=e;let r=P({start:l(a=>{this._argsTextController=a},"start")}),n=!1;this._mergeTask=r.pipeTo(new WritableStream({write:l(a=>{switch(a.type){case"text-delta":n=!0,this._controller.enqueue(a);break;case"part-finish":n||this._controller.enqueue({type:"text-delta",textDelta:"{}",path:[]}),this._controller.enqueue({type:"tool-call-args-text-finish",path:[]});break;default:throw new Error(`Unexpected chunk type: ${a.type}`)}},"write")}))}get argsText(){return this._argsTextController}async setResponse(e){this._argsTextController.close(),await Promise.resolve(),this._controller.enqueue({type:"result",path:[],...e.artifact!==void 0?{artifact:e.artifact}:{},result:e.result,isError:e.isError??!1})}async close(){this._isClosed||(this._isClosed=!0,this._argsTextController.close(),await this._mergeTask,this._controller.enqueue({type:"part-finish",path:[]}),this._controller.close())}},l(f,"ToolCallStreamControllerImpl"),f),z=l(t=>new ReadableStream({start(e){return t.start?.(new O(e))},pull(e){return t.pull?.(new O(e))},cancel(e){return t.cancel?.(e)}}),"createToolCallStream"),U=l(()=>{let t;return[z({start(r){t=r}}),t]},"createToolCallStreamController");var g,v=(g=class{constructor(){u(this,"value",-1)}up(){return++this.value}},l(g,"Counter"),g);var h,F=(h=class extends TransformStream{constructor(e){super({transform(r,n){n.enqueue({...r,path:[e,...r.path]})}})}},l(h,"PathAppendEncoder"),h),x,xe=(x=class extends TransformStream{constructor(e){super({transform(r,n){let{path:[a,...i]}=r;if(e!==a)throw new Error(`Path mismatch: expected ${e}, got ${a}`);n.enqueue({...r,path:i})}})}},l(x,"PathAppendDecoder"),x),y,j=(y=class extends TransformStream{constructor(e){let r=new v,n=new Map;super({transform(a,i){a.type==="part-start"&&a.path.length===0&&n.set(r.up(),e.up());let[s,...o]=a.path;if(s===void 0){i.enqueue(a);return}let p=n.get(s);if(p===void 0)throw new Error("Path not found");i.enqueue({...a,path:[p,...o]})}})}},l(y,"PathMergeEncoder"),y);var T,$=(T=class extends TransformStream{constructor(e){super();let r=e(super.readable);Object.defineProperty(this,"readable",{value:r,writable:!1})}},l(T,"PipeableTransformStream"),T);var c=(t=>(t.TextDelta="0",t.Data="2",t.Error="3",t.Annotation="8",t.ToolCall="9",t.ToolCallResult="a",t.StartToolCall="b",t.ToolCallArgsTextDelta="c",t.FinishMessage="d",t.FinishStep="e",t.StartStep="f",t.ReasoningDelta="g",t.Source="h",t.RedactedReasoning="i",t.ReasoningSignature="j",t.File="k",t.AuiUpdateStateOperations="aui-state",t.AuiTextDelta="aui-text-delta",t.AuiReasoningDelta="aui-reasoning-delta",t))(c||{});var C,J=(C=class extends TransformStream{constructor(){super({transform:l((e,r)=>{r.enqueue(`${e.type}:${JSON.stringify(e.value)}
|
|
5
|
+
`)},"transform")})}},l(C,"DataStreamChunkEncoder"),C),w,K=(w=class extends TransformStream{constructor(){super({transform:l((e,r)=>{let n=e.indexOf(":");if(n===-1)throw new Error("Invalid stream part");r.enqueue({type:e.slice(0,n),value:JSON.parse(e.slice(n+1))})},"transform")})}},l(w,"DataStreamChunkDecoder"),w);var b,B=(b=class extends TransformStream{constructor(){let e=[];super({transform(r,n){if(r.type==="part-start"){if(r.path.length!==0){n.error(new Error("Nested parts are not supported"));return}e.push(r.part),n.enqueue(r);return}if(r.type==="text-delta"||r.type==="result"||r.type==="part-finish"||r.type==="tool-call-args-text-finish"){if(r.path.length!==1){n.error(new Error(`${r.type} chunks must have a path of length 1`));return}let a=r.path[0];if(a<0||a>=e.length){n.error(new Error(`Invalid path index: ${a}`));return}let i=e[a];n.enqueue({...r,meta:i});return}n.enqueue(r)}})}},l(b,"AssistantMetaTransformStream"),b);var S,q=(S=class extends ${constructor(){super(r=>{let n=new TransformStream({transform(a,i){let s=a.type;switch(s){case"part-start":{let o=a.part;if(o.type==="tool-call"){let{type:p,..._}=o;i.enqueue({type:c.StartToolCall,value:_})}if(o.type==="source"){let{type:p,..._}=o;i.enqueue({type:c.Source,value:_})}break}case"text-delta":{let o=a.meta;switch(o.type){case"text":{o.parentId?i.enqueue({type:c.AuiTextDelta,value:{textDelta:a.textDelta,parentId:o.parentId}}):i.enqueue({type:c.TextDelta,value:a.textDelta});break}case"reasoning":{o.parentId?i.enqueue({type:c.AuiReasoningDelta,value:{reasoningDelta:a.textDelta,parentId:o.parentId}}):i.enqueue({type:c.ReasoningDelta,value:a.textDelta});break}case"tool-call":{i.enqueue({type:c.ToolCallArgsTextDelta,value:{toolCallId:o.toolCallId,argsTextDelta:a.textDelta}});break}default:throw new Error(`Unsupported part type for text-delta: ${o.type}`)}break}case"result":{let o=a.meta;if(o.type!=="tool-call")throw new Error(`Result chunk on non-tool-call part not supported: ${o.type}`);i.enqueue({type:c.ToolCallResult,value:{toolCallId:o.toolCallId,result:a.result,artifact:a.artifact,...a.isError?{isError:a.isError}:{}}});break}case"step-start":{let{type:o,...p}=a;i.enqueue({type:c.StartStep,value:p});break}case"step-finish":{let{type:o,...p}=a;i.enqueue({type:c.FinishStep,value:p});break}case"message-finish":{let{type:o,...p}=a;i.enqueue({type:c.FinishMessage,value:p});break}case"error":{i.enqueue({type:c.Error,value:a.error});break}case"annotations":{i.enqueue({type:c.Annotation,value:a.annotations});break}case"data":{i.enqueue({type:c.Data,value:a.data});break}case"update-state":{i.enqueue({type:c.AuiUpdateStateOperations,value:a.operations});break}case"tool-call-args-text-finish":case"part-finish":break;default:{let o=s;throw new Error(`Unsupported chunk type: ${o}`)}}}});return r.pipeThrough(new B).pipeThrough(n).pipeThrough(new J).pipeThrough(new TextEncoderStream)});u(this,"headers",new Headers({"Content-Type":"text/plain; charset=utf-8","x-vercel-ai-data-stream":"v1"}))}},l(S,"DataStreamEncoder"),S),qe=[c.StartToolCall,c.ToolCall,c.TextDelta,c.ReasoningDelta,c.Source,c.Error,c.FinishStep,c.FinishMessage,c.AuiTextDelta,c.AuiReasoningDelta];var L=l((t,e=21)=>(r=e)=>{let n="",a=r|0;for(;a--;)n+=t[Math.random()*t.length|0];return n},"customAlphabet");var W=L("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",7);var d,Q=(d=class{constructor(e){u(this,"_state");u(this,"_parentId");this._state=e||{merger:k(),contentCounter:new v}}get __internal_isClosed(){return this._state.merger.isSealed()}__internal_getReadable(){return this._state.merger.readable}__internal_subscribeToClose(e){this._state.closeSubscriber=e}_addPart(e,r){this._state.append&&(this._state.append.controller.close(),this._state.append=void 0),this.enqueue({type:"part-start",part:e,path:[]}),this._state.merger.addStream(r.pipeThrough(new F(this._state.contentCounter.value)))}merge(e){this._state.merger.addStream(e.pipeThrough(new j(this._state.contentCounter)))}appendText(e){this._state.append?.kind!=="text"&&(this._state.append={kind:"text",controller:this.addTextPart()}),this._state.append.controller.append(e)}appendReasoning(e){this._state.append?.kind!=="reasoning"&&(this._state.append={kind:"reasoning",controller:this.addReasoningPart()}),this._state.append.controller.append(e)}addTextPart(){let[e,r]=E();return this._addPart({type:"text"},e),r}addReasoningPart(){let[e,r]=E();return this._addPart({type:"reasoning"},e),r}addToolCallPart(e){let r=typeof e=="string"?{toolName:e}:e,n=r.toolName,a=r.toolCallId??W(),[i,s]=U();return this._addPart({type:"tool-call",toolName:n,toolCallId:a,...this._parentId&&{parentId:this._parentId}},i),r.argsText!==void 0&&(s.argsText.append(r.argsText),s.argsText.close()),r.args!==void 0&&(s.argsText.append(JSON.stringify(r.args)),s.argsText.close()),r.response!==void 0&&s.setResponse(r.response),s}appendSource(e){this._addPart({...e,...this._parentId&&{parentId:this._parentId}},new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}appendFile(e){this._addPart(e,new ReadableStream({start(r){r.enqueue({type:"part-finish",path:[]}),r.close()}}))}enqueue(e){this._state.merger.enqueue(e),e.type==="part-start"&&e.path.length===0&&this._state.contentCounter.up()}withParentId(e){let r=new d(this._state);return r._parentId=e,r}close(){this._state.append?.controller?.close(),this._state.merger.seal(),this._state.closeSubscriber?.()}},l(d,"_AssistantStreamControllerImpl"),d);function V(t){let e=new Q;return l(async()=>{try{await t(e)}catch(n){throw e.__internal_isClosed||e.enqueue({type:"error",path:[],error:String(n)}),n}finally{e.__internal_isClosed||e.close()}},"runTask")(),e.__internal_getReadable()}l(V,"createAssistantStream");function D(){let{resolve:t,promise:e}=A(),r;return[V(a=>(r=a,r.__internal_subscribeToClose(t),e)),r]}l(D,"createAssistantStreamController");var G=l(t=>{if(typeof t=="string")return t;if(t===void 0)return"";try{return JSON.stringify(t)}catch{return""}},"serializeStructuredData");var R=l(t=>t==null?null:typeof t=="string"||typeof t=="number"||typeof t=="boolean"?t:Array.isArray(t)?t.map(e=>R(e)):typeof t=="object"?Object.fromEntries(Object.entries(t).map(([e,r])=>[e,R(r)])):JSON.stringify(t),"toJsonValue"),X=l((t,e)=>e?typeof t=="string"?{type:"error-text",value:t}:{type:"error-json",value:R(t)}:typeof t=="string"?{type:"text",value:t}:{type:"json",value:R(t)},"buildToolResultOutput"),Y=l(t=>{switch(t.type){case"text":return{type:"text",text:typeof t.text=="string"?t.text:""};case"tool-call":return{type:"tool-call",toolCallId:typeof t.toolCallId=="string"?t.toolCallId:`unknown-${Date.now()}`,toolName:typeof t.toolName=="string"?t.toolName:"unknown",input:R(t.args??t.input??{})};default:return null}},"mapAssistantContentPart"),Z=l(t=>t.type!=="tool-result"?null:{type:"tool-result",toolCallId:typeof t.toolCallId=="string"?t.toolCallId:`unknown-${Date.now()}`,toolName:typeof t.toolName=="string"?t.toolName:"unknown",output:X(t.result??t.output,!!t.isError)},"mapToolContentPart"),ee=l(t=>t.map(e=>{let r=Array.isArray(e.content)?e.content:[];switch(e.role){case"system":return{role:"system",content:r.map(a=>a.type==="text"&&typeof a.text=="string"?a.text:"").join("")};case"user":return{role:"user",content:r.map(a=>{switch(a.type){case"text":return{type:"text",text:typeof a.text=="string"?a.text:""};default:return null}}).filter(Boolean)};case"assistant":return{role:"assistant",content:r.map(a=>Y(a)).filter(Boolean)};case"tool":{let n=r.map(a=>Z(a)).filter(Boolean);return n.length>0?{role:"tool",content:n}:null}default:return null}}).filter(e=>e!==null),"convertMessagesToModelMessages");async function te(t){let[e,r]=D();(async()=>{try{let a=null,i=new Map;for await(let s of t.fullStream)switch(s.type){case"text-start":a=r.addTextPart();break;case"text-delta":a||(a=r.addTextPart()),a.append(s.text);break;case"text-end":a?.close(),a=null;break;case"tool-input-start":{let o=s.id;if(!i.has(o)){let p=r.addToolCallPart({toolCallId:o,toolName:s.toolName});i.set(o,p)}break}case"tool-input-delta":{let o=s.id,p=i.get(o);p&&p.argsText.append(s.delta);break}case"tool-input-end":{let o=s.id,p=i.get(o);p&&p.argsText.close();break}case"tool-call":{let o=s.toolCallId;if(!i.get(o)){let _=r.addToolCallPart({toolCallId:o,toolName:s.toolName,args:s.input});i.set(o,_)}break}case"tool-result":{let o=s.toolCallId,p=i.get(o);p&&p.setResponse({result:G(s.output),isError:!1});break}case"tool-error":{let o=s.toolCallId,p=i.get(o);p&&p.setResponse({result:G(s.error),isError:!0});break}case"start-step":{let o=`msg-${Date.now()}-${Math.random().toString(36).slice(2)}`;r.enqueue({type:"step-start",path:[],messageId:o});break}case"finish-step":{let o=s.usage;r.enqueue({type:"step-finish",path:[],finishReason:s.finishReason,usage:{promptTokens:o.promptTokens??o.prompt?.tokens??0,completionTokens:o.completionTokens??o.completion?.tokens??0},isContinued:!1});break}case"finish":{let o=s.totalUsage;r.enqueue({type:"message-finish",path:[],finishReason:s.finishReason,usage:{promptTokens:o.promptTokens??o.prompt?.tokens??0,completionTokens:o.completionTokens??o.completion?.tokens??0}});break}case"error":{r.enqueue({type:"error",path:[],error:s.error instanceof Error?s.error.message:typeof s.error=="string"?s.error:"Unknown error"});break}case"start":case"abort":case"raw":case"reasoning-start":case"reasoning-delta":case"reasoning-end":case"source":case"file":break}a?.close(),i.forEach(s=>s.close()),r.close()}catch(a){r.enqueue({type:"error",path:[],error:a instanceof Error?a.message:typeof a=="string"?a:"Unknown error"}),r.close()}})();let n=new q;return I.toResponse(e,n)}l(te,"streamTextToDataStreamResponse");export{ee as convertMessagesToModelMessages,te as streamTextToDataStreamResponse};
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@legit-sdk/assistant-ui",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Legit integration for Assistant UI",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./server": {
|
|
16
|
+
"types": "./dist/server.d.ts",
|
|
17
|
+
"import": "./dist/server.js",
|
|
18
|
+
"require": "./dist/server.js"
|
|
19
|
+
}
|
|
20
|
+
},
|
|
21
|
+
"keywords": [],
|
|
22
|
+
"author": "",
|
|
23
|
+
"license": "PolyForm Noncommercial License 1.0.0",
|
|
24
|
+
"files": [
|
|
25
|
+
"dist/index.js",
|
|
26
|
+
"dist/index.d.ts",
|
|
27
|
+
"dist/server.js",
|
|
28
|
+
"dist/server.d.ts"
|
|
29
|
+
],
|
|
30
|
+
"peerDependencies": {
|
|
31
|
+
"react": ">=18",
|
|
32
|
+
"assistant-cloud": "0.x",
|
|
33
|
+
"assistant-stream": "0.x",
|
|
34
|
+
"@assistant-ui/react": "0.x"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@types/react": "^19.2.2",
|
|
38
|
+
"@types/react-dom": "^19.2.2",
|
|
39
|
+
"esbuild": "^0.24.0",
|
|
40
|
+
"happy-dom": "^14.12.3",
|
|
41
|
+
"memfs": "^4.14.0",
|
|
42
|
+
"rollup": "^4.24.0",
|
|
43
|
+
"rollup-plugin-dts": "^6.1.1",
|
|
44
|
+
"typescript": "^5.9.3",
|
|
45
|
+
"vitest": "^3.1.1"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"ai": "^5.0.59",
|
|
49
|
+
"@legit-sdk/core": "0.1.10"
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public"
|
|
53
|
+
},
|
|
54
|
+
"scripts": {
|
|
55
|
+
"test": "vitest",
|
|
56
|
+
"test:watch": "vitest --watch",
|
|
57
|
+
"build": "tsc && rollup -c rollup.dts.config.js && node esbuild.config.js"
|
|
58
|
+
}
|
|
59
|
+
}
|