@granular-software/sdk 0.4.68 → 0.4.70

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.
@@ -0,0 +1,350 @@
1
+ // src/endpoints.ts
2
+ var LOCAL_API_URL = "ws://localhost:8787/granular";
3
+ var PRODUCTION_API_URL = "wss://cf-api-gateway.arthur6084.workers.dev/granular";
4
+ function readEnv(name) {
5
+ if (typeof process === "undefined" || !process.env) return void 0;
6
+ return process.env[name];
7
+ }
8
+ function normalizeMode(value) {
9
+ if (!value) return void 0;
10
+ const normalized = value.trim().toLowerCase();
11
+ if (normalized === "local") return "local";
12
+ if (normalized === "prod" || normalized === "production") return "production";
13
+ if (normalized === "auto") return "auto";
14
+ return void 0;
15
+ }
16
+ function isTruthy(value) {
17
+ if (!value) return false;
18
+ const normalized = value.trim().toLowerCase();
19
+ return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
20
+ }
21
+ function resolveEndpointMode(explicitMode) {
22
+ const explicit = normalizeMode(explicitMode);
23
+ if (explicit === "local" || explicit === "production") {
24
+ return explicit;
25
+ }
26
+ const envMode = normalizeMode(
27
+ readEnv("GRANULAR_ENDPOINT_MODE") || readEnv("GRANULAR_ENV")
28
+ );
29
+ if (envMode === "local" || envMode === "production") {
30
+ return envMode;
31
+ }
32
+ if (isTruthy(readEnv("GRANULAR_USE_LOCAL_ENDPOINTS")) || isTruthy(readEnv("GRANULAR_LOCAL"))) {
33
+ return "local";
34
+ }
35
+ if (isTruthy(readEnv("GRANULAR_USE_PRODUCTION_ENDPOINTS")) || isTruthy(readEnv("GRANULAR_PROD"))) {
36
+ return "production";
37
+ }
38
+ return readEnv("NODE_ENV") === "development" ? "local" : "production";
39
+ }
40
+ function resolveApiUrl(explicitApiUrl, mode) {
41
+ if (explicitApiUrl) {
42
+ return explicitApiUrl;
43
+ }
44
+ return resolveEndpointMode(mode) === "local" ? LOCAL_API_URL : PRODUCTION_API_URL;
45
+ }
46
+
47
+ // src/delegated-auth.ts
48
+ var DEFAULT_SESSION_REQUEST_TIMEOUT_MS = 3e4;
49
+ var MAX_SESSION_REQUEST_BYTES = 8192;
50
+ var PUBLIC_UPSTREAM_ERRORS = /* @__PURE__ */ new Map([
51
+ ["invalid_request", { status: 400, message: "The session request is invalid." }],
52
+ ["invalid_embedded_ui_key", {
53
+ status: 401,
54
+ message: "The Embedded UI key is invalid or has been revoked."
55
+ }],
56
+ ["server_side_only", {
57
+ status: 403,
58
+ message: "Create browser sessions from your server route."
59
+ }],
60
+ ["insufficient_key_permissions", {
61
+ status: 403,
62
+ message: "Use an Embedded UI API key for this session route."
63
+ }],
64
+ ["subject_not_provisioned", {
65
+ status: 403,
66
+ message: "This product user does not have Granular access yet. Assign the user to this ontology first."
67
+ }],
68
+ ["sandbox_not_authorized", {
69
+ status: 403,
70
+ message: "This product user is not assigned to the requested ontology."
71
+ }],
72
+ ["environment_scope_mismatch", {
73
+ status: 403,
74
+ message: "The requested environment does not match this user's access."
75
+ }],
76
+ ["environment_not_found", {
77
+ status: 404,
78
+ message: "This environment is not ready yet. Provision it from your server or the Granular console, then try again."
79
+ }],
80
+ ["rate_limited", {
81
+ status: 429,
82
+ message: "Too many session requests. Try again shortly."
83
+ }]
84
+ ]);
85
+ function env(name) {
86
+ if (typeof process === "undefined" || !process.env) return void 0;
87
+ return process.env[name];
88
+ }
89
+ function json(body, status, extraHeaders) {
90
+ const headers = new Headers(extraHeaders);
91
+ headers.set("Content-Type", "application/json");
92
+ headers.set("Cache-Control", "no-store");
93
+ headers.set("Pragma", "no-cache");
94
+ headers.set("Referrer-Policy", "no-referrer");
95
+ return new Response(JSON.stringify(body), { status, headers });
96
+ }
97
+ function normalizedOrigin(value) {
98
+ try {
99
+ return new URL(value).origin;
100
+ } catch {
101
+ return null;
102
+ }
103
+ }
104
+ function originHeaders(request, allowedOrigins) {
105
+ const headers = new Headers({ Vary: "Origin" });
106
+ const origin = request.headers.get("origin");
107
+ if (origin && allowedOrigins.has(origin)) {
108
+ headers.set("Access-Control-Allow-Origin", origin);
109
+ headers.set("Access-Control-Allow-Credentials", "true");
110
+ }
111
+ return headers;
112
+ }
113
+ function isAllowedBrowserRequest(request, allowedOrigins) {
114
+ const origin = request.headers.get("origin");
115
+ if (!origin) return true;
116
+ const normalized = normalizedOrigin(origin);
117
+ if (!normalized) return false;
118
+ if (normalized === new URL(request.url).origin) return true;
119
+ return allowedOrigins.has(normalized);
120
+ }
121
+ function optionalString(record, key, maxLength) {
122
+ const value = record[key];
123
+ if (value === void 0 || value === null || value === "") return void 0;
124
+ if (typeof value !== "string") {
125
+ throw new Error(`${key} must be a string`);
126
+ }
127
+ const normalized = value.trim();
128
+ if (!normalized || normalized.length > maxLength) {
129
+ throw new Error(`${key} is invalid`);
130
+ }
131
+ return normalized;
132
+ }
133
+ async function readSessionRequest(request) {
134
+ const contentType = request.headers.get("content-type") || "";
135
+ if (!contentType.toLowerCase().includes("application/json")) {
136
+ throw new Error("Content-Type must be application/json");
137
+ }
138
+ const contentLength = Number(request.headers.get("content-length") || "0");
139
+ if (Number.isFinite(contentLength) && contentLength > MAX_SESSION_REQUEST_BYTES) {
140
+ throw new Error("Request body is too large");
141
+ }
142
+ const text = await request.text();
143
+ if (new TextEncoder().encode(text).byteLength > MAX_SESSION_REQUEST_BYTES) {
144
+ throw new Error("Request body is too large");
145
+ }
146
+ const parsed = JSON.parse(text);
147
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
148
+ throw new Error("Request body must be an object");
149
+ }
150
+ const record = parsed;
151
+ const allowedFields = /* @__PURE__ */ new Set([
152
+ "ontologyId",
153
+ "environmentName",
154
+ "environmentId",
155
+ "environmentTagName"
156
+ ]);
157
+ if (Object.keys(record).some((key) => !allowedFields.has(key))) {
158
+ throw new Error("Request body contains unsupported fields");
159
+ }
160
+ const ontologyId = optionalString(record, "ontologyId", 256);
161
+ if (!ontologyId) throw new Error("ontologyId is required");
162
+ return {
163
+ ontologyId,
164
+ environmentName: optionalString(record, "environmentName", 128),
165
+ environmentId: optionalString(record, "environmentId", 256),
166
+ environmentTagName: optionalString(record, "environmentTagName", 128)
167
+ };
168
+ }
169
+ function gatewayHttpUrl(apiUrl) {
170
+ const resolved = new URL(resolveApiUrl(apiUrl));
171
+ if (resolved.protocol === "ws:") {
172
+ resolved.protocol = "http:";
173
+ } else if (resolved.protocol === "wss:") {
174
+ resolved.protocol = "https:";
175
+ }
176
+ resolved.search = "";
177
+ resolved.hash = "";
178
+ resolved.pathname = resolved.pathname.replace(/\/+$/, "").replace(/\/ws\/connect$/, "").replace(/\/ws$/, "") || "/granular";
179
+ return resolved.toString().replace(/\/$/, "");
180
+ }
181
+ function createGranularSessionRoute(options) {
182
+ const configuredOrigins = new Set(
183
+ (options.allowedOrigins || []).map(normalizedOrigin).filter((value) => Boolean(value))
184
+ );
185
+ return async (request) => {
186
+ const responseOriginHeaders = originHeaders(request, configuredOrigins);
187
+ if (!isAllowedBrowserRequest(request, configuredOrigins)) {
188
+ return json(
189
+ { error: "origin_not_allowed", message: "This origin is not allowed." },
190
+ 403,
191
+ responseOriginHeaders
192
+ );
193
+ }
194
+ if (request.method === "OPTIONS") {
195
+ responseOriginHeaders.set("Access-Control-Allow-Methods", "POST");
196
+ responseOriginHeaders.set(
197
+ "Access-Control-Allow-Headers",
198
+ request.headers.get("access-control-request-headers") || "Content-Type"
199
+ );
200
+ responseOriginHeaders.set("Access-Control-Max-Age", "600");
201
+ return new Response(null, {
202
+ status: 204,
203
+ headers: responseOriginHeaders
204
+ });
205
+ }
206
+ if (request.method !== "POST") {
207
+ return json({ error: "method_not_allowed", message: "Use POST." }, 405, {
208
+ ...Object.fromEntries(responseOriginHeaders),
209
+ Allow: "POST"
210
+ });
211
+ }
212
+ let requestBody;
213
+ try {
214
+ requestBody = await readSessionRequest(request);
215
+ } catch (error) {
216
+ return json(
217
+ {
218
+ error: "invalid_request",
219
+ message: error instanceof Error ? error.message : "Invalid request."
220
+ },
221
+ 400,
222
+ responseOriginHeaders
223
+ );
224
+ }
225
+ let subject;
226
+ try {
227
+ subject = await options.getSubject(request);
228
+ } catch {
229
+ return json(
230
+ {
231
+ error: "authentication_failed",
232
+ message: "Login could not be verified."
233
+ },
234
+ 401,
235
+ responseOriginHeaders
236
+ );
237
+ }
238
+ const externalSubjectId = typeof subject === "string" ? subject.trim() : "";
239
+ if (!externalSubjectId || externalSubjectId.length > 512) {
240
+ return json(
241
+ { error: "login_required", message: "Log in to continue." },
242
+ 401,
243
+ responseOriginHeaders
244
+ );
245
+ }
246
+ const apiKey = (options.apiKey || env("GRANULAR_EMBEDDED_UI_API_KEY") || "").trim();
247
+ if (!apiKey) {
248
+ return json(
249
+ {
250
+ error: "server_not_configured",
251
+ message: "Granular authentication is not configured."
252
+ },
253
+ 503,
254
+ responseOriginHeaders
255
+ );
256
+ }
257
+ const controller = new AbortController();
258
+ const abortFromRequest = () => controller.abort(request.signal.reason);
259
+ if (request.signal.aborted) {
260
+ abortFromRequest();
261
+ } else {
262
+ request.signal.addEventListener("abort", abortFromRequest, {
263
+ once: true
264
+ });
265
+ }
266
+ const timeout = setTimeout(
267
+ () => controller.abort(),
268
+ options.timeoutMs ?? DEFAULT_SESSION_REQUEST_TIMEOUT_MS
269
+ );
270
+ try {
271
+ const response = await (options.fetch || globalThis.fetch)(
272
+ `${gatewayHttpUrl(options.apiUrl)}/sdk/browser-access-token`,
273
+ {
274
+ method: "POST",
275
+ headers: {
276
+ Accept: "application/json",
277
+ Authorization: `Bearer ${apiKey}`,
278
+ "Content-Type": "application/json"
279
+ },
280
+ body: JSON.stringify({
281
+ externalSubjectId,
282
+ sandboxId: requestBody.ontologyId,
283
+ environment: requestBody.environmentName || "prod",
284
+ environmentId: requestBody.environmentId,
285
+ tagName: requestBody.environmentTagName
286
+ }),
287
+ signal: controller.signal
288
+ }
289
+ );
290
+ const responseText = await response.text();
291
+ let responseBody;
292
+ try {
293
+ const parsed = JSON.parse(responseText);
294
+ responseBody = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
295
+ } catch {
296
+ responseBody = {};
297
+ }
298
+ if (!response.ok) {
299
+ const retryAfter = response.headers.get("Retry-After");
300
+ if (retryAfter) responseOriginHeaders.set("Retry-After", retryAfter);
301
+ const upstreamCode = typeof responseBody.error === "string" ? responseBody.error : "";
302
+ const publicError = PUBLIC_UPSTREAM_ERRORS.get(upstreamCode);
303
+ return json(
304
+ publicError ? { error: upstreamCode, message: publicError.message } : {
305
+ error: "session_creation_failed",
306
+ message: "Granular could not start this session."
307
+ },
308
+ publicError ? publicError.status : 503,
309
+ responseOriginHeaders
310
+ );
311
+ }
312
+ if (typeof responseBody.access_token !== "string" || typeof responseBody.expires_in !== "number" || !responseBody.user || typeof responseBody.user !== "object" || Array.isArray(responseBody.user)) {
313
+ return json(
314
+ {
315
+ error: "invalid_granular_response",
316
+ message: "Granular returned an invalid session response."
317
+ },
318
+ 503,
319
+ responseOriginHeaders
320
+ );
321
+ }
322
+ return json(
323
+ {
324
+ access_token: responseBody.access_token,
325
+ token_type: typeof responseBody.token_type === "string" ? responseBody.token_type : "Bearer",
326
+ expires_in: responseBody.expires_in,
327
+ user: responseBody.user
328
+ },
329
+ 200,
330
+ responseOriginHeaders
331
+ );
332
+ } catch (error) {
333
+ return json(
334
+ {
335
+ error: "session_service_unavailable",
336
+ message: error instanceof Error && error.name === "AbortError" ? "Granular took too long to start the session." : "Granular is temporarily unavailable."
337
+ },
338
+ 503,
339
+ responseOriginHeaders
340
+ );
341
+ } finally {
342
+ clearTimeout(timeout);
343
+ request.signal.removeEventListener("abort", abortFromRequest);
344
+ }
345
+ };
346
+ }
347
+
348
+ export { createGranularSessionRoute };
349
+ //# sourceMappingURL=delegated-auth.mjs.map
350
+ //# sourceMappingURL=delegated-auth.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/endpoints.ts","../src/delegated-auth.ts"],"names":[],"mappings":";AAEO,IAAM,aAAA,GAAgB,8BAAA;AACtB,IAAM,kBAAA,GACX,sDA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OAAO,YAAA,CAAa,UAAA,KAAe,QAAA,GAC/B,aAAa,UAAA,GACb,QAAA;AAAA,UACN,YAAY,YAAA,CAAa,UAAA;AAAA,UACzB,MAAM,YAAA,CAAa;AAAA,SACrB;AAAA,QACA,GAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,OAAO,IAAA;AAAA,QACL;AAAA,UACE,KAAA,EAAO,6BAAA;AAAA,UACP,SACE,KAAA,YAAiB,KAAA,IAAS,KAAA,CAAM,IAAA,KAAS,eACrC,8CAAA,GACA;AAAA,SACR;AAAA,QACA,GAAA;AAAA,QACA;AAAA,OACF;AAAA,IACF,CAAA,SAAE;AACA,MAAA,YAAA,CAAa,OAAO,CAAA;AACpB,MAAA,OAAA,CAAQ,MAAA,CAAO,mBAAA,CAAoB,OAAA,EAAS,gBAAgB,CAAA;AAAA,IAC9D;AAAA,EACF,CAAA;AACF","file":"delegated-auth.mjs","sourcesContent":["import type { EndpointMode } from \"./types\";\n\nexport const LOCAL_API_URL = \"ws://localhost:8787/granular\";\nexport const PRODUCTION_API_URL =\n \"wss://cf-api-gateway.arthur6084.workers.dev/granular\";\nexport const DEFAULT_LOCAL_API_KEY =\n \"gn_sk_tenant_default_principal_local_e2e_00000000\";\n\nexport const LOCAL_AUTH_URL = \"http://localhost:3000\";\nexport const PRODUCTION_AUTH_URL = \"https://app.granular.software\";\n\ntype ResolvedEndpointMode = \"local\" | \"production\";\n\nfunction readEnv(name: string): string | undefined {\n if (typeof process === \"undefined\" || !process.env) return undefined;\n return process.env[name];\n}\n\nfunction normalizeMode(value?: string): EndpointMode | undefined {\n if (!value) return undefined;\n const normalized = value.trim().toLowerCase();\n if (normalized === \"local\") return \"local\";\n if (normalized === \"prod\" || normalized === \"production\") return \"production\";\n if (normalized === \"auto\") return \"auto\";\n return undefined;\n}\n\nfunction isTruthy(value?: string): boolean {\n if (!value) return false;\n const normalized = value.trim().toLowerCase();\n return (\n normalized === \"1\" ||\n normalized === \"true\" ||\n normalized === \"yes\" ||\n normalized === \"on\"\n );\n}\n\nexport function isLocalApiUrl(url: string): boolean {\n try {\n const parsed = new URL(url);\n return parsed.hostname === \"localhost\" || parsed.hostname === \"127.0.0.1\";\n } catch {\n return false;\n }\n}\n\n/**\n * Local dev + `sk_*` (WorkOS org key in env): map to the local gn_sk e2e key by default so every\n * request (HTTP + WebSocket) uses the same tenant as the v2 UI on localhost (`default`). Without\n * this, the SDK passes `sk_*` through → gateway resolves org_… while the UI still uses gn_sk →\n * you only see old default-tenant sandboxes and new ingest data looks “missing”.\n *\n * - `GRANULAR_LOCAL_API_KEY` — explicit key to use instead (e.g. another gn_sk).\n * - `GRANULAR_DISABLE_LOCAL_API_KEY_FALLBACK=1` — do not swap; send the real `sk_*` (org tenant +\n * WorkOS validation on the gateway). Use when the UI is also on that org (e.g. session auth +\n * NEXT_PUBLIC_DISABLE_LOCAL_API_KEY_FALLBACK on the app).\n */\nexport function resolveAuthTokenForApiUrl(\n authToken: string,\n apiUrl: string,\n): string {\n if (\n !authToken.startsWith(\"sk_\") ||\n !isLocalApiUrl(apiUrl) ||\n isTruthy(readEnv(\"GRANULAR_DISABLE_LOCAL_API_KEY_FALLBACK\"))\n ) {\n return authToken;\n }\n\n const override = readEnv(\"GRANULAR_LOCAL_API_KEY\")?.trim();\n return override || DEFAULT_LOCAL_API_KEY;\n}\n\nexport function resolveEndpointMode(\n explicitMode?: EndpointMode,\n): ResolvedEndpointMode {\n const explicit = normalizeMode(explicitMode);\n if (explicit === \"local\" || explicit === \"production\") {\n return explicit;\n }\n\n const envMode = normalizeMode(\n readEnv(\"GRANULAR_ENDPOINT_MODE\") || readEnv(\"GRANULAR_ENV\"),\n );\n if (envMode === \"local\" || envMode === \"production\") {\n return envMode;\n }\n\n if (\n isTruthy(readEnv(\"GRANULAR_USE_LOCAL_ENDPOINTS\")) ||\n isTruthy(readEnv(\"GRANULAR_LOCAL\"))\n ) {\n return \"local\";\n }\n if (\n isTruthy(readEnv(\"GRANULAR_USE_PRODUCTION_ENDPOINTS\")) ||\n isTruthy(readEnv(\"GRANULAR_PROD\"))\n ) {\n return \"production\";\n }\n\n return readEnv(\"NODE_ENV\") === \"development\" ? \"local\" : \"production\";\n}\n\nexport function resolveApiUrl(\n explicitApiUrl?: string,\n mode?: EndpointMode,\n): string {\n if (explicitApiUrl) {\n return explicitApiUrl;\n }\n\n return resolveEndpointMode(mode) === \"local\"\n ? LOCAL_API_URL\n : PRODUCTION_API_URL;\n}\n\nexport function resolveAuthUrl(\n explicitAuthUrl?: string,\n mode?: EndpointMode,\n): string {\n if (explicitAuthUrl) {\n return explicitAuthUrl;\n }\n\n return resolveEndpointMode(mode) === \"local\"\n ? LOCAL_AUTH_URL\n : PRODUCTION_AUTH_URL;\n}\n","import { resolveApiUrl } from \"./endpoints\";\n\nconst DEFAULT_SESSION_REQUEST_TIMEOUT_MS = 30_000;\nconst MAX_SESSION_REQUEST_BYTES = 8_192;\n\nexport type GranularSessionSubject = string | null | undefined;\n\nexport interface CreateGranularSessionRouteOptions {\n /** Resolve the stable product-user ID from the request's trusted server session. */\n getSubject: (\n request: Request,\n ) => GranularSessionSubject | Promise<GranularSessionSubject>;\n /** Server-only Embedded UI API key. Defaults to GRANULAR_EMBEDDED_UI_API_KEY. */\n apiKey?: string;\n /** Granular gateway URL. Defaults to the normal SDK endpoint selection. */\n apiUrl?: string;\n /** Additional browser origins allowed to call this route. Same-origin is always allowed. */\n allowedOrigins?: string[];\n /** Upstream timeout. The default is 30 seconds. */\n timeoutMs?: number;\n /** Test or runtime-specific fetch implementation. */\n fetch?: typeof globalThis.fetch;\n}\n\ntype SessionRequestBody = {\n ontologyId: string;\n environmentName?: string;\n environmentId?: string;\n environmentTagName?: string;\n};\n\nconst PUBLIC_UPSTREAM_ERRORS = new Map<\n string,\n { status: number; message: string }\n>([\n [\"invalid_request\", { status: 400, message: \"The session request is invalid.\" }],\n [\"invalid_embedded_ui_key\", {\n status: 401,\n message: \"The Embedded UI key is invalid or has been revoked.\",\n }],\n [\"server_side_only\", {\n status: 403,\n message: \"Create browser sessions from your server route.\",\n }],\n [\"insufficient_key_permissions\", {\n status: 403,\n message: \"Use an Embedded UI API key for this session route.\",\n }],\n [\"subject_not_provisioned\", {\n status: 403,\n message:\n \"This product user does not have Granular access yet. Assign the user to this ontology first.\",\n }],\n [\"sandbox_not_authorized\", {\n status: 403,\n message: \"This product user is not assigned to the requested ontology.\",\n }],\n [\"environment_scope_mismatch\", {\n status: 403,\n message: \"The requested environment does not match this user's access.\",\n }],\n [\"environment_not_found\", {\n status: 404,\n message:\n \"This environment is not ready yet. Provision it from your server or the Granular console, then try again.\",\n }],\n [\"rate_limited\", {\n status: 429,\n message: \"Too many session requests. Try again shortly.\",\n }],\n]);\n\nfunction env(name: string): string | undefined {\n if (typeof process === \"undefined\" || !process.env) return undefined;\n return process.env[name];\n}\n\nfunction json(\n body: Record<string, unknown>,\n status: number,\n extraHeaders?: ConstructorParameters<typeof Headers>[0],\n): Response {\n const headers = new Headers(extraHeaders);\n headers.set(\"Content-Type\", \"application/json\");\n headers.set(\"Cache-Control\", \"no-store\");\n headers.set(\"Pragma\", \"no-cache\");\n headers.set(\"Referrer-Policy\", \"no-referrer\");\n return new Response(JSON.stringify(body), { status, headers });\n}\n\nfunction normalizedOrigin(value: string): string | null {\n try {\n return new URL(value).origin;\n } catch {\n return null;\n }\n}\n\nfunction originHeaders(request: Request, allowedOrigins: Set<string>): Headers {\n const headers = new Headers({ Vary: \"Origin\" });\n const origin = request.headers.get(\"origin\");\n if (origin && allowedOrigins.has(origin)) {\n headers.set(\"Access-Control-Allow-Origin\", origin);\n headers.set(\"Access-Control-Allow-Credentials\", \"true\");\n }\n return headers;\n}\n\nfunction isAllowedBrowserRequest(\n request: Request,\n allowedOrigins: Set<string>,\n): boolean {\n const origin = request.headers.get(\"origin\");\n if (!origin) return true;\n const normalized = normalizedOrigin(origin);\n if (!normalized) return false;\n if (normalized === new URL(request.url).origin) return true;\n return allowedOrigins.has(normalized);\n}\n\nfunction optionalString(\n record: Record<string, unknown>,\n key: string,\n maxLength: number,\n): string | undefined {\n const value = record[key];\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") {\n throw new Error(`${key} must be a string`);\n }\n const normalized = value.trim();\n if (!normalized || normalized.length > maxLength) {\n throw new Error(`${key} is invalid`);\n }\n return normalized;\n}\n\nasync function readSessionRequest(\n request: Request,\n): Promise<SessionRequestBody> {\n const contentType = request.headers.get(\"content-type\") || \"\";\n if (!contentType.toLowerCase().includes(\"application/json\")) {\n throw new Error(\"Content-Type must be application/json\");\n }\n const contentLength = Number(request.headers.get(\"content-length\") || \"0\");\n if (\n Number.isFinite(contentLength) &&\n contentLength > MAX_SESSION_REQUEST_BYTES\n ) {\n throw new Error(\"Request body is too large\");\n }\n const text = await request.text();\n if (new TextEncoder().encode(text).byteLength > MAX_SESSION_REQUEST_BYTES) {\n throw new Error(\"Request body is too large\");\n }\n const parsed = JSON.parse(text) as unknown;\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new Error(\"Request body must be an object\");\n }\n const record = parsed as Record<string, unknown>;\n const allowedFields = new Set([\n \"ontologyId\",\n \"environmentName\",\n \"environmentId\",\n \"environmentTagName\",\n ]);\n if (Object.keys(record).some((key) => !allowedFields.has(key))) {\n throw new Error(\"Request body contains unsupported fields\");\n }\n const ontologyId = optionalString(record, \"ontologyId\", 256);\n if (!ontologyId) throw new Error(\"ontologyId is required\");\n return {\n ontologyId,\n environmentName: optionalString(record, \"environmentName\", 128),\n environmentId: optionalString(record, \"environmentId\", 256),\n environmentTagName: optionalString(record, \"environmentTagName\", 128),\n };\n}\n\nfunction gatewayHttpUrl(apiUrl?: string): string {\n const resolved = new URL(resolveApiUrl(apiUrl));\n if (resolved.protocol === \"ws:\") {\n resolved.protocol = \"http:\";\n } else if (resolved.protocol === \"wss:\") {\n resolved.protocol = \"https:\";\n }\n resolved.search = \"\";\n resolved.hash = \"\";\n resolved.pathname =\n resolved.pathname\n .replace(/\\/+$/, \"\")\n .replace(/\\/ws\\/connect$/, \"\")\n .replace(/\\/ws$/, \"\") || \"/granular\";\n return resolved.toString().replace(/\\/$/, \"\");\n}\n\n/**\n * Create the one customer-owned delegated-auth endpoint used by Granular React.\n *\n * The browser supplies only public resource selection. `getSubject` is the\n * sole identity boundary and must derive its value from the existing trusted\n * server session, never from the request body.\n */\nexport function createGranularSessionRoute(\n options: CreateGranularSessionRouteOptions,\n): (request: Request) => Promise<Response> {\n const configuredOrigins = new Set(\n (options.allowedOrigins || [])\n .map(normalizedOrigin)\n .filter((value): value is string => Boolean(value)),\n );\n\n return async (request: Request): Promise<Response> => {\n const responseOriginHeaders = originHeaders(request, configuredOrigins);\n if (!isAllowedBrowserRequest(request, configuredOrigins)) {\n return json(\n { error: \"origin_not_allowed\", message: \"This origin is not allowed.\" },\n 403,\n responseOriginHeaders,\n );\n }\n if (request.method === \"OPTIONS\") {\n responseOriginHeaders.set(\"Access-Control-Allow-Methods\", \"POST\");\n responseOriginHeaders.set(\n \"Access-Control-Allow-Headers\",\n request.headers.get(\"access-control-request-headers\") || \"Content-Type\",\n );\n responseOriginHeaders.set(\"Access-Control-Max-Age\", \"600\");\n return new Response(null, {\n status: 204,\n headers: responseOriginHeaders,\n });\n }\n if (request.method !== \"POST\") {\n return json({ error: \"method_not_allowed\", message: \"Use POST.\" }, 405, {\n ...Object.fromEntries(responseOriginHeaders),\n Allow: \"POST\",\n });\n }\n\n let requestBody: SessionRequestBody;\n try {\n requestBody = await readSessionRequest(request);\n } catch (error) {\n return json(\n {\n error: \"invalid_request\",\n message: error instanceof Error ? error.message : \"Invalid request.\",\n },\n 400,\n responseOriginHeaders,\n );\n }\n\n let subject: GranularSessionSubject;\n try {\n subject = await options.getSubject(request);\n } catch {\n return json(\n {\n error: \"authentication_failed\",\n message: \"Login could not be verified.\",\n },\n 401,\n responseOriginHeaders,\n );\n }\n const externalSubjectId = typeof subject === \"string\" ? subject.trim() : \"\";\n if (!externalSubjectId || externalSubjectId.length > 512) {\n return json(\n { error: \"login_required\", message: \"Log in to continue.\" },\n 401,\n responseOriginHeaders,\n );\n }\n\n const apiKey = (\n options.apiKey ||\n env(\"GRANULAR_EMBEDDED_UI_API_KEY\") ||\n \"\"\n ).trim();\n if (!apiKey) {\n return json(\n {\n error: \"server_not_configured\",\n message: \"Granular authentication is not configured.\",\n },\n 503,\n responseOriginHeaders,\n );\n }\n\n const controller = new AbortController();\n const abortFromRequest = () => controller.abort(request.signal.reason);\n if (request.signal.aborted) {\n abortFromRequest();\n } else {\n request.signal.addEventListener(\"abort\", abortFromRequest, {\n once: true,\n });\n }\n const timeout = setTimeout(\n () => controller.abort(),\n options.timeoutMs ?? DEFAULT_SESSION_REQUEST_TIMEOUT_MS,\n );\n try {\n const response = await (options.fetch || globalThis.fetch)(\n `${gatewayHttpUrl(options.apiUrl)}/sdk/browser-access-token`,\n {\n method: \"POST\",\n headers: {\n Accept: \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({\n externalSubjectId,\n sandboxId: requestBody.ontologyId,\n environment: requestBody.environmentName || \"prod\",\n environmentId: requestBody.environmentId,\n tagName: requestBody.environmentTagName,\n }),\n signal: controller.signal,\n },\n );\n const responseText = await response.text();\n let responseBody: Record<string, unknown>;\n try {\n const parsed = JSON.parse(responseText) as unknown;\n responseBody =\n parsed && typeof parsed === \"object\" && !Array.isArray(parsed)\n ? (parsed as Record<string, unknown>)\n : {};\n } catch {\n responseBody = {};\n }\n if (!response.ok) {\n const retryAfter = response.headers.get(\"Retry-After\");\n if (retryAfter) responseOriginHeaders.set(\"Retry-After\", retryAfter);\n const upstreamCode =\n typeof responseBody.error === \"string\" ? responseBody.error : \"\";\n const publicError = PUBLIC_UPSTREAM_ERRORS.get(upstreamCode);\n return json(\n publicError\n ? { error: upstreamCode, message: publicError.message }\n : {\n error: \"session_creation_failed\",\n message: \"Granular could not start this session.\",\n },\n publicError ? publicError.status : 503,\n responseOriginHeaders,\n );\n }\n if (\n typeof responseBody.access_token !== \"string\" ||\n typeof responseBody.expires_in !== \"number\" ||\n !responseBody.user ||\n typeof responseBody.user !== \"object\" ||\n Array.isArray(responseBody.user)\n ) {\n return json(\n {\n error: \"invalid_granular_response\",\n message: \"Granular returned an invalid session response.\",\n },\n 503,\n responseOriginHeaders,\n );\n }\n return json(\n {\n access_token: responseBody.access_token,\n token_type:\n typeof responseBody.token_type === \"string\"\n ? responseBody.token_type\n : \"Bearer\",\n expires_in: responseBody.expires_in,\n user: responseBody.user,\n },\n 200,\n responseOriginHeaders,\n );\n } catch (error) {\n return json(\n {\n error: \"session_service_unavailable\",\n message:\n error instanceof Error && error.name === \"AbortError\"\n ? \"Granular took too long to start the session.\"\n : \"Granular is temporarily unavailable.\",\n },\n 503,\n responseOriginHeaders,\n );\n } finally {\n clearTimeout(timeout);\n request.signal.removeEventListener(\"abort\", abortFromRequest);\n }\n };\n}\n"]}
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
- export { E as Environment, a as EnvironmentSession, G as Granular, O as OntologyHandle, S as Session, W as WSClient, i as isGraphQLMutationDocument } from './client-BNpPrX2X.mjs';
2
- import { E as EnvironmentData, a as EnvironmentRecordImportSummary, b as EndpointMode, c as EffectCommitRequest, C as CommitReceipt, T as ToolWithHandler, P as ProjectionResult, d as ProjectionMapper, e as CommitTransitionOutcomeDeclaration, f as CommitDeclaration, g as EffectHandlerContext, F as FeedPublishTransport, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, h as RecordObjectOptions, i as ManifestContent, j as CommitTransitionInvocation, S as SessionHeapEntry, k as SessionHeapList, l as FeedItem, m as SessionHeapSnapshot, n as Prompt, o as SessionTranscriptEntry } from './spend-BDGtgZtl.mjs';
3
- export { ef as APIError, aS as AccessTokenProvider, Y as ActionSuggestionFeedItem, aZ as AdoptEnvironmentOptions, bK as AgentCommitStatus, cL as ArtifactApprovalDecisionInput, cM as ArtifactApprovalDecisionResult, cJ as ArtifactApprovalTask, cK as ArtifactApprovalTaskListOptions, cI as ArtifactApprovalTaskStatus, U as ArtifactFeedItem, b_ as ArtifactOptionsHandler, bj as Assignment, bk as AssignmentListResponse, cm as AssistantReplyPublicationInput, cn as AssistantReplyPublicationResult, bH as BaseProjectionResult, bt as Build, bv as BuildListResponse, bl as BuildPolicy, bs as BuildStatus, bC as CanonicalProjectedRecord, bL as CommitChangeReceipt, bA as CommitSafeError, bM as CommitTransitionReceipt, aO as ConditionIR, a_ as ConnectOptions, b0 as ConversationSessionInfo, b2 as ConversationSessionListOptions, b3 as ConversationSessionListResponse, b1 as ConversationSessionListStatus, bo as CreateEnvironmentData, bh as CreatePermissionProfileData, bd as CreateSandboxData, a$ as CreateSessionOptions, dp as DefineRelationshipOptions, eg as DeleteResponse, D as DomainState, bW as EffectArtifactOptionsInvocation, bY as EffectArtifactRelationshipOption, bZ as EffectArtifactRelationshipOptionsResult, bQ as EffectCommitContext, c7 as EffectHandler, c4 as EffectInfo, bX as EffectInvocationMetadata, bV as EffectInvocationMode, bI as EffectProjectionResult, b$ as EffectSchema, c2 as EffectVersionSelector, c0 as EffectWithHandler, c6 as EffectsChangedEvent, cf as EnvironmentFeedbackRecord, dM as EnvironmentImporter, dL as EnvironmentImporterImportOptions, bp as EnvironmentListResponse, dK as EnvironmentSetupImporterClaim, dI as EnvironmentSetupLifecycleStatus, dJ as EnvironmentSetupSummary, dG as EnvironmentSetupTriggerReason, du as EnvironmentStateMachineProxy, ds as EnvironmentStateObservationInput, dv as EnvironmentStateProxy, dr as EnvironmentStateTarget, dt as EnvironmentStateUpdateInput, bN as ExternalCommitOptions, ac as FeedDiagnostic, ad as FeedDiagnosticListener, ak as FeedDocumentState, v as FeedFeedbackTone, V as FeedFileSource, u as FeedIconToken, z as FeedItemBase, x as FeedItemKind, a3 as FeedListOptions, aa as FeedListTransport, G as FeedObjectReference, a4 as FeedPage, av as FeedPublisher, a2 as FeedSnapshot, ab as FeedSnapshotRegressionReason, t as FeedSource, s as FeedSourceActor, a5 as FeedSubscribeOptions, a6 as FeedSubscriptionChange, H as FeedTableCell, J as FeedTableColumn, N as FeedTableProjection, L as FeedTableRow, K as FeedTableRowReference, y as FeedTarget, w as FeedTransientFeedbackTone, B as FeedbackFeedItem, W as FileFeedItem, ae as GRANULAR_FEED_DIAGNOSTIC_EVENT, aU as GranularAuth, aT as GranularOptions, ba as GranularQuotaPolicy, bb as GranularQuotaProgress, aE as GranularSpendContext, ee as GraphQLResult, c8 as InstanceEffectHandler, I as InstanceToolHandler, ch as Job, cd as JobFeedbackInput, cc as JobFeedbackMetadata, ce as JobFeedbackRecord, ca as JobFeedbackSentiment, cb as JobFeedbackToolCall, c9 as JobStatus, cg as JobSubmitResult, bq as Manifest, e4 as ManifestApprovalRequiredSpec, e5 as ManifestCreatesSpec, e2 as ManifestDryRunSpec, e8 as ManifestEffectDeclaration, e7 as ManifestEffectSchema, dP as ManifestEnumRuleSpec, ea as ManifestEventStreamDef, e9 as ManifestEventTypeDef, dQ as ManifestFilterBySpec, ec as ManifestImport, br as ManifestListResponse, eb as ManifestOperation, e1 as ManifestPostConditionSpec, dN as ManifestPropertySpec, e6 as ManifestRelationshipDef, e3 as ManifestReverseSpec, e0 as ManifestStateMachineSpec, dS as ManifestStateMachineStateSpec, d$ as ManifestStateMachineTransitionSpec, dU as ManifestStateTransitionActionSpec, dV as ManifestStateTransitionAssigneeSpec, dZ as ManifestStateTransitionExpectedOutcomeSpec, dT as ManifestStateTransitionInputBinding, d_ as ManifestStateTransitionOutcomeSpec, dY as ManifestStateTransitionPermissionSpec, dW as ManifestStateTransitionRelatedStateRequirementSpec, dX as ManifestStateTransitionRequirementsSpec, dO as ManifestValidationOperator, dR as ManifestValidationRuleSpec, ed as ManifestVolume, cU as ManualActionListOptions, cS as ManualActionOccurrence, cT as ManualActionRecordResult, cQ as ManualActionRelatedRecord, cO as ManualActionSource, cN as ManualActionStatus, cV as ManualActionSuggestion, cW as ManualActionSuggestionOptions, cP as ManualActionTarget, dc as MarkUserEnvironmentReadOptions, aR as MatchedPolicy, A as MessageFeedItem, dm as ModelRef, ay as NormalizedOpenAIUsage, X as NormalizedSuggestedArtifact, aA as OPENAI_MODEL_PRICING_USD_PER_MILLION, bD as ObjectProjectionChange, by as ObjectReference, O as ObjectsFeedItem, bO as ObservationReceipt, ax as OpenAIModelPricing, az as OpenAITokenSpend, aF as OpenAIUsageSpendEvent, aY as OpenEnvironmentOptions, bg as PermissionProfile, bi as PermissionProfileListResponse, bf as PermissionRules, aN as PolicyOperator, aP as PolicyOrigin, aM as PolicyPredicateSource, aQ as PolicyRuleIR, aL as PolicySource, bG as ProjectionChange, Z as PromptFeedItem, c1 as PublishEffectsResult, ar as PublishFeedbackOptions, q as PublishToolsResult, as as PublishTransientFeedbackOptions, b9 as QuotaLineItemFilter, b6 as QuotaPeriod, b5 as QuotaScopeType, b7 as QuotaStatus, dg as RPCRequest, dj as RPCRequestFromServer, dh as RPCResponse, dF as RecordImport, dE as RecordImportItem, dC as RecordImportItemStatus, dA as RecordImportOptions, dD as RecordImportStats, dB as RecordImportStatus, dz as RecordImportWriteMode, cR as RecordManualActionInput, d2 as RecordMentionInput, dw as RecordObjectResult, dq as RecordObjectStateValue, dx as RecordObjectsChunkInfo, dy as RecordObjectsOptions, aG as RecordOpenAIUsageSpendOptions, aH as RecordOpenAIUsageSpendResult, d1 as RecordSearchOptions, d0 as RecordSearchResult, aW as RecordUserOptions, dn as RelationshipInfo, bE as RelationshipProjectionChange, bU as ResolvedEffectApprovalRequired, bS as ResolvedEffectDryRun, bR as ResolvedEffectPostCondition, bT as ResolvedEffectReverse, dH as RunEnvironmentImporterOptions, bc as Sandbox, be as SandboxListResponse, bx as SemanticVersionDiff, bw as SemanticVersionDiffEntry, cH as SessionArtifactApprovalOptions, cx as SessionArtifactAutonomyPolicy, cG as SessionArtifactExecutionOptions, cF as SessionArtifactExecutionResult, cw as SessionArtifactKind, cz as SessionArtifactListOptions, cy as SessionArtifactRecord, cE as SessionArtifactRelationshipCreateInput, cC as SessionArtifactRelationshipOption, cB as SessionArtifactRelationshipOptionsInput, cD as SessionArtifactRelationshipOptionsResult, cv as SessionArtifactStatus, cA as SessionArtifactValidationResult, d4 as SessionCollectionListOptions, d6 as SessionCollectionListResult, d3 as SessionDocumentResult, a7 as SessionFeedApi, aq as SessionFeedController, aj as SessionFeedControllerOptions, cs as SessionFileKind, cu as SessionFileRecord, cr as SessionFileSource, ct as SessionFileStatus, cX as SessionFileUploadOptions, cZ as SessionHeapFieldType, c_ as SessionHeapFieldValue, c$ as SessionHeapVariable, d5 as SessionJobListOptions, cY as SessionJobRecord, bP as SessionMutationView, cq as SessionTimelineEvent, co as SessionTranscriptActionSuggestion, cp as SessionTranscriptShowRefs, at as SettleTransientFeedbackOptions, di as SnapshotResetMessage, bz as SourceAcknowledgement, b4 as SpendLineItemType, b8 as SpendSummary, bF as StateObservationProjectionChange, eh as StreamEvent, ej as StreamStats, ei as StreamSubscription, aX as Subject, Q as TableFeedItem, r as ToolHandler, c3 as ToolInfo, dk as ToolInvokeParams, dl as ToolResultParams, p as ToolSchema, c5 as ToolsChangedEvent, a1 as TransientFeedItem, _ as TransientFeedItemBase, a0 as TransientFeedbackFeedItem, au as TransientFeedbackHandle, $ as TransientMessageFeedItem, bB as TransitionOutcomeProjection, bJ as TransitionProjectionResult, aV as User, d8 as UserEnvironmentMessagePreview, d7 as UserEnvironmentPrompt, d9 as UserEnvironmentSessionState, da as UserEnvironmentState, db as UserEnvironmentStateOptions, cl as UserMessageAppendResult, ck as UserMessageInput, ci as UserMessageShowRefs, cj as UserMessageTarget, bu as Version, bn as VersionTag, bm as VersionTracking, df as WSClientOptions, dd as WSDisconnectInfo, de as WSReconnectErrorInfo, aJ as buildOpenAISpendEventId, aD as calculateOpenAITokenSpend, aw as createFeedPublisher, ai as emitFeedDiagnostic, ah as emitFeedDiagnosticToDefaultSink, al as emptyFeedSnapshot, aB as getOpenAIModelPricing, am as hasCanonicalSessionFeedActivation, an as isCanonicalSessionFeedDocument, a8 as mergeFeedItemsBySequence, ag as normalizeFeedDiagnostic, af as normalizeFeedDiagnosticKind, ap as normalizeFeedPage, aC as normalizeOpenAIUsage, a9 as orderTransientFeedItems, ao as readSessionFeedSnapshot, aK as recordOpenAIUsageSpend, aI as toGranularHttpBase } from './spend-BDGtgZtl.mjs';
1
+ export { E as Environment, a as EnvironmentSession, G as Granular, O as OntologyHandle, S as Session, W as WSClient, i as isGraphQLMutationDocument } from './client-qgWZ495o.mjs';
2
+ import { E as EnvironmentData, a as EnvironmentRecordImportSummary, b as EndpointMode, c as EffectCommitRequest, C as CommitReceipt, T as ToolWithHandler, P as ProjectionResult, d as ProjectionMapper, e as CommitTransitionOutcomeDeclaration, f as CommitDeclaration, g as EffectHandlerContext, F as FeedPublishTransport, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, h as RecordObjectOptions, i as ManifestContent, j as CommitTransitionInvocation, S as SessionHeapEntry, k as SessionHeapList, l as FeedItem, m as SessionHeapSnapshot, n as Prompt, o as SessionTranscriptEntry } from './spend-B-IQmp7F.mjs';
3
+ export { eh as APIError, aS as AccessTokenProvider, Y as ActionSuggestionFeedItem, aZ as AdoptEnvironmentOptions, bK as AgentCommitStatus, cN as ArtifactApprovalDecisionInput, cO as ArtifactApprovalDecisionResult, cL as ArtifactApprovalTask, cM as ArtifactApprovalTaskListOptions, cK as ArtifactApprovalTaskStatus, U as ArtifactFeedItem, b_ as ArtifactOptionsHandler, bj as Assignment, bk as AssignmentListResponse, cm as AssistantReplyPublicationInput, cn as AssistantReplyPublicationResult, bH as BaseProjectionResult, bt as Build, bv as BuildListResponse, bl as BuildPolicy, bs as BuildStatus, bC as CanonicalProjectedRecord, bL as CommitChangeReceipt, bA as CommitSafeError, bM as CommitTransitionReceipt, aO as ConditionIR, a_ as ConnectOptions, b0 as ConversationSessionInfo, b2 as ConversationSessionListOptions, b3 as ConversationSessionListResponse, b1 as ConversationSessionListStatus, bo as CreateEnvironmentData, bh as CreatePermissionProfileData, bd as CreateSandboxData, a$ as CreateSessionOptions, dr as DefineRelationshipOptions, ei as DeleteResponse, D as DomainState, bW as EffectArtifactOptionsInvocation, bY as EffectArtifactRelationshipOption, bZ as EffectArtifactRelationshipOptionsResult, bQ as EffectCommitContext, c7 as EffectHandler, c4 as EffectInfo, bX as EffectInvocationMetadata, bV as EffectInvocationMode, bI as EffectProjectionResult, b$ as EffectSchema, c2 as EffectVersionSelector, c0 as EffectWithHandler, c6 as EffectsChangedEvent, cf as EnvironmentFeedbackRecord, dO as EnvironmentImporter, dN as EnvironmentImporterImportOptions, bp as EnvironmentListResponse, dM as EnvironmentSetupImporterClaim, dK as EnvironmentSetupLifecycleStatus, dL as EnvironmentSetupSummary, dI as EnvironmentSetupTriggerReason, dw as EnvironmentStateMachineProxy, du as EnvironmentStateObservationInput, dx as EnvironmentStateProxy, dt as EnvironmentStateTarget, dv as EnvironmentStateUpdateInput, bN as ExternalCommitOptions, ac as FeedDiagnostic, ad as FeedDiagnosticListener, ak as FeedDocumentState, v as FeedFeedbackTone, V as FeedFileSource, u as FeedIconToken, z as FeedItemBase, x as FeedItemKind, a3 as FeedListOptions, aa as FeedListTransport, G as FeedObjectReference, a4 as FeedPage, av as FeedPublisher, a2 as FeedSnapshot, ab as FeedSnapshotRegressionReason, t as FeedSource, s as FeedSourceActor, a5 as FeedSubscribeOptions, a6 as FeedSubscriptionChange, H as FeedTableCell, J as FeedTableColumn, N as FeedTableProjection, L as FeedTableRow, K as FeedTableRowReference, y as FeedTarget, w as FeedTransientFeedbackTone, B as FeedbackFeedItem, W as FileFeedItem, ae as GRANULAR_FEED_DIAGNOSTIC_EVENT, aU as GranularAuth, aT as GranularOptions, ba as GranularQuotaPolicy, bb as GranularQuotaProgress, aE as GranularSpendContext, eg as GraphQLResult, c8 as InstanceEffectHandler, I as InstanceToolHandler, ch as Job, cd as JobFeedbackInput, cc as JobFeedbackMetadata, ce as JobFeedbackRecord, ca as JobFeedbackSentiment, cb as JobFeedbackToolCall, c9 as JobStatus, cg as JobSubmitResult, bq as Manifest, e6 as ManifestApprovalRequiredSpec, e7 as ManifestCreatesSpec, e4 as ManifestDryRunSpec, ea as ManifestEffectDeclaration, e9 as ManifestEffectSchema, dR as ManifestEnumRuleSpec, ec as ManifestEventStreamDef, eb as ManifestEventTypeDef, dS as ManifestFilterBySpec, ee as ManifestImport, br as ManifestListResponse, ed as ManifestOperation, e3 as ManifestPostConditionSpec, dP as ManifestPropertySpec, e8 as ManifestRelationshipDef, e5 as ManifestReverseSpec, e2 as ManifestStateMachineSpec, dU as ManifestStateMachineStateSpec, e1 as ManifestStateMachineTransitionSpec, dW as ManifestStateTransitionActionSpec, dX as ManifestStateTransitionAssigneeSpec, d$ as ManifestStateTransitionExpectedOutcomeSpec, dV as ManifestStateTransitionInputBinding, e0 as ManifestStateTransitionOutcomeSpec, d_ as ManifestStateTransitionPermissionSpec, dY as ManifestStateTransitionRelatedStateRequirementSpec, dZ as ManifestStateTransitionRequirementsSpec, dQ as ManifestValidationOperator, dT as ManifestValidationRuleSpec, ef as ManifestVolume, cW as ManualActionListOptions, cU as ManualActionOccurrence, cV as ManualActionRecordResult, cS as ManualActionRelatedRecord, cQ as ManualActionSource, cP as ManualActionStatus, cX as ManualActionSuggestion, cY as ManualActionSuggestionOptions, cR as ManualActionTarget, de as MarkUserEnvironmentReadOptions, aR as MatchedPolicy, A as MessageFeedItem, dp as ModelRef, ay as NormalizedOpenAIUsage, X as NormalizedSuggestedArtifact, aA as OPENAI_MODEL_PRICING_USD_PER_MILLION, bD as ObjectProjectionChange, by as ObjectReference, O as ObjectsFeedItem, bO as ObservationReceipt, ax as OpenAIModelPricing, az as OpenAITokenSpend, aF as OpenAIUsageSpendEvent, aY as OpenEnvironmentOptions, bg as PermissionProfile, bi as PermissionProfileListResponse, bf as PermissionRules, aN as PolicyOperator, aP as PolicyOrigin, aM as PolicyPredicateSource, aQ as PolicyRuleIR, aL as PolicySource, bG as ProjectionChange, Z as PromptFeedItem, c1 as PublishEffectsResult, ar as PublishFeedbackOptions, q as PublishToolsResult, as as PublishTransientFeedbackOptions, b9 as QuotaLineItemFilter, b6 as QuotaPeriod, b5 as QuotaScopeType, b7 as QuotaStatus, di as RPCRequest, dl as RPCRequestFromServer, dj as RPCResponse, dH as RecordImport, dG as RecordImportItem, dE as RecordImportItemStatus, dC as RecordImportOptions, dF as RecordImportStats, dD as RecordImportStatus, dB as RecordImportWriteMode, cT as RecordManualActionInput, d4 as RecordMentionInput, dy as RecordObjectResult, ds as RecordObjectStateValue, dz as RecordObjectsChunkInfo, dA as RecordObjectsOptions, aG as RecordOpenAIUsageSpendOptions, aH as RecordOpenAIUsageSpendResult, d3 as RecordSearchOptions, d2 as RecordSearchResult, aW as RecordUserOptions, dq as RelationshipInfo, bE as RelationshipProjectionChange, bU as ResolvedEffectApprovalRequired, bS as ResolvedEffectDryRun, bR as ResolvedEffectPostCondition, bT as ResolvedEffectReverse, dJ as RunEnvironmentImporterOptions, bc as Sandbox, be as SandboxListResponse, bx as SemanticVersionDiff, bw as SemanticVersionDiffEntry, cJ as SessionArtifactApprovalOptions, cx as SessionArtifactAutonomyPolicy, cI as SessionArtifactExecutionOptions, cH as SessionArtifactExecutionResult, cz as SessionArtifactFieldProvenance, cy as SessionArtifactFieldProvenanceSource, cw as SessionArtifactKind, cB as SessionArtifactListOptions, cA as SessionArtifactRecord, cG as SessionArtifactRelationshipCreateInput, cE as SessionArtifactRelationshipOption, cD as SessionArtifactRelationshipOptionsInput, cF as SessionArtifactRelationshipOptionsResult, cv as SessionArtifactStatus, cC as SessionArtifactValidationResult, d6 as SessionCollectionListOptions, d8 as SessionCollectionListResult, d5 as SessionDocumentResult, a7 as SessionFeedApi, aq as SessionFeedController, aj as SessionFeedControllerOptions, cs as SessionFileKind, cu as SessionFileRecord, cr as SessionFileSource, ct as SessionFileStatus, cZ as SessionFileUploadOptions, c$ as SessionHeapFieldType, d0 as SessionHeapFieldValue, d1 as SessionHeapVariable, d7 as SessionJobListOptions, c_ as SessionJobRecord, bP as SessionMutationView, cq as SessionTimelineEvent, co as SessionTranscriptActionSuggestion, cp as SessionTranscriptShowRefs, at as SettleTransientFeedbackOptions, dk as SnapshotResetMessage, bz as SourceAcknowledgement, b4 as SpendLineItemType, b8 as SpendSummary, bF as StateObservationProjectionChange, ej as StreamEvent, el as StreamStats, ek as StreamSubscription, aX as Subject, Q as TableFeedItem, r as ToolHandler, c3 as ToolInfo, dm as ToolInvokeParams, dn as ToolResultParams, p as ToolSchema, c5 as ToolsChangedEvent, a1 as TransientFeedItem, _ as TransientFeedItemBase, a0 as TransientFeedbackFeedItem, au as TransientFeedbackHandle, $ as TransientMessageFeedItem, bB as TransitionOutcomeProjection, bJ as TransitionProjectionResult, aV as User, da as UserEnvironmentMessagePreview, d9 as UserEnvironmentPrompt, db as UserEnvironmentSessionState, dc as UserEnvironmentState, dd as UserEnvironmentStateOptions, cl as UserMessageAppendResult, ck as UserMessageInput, ci as UserMessageShowRefs, cj as UserMessageTarget, bu as Version, bn as VersionTag, bm as VersionTracking, dh as WSClientOptions, df as WSDisconnectInfo, dg as WSReconnectErrorInfo, aJ as buildOpenAISpendEventId, aD as calculateOpenAITokenSpend, aw as createFeedPublisher, ai as emitFeedDiagnostic, ah as emitFeedDiagnosticToDefaultSink, al as emptyFeedSnapshot, aB as getOpenAIModelPricing, am as hasCanonicalSessionFeedActivation, an as isCanonicalSessionFeedDocument, a8 as mergeFeedItemsBySequence, ag as normalizeFeedDiagnostic, af as normalizeFeedDiagnosticKind, ap as normalizeFeedPage, aC as normalizeOpenAIUsage, a9 as orderTransientFeedItems, ao as readSessionFeedSnapshot, aK as recordOpenAIUsageSpend, aI as toGranularHttpBase } from './spend-B-IQmp7F.mjs';
4
4
  export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentManualActionMemorySuggestion, GranularAgentPromptCapabilities, GranularAgentReferentFocus, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, GranularReasoningTraceChunkResult, GranularReasoningTraceOptions, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessRenderedContinuation, HarnessRenderedPrompt, HarnessTemplate, HarnessTemplateManifest, HarnessTemplateSelectionOptions, HarnessTemplateStatus, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, ReviewGeneratedJobCodeOptions, buildContinuationInstruction, buildContinuationInstructionFromTemplate, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentFileBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentManualActionBlock, buildGranularAgentManualActionMemorySummary, buildGranularAgentReferentBlock, buildGranularAgentRuntimeImportsBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentSystemPromptFromTemplate, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getDefaultHarnessTemplateId, getExclusivePromptTarget, hasOpenPrompt, hashHarnessTemplateValue, listHarnessTemplates, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectSessionFileSummary, projectWorkflowFocus, projectWorkflowSummary, renderContinuationInstructionFromTemplate, renderGranularAgentSystemPromptFromTemplate, resolveHarnessTemplate, reviewGeneratedJobCode, stripGranularReasoningTrace, validateHarnessTemplateManifest } from './agent-harness.mjs';
5
5
  import '@automerge/automerge';
6
6
  import '@automerge/automerge/slim';
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { E as Environment, a as EnvironmentSession, G as Granular, O as OntologyHandle, S as Session, W as WSClient, i as isGraphQLMutationDocument } from './client-C-GYQSJC.js';
2
- import { E as EnvironmentData, a as EnvironmentRecordImportSummary, b as EndpointMode, c as EffectCommitRequest, C as CommitReceipt, T as ToolWithHandler, P as ProjectionResult, d as ProjectionMapper, e as CommitTransitionOutcomeDeclaration, f as CommitDeclaration, g as EffectHandlerContext, F as FeedPublishTransport, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, h as RecordObjectOptions, i as ManifestContent, j as CommitTransitionInvocation, S as SessionHeapEntry, k as SessionHeapList, l as FeedItem, m as SessionHeapSnapshot, n as Prompt, o as SessionTranscriptEntry } from './spend-BDGtgZtl.js';
3
- export { ef as APIError, aS as AccessTokenProvider, Y as ActionSuggestionFeedItem, aZ as AdoptEnvironmentOptions, bK as AgentCommitStatus, cL as ArtifactApprovalDecisionInput, cM as ArtifactApprovalDecisionResult, cJ as ArtifactApprovalTask, cK as ArtifactApprovalTaskListOptions, cI as ArtifactApprovalTaskStatus, U as ArtifactFeedItem, b_ as ArtifactOptionsHandler, bj as Assignment, bk as AssignmentListResponse, cm as AssistantReplyPublicationInput, cn as AssistantReplyPublicationResult, bH as BaseProjectionResult, bt as Build, bv as BuildListResponse, bl as BuildPolicy, bs as BuildStatus, bC as CanonicalProjectedRecord, bL as CommitChangeReceipt, bA as CommitSafeError, bM as CommitTransitionReceipt, aO as ConditionIR, a_ as ConnectOptions, b0 as ConversationSessionInfo, b2 as ConversationSessionListOptions, b3 as ConversationSessionListResponse, b1 as ConversationSessionListStatus, bo as CreateEnvironmentData, bh as CreatePermissionProfileData, bd as CreateSandboxData, a$ as CreateSessionOptions, dp as DefineRelationshipOptions, eg as DeleteResponse, D as DomainState, bW as EffectArtifactOptionsInvocation, bY as EffectArtifactRelationshipOption, bZ as EffectArtifactRelationshipOptionsResult, bQ as EffectCommitContext, c7 as EffectHandler, c4 as EffectInfo, bX as EffectInvocationMetadata, bV as EffectInvocationMode, bI as EffectProjectionResult, b$ as EffectSchema, c2 as EffectVersionSelector, c0 as EffectWithHandler, c6 as EffectsChangedEvent, cf as EnvironmentFeedbackRecord, dM as EnvironmentImporter, dL as EnvironmentImporterImportOptions, bp as EnvironmentListResponse, dK as EnvironmentSetupImporterClaim, dI as EnvironmentSetupLifecycleStatus, dJ as EnvironmentSetupSummary, dG as EnvironmentSetupTriggerReason, du as EnvironmentStateMachineProxy, ds as EnvironmentStateObservationInput, dv as EnvironmentStateProxy, dr as EnvironmentStateTarget, dt as EnvironmentStateUpdateInput, bN as ExternalCommitOptions, ac as FeedDiagnostic, ad as FeedDiagnosticListener, ak as FeedDocumentState, v as FeedFeedbackTone, V as FeedFileSource, u as FeedIconToken, z as FeedItemBase, x as FeedItemKind, a3 as FeedListOptions, aa as FeedListTransport, G as FeedObjectReference, a4 as FeedPage, av as FeedPublisher, a2 as FeedSnapshot, ab as FeedSnapshotRegressionReason, t as FeedSource, s as FeedSourceActor, a5 as FeedSubscribeOptions, a6 as FeedSubscriptionChange, H as FeedTableCell, J as FeedTableColumn, N as FeedTableProjection, L as FeedTableRow, K as FeedTableRowReference, y as FeedTarget, w as FeedTransientFeedbackTone, B as FeedbackFeedItem, W as FileFeedItem, ae as GRANULAR_FEED_DIAGNOSTIC_EVENT, aU as GranularAuth, aT as GranularOptions, ba as GranularQuotaPolicy, bb as GranularQuotaProgress, aE as GranularSpendContext, ee as GraphQLResult, c8 as InstanceEffectHandler, I as InstanceToolHandler, ch as Job, cd as JobFeedbackInput, cc as JobFeedbackMetadata, ce as JobFeedbackRecord, ca as JobFeedbackSentiment, cb as JobFeedbackToolCall, c9 as JobStatus, cg as JobSubmitResult, bq as Manifest, e4 as ManifestApprovalRequiredSpec, e5 as ManifestCreatesSpec, e2 as ManifestDryRunSpec, e8 as ManifestEffectDeclaration, e7 as ManifestEffectSchema, dP as ManifestEnumRuleSpec, ea as ManifestEventStreamDef, e9 as ManifestEventTypeDef, dQ as ManifestFilterBySpec, ec as ManifestImport, br as ManifestListResponse, eb as ManifestOperation, e1 as ManifestPostConditionSpec, dN as ManifestPropertySpec, e6 as ManifestRelationshipDef, e3 as ManifestReverseSpec, e0 as ManifestStateMachineSpec, dS as ManifestStateMachineStateSpec, d$ as ManifestStateMachineTransitionSpec, dU as ManifestStateTransitionActionSpec, dV as ManifestStateTransitionAssigneeSpec, dZ as ManifestStateTransitionExpectedOutcomeSpec, dT as ManifestStateTransitionInputBinding, d_ as ManifestStateTransitionOutcomeSpec, dY as ManifestStateTransitionPermissionSpec, dW as ManifestStateTransitionRelatedStateRequirementSpec, dX as ManifestStateTransitionRequirementsSpec, dO as ManifestValidationOperator, dR as ManifestValidationRuleSpec, ed as ManifestVolume, cU as ManualActionListOptions, cS as ManualActionOccurrence, cT as ManualActionRecordResult, cQ as ManualActionRelatedRecord, cO as ManualActionSource, cN as ManualActionStatus, cV as ManualActionSuggestion, cW as ManualActionSuggestionOptions, cP as ManualActionTarget, dc as MarkUserEnvironmentReadOptions, aR as MatchedPolicy, A as MessageFeedItem, dm as ModelRef, ay as NormalizedOpenAIUsage, X as NormalizedSuggestedArtifact, aA as OPENAI_MODEL_PRICING_USD_PER_MILLION, bD as ObjectProjectionChange, by as ObjectReference, O as ObjectsFeedItem, bO as ObservationReceipt, ax as OpenAIModelPricing, az as OpenAITokenSpend, aF as OpenAIUsageSpendEvent, aY as OpenEnvironmentOptions, bg as PermissionProfile, bi as PermissionProfileListResponse, bf as PermissionRules, aN as PolicyOperator, aP as PolicyOrigin, aM as PolicyPredicateSource, aQ as PolicyRuleIR, aL as PolicySource, bG as ProjectionChange, Z as PromptFeedItem, c1 as PublishEffectsResult, ar as PublishFeedbackOptions, q as PublishToolsResult, as as PublishTransientFeedbackOptions, b9 as QuotaLineItemFilter, b6 as QuotaPeriod, b5 as QuotaScopeType, b7 as QuotaStatus, dg as RPCRequest, dj as RPCRequestFromServer, dh as RPCResponse, dF as RecordImport, dE as RecordImportItem, dC as RecordImportItemStatus, dA as RecordImportOptions, dD as RecordImportStats, dB as RecordImportStatus, dz as RecordImportWriteMode, cR as RecordManualActionInput, d2 as RecordMentionInput, dw as RecordObjectResult, dq as RecordObjectStateValue, dx as RecordObjectsChunkInfo, dy as RecordObjectsOptions, aG as RecordOpenAIUsageSpendOptions, aH as RecordOpenAIUsageSpendResult, d1 as RecordSearchOptions, d0 as RecordSearchResult, aW as RecordUserOptions, dn as RelationshipInfo, bE as RelationshipProjectionChange, bU as ResolvedEffectApprovalRequired, bS as ResolvedEffectDryRun, bR as ResolvedEffectPostCondition, bT as ResolvedEffectReverse, dH as RunEnvironmentImporterOptions, bc as Sandbox, be as SandboxListResponse, bx as SemanticVersionDiff, bw as SemanticVersionDiffEntry, cH as SessionArtifactApprovalOptions, cx as SessionArtifactAutonomyPolicy, cG as SessionArtifactExecutionOptions, cF as SessionArtifactExecutionResult, cw as SessionArtifactKind, cz as SessionArtifactListOptions, cy as SessionArtifactRecord, cE as SessionArtifactRelationshipCreateInput, cC as SessionArtifactRelationshipOption, cB as SessionArtifactRelationshipOptionsInput, cD as SessionArtifactRelationshipOptionsResult, cv as SessionArtifactStatus, cA as SessionArtifactValidationResult, d4 as SessionCollectionListOptions, d6 as SessionCollectionListResult, d3 as SessionDocumentResult, a7 as SessionFeedApi, aq as SessionFeedController, aj as SessionFeedControllerOptions, cs as SessionFileKind, cu as SessionFileRecord, cr as SessionFileSource, ct as SessionFileStatus, cX as SessionFileUploadOptions, cZ as SessionHeapFieldType, c_ as SessionHeapFieldValue, c$ as SessionHeapVariable, d5 as SessionJobListOptions, cY as SessionJobRecord, bP as SessionMutationView, cq as SessionTimelineEvent, co as SessionTranscriptActionSuggestion, cp as SessionTranscriptShowRefs, at as SettleTransientFeedbackOptions, di as SnapshotResetMessage, bz as SourceAcknowledgement, b4 as SpendLineItemType, b8 as SpendSummary, bF as StateObservationProjectionChange, eh as StreamEvent, ej as StreamStats, ei as StreamSubscription, aX as Subject, Q as TableFeedItem, r as ToolHandler, c3 as ToolInfo, dk as ToolInvokeParams, dl as ToolResultParams, p as ToolSchema, c5 as ToolsChangedEvent, a1 as TransientFeedItem, _ as TransientFeedItemBase, a0 as TransientFeedbackFeedItem, au as TransientFeedbackHandle, $ as TransientMessageFeedItem, bB as TransitionOutcomeProjection, bJ as TransitionProjectionResult, aV as User, d8 as UserEnvironmentMessagePreview, d7 as UserEnvironmentPrompt, d9 as UserEnvironmentSessionState, da as UserEnvironmentState, db as UserEnvironmentStateOptions, cl as UserMessageAppendResult, ck as UserMessageInput, ci as UserMessageShowRefs, cj as UserMessageTarget, bu as Version, bn as VersionTag, bm as VersionTracking, df as WSClientOptions, dd as WSDisconnectInfo, de as WSReconnectErrorInfo, aJ as buildOpenAISpendEventId, aD as calculateOpenAITokenSpend, aw as createFeedPublisher, ai as emitFeedDiagnostic, ah as emitFeedDiagnosticToDefaultSink, al as emptyFeedSnapshot, aB as getOpenAIModelPricing, am as hasCanonicalSessionFeedActivation, an as isCanonicalSessionFeedDocument, a8 as mergeFeedItemsBySequence, ag as normalizeFeedDiagnostic, af as normalizeFeedDiagnosticKind, ap as normalizeFeedPage, aC as normalizeOpenAIUsage, a9 as orderTransientFeedItems, ao as readSessionFeedSnapshot, aK as recordOpenAIUsageSpend, aI as toGranularHttpBase } from './spend-BDGtgZtl.js';
1
+ export { E as Environment, a as EnvironmentSession, G as Granular, O as OntologyHandle, S as Session, W as WSClient, i as isGraphQLMutationDocument } from './client-D1gq4TO4.js';
2
+ import { E as EnvironmentData, a as EnvironmentRecordImportSummary, b as EndpointMode, c as EffectCommitRequest, C as CommitReceipt, T as ToolWithHandler, P as ProjectionResult, d as ProjectionMapper, e as CommitTransitionOutcomeDeclaration, f as CommitDeclaration, g as EffectHandlerContext, F as FeedPublishTransport, M as ManifestEffectMetamodelSpec, R as ResolvedEffectBehaviors, h as RecordObjectOptions, i as ManifestContent, j as CommitTransitionInvocation, S as SessionHeapEntry, k as SessionHeapList, l as FeedItem, m as SessionHeapSnapshot, n as Prompt, o as SessionTranscriptEntry } from './spend-B-IQmp7F.js';
3
+ export { eh as APIError, aS as AccessTokenProvider, Y as ActionSuggestionFeedItem, aZ as AdoptEnvironmentOptions, bK as AgentCommitStatus, cN as ArtifactApprovalDecisionInput, cO as ArtifactApprovalDecisionResult, cL as ArtifactApprovalTask, cM as ArtifactApprovalTaskListOptions, cK as ArtifactApprovalTaskStatus, U as ArtifactFeedItem, b_ as ArtifactOptionsHandler, bj as Assignment, bk as AssignmentListResponse, cm as AssistantReplyPublicationInput, cn as AssistantReplyPublicationResult, bH as BaseProjectionResult, bt as Build, bv as BuildListResponse, bl as BuildPolicy, bs as BuildStatus, bC as CanonicalProjectedRecord, bL as CommitChangeReceipt, bA as CommitSafeError, bM as CommitTransitionReceipt, aO as ConditionIR, a_ as ConnectOptions, b0 as ConversationSessionInfo, b2 as ConversationSessionListOptions, b3 as ConversationSessionListResponse, b1 as ConversationSessionListStatus, bo as CreateEnvironmentData, bh as CreatePermissionProfileData, bd as CreateSandboxData, a$ as CreateSessionOptions, dr as DefineRelationshipOptions, ei as DeleteResponse, D as DomainState, bW as EffectArtifactOptionsInvocation, bY as EffectArtifactRelationshipOption, bZ as EffectArtifactRelationshipOptionsResult, bQ as EffectCommitContext, c7 as EffectHandler, c4 as EffectInfo, bX as EffectInvocationMetadata, bV as EffectInvocationMode, bI as EffectProjectionResult, b$ as EffectSchema, c2 as EffectVersionSelector, c0 as EffectWithHandler, c6 as EffectsChangedEvent, cf as EnvironmentFeedbackRecord, dO as EnvironmentImporter, dN as EnvironmentImporterImportOptions, bp as EnvironmentListResponse, dM as EnvironmentSetupImporterClaim, dK as EnvironmentSetupLifecycleStatus, dL as EnvironmentSetupSummary, dI as EnvironmentSetupTriggerReason, dw as EnvironmentStateMachineProxy, du as EnvironmentStateObservationInput, dx as EnvironmentStateProxy, dt as EnvironmentStateTarget, dv as EnvironmentStateUpdateInput, bN as ExternalCommitOptions, ac as FeedDiagnostic, ad as FeedDiagnosticListener, ak as FeedDocumentState, v as FeedFeedbackTone, V as FeedFileSource, u as FeedIconToken, z as FeedItemBase, x as FeedItemKind, a3 as FeedListOptions, aa as FeedListTransport, G as FeedObjectReference, a4 as FeedPage, av as FeedPublisher, a2 as FeedSnapshot, ab as FeedSnapshotRegressionReason, t as FeedSource, s as FeedSourceActor, a5 as FeedSubscribeOptions, a6 as FeedSubscriptionChange, H as FeedTableCell, J as FeedTableColumn, N as FeedTableProjection, L as FeedTableRow, K as FeedTableRowReference, y as FeedTarget, w as FeedTransientFeedbackTone, B as FeedbackFeedItem, W as FileFeedItem, ae as GRANULAR_FEED_DIAGNOSTIC_EVENT, aU as GranularAuth, aT as GranularOptions, ba as GranularQuotaPolicy, bb as GranularQuotaProgress, aE as GranularSpendContext, eg as GraphQLResult, c8 as InstanceEffectHandler, I as InstanceToolHandler, ch as Job, cd as JobFeedbackInput, cc as JobFeedbackMetadata, ce as JobFeedbackRecord, ca as JobFeedbackSentiment, cb as JobFeedbackToolCall, c9 as JobStatus, cg as JobSubmitResult, bq as Manifest, e6 as ManifestApprovalRequiredSpec, e7 as ManifestCreatesSpec, e4 as ManifestDryRunSpec, ea as ManifestEffectDeclaration, e9 as ManifestEffectSchema, dR as ManifestEnumRuleSpec, ec as ManifestEventStreamDef, eb as ManifestEventTypeDef, dS as ManifestFilterBySpec, ee as ManifestImport, br as ManifestListResponse, ed as ManifestOperation, e3 as ManifestPostConditionSpec, dP as ManifestPropertySpec, e8 as ManifestRelationshipDef, e5 as ManifestReverseSpec, e2 as ManifestStateMachineSpec, dU as ManifestStateMachineStateSpec, e1 as ManifestStateMachineTransitionSpec, dW as ManifestStateTransitionActionSpec, dX as ManifestStateTransitionAssigneeSpec, d$ as ManifestStateTransitionExpectedOutcomeSpec, dV as ManifestStateTransitionInputBinding, e0 as ManifestStateTransitionOutcomeSpec, d_ as ManifestStateTransitionPermissionSpec, dY as ManifestStateTransitionRelatedStateRequirementSpec, dZ as ManifestStateTransitionRequirementsSpec, dQ as ManifestValidationOperator, dT as ManifestValidationRuleSpec, ef as ManifestVolume, cW as ManualActionListOptions, cU as ManualActionOccurrence, cV as ManualActionRecordResult, cS as ManualActionRelatedRecord, cQ as ManualActionSource, cP as ManualActionStatus, cX as ManualActionSuggestion, cY as ManualActionSuggestionOptions, cR as ManualActionTarget, de as MarkUserEnvironmentReadOptions, aR as MatchedPolicy, A as MessageFeedItem, dp as ModelRef, ay as NormalizedOpenAIUsage, X as NormalizedSuggestedArtifact, aA as OPENAI_MODEL_PRICING_USD_PER_MILLION, bD as ObjectProjectionChange, by as ObjectReference, O as ObjectsFeedItem, bO as ObservationReceipt, ax as OpenAIModelPricing, az as OpenAITokenSpend, aF as OpenAIUsageSpendEvent, aY as OpenEnvironmentOptions, bg as PermissionProfile, bi as PermissionProfileListResponse, bf as PermissionRules, aN as PolicyOperator, aP as PolicyOrigin, aM as PolicyPredicateSource, aQ as PolicyRuleIR, aL as PolicySource, bG as ProjectionChange, Z as PromptFeedItem, c1 as PublishEffectsResult, ar as PublishFeedbackOptions, q as PublishToolsResult, as as PublishTransientFeedbackOptions, b9 as QuotaLineItemFilter, b6 as QuotaPeriod, b5 as QuotaScopeType, b7 as QuotaStatus, di as RPCRequest, dl as RPCRequestFromServer, dj as RPCResponse, dH as RecordImport, dG as RecordImportItem, dE as RecordImportItemStatus, dC as RecordImportOptions, dF as RecordImportStats, dD as RecordImportStatus, dB as RecordImportWriteMode, cT as RecordManualActionInput, d4 as RecordMentionInput, dy as RecordObjectResult, ds as RecordObjectStateValue, dz as RecordObjectsChunkInfo, dA as RecordObjectsOptions, aG as RecordOpenAIUsageSpendOptions, aH as RecordOpenAIUsageSpendResult, d3 as RecordSearchOptions, d2 as RecordSearchResult, aW as RecordUserOptions, dq as RelationshipInfo, bE as RelationshipProjectionChange, bU as ResolvedEffectApprovalRequired, bS as ResolvedEffectDryRun, bR as ResolvedEffectPostCondition, bT as ResolvedEffectReverse, dJ as RunEnvironmentImporterOptions, bc as Sandbox, be as SandboxListResponse, bx as SemanticVersionDiff, bw as SemanticVersionDiffEntry, cJ as SessionArtifactApprovalOptions, cx as SessionArtifactAutonomyPolicy, cI as SessionArtifactExecutionOptions, cH as SessionArtifactExecutionResult, cz as SessionArtifactFieldProvenance, cy as SessionArtifactFieldProvenanceSource, cw as SessionArtifactKind, cB as SessionArtifactListOptions, cA as SessionArtifactRecord, cG as SessionArtifactRelationshipCreateInput, cE as SessionArtifactRelationshipOption, cD as SessionArtifactRelationshipOptionsInput, cF as SessionArtifactRelationshipOptionsResult, cv as SessionArtifactStatus, cC as SessionArtifactValidationResult, d6 as SessionCollectionListOptions, d8 as SessionCollectionListResult, d5 as SessionDocumentResult, a7 as SessionFeedApi, aq as SessionFeedController, aj as SessionFeedControllerOptions, cs as SessionFileKind, cu as SessionFileRecord, cr as SessionFileSource, ct as SessionFileStatus, cZ as SessionFileUploadOptions, c$ as SessionHeapFieldType, d0 as SessionHeapFieldValue, d1 as SessionHeapVariable, d7 as SessionJobListOptions, c_ as SessionJobRecord, bP as SessionMutationView, cq as SessionTimelineEvent, co as SessionTranscriptActionSuggestion, cp as SessionTranscriptShowRefs, at as SettleTransientFeedbackOptions, dk as SnapshotResetMessage, bz as SourceAcknowledgement, b4 as SpendLineItemType, b8 as SpendSummary, bF as StateObservationProjectionChange, ej as StreamEvent, el as StreamStats, ek as StreamSubscription, aX as Subject, Q as TableFeedItem, r as ToolHandler, c3 as ToolInfo, dm as ToolInvokeParams, dn as ToolResultParams, p as ToolSchema, c5 as ToolsChangedEvent, a1 as TransientFeedItem, _ as TransientFeedItemBase, a0 as TransientFeedbackFeedItem, au as TransientFeedbackHandle, $ as TransientMessageFeedItem, bB as TransitionOutcomeProjection, bJ as TransitionProjectionResult, aV as User, da as UserEnvironmentMessagePreview, d9 as UserEnvironmentPrompt, db as UserEnvironmentSessionState, dc as UserEnvironmentState, dd as UserEnvironmentStateOptions, cl as UserMessageAppendResult, ck as UserMessageInput, ci as UserMessageShowRefs, cj as UserMessageTarget, bu as Version, bn as VersionTag, bm as VersionTracking, dh as WSClientOptions, df as WSDisconnectInfo, dg as WSReconnectErrorInfo, aJ as buildOpenAISpendEventId, aD as calculateOpenAITokenSpend, aw as createFeedPublisher, ai as emitFeedDiagnostic, ah as emitFeedDiagnosticToDefaultSink, al as emptyFeedSnapshot, aB as getOpenAIModelPricing, am as hasCanonicalSessionFeedActivation, an as isCanonicalSessionFeedDocument, a8 as mergeFeedItemsBySequence, ag as normalizeFeedDiagnostic, af as normalizeFeedDiagnosticKind, ap as normalizeFeedPage, aC as normalizeOpenAIUsage, a9 as orderTransientFeedItems, ao as readSessionFeedSnapshot, aK as recordOpenAIUsageSpend, aI as toGranularHttpBase } from './spend-B-IQmp7F.js';
4
4
  export { BuildGranularAgentSystemPromptInput, GeneratedJobCodeIssue, GranularAgentExecutionCheckpoint, GranularAgentHeapSummaryOptions, GranularAgentManualActionMemorySuggestion, GranularAgentPromptCapabilities, GranularAgentReferentFocus, GranularAgentSessionContext, GranularAgentToolInfo, GranularAgentWorkflowFocus, GranularReasoningTraceChunkResult, GranularReasoningTraceOptions, HarnessContinuationDecision, HarnessControllerBudgets, HarnessProjectionOptions, HarnessPromptLike, HarnessRenderedContinuation, HarnessRenderedPrompt, HarnessTemplate, HarnessTemplateManifest, HarnessTemplateSelectionOptions, HarnessTemplateStatus, HarnessVerifierSnapshot, HarnessVerifierSnapshotInput, ReviewGeneratedJobCodeOptions, buildContinuationInstruction, buildContinuationInstructionFromTemplate, buildGranularAgentCheckpointBlock, buildGranularAgentDomainBlock, buildGranularAgentFileBlock, buildGranularAgentHeapBlock, buildGranularAgentLoopBlock, buildGranularAgentManualActionBlock, buildGranularAgentManualActionMemorySummary, buildGranularAgentReferentBlock, buildGranularAgentRuntimeImportsBlock, buildGranularAgentSessionBlock, buildGranularAgentSystemPrompt, buildGranularAgentSystemPromptFromTemplate, buildGranularAgentToolBlock, buildGranularAgentWorkflowBlock, consumeGranularReasoningOnlyChunk, consumeGranularReasoningTraceChunk, createHarnessVerifierSnapshot, evaluateContinuation, getCurrentClosureId, getDefaultHarnessTemplateId, getExclusivePromptTarget, hasOpenPrompt, hashHarnessTemplateValue, listHarnessTemplates, projectConversationReferentFocus, projectConversationReferentSummary, projectHeapSummary, projectLoopSummary, projectSessionFileSummary, projectWorkflowFocus, projectWorkflowSummary, renderContinuationInstructionFromTemplate, renderGranularAgentSystemPromptFromTemplate, resolveHarnessTemplate, reviewGeneratedJobCode, stripGranularReasoningTrace, validateHarnessTemplateManifest } from './agent-harness.js';
5
5
  import '@automerge/automerge';
6
6
  import '@automerge/automerge/slim';