@tangle-network/agent-app 0.50.5 → 0.50.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assistant/index.js +1 -1
- package/dist/chat-routes/index.js +19 -9
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/chat-routes/sandbox-producer.d.ts +4 -0
- package/dist/{chunk-DEXBRUZR.js → chunk-63EKFZOE.js} +31 -5
- package/dist/chunk-63EKFZOE.js.map +1 -0
- package/dist/model-resolution/failover.d.ts +6 -0
- package/dist/model-resolution/index.js +1 -1
- package/dist/teams/index.js +5 -5
- package/dist/teams/invitations-api.js +4 -4
- package/dist/web-react/index.js +3 -3
- package/dist/workspace-apps/index.d.ts +66 -0
- package/dist/workspace-apps/index.js +99 -0
- package/dist/workspace-apps/index.js.map +1 -0
- package/dist/workspace-react/index.d.ts +15 -1
- package/dist/workspace-react/index.js +28 -7
- package/dist/workspace-react/index.js.map +1 -1
- package/package.json +6 -1
- package/dist/chunk-DEXBRUZR.js.map +0 -1
|
@@ -145,6 +145,10 @@ export interface SandboxChatProducerOptions {
|
|
|
145
145
|
* outcomes; the promotion mechanics (vault write, key derivation, notice
|
|
146
146
|
* construction) live in the caller's callback, not here. */
|
|
147
147
|
promoteFilePart?: (raw: JsonRecord) => Promise<FilePartPromotionOutcome>;
|
|
148
|
+
/** Append terminal error explanations to assistant text. Default true.
|
|
149
|
+
* Set false when the application renders the structured error separately.
|
|
150
|
+
* Error events, diagnostics, partial answers and tool settlement remain available. */
|
|
151
|
+
includeErrorText?: boolean;
|
|
148
152
|
log?: (message: string, meta?: Record<string, unknown>) => void;
|
|
149
153
|
}
|
|
150
154
|
/** Create a sandbox chat producer that manages chat turn routing with logging and interaction rendering options */
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// src/model-resolution/failover.ts
|
|
2
2
|
var UPSTREAM_UNAVAILABLE_CODES = [
|
|
3
3
|
"provider_inference_unavailable",
|
|
4
|
+
"provider_quota_exhausted",
|
|
4
5
|
"upstream_unavailable",
|
|
5
6
|
"insufficient_quota",
|
|
6
7
|
"model_not_available",
|
|
@@ -51,14 +52,23 @@ function readString(source, key) {
|
|
|
51
52
|
const value = source[key];
|
|
52
53
|
return typeof value === "string" && value.trim().length > 0 ? value : void 0;
|
|
53
54
|
}
|
|
55
|
+
function readUpstreamUnavailableCode(signal) {
|
|
56
|
+
if (signal === null || typeof signal !== "object") return void 0;
|
|
57
|
+
const record = signal;
|
|
58
|
+
const nested = record.error;
|
|
59
|
+
const nestedRecord = nested !== null && typeof nested === "object" ? nested : void 0;
|
|
60
|
+
const code = readString(record, "errorCode") ?? readString(record, "code") ?? (nestedRecord ? readString(nestedRecord, "code") ?? readString(nestedRecord, "type") : void 0);
|
|
61
|
+
if (code && UPSTREAM_UNAVAILABLE_CODES.includes(code)) return code;
|
|
62
|
+
const message = readString(record, "message") ?? readString(record, "error") ?? (nestedRecord ? readString(nestedRecord, "message") : void 0);
|
|
63
|
+
return message && /\(\s*provider_quota_exhausted\s*\)/i.test(message) ? "provider_quota_exhausted" : void 0;
|
|
64
|
+
}
|
|
54
65
|
function isUpstreamUnavailable(signal) {
|
|
55
66
|
if (signal === null || typeof signal !== "object") return false;
|
|
56
67
|
const record = signal;
|
|
57
68
|
if (record.success === true) return false;
|
|
58
69
|
const nested = record.error;
|
|
59
70
|
const nestedRecord = nested !== null && typeof nested === "object" ? nested : void 0;
|
|
60
|
-
|
|
61
|
-
if (code && UPSTREAM_UNAVAILABLE_CODES.includes(code)) return true;
|
|
71
|
+
if (readUpstreamUnavailableCode(record)) return true;
|
|
62
72
|
for (const key of ["status", "statusCode", "httpStatus"]) {
|
|
63
73
|
const value = record[key];
|
|
64
74
|
if (typeof value === "number" && UPSTREAM_UNAVAILABLE_STATUSES.includes(value)) return true;
|
|
@@ -75,11 +85,14 @@ function isUpstreamUnavailable(signal) {
|
|
|
75
85
|
}
|
|
76
86
|
var ModelFailoverExhaustedError = class extends Error {
|
|
77
87
|
attempts;
|
|
88
|
+
/** Last recognized upstream code across the exhausted chain, when present. */
|
|
89
|
+
upstreamCode;
|
|
78
90
|
constructor(attempts) {
|
|
79
91
|
const trail = attempts.map((a) => `${a.model}: ${a.reason ?? "failed"}`).join(" | ");
|
|
80
92
|
super(`All ${attempts.length} model(s) failed. ${trail}`);
|
|
81
93
|
this.name = "ModelFailoverExhaustedError";
|
|
82
94
|
this.attempts = attempts;
|
|
95
|
+
this.upstreamCode = [...attempts].reverse().find((attempt) => attempt.errorCode)?.errorCode;
|
|
83
96
|
}
|
|
84
97
|
};
|
|
85
98
|
function describe(signal) {
|
|
@@ -104,14 +117,26 @@ async function runWithModelFailover(input) {
|
|
|
104
117
|
result = await input.run(model);
|
|
105
118
|
} catch (error) {
|
|
106
119
|
if (!isUnavailableError(error)) throw error;
|
|
107
|
-
const
|
|
120
|
+
const errorCode = readUpstreamUnavailableCode(error);
|
|
121
|
+
const attempt = {
|
|
122
|
+
model,
|
|
123
|
+
ok: false,
|
|
124
|
+
reason: describe(error),
|
|
125
|
+
...errorCode ? { errorCode } : {}
|
|
126
|
+
};
|
|
108
127
|
attempts.push(attempt);
|
|
109
128
|
const next = models[index + 1];
|
|
110
129
|
if (next) input.onFallback?.(attempt, next);
|
|
111
130
|
continue;
|
|
112
131
|
}
|
|
113
132
|
if (isUnavailableResult(result)) {
|
|
114
|
-
const
|
|
133
|
+
const errorCode = readUpstreamUnavailableCode(result);
|
|
134
|
+
const attempt = {
|
|
135
|
+
model,
|
|
136
|
+
ok: false,
|
|
137
|
+
reason: describe(result),
|
|
138
|
+
...errorCode ? { errorCode } : {}
|
|
139
|
+
};
|
|
115
140
|
attempts.push(attempt);
|
|
116
141
|
const next = models[index + 1];
|
|
117
142
|
if (next) input.onFallback?.(attempt, next);
|
|
@@ -135,9 +160,10 @@ export {
|
|
|
135
160
|
UPSTREAM_UNAVAILABLE_CODES,
|
|
136
161
|
UPSTREAM_UNAVAILABLE_STATUSES,
|
|
137
162
|
readHttpStatusHint,
|
|
163
|
+
readUpstreamUnavailableCode,
|
|
138
164
|
isUpstreamUnavailable,
|
|
139
165
|
ModelFailoverExhaustedError,
|
|
140
166
|
runWithModelFailover,
|
|
141
167
|
buildModelChain
|
|
142
168
|
};
|
|
143
|
-
//# sourceMappingURL=chunk-
|
|
169
|
+
//# sourceMappingURL=chunk-63EKFZOE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/model-resolution/failover.ts"],"sourcesContent":["/**\n * Model failover — the answer to \"one upstream hit a quota wall and the customer\n * got a Bad Gateway even though the router had abundant healthy capacity\".\n *\n * This is deliberately NOT a health probe. Probing before every turn buys a\n * round-trip of latency on the happy path and still races the outage (a model\n * healthy at probe time can 502 a second later). Failover is REACTIVE: run the\n * preferred model, and on an upstream-outage signal move to the next model in\n * the chain. Zero added latency when the preferred model works.\n *\n * Two facts drive the design, both measured against a live box during the\n * 2026-07-25 Anthropic/DeepSeek outage:\n *\n * 1. An outage is NOT always a thrown error. The sandbox resolves with a\n * payload — `{ success: false, errorCode: 'provider_inference_unavailable' }`\n * — so a classifier that only inspects `catch` misses the customer-visible\n * case entirely. `isUpstreamUnavailable` inspects resolved values too.\n * 2. Catalog membership is NOT liveness. The router's `/v1/models` still listed\n * every dead model during the outage, so `validateChatModelId` admitted\n * `claude-sonnet-4-6` while every call to it returned 502. Nothing upstream\n * of the actual call can be trusted to tell you a model is serving.\n *\n * Substrate-free: the caller injects `run`, so this composes with a sandbox\n * turn, a router chat completion, or a test fake without importing any of them.\n */\n\n/**\n * Error codes that mean \"this model's upstream is unavailable — a different\n * model may still work\". Deliberately excludes codes that would fail identically\n * on every model (bad request, auth, content filter): retrying those down a\n * chain burns latency and money to reach the same failure.\n */\nexport const UPSTREAM_UNAVAILABLE_CODES: readonly string[] = [\n 'provider_inference_unavailable',\n 'provider_quota_exhausted',\n 'upstream_unavailable',\n 'insufficient_quota',\n 'model_not_available',\n 'server_error',\n 'bad_gateway',\n 'service_unavailable',\n]\n\n/** HTTP statuses that indicate an upstream capacity/availability problem. */\nexport const UPSTREAM_UNAVAILABLE_STATUSES: readonly number[] = [429, 500, 502, 503, 504]\n\n/**\n * Statuses that mean the REQUEST is wrong, so every model in the chain would\n * fail on it identically. Listed explicitly rather than as \"any 4xx\" because\n * 404 is NOT one of them: a model the endpoint cannot find is model-scoped, and\n * the next model in the chain may well be there. 429 is absent for the same\n * reason in reverse — it is a capacity signal and lives in the list above.\n */\nconst REQUEST_ERROR_STATUSES: readonly number[] = [400, 401, 403, 405, 413, 422]\n\n/**\n * Message fragments emitted by real upstreams during this class of outage.\n * Matched case-insensitively as a last resort, after code and status.\n */\nconst UPSTREAM_UNAVAILABLE_MESSAGES: readonly string[] = [\n 'bad gateway',\n 'service unavailable',\n 'inference temporarily unavailable',\n 'provider inference is unavailable',\n 'insufficient balance',\n 'usage limits',\n 'quota exceeded',\n 'rate limit',\n 'overloaded',\n 'temporarily unavailable',\n // Model-SCOPED unavailability. A different model in the chain can still\n // serve, so this belongs here and not with the client errors. Measured on a\n // real box 2026-07-27: the sandbox now reports an unservable model as a\n // terminal `error` whose data is `{\"message\":\"Session error:\n // {\\\"error\\\":{\\\"name\\\":\\\"UnknownError\\\",\\\"data\\\":{\\\"message\\\":\\\"Model not\n // found: openai-compat/zai/glm-4.7.\\\"}}}\"}` — no `code`, no numeric status,\n // and none of the fragments above. The shipped live product-path proof went\n // red on exactly this: `usedFallback:false`, `failed:true`, an error row to\n // the customer where a fallback was available and would have answered.\n 'model not found',\n 'is not currently available',\n]\n\n/**\n * Textual forms an HTTP status arrives in when NO numeric field carries it.\n *\n * The case that forced this is the opaque Cloudflare 502. Captured verbatim\n * from `router.tangle.tools` on 2026-07-27 17:48:12 GMT (cf-ray\n * `a21d793899f6cef3-DEN`): `HTTP/2 502`, `content-type: text/plain;\n * charset=UTF-8`, a 16-byte body reading `error code: 502\\n`, `server:\n * cloudflare`, and **zero `x-tangle-*` headers** where a healthy 200 from the\n * same endpoint carries nine of them.\n *\n * That capture was originally read as \"zero headers means the origin never\n * executed\". It does not, and the correction matters more than the original\n * guess did. Matching client-observed cf-rays against the origin's own access\n * log (tangle-router #307) showed all 62 of those responses WERE produced by\n * the router — `content-type: application/json`, an `X-Generation-Id`, and a\n * routing trace showing the upstream had returned 200 — and Cloudflare\n * replaced the body and every response header with its own error page, because\n * an origin 502 reads to the edge as the origin having failed.\n *\n * The classifier's BEHAVIOR here was right for the wrong reason, and stays\n * exactly as it is. What changes is why: the rescue is needed not because the\n * origin is unreachable, but because a response the origin carefully\n * structured arrives at the client as sixteen unlabelled bytes. The router now\n * emits 503 instead of 502 on those paths so the body survives, but this\n * pattern must remain — it is the client's only handle on any origin 5xx the\n * edge decides to rewrite, including from a router that has not deployed the\n * fix yet.\n *\n * Every pattern below matches a string a real producer emits:\n * - `error code: 502` — Cloudflare's edge body (the capture above).\n * - `(HTTP 502)` — `src/runtime/openai-stream.ts` wrapping a non-ok response.\n * - `returned 502` — `src/runtime/model-catalog.ts`.\n * - `failed with status 502` — `src/turn-stream/adapters.ts`.\n * - `502 Bad Gateway` — an HTTP/1.1 status line. HTTP/2 carries no reason\n * phrase at all, which is precisely why matching the phrase alone (the\n * `'bad gateway'` fragment below) read the capture as a non-outage.\n */\nconst HTTP_STATUS_HINT_PATTERNS: readonly RegExp[] = [\n /\\berror\\s+code:?\\s*([1-5]\\d{2})\\b/i,\n /\\bhttp(?:\\/[\\d.]+)?[\\s:]\\s*([1-5]\\d{2})\\b/i,\n /\\bstatus(?:\\s*code)?[\\s:=]\\s*([1-5]\\d{2})\\b/i,\n /\\b(?:returned|responded(?:\\s+with)?)\\s+([1-5]\\d{2})\\b/i,\n /\\b([1-5]\\d{2})\\s+(?:bad\\s+gateway|service\\s+unavailable|gateway\\s+time-?out|internal\\s+server\\s+error|too\\s+many\\s+requests)\\b/i,\n]\n\n/**\n * The HTTP status a message states in prose, or `undefined` when it states\n * none. Deliberately NOT \"any three digits in the string\" — an unanchored digit\n * scan would read a token count or a duration as a status.\n */\nexport function readHttpStatusHint(text: string): number | undefined {\n for (const pattern of HTTP_STATUS_HINT_PATTERNS) {\n const match = pattern.exec(text)\n if (match?.[1]) return Number(match[1])\n }\n return undefined\n}\n\nfunction readString(source: Record<string, unknown>, key: string): string | undefined {\n const value = source[key]\n return typeof value === 'string' && value.trim().length > 0 ? value : undefined\n}\n\n/** Read a recognized upstream code, including the terminal message-only shape. */\nexport function readUpstreamUnavailableCode(signal: unknown): string | undefined {\n if (signal === null || typeof signal !== 'object') return undefined\n const record = signal as Record<string, unknown>\n const nested = record.error\n const nestedRecord = nested !== null && typeof nested === 'object' ? (nested as Record<string, unknown>) : undefined\n const code =\n readString(record, 'errorCode') ??\n readString(record, 'code') ??\n (nestedRecord ? (readString(nestedRecord, 'code') ?? readString(nestedRecord, 'type')) : undefined)\n if (code && UPSTREAM_UNAVAILABLE_CODES.includes(code)) return code\n\n const message =\n readString(record, 'message') ??\n readString(record, 'error') ??\n (nestedRecord ? readString(nestedRecord, 'message') : undefined)\n return message && /\\(\\s*provider_quota_exhausted\\s*\\)/i.test(message)\n ? 'provider_quota_exhausted'\n : undefined\n}\n\n/**\n * True when `signal` — a thrown error OR a resolved result payload — indicates\n * the model's upstream is unavailable and another model is worth trying.\n *\n * Checked in order of decreasing confidence: explicit code, HTTP status, then\n * message text. A resolved payload only counts as a failure when it carries an\n * explicit failure marker (`success: false`, or an `error`/`errorCode` field) —\n * a successful result is never misread as an outage.\n */\nexport function isUpstreamUnavailable(signal: unknown): boolean {\n if (signal === null || typeof signal !== 'object') return false\n const record = signal as Record<string, unknown>\n\n // A resolved payload that explicitly reports success is never an outage.\n if (record.success === true) return false\n\n const nested = record.error\n const nestedRecord = nested !== null && typeof nested === 'object' ? (nested as Record<string, unknown>) : undefined\n if (readUpstreamUnavailableCode(record)) return true\n\n for (const key of ['status', 'statusCode', 'httpStatus']) {\n const value = record[key]\n if (typeof value === 'number' && UPSTREAM_UNAVAILABLE_STATUSES.includes(value)) return true\n }\n\n const message =\n readString(record, 'message') ??\n readString(record, 'error') ??\n (nestedRecord ? readString(nestedRecord, 'message') : undefined)\n if (!message) return false\n\n // A status carried as PROSE, checked before the fragment list because it is\n // the stronger signal and it cuts BOTH ways. An edge 502 names no exception\n // type and sets no numeric field, so without this the shipped classifier read\n // `error code: 502` as a non-outage and handed the customer a Bad Gateway\n // instead of trying the next model — the exact failure the router cannot\n // rescue from inside its own origin.\n const hinted = readHttpStatusHint(message)\n if (hinted !== undefined) {\n if (UPSTREAM_UNAVAILABLE_STATUSES.includes(hinted)) return true\n // An explicit REQUEST-error status is decisive the OTHER way. A 400\n // carrying a validation message must surface rather than walk the chain,\n // even when its body happens to contain a word from the fragment list —\n // the router's own `Function tools with reasoning_effort are not supported`\n // 400 is a request-shaping bug that fails identically on every model.\n if (REQUEST_ERROR_STATUSES.includes(hinted)) return false\n }\n\n const lowered = message.toLowerCase()\n return UPSTREAM_UNAVAILABLE_MESSAGES.some((fragment) => lowered.includes(fragment))\n}\n\n/** One model tried, and how it went. */\nexport interface ModelFailoverAttempt {\n model: string\n ok: boolean\n /** Why this model was abandoned. Absent when `ok`. */\n reason?: string\n /** Recognized upstream code carried by this failed attempt. */\n errorCode?: string\n}\n\n/** The outcome of a failover run: the value plus the full attempt trail. */\nexport interface ModelFailoverResult<T> {\n value: T\n /** The model that actually produced `value`. */\n model: string\n attempts: ModelFailoverAttempt[]\n /** True when the preferred (first) model did not serve the request. */\n usedFallback: boolean\n}\n\n/** Every model in the chain failed; carries the trail for logging. */\nexport class ModelFailoverExhaustedError extends Error {\n readonly attempts: ModelFailoverAttempt[]\n /** Last recognized upstream code across the exhausted chain, when present. */\n readonly upstreamCode?: string\n constructor(attempts: ModelFailoverAttempt[]) {\n const trail = attempts.map((a) => `${a.model}: ${a.reason ?? 'failed'}`).join(' | ')\n super(`All ${attempts.length} model(s) failed. ${trail}`)\n this.name = 'ModelFailoverExhaustedError'\n this.attempts = attempts\n this.upstreamCode = [...attempts].reverse().find((attempt) => attempt.errorCode)?.errorCode\n }\n}\n\n/** Inputs to {@link runWithModelFailover}. */\nexport interface RunWithModelFailoverInput<T> {\n /** Preferred model first, then fallbacks in descending preference. */\n models: readonly string[]\n /** Executes one turn with the given model. */\n run: (model: string) => Promise<T>\n /**\n * Classifies a resolved result as an upstream outage. Defaults to\n * {@link isUpstreamUnavailable}, which understands the sandbox's\n * `{ success: false, errorCode }` payload.\n */\n isUnavailableResult?: (result: T) => boolean\n /** Classifies a thrown error. Defaults to {@link isUpstreamUnavailable}. */\n isUnavailableError?: (error: unknown) => boolean\n /** Observability hook fired each time a model is abandoned. */\n onFallback?: (attempt: ModelFailoverAttempt, nextModel: string) => void\n}\n\nfunction describe(signal: unknown): string {\n if (signal instanceof Error) return signal.message\n if (signal !== null && typeof signal === 'object') {\n const record = signal as Record<string, unknown>\n const message = readString(record, 'error') ?? readString(record, 'message') ?? readString(record, 'errorCode')\n if (message) return message\n }\n return String(signal)\n}\n\n/**\n * Run `run` against the first model in `models` that does not report an upstream\n * outage, falling through the chain in order.\n *\n * A non-outage failure (bad request, auth, content filter) is re-thrown\n * immediately rather than retried down the chain — those fail identically on\n * every model, so walking the chain would only multiply latency and spend.\n *\n * @throws ModelFailoverExhaustedError when every model reports an outage.\n */\nexport async function runWithModelFailover<T>(\n input: RunWithModelFailoverInput<T>,\n): Promise<ModelFailoverResult<T>> {\n const models = input.models.map((m) => m.trim()).filter((m) => m.length > 0)\n if (models.length === 0) throw new Error('runWithModelFailover requires at least one model')\n\n const isUnavailableResult = input.isUnavailableResult ?? ((r: T) => isUpstreamUnavailable(r))\n const isUnavailableError = input.isUnavailableError ?? isUpstreamUnavailable\n const attempts: ModelFailoverAttempt[] = []\n\n for (let index = 0; index < models.length; index += 1) {\n const model = models[index]!\n let result: T\n try {\n result = await input.run(model)\n } catch (error) {\n if (!isUnavailableError(error)) throw error\n const errorCode = readUpstreamUnavailableCode(error)\n const attempt: ModelFailoverAttempt = {\n model,\n ok: false,\n reason: describe(error),\n ...(errorCode ? { errorCode } : {}),\n }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n if (isUnavailableResult(result)) {\n const errorCode = readUpstreamUnavailableCode(result)\n const attempt: ModelFailoverAttempt = {\n model,\n ok: false,\n reason: describe(result),\n ...(errorCode ? { errorCode } : {}),\n }\n attempts.push(attempt)\n const next = models[index + 1]\n if (next) input.onFallback?.(attempt, next)\n continue\n }\n\n attempts.push({ model, ok: true })\n return { value: result, model, attempts, usedFallback: index > 0 }\n }\n\n throw new ModelFailoverExhaustedError(attempts)\n}\n\n/**\n * Build a failover chain: the preferred model first, then `fallbacks`, with\n * duplicates removed so a model is never retried twice in one turn.\n */\nexport function buildModelChain(preferred: string, fallbacks: readonly string[]): string[] {\n const chain: string[] = []\n for (const model of [preferred, ...fallbacks]) {\n const cleaned = typeof model === 'string' ? model.trim() : ''\n if (cleaned.length > 0 && !chain.includes(cleaned)) chain.push(cleaned)\n }\n return chain\n}\n"],"mappings":";AAgCO,IAAM,6BAAgD;AAAA,EAC3D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGO,IAAM,gCAAmD,CAAC,KAAK,KAAK,KAAK,KAAK,GAAG;AASxF,IAAM,yBAA4C,CAAC,KAAK,KAAK,KAAK,KAAK,KAAK,GAAG;AAM/E,IAAM,gCAAmD;AAAA,EACvD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA;AAAA,EACA;AACF;AAuCA,IAAM,4BAA+C;AAAA,EACnD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,SAAS,mBAAmB,MAAkC;AACnE,aAAW,WAAW,2BAA2B;AAC/C,UAAM,QAAQ,Q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WAAW,MAAM,KAAK,IAAI;AAC3D,QAAI,QAAQ,SAAS,KAAK,CAAC,MAAM,SAAS,OAAO,EAAG,OAAM,KAAK,OAAO;AAAA,EACxE;AACA,SAAO;AACT;","names":[]}
|
|
@@ -38,6 +38,8 @@ export declare const UPSTREAM_UNAVAILABLE_STATUSES: readonly number[];
|
|
|
38
38
|
* scan would read a token count or a duration as a status.
|
|
39
39
|
*/
|
|
40
40
|
export declare function readHttpStatusHint(text: string): number | undefined;
|
|
41
|
+
/** Read a recognized upstream code, including the terminal message-only shape. */
|
|
42
|
+
export declare function readUpstreamUnavailableCode(signal: unknown): string | undefined;
|
|
41
43
|
/**
|
|
42
44
|
* True when `signal` — a thrown error OR a resolved result payload — indicates
|
|
43
45
|
* the model's upstream is unavailable and another model is worth trying.
|
|
@@ -54,6 +56,8 @@ export interface ModelFailoverAttempt {
|
|
|
54
56
|
ok: boolean;
|
|
55
57
|
/** Why this model was abandoned. Absent when `ok`. */
|
|
56
58
|
reason?: string;
|
|
59
|
+
/** Recognized upstream code carried by this failed attempt. */
|
|
60
|
+
errorCode?: string;
|
|
57
61
|
}
|
|
58
62
|
/** The outcome of a failover run: the value plus the full attempt trail. */
|
|
59
63
|
export interface ModelFailoverResult<T> {
|
|
@@ -67,6 +71,8 @@ export interface ModelFailoverResult<T> {
|
|
|
67
71
|
/** Every model in the chain failed; carries the trail for logging. */
|
|
68
72
|
export declare class ModelFailoverExhaustedError extends Error {
|
|
69
73
|
readonly attempts: ModelFailoverAttempt[];
|
|
74
|
+
/** Last recognized upstream code across the exhausted chain, when present. */
|
|
75
|
+
readonly upstreamCode?: string;
|
|
70
76
|
constructor(attempts: ModelFailoverAttempt[]);
|
|
71
77
|
}
|
|
72
78
|
/** Inputs to {@link runWithModelFailover}. */
|
package/dist/teams/index.js
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
generateInviteToken,
|
|
3
|
+
isInviteTokenShape,
|
|
4
|
+
validateInviteToken
|
|
5
|
+
} from "../chunk-DJ4VJIH5.js";
|
|
1
6
|
import {
|
|
2
7
|
INVITATION_EXPIRY_DAYS,
|
|
3
8
|
generateInvitationToken,
|
|
@@ -7,11 +12,6 @@ import {
|
|
|
7
12
|
parseInvitationPermission,
|
|
8
13
|
renderInvitationEmail
|
|
9
14
|
} from "../chunk-2DRYTJHI.js";
|
|
10
|
-
import {
|
|
11
|
-
generateInviteToken,
|
|
12
|
-
isInviteTokenShape,
|
|
13
|
-
validateInviteToken
|
|
14
|
-
} from "../chunk-DJ4VJIH5.js";
|
|
15
15
|
import {
|
|
16
16
|
ASSIGNABLE_WORKSPACE_ROLES,
|
|
17
17
|
ORGANIZATION_ROLES,
|
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SeatLimitError
|
|
3
|
+
} from "../chunk-MEUNTJL5.js";
|
|
4
|
+
import "../chunk-DJ4VJIH5.js";
|
|
1
5
|
import {
|
|
2
6
|
generateInvitationToken,
|
|
3
7
|
getInvitationExpiresAt,
|
|
@@ -5,10 +9,6 @@ import {
|
|
|
5
9
|
normalizeInvitationEmail,
|
|
6
10
|
parseInvitationPermission
|
|
7
11
|
} from "../chunk-2DRYTJHI.js";
|
|
8
|
-
import {
|
|
9
|
-
SeatLimitError
|
|
10
|
-
} from "../chunk-MEUNTJL5.js";
|
|
11
|
-
import "../chunk-DJ4VJIH5.js";
|
|
12
12
|
import {
|
|
13
13
|
hasWorkspaceRole
|
|
14
14
|
} from "../chunk-6XIAPIW6.js";
|
package/dist/web-react/index.js
CHANGED
|
@@ -129,9 +129,6 @@ import {
|
|
|
129
129
|
withoutRecordGridRemoved,
|
|
130
130
|
withoutRecordGridUpdate
|
|
131
131
|
} from "../chunk-5DEQ2FJK.js";
|
|
132
|
-
import {
|
|
133
|
-
MENTION_PILL_CLASS
|
|
134
|
-
} from "../chunk-3HUFJ5LO.js";
|
|
135
132
|
import {
|
|
136
133
|
SessionHistoryPanel,
|
|
137
134
|
formatSessionTimestamp,
|
|
@@ -139,6 +136,9 @@ import {
|
|
|
139
136
|
useSessionActions,
|
|
140
137
|
useSessionHistory
|
|
141
138
|
} from "../chunk-F32T3DRJ.js";
|
|
139
|
+
import {
|
|
140
|
+
MENTION_PILL_CLASS
|
|
141
|
+
} from "../chunk-3HUFJ5LO.js";
|
|
142
142
|
import "../chunk-FBVLEGEG.js";
|
|
143
143
|
import {
|
|
144
144
|
EvidenceLineageTable,
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/** A sandbox app registered in one product workspace. Products persist and authorize these rows. */
|
|
2
|
+
export interface WorkspaceAppRecord {
|
|
3
|
+
id: string;
|
|
4
|
+
workspaceId: string;
|
|
5
|
+
name: string;
|
|
6
|
+
sandboxId: string;
|
|
7
|
+
previewId: string;
|
|
8
|
+
port: number;
|
|
9
|
+
previewUrl: string;
|
|
10
|
+
status: 'starting' | 'ready' | 'unavailable';
|
|
11
|
+
createdAt: string;
|
|
12
|
+
updatedAt: string;
|
|
13
|
+
}
|
|
14
|
+
/** Structural shape returned by the Sandbox SDK previewLinks API. */
|
|
15
|
+
export interface WorkspaceAppPreviewLink {
|
|
16
|
+
previewId: string;
|
|
17
|
+
sandboxId: string;
|
|
18
|
+
port: number;
|
|
19
|
+
protocol: 'tcp' | 'udp';
|
|
20
|
+
hostname: string;
|
|
21
|
+
url: string;
|
|
22
|
+
status: 'provisioning' | 'ready' | 'error' | 'disabled';
|
|
23
|
+
}
|
|
24
|
+
export interface WorkspaceAppIdentity {
|
|
25
|
+
/** Assigned by the product, stable across preview updates and deliberate republishes. */
|
|
26
|
+
id: string;
|
|
27
|
+
/** Taken from the authenticated route or session, never agent tool arguments. */
|
|
28
|
+
workspaceId: string;
|
|
29
|
+
/** Current box resolved by the product from that workspace or session. */
|
|
30
|
+
sandboxId: string;
|
|
31
|
+
name: string;
|
|
32
|
+
/** Preserve this when republishing the same app onto a replacement sandbox. */
|
|
33
|
+
createdAt?: string;
|
|
34
|
+
updatedAt?: string;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Build a durable registration from a preview link created on the box that
|
|
38
|
+
* the authenticated product request resolved. The product owns row identity,
|
|
39
|
+
* access policy, persistence, and the decision to publish.
|
|
40
|
+
*/
|
|
41
|
+
export declare function workspaceAppFromPreviewLink(identity: WorkspaceAppIdentity, link: WorkspaceAppPreviewLink): WorkspaceAppRecord;
|
|
42
|
+
export interface WorkspaceAppHttpProof {
|
|
43
|
+
/** The exact trusted SDK preview URL requested by the server. */
|
|
44
|
+
previewUrl: string;
|
|
45
|
+
status: number;
|
|
46
|
+
contentType: string;
|
|
47
|
+
/** Number of bytes read from the response body, excluding headers. */
|
|
48
|
+
bodyBytes: number;
|
|
49
|
+
checkedAt: string;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Mark an app ready only after the host fetched its HTML over the trusted
|
|
53
|
+
* preview URL. The host owns the request timeout, redirect and credential
|
|
54
|
+
* policy, authorization, and compare-and-swap storage update.
|
|
55
|
+
*/
|
|
56
|
+
export declare function confirmWorkspaceAppReady(app: WorkspaceAppRecord, proof: WorkspaceAppHttpProof): WorkspaceAppRecord;
|
|
57
|
+
/** Refresh delivery state without changing which sandbox service this app means. */
|
|
58
|
+
export declare function refreshWorkspaceAppPreview(app: WorkspaceAppRecord, link: WorkspaceAppPreviewLink, updatedAt?: string): WorkspaceAppRecord;
|
|
59
|
+
export interface WorkspaceAppBuilderInstructionsOptions {
|
|
60
|
+
/** Host tool that writes or updates the app registration after creating a preview link. */
|
|
61
|
+
publishTool: string;
|
|
62
|
+
/** Optional host tool for finding app IDs the builder may update. */
|
|
63
|
+
listTool?: string;
|
|
64
|
+
}
|
|
65
|
+
/** Portable instructions for an agent profile that builds workspace apps. */
|
|
66
|
+
export declare function workspaceAppBuilderInstructions({ publishTool, listTool, }: WorkspaceAppBuilderInstructionsOptions): string[];
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
// src/workspace-apps/index.ts
|
|
2
|
+
function nonempty(value, field) {
|
|
3
|
+
if (typeof value !== "string" || !value.trim() || /[\u0000-\u001f\u007f]/.test(value)) {
|
|
4
|
+
throw new Error("Invalid workspace app " + field);
|
|
5
|
+
}
|
|
6
|
+
return value.trim();
|
|
7
|
+
}
|
|
8
|
+
function checkedLink(link, sandboxId) {
|
|
9
|
+
if (link.sandboxId !== sandboxId) {
|
|
10
|
+
throw new Error("Preview link belongs to another sandbox");
|
|
11
|
+
}
|
|
12
|
+
nonempty(link.previewId, "previewId");
|
|
13
|
+
if (link.protocol !== "tcp") throw new Error("Workspace app preview must use TCP");
|
|
14
|
+
if (!Number.isInteger(link.port) || link.port < 1 || link.port > 65535) {
|
|
15
|
+
throw new Error("Invalid workspace app port");
|
|
16
|
+
}
|
|
17
|
+
if (!["provisioning", "ready", "error", "disabled"].includes(link.status)) {
|
|
18
|
+
throw new Error("Invalid workspace app preview status");
|
|
19
|
+
}
|
|
20
|
+
let url;
|
|
21
|
+
try {
|
|
22
|
+
url = new URL(link.url);
|
|
23
|
+
} catch {
|
|
24
|
+
throw new Error("Invalid workspace app preview URL");
|
|
25
|
+
}
|
|
26
|
+
if (url.protocol !== "https:" || !url.hostname || url.hostname !== link.hostname || url.username || url.password || url.search || url.hash) {
|
|
27
|
+
throw new Error("Invalid workspace app preview URL");
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
function appStatus(status) {
|
|
31
|
+
if (status === "ready" || status === "provisioning") return "starting";
|
|
32
|
+
return "unavailable";
|
|
33
|
+
}
|
|
34
|
+
function workspaceAppFromPreviewLink(identity, link) {
|
|
35
|
+
const sandboxId = nonempty(identity.sandboxId, "sandboxId");
|
|
36
|
+
checkedLink(link, sandboxId);
|
|
37
|
+
const timestamp = identity.updatedAt ?? (/* @__PURE__ */ new Date()).toISOString();
|
|
38
|
+
return {
|
|
39
|
+
id: nonempty(identity.id, "id"),
|
|
40
|
+
workspaceId: nonempty(identity.workspaceId, "workspaceId"),
|
|
41
|
+
name: nonempty(identity.name, "name"),
|
|
42
|
+
sandboxId,
|
|
43
|
+
previewId: link.previewId,
|
|
44
|
+
port: link.port,
|
|
45
|
+
previewUrl: link.url,
|
|
46
|
+
status: appStatus(link.status),
|
|
47
|
+
createdAt: identity.createdAt ?? timestamp,
|
|
48
|
+
updatedAt: timestamp
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
function confirmWorkspaceAppReady(app, proof) {
|
|
52
|
+
if (proof.previewUrl !== app.previewUrl || proof.status !== 200 || !/^text\/html(?:\s*;|\s*$)/i.test(proof.contentType) || !Number.isInteger(proof.bodyBytes) || proof.bodyBytes < 1 || !Number.isFinite(Date.parse(proof.checkedAt))) {
|
|
53
|
+
throw new Error("Workspace app HTML preview is not ready");
|
|
54
|
+
}
|
|
55
|
+
return { ...app, status: "ready", updatedAt: proof.checkedAt };
|
|
56
|
+
}
|
|
57
|
+
function refreshWorkspaceAppPreview(app, link, updatedAt = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
58
|
+
checkedLink(link, app.sandboxId);
|
|
59
|
+
if (link.previewId !== app.previewId || link.port !== app.port) {
|
|
60
|
+
throw new Error("Preview link does not match workspace app");
|
|
61
|
+
}
|
|
62
|
+
return {
|
|
63
|
+
...app,
|
|
64
|
+
previewUrl: link.url,
|
|
65
|
+
status: appStatus(link.status),
|
|
66
|
+
updatedAt
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
function toolName(value) {
|
|
70
|
+
if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(value)) {
|
|
71
|
+
throw new Error("Invalid workspace app tool name");
|
|
72
|
+
}
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
function workspaceAppBuilderInstructions({
|
|
76
|
+
publishTool,
|
|
77
|
+
listTool
|
|
78
|
+
}) {
|
|
79
|
+
const publish = toolName(publishTool);
|
|
80
|
+
const list = listTool ? toolName(listTool) : void 0;
|
|
81
|
+
return [
|
|
82
|
+
"Build a working HTTP application in the current sandbox when the user asks for an app.",
|
|
83
|
+
...list ? ["Use " + list + " to inspect the existing apps before creating or updating one."] : [],
|
|
84
|
+
"Start its server on 0.0.0.0 using an available, unclaimed port.",
|
|
85
|
+
"Call " + publish + " with the app name, stable app ID when updating, and listening port.",
|
|
86
|
+
"Use the host tool result as the source of the registered app URL and status; never invent a preview URL.",
|
|
87
|
+
"Keep the same app ID for later revisions of that app.",
|
|
88
|
+
"Treat a preview link as public. Do not embed secrets or private business facts in client code or responses.",
|
|
89
|
+
"Read real business data through authorized product APIs. Do not fabricate records to make the app look complete.",
|
|
90
|
+
"Report the app as available only after the host confirms its preview is ready."
|
|
91
|
+
];
|
|
92
|
+
}
|
|
93
|
+
export {
|
|
94
|
+
confirmWorkspaceAppReady,
|
|
95
|
+
refreshWorkspaceAppPreview,
|
|
96
|
+
workspaceAppBuilderInstructions,
|
|
97
|
+
workspaceAppFromPreviewLink
|
|
98
|
+
};
|
|
99
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/workspace-apps/index.ts"],"sourcesContent":["/** A sandbox app registered in one product workspace. Products persist and authorize these rows. */\nexport interface WorkspaceAppRecord {\n id: string\n workspaceId: string\n name: string\n sandboxId: string\n previewId: string\n port: number\n previewUrl: string\n status: 'starting' | 'ready' | 'unavailable'\n createdAt: string\n updatedAt: string\n}\n\n/** Structural shape returned by the Sandbox SDK previewLinks API. */\nexport interface WorkspaceAppPreviewLink {\n previewId: string\n sandboxId: string\n port: number\n protocol: 'tcp' | 'udp'\n hostname: string\n url: string\n status: 'provisioning' | 'ready' | 'error' | 'disabled'\n}\n\nexport interface WorkspaceAppIdentity {\n /** Assigned by the product, stable across preview updates and deliberate republishes. */\n id: string\n /** Taken from the authenticated route or session, never agent tool arguments. */\n workspaceId: string\n /** Current box resolved by the product from that workspace or session. */\n sandboxId: string\n name: string\n /** Preserve this when republishing the same app onto a replacement sandbox. */\n createdAt?: string\n updatedAt?: string\n}\n\nfunction nonempty(value: string, field: string): string {\n if (typeof value !== 'string' || !value.trim() || /[\\u0000-\\u001f\\u007f]/.test(value)) {\n throw new Error('Invalid workspace app ' + field)\n }\n return value.trim()\n}\n\nfunction checkedLink(link: WorkspaceAppPreviewLink, sandboxId: string): void {\n if (link.sandboxId !== sandboxId) {\n throw new Error('Preview link belongs to another sandbox')\n }\n nonempty(link.previewId, 'previewId')\n if (link.protocol !== 'tcp') throw new Error('Workspace app preview must use TCP')\n if (!Number.isInteger(link.port) || link.port < 1 || link.port > 65535) {\n throw new Error('Invalid workspace app port')\n }\n if (!['provisioning', 'ready', 'error', 'disabled'].includes(link.status)) {\n throw new Error('Invalid workspace app preview status')\n }\n let url: URL\n try {\n url = new URL(link.url)\n } catch {\n throw new Error('Invalid workspace app preview URL')\n }\n if (\n url.protocol !== 'https:' ||\n !url.hostname ||\n url.hostname !== link.hostname ||\n url.username ||\n url.password ||\n url.search ||\n url.hash\n ) {\n throw new Error('Invalid workspace app preview URL')\n }\n}\n\nfunction appStatus(status: WorkspaceAppPreviewLink['status']): WorkspaceAppRecord['status'] {\n if (status === 'ready' || status === 'provisioning') return 'starting'\n return 'unavailable'\n}\n\n/**\n * Build a durable registration from a preview link created on the box that\n * the authenticated product request resolved. The product owns row identity,\n * access policy, persistence, and the decision to publish.\n */\nexport function workspaceAppFromPreviewLink(\n identity: WorkspaceAppIdentity,\n link: WorkspaceAppPreviewLink,\n): WorkspaceAppRecord {\n const sandboxId = nonempty(identity.sandboxId, 'sandboxId')\n checkedLink(link, sandboxId)\n const timestamp = identity.updatedAt ?? new Date().toISOString()\n return {\n id: nonempty(identity.id, 'id'),\n workspaceId: nonempty(identity.workspaceId, 'workspaceId'),\n name: nonempty(identity.name, 'name'),\n sandboxId,\n previewId: link.previewId,\n port: link.port,\n previewUrl: link.url,\n status: appStatus(link.status),\n createdAt: identity.createdAt ?? timestamp,\n updatedAt: timestamp,\n }\n}\n\nexport interface WorkspaceAppHttpProof {\n /** The exact trusted SDK preview URL requested by the server. */\n previewUrl: string\n status: number\n contentType: string\n /** Number of bytes read from the response body, excluding headers. */\n bodyBytes: number\n checkedAt: string\n}\n\n/**\n * Mark an app ready only after the host fetched its HTML over the trusted\n * preview URL. The host owns the request timeout, redirect and credential\n * policy, authorization, and compare-and-swap storage update.\n */\nexport function confirmWorkspaceAppReady(\n app: WorkspaceAppRecord,\n proof: WorkspaceAppHttpProof,\n): WorkspaceAppRecord {\n if (\n proof.previewUrl !== app.previewUrl ||\n proof.status !== 200 ||\n !/^text\\/html(?:\\s*;|\\s*$)/i.test(proof.contentType) ||\n !Number.isInteger(proof.bodyBytes) ||\n proof.bodyBytes < 1 ||\n !Number.isFinite(Date.parse(proof.checkedAt))\n ) {\n throw new Error('Workspace app HTML preview is not ready')\n }\n return { ...app, status: 'ready', updatedAt: proof.checkedAt }\n}\n\n/** Refresh delivery state without changing which sandbox service this app means. */\nexport function refreshWorkspaceAppPreview(\n app: WorkspaceAppRecord,\n link: WorkspaceAppPreviewLink,\n updatedAt = new Date().toISOString(),\n): WorkspaceAppRecord {\n checkedLink(link, app.sandboxId)\n if (link.previewId !== app.previewId || link.port !== app.port) {\n throw new Error('Preview link does not match workspace app')\n }\n return {\n ...app,\n previewUrl: link.url,\n status: appStatus(link.status),\n updatedAt,\n }\n}\n\nexport interface WorkspaceAppBuilderInstructionsOptions {\n /** Host tool that writes or updates the app registration after creating a preview link. */\n publishTool: string\n /** Optional host tool for finding app IDs the builder may update. */\n listTool?: string\n}\n\nfunction toolName(value: string): string {\n if (!/^[A-Za-z][A-Za-z0-9_.-]*$/.test(value)) {\n throw new Error('Invalid workspace app tool name')\n }\n return value\n}\n\n/** Portable instructions for an agent profile that builds workspace apps. */\nexport function workspaceAppBuilderInstructions({\n publishTool,\n listTool,\n}: WorkspaceAppBuilderInstructionsOptions): string[] {\n const publish = toolName(publishTool)\n const list = listTool ? toolName(listTool) : undefined\n return [\n 'Build a working HTTP application in the current sandbox when the user asks for an app.',\n ...(list ? ['Use ' + list + ' to inspect the existing apps before creating or updating one.'] : []),\n 'Start its server on 0.0.0.0 using an available, unclaimed port.',\n 'Call ' + publish + ' with the app name, stable app ID when updating, and listening port.',\n 'Use the host tool result as the source of the registered app URL and status; never invent a preview URL.',\n 'Keep the same app ID for later revisions of that app.',\n 'Treat a preview link as public. Do not embed secrets or private business facts in client code or responses.',\n 'Read real business data through authorized product APIs. Do not fabricate records to make the app look complete.',\n 'Report the app as available only after the host confirms its preview is ready.',\n ]\n}\n"],"mappings":";AAsCA,SAAS,SAAS,OAAe,OAAuB;AACtD,MAAI,OAAO,UAAU,YAAY,CAAC,MAAM,KAAK,KAAK,wBAAwB,KAAK,KAAK,GAAG;AACrF,UAAM,IAAI,MAAM,2BAA2B,KAAK;AAAA,EAClD;AACA,SAAO,MAAM,KAAK;AACpB;AAEA,SAAS,YAAY,MAA+B,WAAyB;AAC3E,MAAI,KAAK,cAAc,WAAW;AAChC,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AACA,WAAS,KAAK,WAAW,WAAW;AACpC,MAAI,KAAK,aAAa,MAAO,OAAM,IAAI,MAAM,oCAAoC;AACjF,MAAI,CAAC,OAAO,UAAU,KAAK,IAAI,KAAK,KAAK,OAAO,KAAK,KAAK,OAAO,OAAO;AACtE,UAAM,IAAI,MAAM,4BAA4B;AAAA,EAC9C;AACA,MAAI,CAAC,CAAC,gBAAgB,SAAS,SAAS,UAAU,EAAE,SAAS,KAAK,MAAM,GAAG;AACzE,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACA,MAAI;AACJ,MAAI;AACF,UAAM,IAAI,IAAI,KAAK,GAAG;AAAA,EACxB,QAAQ;AACN,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AACA,MACE,IAAI,aAAa,YACjB,CAAC,IAAI,YACL,IAAI,aAAa,KAAK,YACtB,IAAI,YACJ,IAAI,YACJ,IAAI,UACJ,IAAI,MACJ;AACA,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AACF;AAEA,SAA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,OAAuB;AACvC,MAAI,CAAC,4BAA4B,KAAK,KAAK,GAAG;AAC5C,UAAM,IAAI,MAAM,iCAAiC;AAAA,EACnD;AACA,SAAO;AACT;AAGO,SAAS,gCAAgC;AAAA,EAC9C;AAAA,EACA;AACF,GAAqD;AACnD,QAAM,UAAU,SAAS,WAAW;AACpC,QAAM,OAAO,WAAW,SAAS,QAAQ,IAAI;AAC7C,SAAO;AAAA,IACL;AAAA,IACA,GAAI,OAAO,CAAC,SAAS,OAAO,gEAAgE,IAAI,CAAC;AAAA,IACjG;AAAA,IACA,UAAU,UAAU;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;","names":[]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard';
|
|
2
2
|
import type { ReactNode } from 'react';
|
|
3
|
+
import type { WorkspaceAppRecord } from '../workspace-apps';
|
|
3
4
|
import { type NavRouteDef, type RailPrefetch, type SessionRowActions, type SessionSummary } from '../session-shell';
|
|
4
5
|
type WorkspaceIcon = SidebarLayoutNavItem['icon'];
|
|
5
6
|
/** The session data and product-owned URLs needed by the default workspace. */
|
|
@@ -43,6 +44,17 @@ export interface AgentWorkspaceSessionConfig {
|
|
|
43
44
|
/** Whether History starts expanded. Defaults to `true`. */
|
|
44
45
|
defaultOpen?: boolean;
|
|
45
46
|
}
|
|
47
|
+
/**
|
|
48
|
+
* Registered apps shown as individual workspace destinations.
|
|
49
|
+
* Products supply authorized rows and their real route; preview URLs never
|
|
50
|
+
* become navigation hrefs.
|
|
51
|
+
*/
|
|
52
|
+
export interface AgentWorkspaceAppsConfig {
|
|
53
|
+
icon: WorkspaceIcon;
|
|
54
|
+
items: readonly Pick<WorkspaceAppRecord, 'id' | 'name'>[];
|
|
55
|
+
hrefForApp: (appId: string) => string;
|
|
56
|
+
prefetch?: RailPrefetch;
|
|
57
|
+
}
|
|
46
58
|
/** Route data for the shared active-nav resolver. */
|
|
47
59
|
export interface AgentWorkspaceActiveRoute {
|
|
48
60
|
/** Current browser pathname, including the product's workspace base. */
|
|
@@ -62,6 +74,8 @@ export interface AgentWorkspaceLayoutProps extends Omit<SidebarLayoutProps, 'act
|
|
|
62
74
|
navItems: SidebarLayoutNavItem[];
|
|
63
75
|
/** Omit for a workflow-only shell with no conversational session rail. */
|
|
64
76
|
sessions?: AgentWorkspaceSessionConfig;
|
|
77
|
+
/** Registered app destinations, in the product's persisted order. */
|
|
78
|
+
apps?: AgentWorkspaceAppsConfig;
|
|
65
79
|
/** When supplied, active navigation is resolved by the shared route rules. */
|
|
66
80
|
activeRoute?: AgentWorkspaceActiveRoute;
|
|
67
81
|
/** Escape hatch for routers that already resolved the active item. */
|
|
@@ -82,5 +96,5 @@ export interface AgentWorkspaceLayoutProps extends Omit<SidebarLayoutProps, 'act
|
|
|
82
96
|
* with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first
|
|
83
97
|
* structure.
|
|
84
98
|
*/
|
|
85
|
-
export declare function AgentWorkspaceLayout({ children, navItems, sessions, activeRoute, activeId, ...sidebarProps }: AgentWorkspaceLayoutProps): import("react").JSX.Element;
|
|
99
|
+
export declare function AgentWorkspaceLayout({ children, navItems, sessions, apps, activeRoute, activeId, ...sidebarProps }: AgentWorkspaceLayoutProps): import("react").JSX.Element;
|
|
86
100
|
export {};
|
|
@@ -18,6 +18,7 @@ function AgentWorkspaceLayout({
|
|
|
18
18
|
children,
|
|
19
19
|
navItems,
|
|
20
20
|
sessions,
|
|
21
|
+
apps,
|
|
21
22
|
activeRoute,
|
|
22
23
|
activeId,
|
|
23
24
|
...sidebarProps
|
|
@@ -49,17 +50,37 @@ function AgentWorkspaceLayout({
|
|
|
49
50
|
defaultOpen: sessions.defaultOpen
|
|
50
51
|
});
|
|
51
52
|
})() : void 0;
|
|
52
|
-
const
|
|
53
|
+
const appNavItems = (apps?.items ?? []).map((app) => {
|
|
54
|
+
const href = apps.hrefForApp(app.id);
|
|
55
|
+
if (!href.startsWith("/") || href.startsWith("//") || /[?#\\]/.test(href)) {
|
|
56
|
+
throw new Error("Workspace app href must be a local route path");
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
id: "workspace-app:" + app.id,
|
|
60
|
+
label: app.name,
|
|
61
|
+
icon: apps.icon,
|
|
62
|
+
href,
|
|
63
|
+
prefetch: apps.prefetch
|
|
64
|
+
};
|
|
65
|
+
});
|
|
66
|
+
const workspaceNavItems = [
|
|
67
|
+
...navItems,
|
|
68
|
+
...appNavItems,
|
|
69
|
+
...sessionNav ? [sessionNav] : []
|
|
70
|
+
];
|
|
71
|
+
const appRoutes = activeRoute ? appNavItems.map((item) => {
|
|
72
|
+
const path = routePathFromHref(item.href, activeRoute.base);
|
|
73
|
+
if (!path) throw new Error("Workspace app href must be under the active workspace");
|
|
74
|
+
return { id: item.id, path };
|
|
75
|
+
}) : [];
|
|
53
76
|
const historyRoutePath = sessions && activeRoute ? routePathFromHref(sessions.href, activeRoute.base) : null;
|
|
54
77
|
const resolvedActiveId = activeRoute ? resolveActiveNavId({
|
|
55
78
|
...activeRoute,
|
|
56
|
-
routes:
|
|
79
|
+
routes: [
|
|
57
80
|
...activeRoute.routes,
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
] : activeRoute.routes
|
|
81
|
+
...appRoutes,
|
|
82
|
+
...sessionNav && historyRoutePath ? [{ id: sessions?.id ?? "history", path: historyRoutePath }] : []
|
|
83
|
+
]
|
|
63
84
|
}) : activeId;
|
|
64
85
|
const layoutProps = {
|
|
65
86
|
hideBelow: "lg",
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/workspace-react/index.tsx"],"sourcesContent":["import { SidebarLayout, type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard'\nimport type { ReactNode } from 'react'\n\nimport {\n buildSessionNavItem,\n composeSidebarSessions,\n resolveActiveNavId,\n type NavRouteDef,\n type RailPrefetch,\n type SessionRowActions,\n type SessionSummary,\n} from '../session-shell'\n\ntype WorkspaceIcon = SidebarLayoutNavItem['icon']\n\nfunction routePathFromHref(href: string, base: string): string | null {\n const path = href.split(/[?#]/, 1)[0] ?? ''\n const root = base.replace(/\\/+$/, '')\n if (path === root) return '/'\n if (!path.startsWith(`${root}/`)) return null\n return path.slice(root.length)\n}\n\n/** The session data and product-owned URLs needed by the default workspace. */\nexport interface AgentWorkspaceSessionConfig {\n /** Icon shown beside the expandable History row. */\n icon: WorkspaceIcon\n /** Id for the session row; defaults to `history`. */\n id?: string\n /** Product copy for the session row; defaults to `History`. */\n label?: string\n /** Full-history route used by the row and overflow item. */\n href: string\n /** Product-owned URL for an individual session. */\n hrefForSession: (sessionId: string) => string\n /** Server-loaded rows, ordered by the product's query. */\n sessions: SessionSummary[]\n /** Sessions created by another tab before the loader revalidates. */\n optimisticSessions?: SessionSummary[]\n /** Number of rows shown in the rail before the full-history link. */\n limit?: number\n /** Total persisted session count, used to decide whether overflow exists. */\n totalCount?: number\n /** Session currently open in the route. */\n activeSessionId?: string | null\n /** Sessions with a live turn. */\n respondingSessionIds?: ReadonlySet<string>\n /** Live unread ids from the product's event channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** Optional product-owned rename/delete/pin actions. */\n actions?: SessionRowActions<WorkspaceIcon>\n /** Label for the overflow row. Defaults to `View all chats`. */\n overflowLabel?: string\n /** Empty state for the expanded rail row. Defaults to `No chats yet`. */\n emptyLabel?: string\n /** Fallback title for untitled sessions. */\n untitledLabel?: string\n /** Router prefetch behavior for session links. */\n prefetch?: RailPrefetch\n /** Whether History starts expanded. Defaults to `true`. */\n defaultOpen?: boolean\n}\n\n/** Route data for the shared active-nav resolver. */\nexport interface AgentWorkspaceActiveRoute {\n /** Current browser pathname, including the product's workspace base. */\n pathname: string\n /** Product route root, for example `/app/ws_123`. */\n base: string\n /** Product-owned rail routes, relative to `base`. */\n routes: NavRouteDef[]\n /** Extra route prefixes that should highlight an existing row. */\n aliases?: Record<string, string>\n /** Route prefixes that intentionally highlight no row. */\n claimsNothing?: string[]\n}\n\nexport interface AgentWorkspaceLayoutProps\n extends Omit<SidebarLayoutProps, 'activeId' | 'children' | 'navItems' | 'hideBelow' | 'railLabels'> {\n children: ReactNode\n /** Product-owned destinations. The shared History row is appended after them. */\n navItems: SidebarLayoutNavItem[]\n /** Omit for a workflow-only shell with no conversational session rail. */\n sessions?: AgentWorkspaceSessionConfig\n /** When supplied, active navigation is resolved by the shared route rules. */\n activeRoute?: AgentWorkspaceActiveRoute\n /** Escape hatch for routers that already resolved the active item. */\n activeId?: string\n /** Hide the fixed desktop rail below this breakpoint. Defaults to `lg`. */\n hideBelow?: SidebarLayoutProps['hideBelow']\n /** Show labels beside rail icons. Defaults to `true`. */\n railLabels?: SidebarLayoutProps['railLabels']\n}\n\n/**\n * The default agent workspace composition.\n *\n * Products own their navigation taxonomy, routes, and session storage. This\n * component owns the repeated assembly: the standard visual layout, the\n * expandable History row, capped session composition, unread state, and active\n * route resolution. The full History route and the empty-state composer stay\n * separate because their data and domain copy belong to the product; pair this\n * with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first\n * structure.\n */\nexport function AgentWorkspaceLayout({\n children,\n navItems,\n sessions,\n activeRoute,\n activeId,\n ...sidebarProps\n}: AgentWorkspaceLayoutProps) {\n const sessionNav = sessions\n ? (() => {\n const composed = composeSidebarSessions({\n loaderSessions: sessions.sessions,\n optimisticSessions: sessions.optimisticSessions,\n limit: sessions.limit ?? 20,\n totalCount: sessions.totalCount,\n liveUnreadIds: sessions.liveUnreadIds,\n locallyReadIds: sessions.locallyReadIds,\n currentSessionId: sessions.activeSessionId,\n })\n\n return buildSessionNavItem<WorkspaceIcon>({\n id: sessions.id,\n label: sessions.label,\n icon: sessions.icon,\n href: sessions.href,\n sessions: composed.sessions,\n hrefForSession: sessions.hrefForSession,\n activeSessionId: sessions.activeSessionId,\n respondingSessionIds: sessions.respondingSessionIds,\n actions: sessions.actions,\n overflow: composed.hasMore\n ? { href: sessions.href, label: sessions.overflowLabel }\n : undefined,\n emptyLabel: sessions.emptyLabel,\n untitledLabel: sessions.untitledLabel,\n prefetch: sessions.prefetch,\n defaultOpen: sessions.defaultOpen,\n })\n })()\n : undefined\n\n const workspaceNavItems: SidebarLayoutNavItem[] = sessionNav\n ? [...navItems, sessionNav]\n : navItems\n\n const historyRoutePath = sessions && activeRoute\n ? routePathFromHref(sessions.href, activeRoute.base)\n : null\n\n const resolvedActiveId = activeRoute\n ? resolveActiveNavId({\n ...activeRoute,\n routes: sessionNav && historyRoutePath\n ? [\n ...activeRoute.routes,\n {\n id: sessions?.id ?? 'history',\n path: historyRoutePath,\n },\n ]\n : activeRoute.routes,\n })\n : activeId\n\n const layoutProps = {\n hideBelow: 'lg' as const,\n railLabels: true,\n ...sidebarProps,\n }\n\n return (\n <SidebarLayout\n {...layoutProps}\n navItems={workspaceNavItems}\n activeId={resolvedActiveId}\n >\n {children}\n </SidebarLayout>\n )\n}\n"],"mappings":";;;;;;;AAAA,SAAS,qBAAyE;AAkL9E;AAnKJ,SAAS,kBAAkB,MAAc,MAA6B;AACpE,QAAM,OAAO,KAAK,MAAM,QAAQ,CAAC,EAAE,CAAC,KAAK;AACzC,QAAM,OAAO,KAAK,QAAQ,QAAQ,EAAE;AACpC,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,EAAG,QAAO;AACzC,SAAO,KAAK,MAAM,KAAK,MAAM;AAC/B;AAsFO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAA8B;AAC5B,QAAM,aAAa,YACd,MAAM;AACL,UAAM,WAAW,uBAAuB;AAAA,MACtC,gBAAgB,SAAS;AAAA,MACzB,oBAAoB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SidebarLayout, type SidebarLayoutNavItem, type SidebarLayoutProps } from '@tangle-network/sandbox-ui/dashboard'\nimport type { ReactNode } from 'react'\n\nimport type { WorkspaceAppRecord } from '../workspace-apps'\n\nimport {\n buildSessionNavItem,\n composeSidebarSessions,\n resolveActiveNavId,\n type NavRouteDef,\n type RailPrefetch,\n type SessionRowActions,\n type SessionSummary,\n} from '../session-shell'\n\ntype WorkspaceIcon = SidebarLayoutNavItem['icon']\n\nfunction routePathFromHref(href: string, base: string): string | null {\n const path = href.split(/[?#]/, 1)[0] ?? ''\n const root = base.replace(/\\/+$/, '')\n if (path === root) return '/'\n if (!path.startsWith(`${root}/`)) return null\n return path.slice(root.length)\n}\n\n/** The session data and product-owned URLs needed by the default workspace. */\nexport interface AgentWorkspaceSessionConfig {\n /** Icon shown beside the expandable History row. */\n icon: WorkspaceIcon\n /** Id for the session row; defaults to `history`. */\n id?: string\n /** Product copy for the session row; defaults to `History`. */\n label?: string\n /** Full-history route used by the row and overflow item. */\n href: string\n /** Product-owned URL for an individual session. */\n hrefForSession: (sessionId: string) => string\n /** Server-loaded rows, ordered by the product's query. */\n sessions: SessionSummary[]\n /** Sessions created by another tab before the loader revalidates. */\n optimisticSessions?: SessionSummary[]\n /** Number of rows shown in the rail before the full-history link. */\n limit?: number\n /** Total persisted session count, used to decide whether overflow exists. */\n totalCount?: number\n /** Session currently open in the route. */\n activeSessionId?: string | null\n /** Sessions with a live turn. */\n respondingSessionIds?: ReadonlySet<string>\n /** Live unread ids from the product's event channel. */\n liveUnreadIds?: ReadonlySet<string>\n /** Ids this tab has opened since the loader ran. */\n locallyReadIds?: ReadonlySet<string>\n /** Optional product-owned rename/delete/pin actions. */\n actions?: SessionRowActions<WorkspaceIcon>\n /** Label for the overflow row. Defaults to `View all chats`. */\n overflowLabel?: string\n /** Empty state for the expanded rail row. Defaults to `No chats yet`. */\n emptyLabel?: string\n /** Fallback title for untitled sessions. */\n untitledLabel?: string\n /** Router prefetch behavior for session links. */\n prefetch?: RailPrefetch\n /** Whether History starts expanded. Defaults to `true`. */\n defaultOpen?: boolean\n}\n\n/**\n * Registered apps shown as individual workspace destinations.\n * Products supply authorized rows and their real route; preview URLs never\n * become navigation hrefs.\n */\nexport interface AgentWorkspaceAppsConfig {\n icon: WorkspaceIcon\n items: readonly Pick<WorkspaceAppRecord, 'id' | 'name'>[]\n hrefForApp: (appId: string) => string\n prefetch?: RailPrefetch\n}\n\n/** Route data for the shared active-nav resolver. */\nexport interface AgentWorkspaceActiveRoute {\n /** Current browser pathname, including the product's workspace base. */\n pathname: string\n /** Product route root, for example `/app/ws_123`. */\n base: string\n /** Product-owned rail routes, relative to `base`. */\n routes: NavRouteDef[]\n /** Extra route prefixes that should highlight an existing row. */\n aliases?: Record<string, string>\n /** Route prefixes that intentionally highlight no row. */\n claimsNothing?: string[]\n}\n\nexport interface AgentWorkspaceLayoutProps\n extends Omit<SidebarLayoutProps, 'activeId' | 'children' | 'navItems' | 'hideBelow' | 'railLabels'> {\n children: ReactNode\n /** Product-owned destinations. The shared History row is appended after them. */\n navItems: SidebarLayoutNavItem[]\n /** Omit for a workflow-only shell with no conversational session rail. */\n sessions?: AgentWorkspaceSessionConfig\n /** Registered app destinations, in the product's persisted order. */\n apps?: AgentWorkspaceAppsConfig\n /** When supplied, active navigation is resolved by the shared route rules. */\n activeRoute?: AgentWorkspaceActiveRoute\n /** Escape hatch for routers that already resolved the active item. */\n activeId?: string\n /** Hide the fixed desktop rail below this breakpoint. Defaults to `lg`. */\n hideBelow?: SidebarLayoutProps['hideBelow']\n /** Show labels beside rail icons. Defaults to `true`. */\n railLabels?: SidebarLayoutProps['railLabels']\n}\n\n/**\n * The default agent workspace composition.\n *\n * Products own their navigation taxonomy, routes, and session storage. This\n * component owns the repeated assembly: the standard visual layout, the\n * expandable History row, capped session composition, unread state, and active\n * route resolution. The full History route and the empty-state composer stay\n * separate because their data and domain copy belong to the product; pair this\n * with `SessionHistoryPanel` and `EntryComposer` for the complete chat-first\n * structure.\n */\nexport function AgentWorkspaceLayout({\n children,\n navItems,\n sessions,\n apps,\n activeRoute,\n activeId,\n ...sidebarProps\n}: AgentWorkspaceLayoutProps) {\n const sessionNav = sessions\n ? (() => {\n const composed = composeSidebarSessions({\n loaderSessions: sessions.sessions,\n optimisticSessions: sessions.optimisticSessions,\n limit: sessions.limit ?? 20,\n totalCount: sessions.totalCount,\n liveUnreadIds: sessions.liveUnreadIds,\n locallyReadIds: sessions.locallyReadIds,\n currentSessionId: sessions.activeSessionId,\n })\n\n return buildSessionNavItem<WorkspaceIcon>({\n id: sessions.id,\n label: sessions.label,\n icon: sessions.icon,\n href: sessions.href,\n sessions: composed.sessions,\n hrefForSession: sessions.hrefForSession,\n activeSessionId: sessions.activeSessionId,\n respondingSessionIds: sessions.respondingSessionIds,\n actions: sessions.actions,\n overflow: composed.hasMore\n ? { href: sessions.href, label: sessions.overflowLabel }\n : undefined,\n emptyLabel: sessions.emptyLabel,\n untitledLabel: sessions.untitledLabel,\n prefetch: sessions.prefetch,\n defaultOpen: sessions.defaultOpen,\n })\n })()\n : undefined\n\n const appNavItems: SidebarLayoutNavItem[] = (apps?.items ?? []).map((app) => {\n const href = apps!.hrefForApp(app.id)\n if (!href.startsWith('/') || href.startsWith('//') || /[?#\\\\]/.test(href)) {\n throw new Error('Workspace app href must be a local route path')\n }\n return {\n id: 'workspace-app:' + app.id,\n label: app.name,\n icon: apps!.icon,\n href,\n prefetch: apps!.prefetch,\n }\n })\n const workspaceNavItems: SidebarLayoutNavItem[] = [\n ...navItems,\n ...appNavItems,\n ...(sessionNav ? [sessionNav] : []),\n ]\n\n const appRoutes: NavRouteDef[] = activeRoute\n ? appNavItems.map((item) => {\n const path = routePathFromHref(item.href!, activeRoute.base)\n if (!path) throw new Error('Workspace app href must be under the active workspace')\n return { id: item.id, path }\n })\n : []\n\n const historyRoutePath = sessions && activeRoute\n ? routePathFromHref(sessions.href, activeRoute.base)\n : null\n\n const resolvedActiveId = activeRoute\n ? resolveActiveNavId({\n ...activeRoute,\n routes: [\n ...activeRoute.routes,\n ...appRoutes,\n ...(sessionNav && historyRoutePath\n ? [{ id: sessions?.id ?? 'history', path: historyRoutePath }]\n : []),\n ],\n })\n : activeId\n\n const layoutProps = {\n hideBelow: 'lg' as const,\n railLabels: true,\n ...sidebarProps,\n }\n\n return (\n <SidebarLayout\n {...layoutProps}\n navItems={workspaceNavItems}\n activeId={resolvedActiveId}\n >\n {children}\n </SidebarLayout>\n )\n}\n"],"mappings":";;;;;;;AAAA,SAAS,qBAAyE;AAwN9E;AAvMJ,SAAS,kBAAkB,MAAc,MAA6B;AACpE,QAAM,OAAO,KAAK,MAAM,QAAQ,CAAC,EAAE,CAAC,KAAK;AACzC,QAAM,OAAO,KAAK,QAAQ,QAAQ,EAAE;AACpC,MAAI,SAAS,KAAM,QAAO;AAC1B,MAAI,CAAC,KAAK,WAAW,GAAG,IAAI,GAAG,EAAG,QAAO;AACzC,SAAO,KAAK,MAAM,KAAK,MAAM;AAC/B;AAoGO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAA8B;AAC5B,QAAM,aAAa,YACd,MAAM;AACL,UAAM,WAAW,uBAAuB;AAAA,MACtC,gBAAgB,SAAS;AAAA,MACzB,oBAAoB,SAAS;AAAA,MAC7B,OAAO,SAAS,SAAS;AAAA,MACzB,YAAY,SAAS;AAAA,MACrB,eAAe,SAAS;AAAA,MACxB,gBAAgB,SAAS;AAAA,MACzB,kBAAkB,SAAS;AAAA,IAC7B,CAAC;AAED,WAAO,oBAAmC;AAAA,MACxC,IAAI,SAAS;AAAA,MACb,OAAO,SAAS;AAAA,MAChB,MAAM,SAAS;AAAA,MACf,MAAM,SAAS;AAAA,MACf,UAAU,SAAS;AAAA,MACnB,gBAAgB,SAAS;AAAA,MACzB,iBAAiB,SAAS;AAAA,MAC1B,sBAAsB,SAAS;AAAA,MAC/B,SAAS,SAAS;AAA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ACP;AAAA,EACF,CAAC,IACD;AAEJ,QAAM,cAAc;AAAA,IAClB,WAAW;AAAA,IACX,YAAY;AAAA,IACZ,GAAG;AAAA,EACL;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACE,GAAG;AAAA,MACJ,UAAU;AAAA,MACV,UAAU;AAAA,MAET;AAAA;AAAA,EACH;AAEJ;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tangle-network/agent-app",
|
|
3
|
-
"version": "0.50.
|
|
3
|
+
"version": "0.50.6",
|
|
4
4
|
"packageManager": "pnpm@11.24.0",
|
|
5
5
|
"description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
|
|
6
6
|
"keywords": [
|
|
@@ -297,6 +297,11 @@
|
|
|
297
297
|
"import": "./dist/chat-react/index.js",
|
|
298
298
|
"default": "./dist/chat-react/index.js"
|
|
299
299
|
},
|
|
300
|
+
"./workspace-apps": {
|
|
301
|
+
"types": "./dist/workspace-apps/index.d.ts",
|
|
302
|
+
"import": "./dist/workspace-apps/index.js",
|
|
303
|
+
"default": "./dist/workspace-apps/index.js"
|
|
304
|
+
},
|
|
300
305
|
"./workspace-react": {
|
|
301
306
|
"types": "./dist/workspace-react/index.d.ts",
|
|
302
307
|
"import": "./dist/workspace-react/index.js",
|