@introspection-sdk/introspection-browser 0.5.1 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/README.md +87 -0
- package/dist/api/client.d.ts +59 -0
- package/dist/api/client.d.ts.map +1 -0
- package/dist/api/client.js +82 -0
- package/dist/api/client.js.map +1 -0
- package/dist/api/conversations.d.ts +84 -0
- package/dist/api/conversations.d.ts.map +1 -0
- package/dist/api/conversations.js +172 -0
- package/dist/api/conversations.js.map +1 -0
- package/dist/api/files.d.ts +61 -0
- package/dist/api/files.d.ts.map +1 -0
- package/dist/api/files.js +145 -0
- package/dist/api/files.js.map +1 -0
- package/dist/api/http.d.ts +36 -0
- package/dist/api/http.d.ts.map +1 -0
- package/dist/api/http.js +34 -0
- package/dist/api/http.js.map +1 -0
- package/dist/api/index.d.ts +38 -0
- package/dist/api/index.d.ts.map +1 -0
- package/dist/api/index.js +37 -0
- package/dist/api/index.js.map +1 -0
- package/dist/api/sse.d.ts +7 -0
- package/dist/api/sse.d.ts.map +1 -0
- package/dist/api/sse.js +7 -0
- package/dist/api/sse.js.map +1 -0
- package/dist/api/tasks.d.ts +83 -0
- package/dist/api/tasks.d.ts.map +1 -0
- package/dist/api/tasks.js +146 -0
- package/dist/api/tasks.js.map +1 -0
- package/package.json +11 -6
- package/src/api/client.ts +106 -0
- package/src/api/conversations.ts +214 -0
- package/src/api/files.ts +196 -0
- package/src/api/http.ts +55 -0
- package/src/api/index.ts +93 -0
- package/src/api/sse.ts +6 -0
- package/src/api/tasks.ts +208 -0
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-side Introspection API client.
|
|
3
|
+
*
|
|
4
|
+
* Lets a single-page app create and stream Introspection tasks directly
|
|
5
|
+
* from the browser, with no API key in JavaScript. The auth boundary:
|
|
6
|
+
*
|
|
7
|
+
* 1. The SPA's own backend ("broker") mints an Introspection access
|
|
8
|
+
* token — via RFC 8693 token-exchange of the partner IdP token, a
|
|
9
|
+
* PKCE `authorization_code`, or `client_credentials`. The IdP
|
|
10
|
+
* secret never leaves the backend. The SPA fetches that token
|
|
11
|
+
* through the `getToken` callback.
|
|
12
|
+
* 2. `connect()` redeems the token at the DP `POST /v1/oauth/exchange`
|
|
13
|
+
* for the HttpOnly `intro_dp_session` cookie.
|
|
14
|
+
* 3. Every subsequent call rides that cookie (`credentials: "include"`)
|
|
15
|
+
* — `client.tasks.start(...)`, `.get(...)`, run streaming, etc.
|
|
16
|
+
*
|
|
17
|
+
* When the session cookie expires, an in-flight request gets a 401, and
|
|
18
|
+
* the client transparently re-runs `getToken` + the DP exchange once
|
|
19
|
+
* before retrying.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { BrowserHttpClient, stripTrailingSlash, toApiError } from "./http.js";
|
|
23
|
+
import { TasksClient } from "./tasks.js";
|
|
24
|
+
import { FilesClient } from "./files.js";
|
|
25
|
+
import { ConversationsClient } from "./conversations.js";
|
|
26
|
+
|
|
27
|
+
export interface IntrospectionApiClientOptions {
|
|
28
|
+
/** Data Plane REST base URL (e.g. `https://dp.us.introspection.dev`). */
|
|
29
|
+
dpUrl: string;
|
|
30
|
+
/** Project the session is scoped to. */
|
|
31
|
+
projectId: string;
|
|
32
|
+
/**
|
|
33
|
+
* Returns a fresh Introspection access token from the app's broker
|
|
34
|
+
* (its own backend). Called on `connect()` and again whenever the DP
|
|
35
|
+
* session cookie needs re-minting after a 401.
|
|
36
|
+
*/
|
|
37
|
+
getToken: () => string | Promise<string>;
|
|
38
|
+
/** Custom `fetch` (for tests or non-standard runtimes). */
|
|
39
|
+
fetch?: typeof fetch;
|
|
40
|
+
/** Extra headers merged into every DP request. */
|
|
41
|
+
additionalHeaders?: Record<string, string>;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export class IntrospectionApiClient {
|
|
45
|
+
/** `/v1/tasks` operations bound to the DP session cookie. */
|
|
46
|
+
readonly tasks: TasksClient;
|
|
47
|
+
/** `/v1/files` operations bound to the DP session cookie. */
|
|
48
|
+
readonly files: FilesClient;
|
|
49
|
+
/** Read-only `/v1/conversations` projection bound to the session cookie. */
|
|
50
|
+
readonly conversations: ConversationsClient;
|
|
51
|
+
|
|
52
|
+
private readonly fetchImpl: typeof fetch;
|
|
53
|
+
|
|
54
|
+
constructor(private readonly opts: IntrospectionApiClientOptions) {
|
|
55
|
+
this.fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
56
|
+
if (!this.fetchImpl) {
|
|
57
|
+
throw new Error(
|
|
58
|
+
"global fetch is unavailable; pass `fetch` or run in a modern browser",
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
const http = new BrowserHttpClient({
|
|
62
|
+
apiUrl: opts.dpUrl,
|
|
63
|
+
additionalHeaders: opts.additionalHeaders,
|
|
64
|
+
fetch: opts.fetch,
|
|
65
|
+
onUnauthorized: () => this.reexchange(),
|
|
66
|
+
});
|
|
67
|
+
this.tasks = new TasksClient(http);
|
|
68
|
+
this.files = new FilesClient(http);
|
|
69
|
+
this.conversations = new ConversationsClient(http);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Mint a token via `getToken` and redeem it at the DP for the
|
|
74
|
+
* `intro_dp_session` cookie. Call once before issuing task requests.
|
|
75
|
+
*/
|
|
76
|
+
async connect(): Promise<void> {
|
|
77
|
+
await this.exchange();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
private async exchange(): Promise<void> {
|
|
81
|
+
const token = await this.opts.getToken();
|
|
82
|
+
const res = await this.fetchImpl(
|
|
83
|
+
`${stripTrailingSlash(this.opts.dpUrl)}/v1/oauth/exchange`,
|
|
84
|
+
{
|
|
85
|
+
method: "POST",
|
|
86
|
+
headers: {
|
|
87
|
+
"Content-Type": "application/json",
|
|
88
|
+
...(this.opts.additionalHeaders ?? {}),
|
|
89
|
+
},
|
|
90
|
+
body: JSON.stringify({ token, project_id: this.opts.projectId }),
|
|
91
|
+
credentials: "include",
|
|
92
|
+
},
|
|
93
|
+
);
|
|
94
|
+
if (!res.ok) throw await toApiError(res);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 401 recovery: re-exchange, reporting success so the call can retry. */
|
|
98
|
+
private async reexchange(): Promise<boolean> {
|
|
99
|
+
try {
|
|
100
|
+
await this.exchange();
|
|
101
|
+
return true;
|
|
102
|
+
} catch {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cookie-authenticated, read-only Conversations client for the browser
|
|
3
|
+
* (`/v1/conversations`).
|
|
4
|
+
*
|
|
5
|
+
* Mirrors the Node SDK's runner-bound `ConversationsApi`, but rides the
|
|
6
|
+
* DP `intro_dp_session` cookie via {@link BrowserHttpClient} instead of a
|
|
7
|
+
* bearer token — so a single-page app reads conversation history with the
|
|
8
|
+
* same identity session it uses for tasks and files. Conversations are a
|
|
9
|
+
* projection over the immutable telemetry store: list summaries, walk a
|
|
10
|
+
* conversation's items, or `retrieve()` the resolved state of one turn.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type {
|
|
14
|
+
ConversationItem,
|
|
15
|
+
ConversationItemInclude,
|
|
16
|
+
ConversationItemList,
|
|
17
|
+
ConversationItemListParams,
|
|
18
|
+
ConversationListParams,
|
|
19
|
+
ConversationResponse,
|
|
20
|
+
ConversationSummary,
|
|
21
|
+
MessagePart,
|
|
22
|
+
Paginated,
|
|
23
|
+
ToolCallResponsePart,
|
|
24
|
+
} from "@introspection-sdk/types";
|
|
25
|
+
import { Paginator, cursorPaginate } from "@introspection-sdk/http";
|
|
26
|
+
import { BrowserHttpClient } from "./http.js";
|
|
27
|
+
|
|
28
|
+
/** Includes requested when building a {@link ConversationResponse}. */
|
|
29
|
+
const RESPONSE_INCLUDES: ConversationItemInclude[] = [
|
|
30
|
+
"gen_ai.input.messages",
|
|
31
|
+
"gen_ai.system_instructions",
|
|
32
|
+
"gen_ai.tool.definitions",
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Items of a conversation (`/v1/conversations/{id}/items`). Read-only.
|
|
37
|
+
*
|
|
38
|
+
* Paging is OpenAI-style underneath: the envelope has NO `next` token —
|
|
39
|
+
* `list()` drives `after` = the previous page's `last_id` while
|
|
40
|
+
* `has_more` is true.
|
|
41
|
+
*/
|
|
42
|
+
export class ConversationItemsClient {
|
|
43
|
+
constructor(private readonly http: BrowserHttpClient) {}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* List items of a conversation. `await` the result for the first page
|
|
47
|
+
* (an OpenAI-style {@link ConversationItemList} envelope), or
|
|
48
|
+
* `for await` it to stream every item across pages (fetched lazily —
|
|
49
|
+
* `limit` sets the page size, `after` the starting cursor; stop early to
|
|
50
|
+
* stop fetching). Pass `order: "asc"` to walk the transcript from the
|
|
51
|
+
* start.
|
|
52
|
+
*
|
|
53
|
+
* Items carry the turn-local delta in `input_messages` — only the
|
|
54
|
+
* messages new to that turn. Use `get()` for the full input history.
|
|
55
|
+
*/
|
|
56
|
+
list(
|
|
57
|
+
conversationId: string,
|
|
58
|
+
params?: ConversationItemListParams,
|
|
59
|
+
): Paginator<ConversationItem, ConversationItemList> {
|
|
60
|
+
return new Paginator(
|
|
61
|
+
{
|
|
62
|
+
fetch: (after) =>
|
|
63
|
+
this.http.request<ConversationItemList>({
|
|
64
|
+
method: "GET",
|
|
65
|
+
path: `/v1/conversations/${encodeURIComponent(conversationId)}/items`,
|
|
66
|
+
query: { ...params, after } as Record<string, unknown>,
|
|
67
|
+
}),
|
|
68
|
+
items: (page) => page.data,
|
|
69
|
+
next: (page) =>
|
|
70
|
+
page.has_more && page.last_id !== null ? page.last_id : undefined,
|
|
71
|
+
},
|
|
72
|
+
params?.after,
|
|
73
|
+
);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Fetch a single conversation item. Unlike the list route, the
|
|
78
|
+
* detail's `input_messages` is the FULL input history for that span.
|
|
79
|
+
*/
|
|
80
|
+
get(
|
|
81
|
+
conversationId: string,
|
|
82
|
+
itemId: string,
|
|
83
|
+
params?: { include?: ConversationItemInclude[] },
|
|
84
|
+
): Promise<ConversationItem> {
|
|
85
|
+
return this.http.request<ConversationItem>({
|
|
86
|
+
method: "GET",
|
|
87
|
+
path: `/v1/conversations/${encodeURIComponent(conversationId)}/items/${encodeURIComponent(itemId)}`,
|
|
88
|
+
query: params as Record<string, unknown> | undefined,
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* Read-only Conversations client (`/v1/conversations`).
|
|
95
|
+
*
|
|
96
|
+
* Both `list()` and `items.list()` are auto-paging, but they drive
|
|
97
|
+
* different wire protocols underneath: `list()` walks the standard
|
|
98
|
+
* Introspection cursor envelope's opaque `next` token, while
|
|
99
|
+
* `items.list()` walks an OpenAI-style envelope via `after` = the
|
|
100
|
+
* previous page's `last_id` while `has_more` is true.
|
|
101
|
+
*/
|
|
102
|
+
export class ConversationsClient {
|
|
103
|
+
/** Items of a conversation — `conversations.items.list(...)` etc. */
|
|
104
|
+
readonly items: ConversationItemsClient;
|
|
105
|
+
|
|
106
|
+
constructor(private readonly http: BrowserHttpClient) {
|
|
107
|
+
this.items = new ConversationItemsClient(http);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* List conversation summaries matching `params`. `await` the result for
|
|
112
|
+
* the first page, or `for await` it to stream every summary across
|
|
113
|
+
* pages (fetched lazily — `limit` sets the page size, `next` the
|
|
114
|
+
* starting cursor; stop early to stop fetching).
|
|
115
|
+
*/
|
|
116
|
+
list(params?: ConversationListParams): Paginator<ConversationSummary> {
|
|
117
|
+
return cursorPaginate(
|
|
118
|
+
(next) =>
|
|
119
|
+
this.http.request<Paginated<ConversationSummary>>({
|
|
120
|
+
method: "GET",
|
|
121
|
+
path: "/v1/conversations",
|
|
122
|
+
query: { ...params, next } as Record<string, unknown>,
|
|
123
|
+
}),
|
|
124
|
+
params?.next,
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Responses-API-style retrieve: load the state of a conversation as of
|
|
130
|
+
* one item — the full input history, output, system instructions, and
|
|
131
|
+
* tool definitions of that turn.
|
|
132
|
+
*
|
|
133
|
+
* When `itemId` is omitted, the latest LLM turn is used: the first
|
|
134
|
+
* item (in descending order) whose `node_type` is `"assistant"` or
|
|
135
|
+
* whose `operation_name` is `"chat"`, falling back to the first item
|
|
136
|
+
* with a non-null `output_message`. Returns `null` when the
|
|
137
|
+
* conversation has no items.
|
|
138
|
+
*
|
|
139
|
+
* For the full per-turn transcript instead, iterate
|
|
140
|
+
* `items.list(conversationId, { order: "asc" })`.
|
|
141
|
+
*/
|
|
142
|
+
async retrieve(
|
|
143
|
+
conversationId: string,
|
|
144
|
+
itemId?: string,
|
|
145
|
+
): Promise<ConversationResponse | null> {
|
|
146
|
+
const targetId = itemId ?? (await this.findLatestTurnId(conversationId));
|
|
147
|
+
if (targetId === null) return null;
|
|
148
|
+
|
|
149
|
+
const detail = await this.items.get(conversationId, targetId, {
|
|
150
|
+
include: RESPONSE_INCLUDES,
|
|
151
|
+
});
|
|
152
|
+
const outputMessages =
|
|
153
|
+
detail.gen_ai_output_messages ??
|
|
154
|
+
(detail.output_message ? [detail.output_message] : []);
|
|
155
|
+
return {
|
|
156
|
+
conversation_id: conversationId,
|
|
157
|
+
response_id: detail.response_id ?? null,
|
|
158
|
+
item_id: detail.id,
|
|
159
|
+
created_at: detail.created_at,
|
|
160
|
+
model:
|
|
161
|
+
detail.model_name ??
|
|
162
|
+
detail.response_model ??
|
|
163
|
+
detail.request_model ??
|
|
164
|
+
null,
|
|
165
|
+
provider_name: detail.provider_name ?? null,
|
|
166
|
+
// The single-item route returns the FULL input history here.
|
|
167
|
+
input_messages: normalizeMessages(detail.input_messages),
|
|
168
|
+
output_messages: normalizeMessages(outputMessages),
|
|
169
|
+
system_instructions: detail.system_instructions ?? null,
|
|
170
|
+
tool_definitions: detail.tool_definitions ?? null,
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Scan items in descending order for the most recent LLM turn. */
|
|
175
|
+
private async findLatestTurnId(
|
|
176
|
+
conversationId: string,
|
|
177
|
+
): Promise<string | null> {
|
|
178
|
+
let fallback: ConversationItem | null = null;
|
|
179
|
+
for await (const item of this.items.list(conversationId, {
|
|
180
|
+
order: "desc",
|
|
181
|
+
})) {
|
|
182
|
+
if (item.node_type === "assistant" || item.operation_name === "chat") {
|
|
183
|
+
return item.id;
|
|
184
|
+
}
|
|
185
|
+
if (fallback === null && item.output_message != null) fallback = item;
|
|
186
|
+
}
|
|
187
|
+
return fallback?.id ?? null;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Defensive normalization for {@link ConversationsClient.retrieve} only:
|
|
193
|
+
* older DP deployments emitted `tool_call_response` parts with a legacy
|
|
194
|
+
* `result` key instead of the semconv `response` key. Map it across so
|
|
195
|
+
* replayed history is always semconv-shaped.
|
|
196
|
+
*/
|
|
197
|
+
function normalizeMessages<T extends { parts: MessagePart[] }>(
|
|
198
|
+
messages: T[],
|
|
199
|
+
): T[] {
|
|
200
|
+
return messages.map((message) => ({
|
|
201
|
+
...message,
|
|
202
|
+
parts: message.parts.map(normalizePart),
|
|
203
|
+
}));
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function normalizePart(part: MessagePart): MessagePart {
|
|
207
|
+
if (part.type !== "tool_call_response") return part;
|
|
208
|
+
const legacy = part as ToolCallResponsePart & { result?: unknown };
|
|
209
|
+
if (legacy.response !== undefined || legacy.result === undefined) {
|
|
210
|
+
return part;
|
|
211
|
+
}
|
|
212
|
+
const { result, ...rest } = legacy;
|
|
213
|
+
return { ...rest, response: result };
|
|
214
|
+
}
|
package/src/api/files.ts
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Cookie-authenticated Files client for the browser (`/v1/files`).
|
|
3
|
+
*
|
|
4
|
+
* Mirrors the Node SDK's runner-bound `FilesApi`, but rides the DP
|
|
5
|
+
* `intro_dp_session` cookie via {@link BrowserHttpClient} instead of a
|
|
6
|
+
* bearer token — so a single-page app reads and writes files with the
|
|
7
|
+
* same identity session it uses for tasks and conversations. The DP
|
|
8
|
+
* derives the owning `identity_key` from the session JWT; per-identity
|
|
9
|
+
* file visibility is enforced server-side.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import type {
|
|
13
|
+
File as FileResource,
|
|
14
|
+
FileCreateOptions,
|
|
15
|
+
FileCreateTextParams,
|
|
16
|
+
FileListParams,
|
|
17
|
+
FileType,
|
|
18
|
+
FileUpdateParams,
|
|
19
|
+
ListParams,
|
|
20
|
+
Paginated,
|
|
21
|
+
} from "@introspection-sdk/types";
|
|
22
|
+
import { Paginator, cursorPaginate } from "@introspection-sdk/http";
|
|
23
|
+
import { BrowserHttpClient } from "./http.js";
|
|
24
|
+
|
|
25
|
+
export type FileUploadBody =
|
|
26
|
+
| { file: Blob; name?: string; file_type?: FileType }
|
|
27
|
+
| {
|
|
28
|
+
file: Uint8Array;
|
|
29
|
+
name: string;
|
|
30
|
+
file_type?: FileType;
|
|
31
|
+
contentType?: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
/** Versions of a file (`/v1/files/{id}/versions`). */
|
|
35
|
+
export class FileVersionsClient {
|
|
36
|
+
constructor(private readonly http: BrowserHttpClient) {}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* List versions of a file. `await` the result for the first page, or
|
|
40
|
+
* `for await` it to stream every version across pages (fetched lazily;
|
|
41
|
+
* stop early to stop fetching).
|
|
42
|
+
*/
|
|
43
|
+
list(fileId: string, params?: ListParams): Paginator<FileResource> {
|
|
44
|
+
return cursorPaginate(
|
|
45
|
+
(next) =>
|
|
46
|
+
this.http.request<Paginated<FileResource>>({
|
|
47
|
+
method: "GET",
|
|
48
|
+
path: `/v1/files/${encodeURIComponent(fileId)}/versions`,
|
|
49
|
+
query: { ...params, next } as Record<string, unknown>,
|
|
50
|
+
}),
|
|
51
|
+
params?.next,
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
get(fileId: string, versionId: string): Promise<FileResource> {
|
|
56
|
+
return this.http.request<FileResource>({
|
|
57
|
+
method: "GET",
|
|
58
|
+
path: `/v1/files/${encodeURIComponent(fileId)}/versions/${encodeURIComponent(versionId)}`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
create(
|
|
63
|
+
fileId: string,
|
|
64
|
+
body: FileUploadBody,
|
|
65
|
+
options?: FileCreateOptions,
|
|
66
|
+
): Promise<FileResource> {
|
|
67
|
+
const form = toFormData(body, options);
|
|
68
|
+
return this.http.request<FileResource>({
|
|
69
|
+
method: "POST",
|
|
70
|
+
path: `/v1/files/${encodeURIComponent(fileId)}/versions`,
|
|
71
|
+
body: form,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Cookie-authenticated `/v1/files` client. Mirrors the Node SDK's
|
|
78
|
+
* `FilesApi` shape but is bound to a DP session cookie rather than a
|
|
79
|
+
* bearer token.
|
|
80
|
+
*/
|
|
81
|
+
export class FilesClient {
|
|
82
|
+
readonly versions: FileVersionsClient;
|
|
83
|
+
|
|
84
|
+
constructor(private readonly http: BrowserHttpClient) {
|
|
85
|
+
this.versions = new FileVersionsClient(http);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* List files matching `params`. `await` the result for the first page,
|
|
90
|
+
* or `for await` it to stream every file across pages (fetched lazily —
|
|
91
|
+
* `limit` sets the page size, `next` the starting cursor; stop early to
|
|
92
|
+
* stop fetching).
|
|
93
|
+
*/
|
|
94
|
+
list(params?: FileListParams): Paginator<FileResource> {
|
|
95
|
+
return cursorPaginate(
|
|
96
|
+
(next) =>
|
|
97
|
+
this.http.request<Paginated<FileResource>>({
|
|
98
|
+
method: "GET",
|
|
99
|
+
path: "/v1/files",
|
|
100
|
+
query: { ...params, next } as Record<string, unknown>,
|
|
101
|
+
}),
|
|
102
|
+
params?.next,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
upload(
|
|
107
|
+
body: FileUploadBody,
|
|
108
|
+
options?: FileCreateOptions,
|
|
109
|
+
): Promise<FileResource> {
|
|
110
|
+
const form = toFormData(body, options);
|
|
111
|
+
return this.http.request<FileResource>({
|
|
112
|
+
method: "POST",
|
|
113
|
+
path: "/v1/files",
|
|
114
|
+
body: form,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
createText(
|
|
119
|
+
body: FileCreateTextParams,
|
|
120
|
+
options?: FileCreateOptions,
|
|
121
|
+
): Promise<FileResource> {
|
|
122
|
+
return this.http.request<FileResource>({
|
|
123
|
+
method: "POST",
|
|
124
|
+
path: "/v1/files",
|
|
125
|
+
body: options?.visibility
|
|
126
|
+
? { ...body, visibility: options.visibility }
|
|
127
|
+
: body,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
get(fileId: string): Promise<FileResource> {
|
|
132
|
+
return this.http.request<FileResource>({
|
|
133
|
+
method: "GET",
|
|
134
|
+
path: `/v1/files/${encodeURIComponent(fileId)}`,
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
update(fileId: string, body: FileUpdateParams): Promise<FileResource> {
|
|
139
|
+
return this.http.request<FileResource>({
|
|
140
|
+
method: "PATCH",
|
|
141
|
+
path: `/v1/files/${encodeURIComponent(fileId)}`,
|
|
142
|
+
body,
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
delete(fileId: string): Promise<void> {
|
|
147
|
+
return this.http.request<void>({
|
|
148
|
+
method: "DELETE",
|
|
149
|
+
path: `/v1/files/${encodeURIComponent(fileId)}`,
|
|
150
|
+
expect: "empty",
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
download(fileId: string): Promise<Uint8Array> {
|
|
155
|
+
return this.http.request<Uint8Array>({
|
|
156
|
+
method: "GET",
|
|
157
|
+
path: `/v1/files/${encodeURIComponent(fileId)}/content`,
|
|
158
|
+
expect: "bytes",
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
downloadStream(fileId: string): Promise<ReadableStream<Uint8Array>> {
|
|
163
|
+
return this.http.request<ReadableStream<Uint8Array>>({
|
|
164
|
+
method: "GET",
|
|
165
|
+
path: `/v1/files/${encodeURIComponent(fileId)}/content`,
|
|
166
|
+
expect: "stream",
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function toFormData(
|
|
172
|
+
body: FileUploadBody,
|
|
173
|
+
options?: FileCreateOptions,
|
|
174
|
+
): FormData {
|
|
175
|
+
const fd = new FormData();
|
|
176
|
+
if ("file" in body && body.file instanceof Blob) {
|
|
177
|
+
fd.append("file", body.file, body.name);
|
|
178
|
+
} else {
|
|
179
|
+
// Uint8Array branch — copy into a fresh ArrayBuffer so the Blob
|
|
180
|
+
// constructor sees a concrete ArrayBuffer (not ArrayBufferLike,
|
|
181
|
+
// which TS rejects under nodenext lib).
|
|
182
|
+
const u8 = (body as { file: Uint8Array }).file;
|
|
183
|
+
const ct =
|
|
184
|
+
(body as { contentType?: string }).contentType ??
|
|
185
|
+
"application/octet-stream";
|
|
186
|
+
const ab = u8.buffer.slice(
|
|
187
|
+
u8.byteOffset,
|
|
188
|
+
u8.byteOffset + u8.byteLength,
|
|
189
|
+
) as ArrayBuffer;
|
|
190
|
+
fd.append("file", new Blob([ab], { type: ct }), body.name);
|
|
191
|
+
}
|
|
192
|
+
if (body.name) fd.append("name", body.name);
|
|
193
|
+
if (body.file_type) fd.append("file_type", body.file_type);
|
|
194
|
+
if (options?.visibility) fd.append("visibility", options.visibility);
|
|
195
|
+
return fd;
|
|
196
|
+
}
|
package/src/api/http.ts
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser HTTP transport for the Introspection Data Plane `/v1` surface.
|
|
3
|
+
*
|
|
4
|
+
* The request/response machinery — URL joining, query building, body
|
|
5
|
+
* serialization, error mapping, SSE — lives in the shared
|
|
6
|
+
* `@introspection-sdk/http` {@link BaseHttpClient}. This module pins the
|
|
7
|
+
* browser auth strategy on top of it: the DP is reached with the HttpOnly
|
|
8
|
+
* `intro_dp_session` cookie minted by `POST /v1/oauth/exchange`, so every
|
|
9
|
+
* request opts into `credentials: "include"` and sends NO bearer token —
|
|
10
|
+
* no Introspection credential ever lives in JavaScript. A 401 (expired
|
|
11
|
+
* session cookie) triggers a single `onUnauthorized` refresh + retry.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import {
|
|
15
|
+
BaseHttpClient,
|
|
16
|
+
stripTrailingSlash,
|
|
17
|
+
toApiError,
|
|
18
|
+
} from "@introspection-sdk/http";
|
|
19
|
+
|
|
20
|
+
// Re-exported for `client.ts`, which redeems the DP session on `connect()`.
|
|
21
|
+
export { stripTrailingSlash, toApiError };
|
|
22
|
+
|
|
23
|
+
export interface BrowserHttpConfig {
|
|
24
|
+
/** DP REST base URL every request is prefixed with. */
|
|
25
|
+
apiUrl: string;
|
|
26
|
+
/** Extra headers merged into every request. */
|
|
27
|
+
additionalHeaders?: Record<string, string>;
|
|
28
|
+
/** Custom `fetch` (for tests or non-standard runtimes). */
|
|
29
|
+
fetch?: typeof fetch;
|
|
30
|
+
/**
|
|
31
|
+
* Invoked when a request comes back `401`. Return `true` if the DP
|
|
32
|
+
* session was refreshed and the request should be retried once;
|
|
33
|
+
* `false` to surface the original error.
|
|
34
|
+
*/
|
|
35
|
+
onUnauthorized?: () => Promise<boolean>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Cookie-authenticated HTTP wrapper bound to one DP endpoint. Has no
|
|
40
|
+
* opinion about which resource it serves — the caller picks the path.
|
|
41
|
+
*/
|
|
42
|
+
export class BrowserHttpClient extends BaseHttpClient {
|
|
43
|
+
constructor(cfg: BrowserHttpConfig) {
|
|
44
|
+
super({
|
|
45
|
+
apiUrl: cfg.apiUrl,
|
|
46
|
+
additionalHeaders: cfg.additionalHeaders,
|
|
47
|
+
fetch: cfg.fetch,
|
|
48
|
+
transport: {
|
|
49
|
+
authHeaders: () => ({}),
|
|
50
|
+
credentials: "include",
|
|
51
|
+
onUnauthorized: cfg.onUnauthorized,
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/api/index.ts
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Introspection Browser API surface — `@introspection-sdk/introspection-browser/api`.
|
|
3
|
+
*
|
|
4
|
+
* A cookie-authenticated client for creating and streaming Introspection
|
|
5
|
+
* tasks directly from a single-page app, with no API key in the browser.
|
|
6
|
+
* Separate from the package's default telemetry export so apps only pull
|
|
7
|
+
* in what they use.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* ```typescript
|
|
11
|
+
* import { IntrospectionApiClient } from "@introspection-sdk/introspection-browser/api";
|
|
12
|
+
*
|
|
13
|
+
* const client = new IntrospectionApiClient({
|
|
14
|
+
* dpUrl: "https://dp.us.introspection.dev",
|
|
15
|
+
* projectId: "proj_…",
|
|
16
|
+
* // your backend mints the Introspection access token
|
|
17
|
+
* getToken: () => fetch("/api/introspection/token").then((r) => r.text()),
|
|
18
|
+
* });
|
|
19
|
+
*
|
|
20
|
+
* await client.connect(); // → intro_dp_session cookie
|
|
21
|
+
* const run = await client.tasks.start({
|
|
22
|
+
* prompt: "Summarize my latest order",
|
|
23
|
+
* agent_name: "support-agent",
|
|
24
|
+
* identity: { user_id: "u_42" },
|
|
25
|
+
* });
|
|
26
|
+
* for await (const ev of run.stream()) console.log(ev.event, ev.data);
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
export {
|
|
31
|
+
IntrospectionApiClient,
|
|
32
|
+
type IntrospectionApiClientOptions,
|
|
33
|
+
} from "./client.js";
|
|
34
|
+
export {
|
|
35
|
+
TasksClient,
|
|
36
|
+
TaskRunsClient,
|
|
37
|
+
RunHandle,
|
|
38
|
+
type CreateTaskParams,
|
|
39
|
+
type StartTaskParams,
|
|
40
|
+
} from "./tasks.js";
|
|
41
|
+
export {
|
|
42
|
+
FilesClient,
|
|
43
|
+
FileVersionsClient,
|
|
44
|
+
type FileUploadBody,
|
|
45
|
+
} from "./files.js";
|
|
46
|
+
export {
|
|
47
|
+
ConversationsClient,
|
|
48
|
+
ConversationItemsClient,
|
|
49
|
+
} from "./conversations.js";
|
|
50
|
+
export { BrowserHttpClient, type BrowserHttpConfig } from "./http.js";
|
|
51
|
+
export { parseSse } from "./sse.js";
|
|
52
|
+
export {
|
|
53
|
+
Paginator,
|
|
54
|
+
cursorPaginate,
|
|
55
|
+
type PageSource,
|
|
56
|
+
} from "@introspection-sdk/http";
|
|
57
|
+
|
|
58
|
+
// Re-exported wire types for convenience.
|
|
59
|
+
export type {
|
|
60
|
+
Task,
|
|
61
|
+
TaskRun,
|
|
62
|
+
TaskStatus,
|
|
63
|
+
TaskVisibility,
|
|
64
|
+
TaskCreateResponse,
|
|
65
|
+
TaskListParams,
|
|
66
|
+
TaskUpdateParams,
|
|
67
|
+
TaskRunCreateParams,
|
|
68
|
+
TaskCancelResponse,
|
|
69
|
+
RunIdentityInput,
|
|
70
|
+
Paginated,
|
|
71
|
+
SseEvent,
|
|
72
|
+
File,
|
|
73
|
+
FileType,
|
|
74
|
+
FileListParams,
|
|
75
|
+
FileUpdateParams,
|
|
76
|
+
FileCreateTextParams,
|
|
77
|
+
FileCreateOptions,
|
|
78
|
+
ListParams,
|
|
79
|
+
ConversationSummary,
|
|
80
|
+
ConversationItem,
|
|
81
|
+
ConversationItemList,
|
|
82
|
+
ConversationListParams,
|
|
83
|
+
ConversationItemListParams,
|
|
84
|
+
ConversationItemInclude,
|
|
85
|
+
ConversationResponse,
|
|
86
|
+
} from "@introspection-sdk/types";
|
|
87
|
+
export {
|
|
88
|
+
IntrospectionAPIError,
|
|
89
|
+
AuthenticationError,
|
|
90
|
+
InsufficientScopeError,
|
|
91
|
+
NotFoundError,
|
|
92
|
+
NetworkError,
|
|
93
|
+
} from "@introspection-sdk/types";
|
package/src/api/sse.ts
ADDED