@tangle-network/agent-app 0.60.69 → 0.60.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.
- package/dist/{chunk-SYP6ZT2W.js → chunk-ZRLKB4KB.js} +4 -5
- package/dist/chunk-ZRLKB4KB.js.map +1 -0
- package/dist/integrations-react/index.d.ts +1 -1
- package/dist/integrations-react/index.js +17 -6
- package/dist/integrations-react/index.js.map +1 -1
- package/dist/integrations-react/panel.d.ts +7 -0
- package/dist/integrations-react/projection.d.ts +1 -1
- package/dist/integrations-react/use-hub-integrations.d.ts +11 -1
- package/dist/launch-invariants/cli.js +1 -1
- package/dist/launch-invariants/testing.d.ts +15 -7
- package/dist/launch-invariants/testing.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-SYP6ZT2W.js.map +0 -1
|
@@ -159,6 +159,8 @@ function emptyReads() {
|
|
|
159
159
|
}
|
|
160
160
|
function measureD1(d1, reads = emptyReads(), options = {}) {
|
|
161
161
|
const sampleHeap = options.sampleHeap ?? true;
|
|
162
|
+
const sampleAfterBytes = options.sampleAfterBytes ?? 64 * 1024;
|
|
163
|
+
const sampleEvery = Math.max(1, options.sampleEvery ?? 50);
|
|
162
164
|
const sample = (sql) => {
|
|
163
165
|
if (!sampleHeap) return;
|
|
164
166
|
forceGc();
|
|
@@ -175,6 +177,7 @@ function measureD1(d1, reads = emptyReads(), options = {}) {
|
|
|
175
177
|
reads.maxQueryBytes = bytes;
|
|
176
178
|
reads.largestSql = sql;
|
|
177
179
|
}
|
|
180
|
+
if (bytes >= sampleAfterBytes || reads.queries % sampleEvery === 0) sample(sql);
|
|
178
181
|
};
|
|
179
182
|
const statement = (target, sql) => new Proxy(target, {
|
|
180
183
|
get(stmt, key) {
|
|
@@ -183,10 +186,8 @@ function measureD1(d1, reads = emptyReads(), options = {}) {
|
|
|
183
186
|
if (key === "bind") return (...params) => statement(value.apply(stmt, params), sql);
|
|
184
187
|
if (key === "all" || key === "raw" || key === "first" || key === "run") {
|
|
185
188
|
return async (...args) => {
|
|
186
|
-
sample(sql);
|
|
187
189
|
const result = await value.apply(stmt, args);
|
|
188
190
|
measure(sql, result);
|
|
189
|
-
sample(sql);
|
|
190
191
|
return result;
|
|
191
192
|
};
|
|
192
193
|
}
|
|
@@ -207,10 +208,8 @@ function measureD1(d1, reads = emptyReads(), options = {}) {
|
|
|
207
208
|
}
|
|
208
209
|
if (key === "batch") {
|
|
209
210
|
return async (statements) => {
|
|
210
|
-
sample("batch");
|
|
211
211
|
const result = await value.call(binding, statements.map((stmt) => unwrap.get(stmt) ?? stmt));
|
|
212
212
|
measure("batch", result);
|
|
213
|
-
sample("batch");
|
|
214
213
|
return result;
|
|
215
214
|
};
|
|
216
215
|
}
|
|
@@ -549,4 +548,4 @@ export {
|
|
|
549
548
|
PLATFORM_LIMITS,
|
|
550
549
|
checkLimitAlarms
|
|
551
550
|
};
|
|
552
|
-
//# sourceMappingURL=chunk-
|
|
551
|
+
//# sourceMappingURL=chunk-ZRLKB4KB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/launch-invariants/testing.ts","../src/launch-invariants/conformance.ts"],"sourcesContent":["/**\n * `/launch-invariants/testing` — the checks an app runs in its own test suite.\n *\n * Each check drives the app's real code through a small adapter and returns an\n * {@link InvariantVerdict}. {@link recordInvariant} fails the calling test with\n * the verdict's findings and, when `agent-app-invariants` runs the suite,\n * records the verdict so the conformance report can say which invariant\n * passed. The checks need no test runner: vitest, node:test and plain scripts\n * all work.\n *\n * Node-only (`node:v8`, `node:vm`, `node:fs`): import it from tests, never from\n * a Worker.\n */\nimport { appendFileSync } from 'node:fs'\nimport v8 from 'node:v8'\nimport vm from 'node:vm'\nimport type { AlertSink, TurnHealthAlert } from '../turn-health/sink.js'\nimport { describeVerdict, LAUNCH_BUDGETS, type InvariantVerdict } from './catalog.js'\nimport { LIMIT_RESOURCES, type LimitAlarms } from './limit-alarms.js'\nimport { isEdgeBlock, PASTED_CODE_SAMPLES } from './pasted-code.js'\n\nexport { describeVerdict } from './catalog.js'\n\n/** Set by `agent-app-invariants` to the file it reads verdicts from. */\nexport const INVARIANT_RESULTS_ENV = 'AGENT_APP_INVARIANTS_RESULTS'\n\nexport interface RecordInvariantOptions {\n /**\n * The app knows this check fails today: why, who owns the fix and the next\n * check. The failure is recorded (the report counts the invariant as not\n * holding) without failing the suite, so an app adopts the kit before every\n * invariant holds. Once the check passes, this fails the caller until the\n * marker is removed, so a fixed invariant cannot regress silently.\n */\n knownFailing?: string\n}\n\n/**\n * Record a verdict for the conformance report and fail the caller when it did\n * not pass. Returns the verdict on a pass.\n */\nexport function recordInvariant(verdict: InvariantVerdict, options: RecordInvariantOptions = {}): InvariantVerdict {\n const known = options.knownFailing?.trim()\n const recorded = known && !verdict.pass ? { ...verdict, knownFailing: known } : verdict\n const file = process.env[INVARIANT_RESULTS_ENV]\n if (file) appendFileSync(file, `${JSON.stringify({ ...recorded, at: new Date().toISOString() })}\\n`)\n if (known && verdict.pass) {\n throw new Error(`${describeVerdict(verdict)}\\n this invariant now holds; remove its knownFailing marker (\"${known}\") so it cannot regress silently`)\n }\n if (!verdict.pass && !known) throw new Error(describeVerdict(verdict))\n return recorded\n}\n\n/** Record several verdicts; fails after recording all of them. */\nexport function recordInvariants(verdicts: readonly InvariantVerdict[], options: RecordInvariantOptions = {}): InvariantVerdict[] {\n const failures: string[] = []\n for (const verdict of verdicts) {\n try {\n recordInvariant(verdict, options)\n } catch (error) {\n failures.push(error instanceof Error ? error.message : String(error))\n }\n }\n if (failures.length) throw new Error(failures.join('\\n'))\n return [...verdicts]\n}\n\n// ── heap ─────────────────────────────────────────────────────────────────────\n\nlet gc: (() => void) | undefined\n\n/** Run a full garbage collection, so a heap reading counts only live objects. */\nexport function forceGc(): void {\n if (!gc) {\n v8.setFlagsFromString('--expose_gc')\n gc = vm.runInNewContext('gc') as () => void\n }\n gc()\n}\n\n// ── measured D1 ──────────────────────────────────────────────────────────────\n\nconst MB = 1024 * 1024\n\n/** What a measured binding saw while one job ran. */\nexport interface D1Reads {\n queries: number\n maxQueryBytes: number\n /** The query that returned the most bytes. */\n largestSql: string\n peakHeapBytes: number\n /** The query running when the heap peaked: where a job holds what it read. */\n peakSql: string\n}\n\nfunction emptyReads(): D1Reads {\n return { queries: 0, maxQueryBytes: 0, largestSql: '', peakHeapBytes: 0, peakSql: '' }\n}\n\nexport interface MeasureD1Options {\n /** Sample the live heap at all. Default true. */\n sampleHeap?: boolean\n /** Sample after every response at least this large. Default 64 KB. */\n sampleAfterBytes?: number\n /** Also sample every this-many queries, so what a job keeps from small reads still shows. Default 50. */\n sampleEvery?: number\n}\n\n/**\n * The D1 binding with every response measured (serialized bytes) and the live\n * heap sampled after a forced collection. A collection costs about 50 ms on a\n * test heap and a job runs hundreds of small queries, so the heap is sampled\n * after each large read and every 50th query (GTM's sweeps budget took 170 s\n * sampling around every query). Works over Cloudflare D1 and the sqlite-backed\n * D1 shims apps test with. A database engine that keeps its pages off the JS\n * heap (node:sqlite, better-sqlite3) leaves heap growth to the job's own objects.\n */\nexport function measureD1<D extends object>(d1: D, reads: D1Reads = emptyReads(), options: MeasureD1Options = {}): { d1: D; reads: D1Reads } {\n const sampleHeap = options.sampleHeap ?? true\n const sampleAfterBytes = options.sampleAfterBytes ?? 64 * 1024\n const sampleEvery = Math.max(1, options.sampleEvery ?? 50)\n const sample = (sql: string) => {\n if (!sampleHeap) return\n forceGc()\n const heap = process.memoryUsage().heapUsed\n if (heap > reads.peakHeapBytes) {\n reads.peakHeapBytes = heap\n reads.peakSql = sql\n }\n }\n const measure = (sql: string, result: unknown) => {\n reads.queries += 1\n const bytes = Buffer.byteLength(JSON.stringify(result) ?? '')\n if (bytes > reads.maxQueryBytes) {\n reads.maxQueryBytes = bytes\n reads.largestSql = sql\n }\n if (bytes >= sampleAfterBytes || reads.queries % sampleEvery === 0) sample(sql)\n }\n const statement = (target: object, sql: string): object => new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object, sql)\n if (key === 'all' || key === 'raw' || key === 'first' || key === 'run') {\n return async (...args: unknown[]) => {\n const result: unknown = await value.apply(stmt, args)\n measure(sql, result)\n return result\n }\n }\n return value.bind(stmt)\n },\n })\n const unwrap = new WeakMap<object, object>()\n const proxy = new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') {\n return (sql: string) => {\n const stmt = (value as (sql: string) => object).call(binding, sql)\n const wrapped = statement(stmt, sql.replace(/\\s+/g, ' ').trim().slice(0, 200))\n unwrap.set(wrapped, stmt)\n return wrapped\n }\n }\n if (key === 'batch') {\n return async (statements: object[]) => {\n const result: unknown = await (value as (s: object[]) => Promise<unknown>).call(binding, statements.map((stmt) => unwrap.get(stmt) ?? stmt))\n measure('batch', result)\n return result\n }\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n return { d1: proxy, reads }\n}\n\n/** One scheduled job (or report route) as the budget check runs it. */\nexport interface BudgetedJob {\n name: string\n run: () => Promise<unknown>\n /** False for a job that reads nothing from D1 (it then passes bounded reads vacuously). Default true. */\n readsD1?: boolean\n}\n\nexport interface JobMeasurement {\n name: string\n reads: D1Reads\n heapGrowthBytes: number\n error?: string\n}\n\nexport interface ScheduledJobBudgetOptions {\n /** The app's D1 over its day-sized fixture. */\n d1: object\n /** Point the app's database accessor at the measured binding (`setD1`, `setDatabase(drizzle(...))`). */\n install: (measured: object) => void\n jobs: readonly BudgetedJob[]\n /** Every job the app schedules, by the names {@link jobs} uses. Each must be measured. */\n scheduled: readonly string[]\n maxQueryBytes?: number\n maxHeapGrowthBytes?: number\n /** Silence the jobs' own logging while they run. Default true. */\n quiet?: boolean\n}\n\n/** Run one job against a measured binding. */\nexport async function measureJob(job: BudgetedJob, d1: object, install: (measured: object) => void, quiet = true): Promise<JobMeasurement> {\n const { d1: measured, reads } = measureD1(d1)\n install(measured)\n forceGc()\n const baseline = process.memoryUsage().heapUsed\n reads.peakHeapBytes = baseline\n const restore = quiet ? silenceConsole() : () => {}\n let error: string | undefined\n try {\n await job.run()\n } catch (caught) {\n error = caught instanceof Error ? caught.message : String(caught)\n } finally {\n restore()\n }\n forceGc()\n const after = process.memoryUsage().heapUsed\n if (after > reads.peakHeapBytes) {\n reads.peakHeapBytes = after\n reads.peakSql = reads.peakSql ? `${reads.peakSql} (still held when the job returned)` : '(after the job returned)'\n }\n return { name: job.name, reads, heapGrowthBytes: reads.peakHeapBytes - baseline, ...(error ? { error } : {}) }\n}\n\nfunction silenceConsole(): () => void {\n const saved = { log: console.log, info: console.info, warn: console.warn, error: console.error }\n console.log = console.info = console.warn = console.error = () => {}\n return () => Object.assign(console, saved)\n}\n\n/**\n * Bounded reads and the memory budget for every scheduled job, on the app's\n * day-sized fixture. Returns a bounded-reads and a memory-budget verdict per\n * job, and a coverage verdict naming any scheduled job that was not run.\n */\nexport async function checkScheduledJobBudgets(options: ScheduledJobBudgetOptions): Promise<InvariantVerdict[]> {\n const maxQueryBytes = options.maxQueryBytes ?? LAUNCH_BUDGETS.queryBytes\n const maxHeap = options.maxHeapGrowthBytes ?? LAUNCH_BUDGETS.heapGrowthBytes\n const verdicts: InvariantVerdict[] = []\n const measured = new Set<string>()\n for (const job of options.jobs) {\n const m = await measureJob(job, options.d1, options.install, options.quiet ?? true)\n measured.add(job.name)\n const failed = m.error ? [`the job threw on the fixture: ${m.error}`] : []\n const readFindings = [...failed]\n if ((job.readsD1 ?? true) && m.reads.queries === 0) readFindings.push('made no D1 query on the fixture; the fixture does not reach it, or it reads through another binding')\n if (m.reads.maxQueryBytes > maxQueryBytes) {\n readFindings.push(`one query returned ${(m.reads.maxQueryBytes / MB).toFixed(1)} MB (the most is ${(maxQueryBytes / MB).toFixed(0)} MB): ${m.reads.largestSql}`)\n }\n verdicts.push({\n invariant: 'bounded-reads',\n subject: job.name,\n pass: readFindings.length === 0,\n details: readFindings.length ? readFindings : [`${m.reads.queries} queries, largest ${(m.reads.maxQueryBytes / MB).toFixed(2)} MB`],\n data: { queries: m.reads.queries, maxQueryBytes: m.reads.maxQueryBytes, largestSql: m.reads.largestSql },\n })\n const heapFindings = [...failed]\n if (m.heapGrowthBytes > maxHeap) {\n heapFindings.push(`the live heap grew ${(m.heapGrowthBytes / MB).toFixed(1)} MB (the most is ${(maxHeap / MB).toFixed(0)} MB), at its peak around: ${m.reads.peakSql}`)\n }\n verdicts.push({\n invariant: 'memory-budget',\n subject: job.name,\n pass: heapFindings.length === 0,\n details: heapFindings.length ? heapFindings : [`heap grew ${(m.heapGrowthBytes / MB).toFixed(1)} MB`],\n data: { heapGrowthBytes: m.heapGrowthBytes, peakSql: m.reads.peakSql },\n })\n }\n const missing = options.scheduled.filter((name) => !measured.has(name))\n verdicts.push({\n invariant: 'memory-budget',\n subject: 'coverage',\n pass: missing.length === 0 && options.scheduled.length > 0,\n details: missing.length\n ? missing.map((name) => `${name} is scheduled but not run on the fixture`)\n : options.scheduled.length === 0\n ? ['no scheduled jobs were named; pass every job the app schedules']\n : [`all ${options.scheduled.length} scheduled jobs ran on the fixture`],\n data: { scheduled: [...options.scheduled], measured: [...measured] },\n })\n return verdicts\n}\n\n// ── a D1 that stalls ─────────────────────────────────────────────────────────\n\nexport type StallMode = 'ok' | 'error' | 'hang'\n\n/** The D1 binding with a switch that makes every query fail or never answer, as an overloaded D1 did. */\nexport function stallingD1<D extends object>(d1: D): { d1: D; stall(mode: StallMode): void; readonly mode: StallMode } {\n let mode: StallMode = 'ok'\n const fail = (): Promise<never> => mode === 'hang'\n ? new Promise<never>(() => {})\n : Promise.reject(new Error('D1_ERROR: Network connection lost.'))\n const unwrapped = new WeakMap<object, object>()\n const statement = (target: object): object => {\n const wrapped = new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object)\n if (key === 'all' || key === 'raw' || key === 'first' || key === 'run') {\n return (...args: unknown[]) => (mode === 'ok' ? value.apply(stmt, args) : fail())\n }\n return value.bind(stmt)\n },\n })\n unwrapped.set(wrapped, target)\n return wrapped\n }\n const proxy = new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') return (sql: string) => statement((value as (sql: string) => object).call(binding, sql))\n if (key === 'batch') {\n return (statements: object[]) => (mode === 'ok'\n ? (value as (s: object[]) => unknown).call(binding, statements.map((stmt) => unwrapped.get(stmt) ?? stmt))\n : fail())\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n return {\n d1: proxy,\n stall(next) {\n mode = next\n },\n get mode() {\n return mode\n },\n }\n}\n\n/** Move `Date.now` forward for the duration of a check; returns the restore. */\nfunction shiftableClock(): { advance(ms: number): void; restore(): void } {\n const real = Date.now\n let offset = 0\n Date.now = () => real() + offset\n return {\n advance(ms) {\n offset += ms\n },\n restore() {\n Date.now = real\n },\n }\n}\n\n// ── auth survives a D1 stall ─────────────────────────────────────────────────\n\nexport interface AuthStallOptions {\n /** A label for the lookup: \"session\", \"API key\". */\n subject: string\n /** Three distinct valid credentials the app's store accepts. */\n credentials: { cached: string; revoked: string; aged: string }\n /** The app's real lookup: truthy when the credential is accepted. A throw or a falsy value is a refusal. */\n verify: (credential: string) => Promise<unknown>\n /** The app's real revoke path (revoke the key, sign the session out). */\n revoke: (credential: string) => Promise<void>\n /** Switch the D1 the lookup reads. */\n stall: (mode: StallMode) => void\n /** The keys the app's auth caches hold. */\n cacheKeys: () => string[]\n /** Include a stall that never answers (costs one lookup deadline, 2.5 s). Default true. */\n hang?: boolean\n}\n\n/**\n * A verified credential keeps working while D1 errors or stalls; it is refused\n * once revoked, and once its last verification is more than 60 s old; and the\n * cache holds SHA-256 keys, not secrets. Uses the app's real lookup, revoke\n * path and D1, with `Date.now` moved forward to age the cache.\n */\nexport async function checkAuthSurvivesStall(options: AuthStallOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n const accepted = async (credential: string): Promise<boolean> => {\n try {\n return Boolean(await options.verify(credential))\n } catch {\n return false\n }\n }\n const { cached, revoked, aged } = options.credentials\n const clock = shiftableClock()\n try {\n options.stall('ok')\n for (const credential of [cached, revoked, aged]) {\n if (!(await accepted(credential))) findings.push(`a valid credential was refused while D1 was healthy (${options.subject})`)\n }\n for (const key of options.cacheKeys()) {\n if (!/^[0-9a-f]{64}$/.test(key) || [cached, revoked, aged].some((credential) => key.includes(credential))) {\n findings.push(`the auth cache holds a key that is not a SHA-256 digest: ${key.slice(0, 12)}…`)\n }\n }\n await options.revoke(revoked)\n if (await accepted(revoked)) findings.push('a revoked credential was accepted while D1 was healthy')\n\n options.stall('error')\n if (!(await accepted(cached))) findings.push('a credential verified moments before was refused while D1 errored')\n if (await accepted(revoked)) findings.push('a revoked credential was accepted from the cache while D1 errored')\n if (options.hang ?? true) {\n options.stall('hang')\n if (!(await accepted(cached))) findings.push('a credential verified moments before was refused while D1 did not answer')\n }\n\n clock.advance(LAUNCH_BUDGETS.authCacheTtlMs + 1_000)\n options.stall('error')\n if (await accepted(aged)) findings.push(`a credential last verified more than ${LAUNCH_BUDGETS.authCacheTtlMs / 1000} s ago was accepted from the cache while D1 errored`)\n } finally {\n options.stall('ok')\n clock.restore()\n }\n return {\n invariant: 'auth-survives-d1-stall',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [\n 'served while D1 errored and while it stalled; refused after revoke and after the 60 s cache window; keys are SHA-256',\n ],\n }\n}\n\n// ── authorization before any stream ──────────────────────────────────────────\n\nexport interface AuthorizeBeforeStreamOptions {\n subject: string\n /** The app's real route handler, as its router mounts it. */\n handle: (request: Request) => Promise<Response>\n /** Requests the route must refuse: no session, another workspace's thread, a revoked key. */\n refused: ReadonlyArray<{ name: string; request: () => Request; status?: readonly number[] }>\n /** Product state the route touched (rows written, producers started); empty after every refusal. */\n touched?: () => readonly string[]\n}\n\nconst STREAM_TYPES = /event-stream|ndjson|x-turn-progress/i\n\n/** Each refused request gets a plain 4xx, opens no stream and touches nothing. */\nexport async function checkAuthorizeBeforeStream(options: AuthorizeBeforeStreamOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n for (const probe of options.refused) {\n const before = options.touched?.().length ?? 0\n const response = await options.handle(probe.request())\n const allowed = probe.status ?? [401, 403, 404]\n if (!allowed.includes(response.status)) findings.push(`${probe.name}: answered ${response.status}, expected ${allowed.join(' or ')}`)\n const type = response.headers.get('content-type') ?? ''\n if (STREAM_TYPES.test(type)) findings.push(`${probe.name}: opened a ${type} stream before refusing`)\n for (const [name] of response.headers) {\n if (/turn-progress|x-turn-id/i.test(name)) findings.push(`${probe.name}: refusal carries turn header ${name}`)\n }\n await response.body?.cancel().catch(() => undefined)\n const after = options.touched?.() ?? []\n if (after.length > before) findings.push(`${probe.name}: touched ${after.slice(before).join(', ')} before refusing`)\n }\n return {\n invariant: 'authorize-before-stream',\n subject: options.subject,\n pass: findings.length === 0 && options.refused.length > 0,\n details: findings.length ? findings : options.refused.length\n ? [`${options.refused.length} refused requests answered plainly with nothing touched`]\n : ['no refused requests were probed'],\n }\n}\n\n// ── pasted code reaches the chat ─────────────────────────────────────────────\n\nexport interface ChatAcceptsCodeOptions {\n subject: string\n /** The app's real chat route handler, as its router mounts it. */\n handle: (request: Request) => Promise<Response>\n /** An authenticated chat request carrying `text` as the message. */\n request: (text: string) => Request\n /** Statuses the route answers an accepted message with. Default any 2xx. */\n accepted?: (status: number) => boolean\n samples?: readonly { name: string; text: string }[]\n}\n\n/** Each pasted-code sample gets the route's normal response, never a refusal or an edge block. Cancels any stream it opens. */\nexport async function checkChatAcceptsCode(options: ChatAcceptsCodeOptions): Promise<InvariantVerdict> {\n const accepted = options.accepted ?? ((status: number) => status >= 200 && status < 300)\n const samples = options.samples ?? PASTED_CODE_SAMPLES\n const findings: string[] = []\n for (const sample of samples) {\n const response = await options.handle(options.request(sample.text))\n if (await isEdgeBlock(response)) findings.push(`${sample.name}: an edge rule blocked it (${response.status})`)\n else if (!accepted(response.status)) {\n const body = (await response.clone().text().catch(() => '')).slice(0, 160)\n findings.push(`${sample.name}: answered ${response.status}${body ? `: ${body}` : ''}`)\n }\n await response.body?.cancel().catch(() => undefined)\n }\n return {\n invariant: 'pasted-code-reaches-chat',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [`${samples.length} pasted-code messages reached the chat and got its normal response`],\n }\n}\n\n// ── coalesced turn events ────────────────────────────────────────────────────\n\n/** One event of the recorded long turn and the turn-relative time it arrived. */\nexport interface TimedTurnEvent {\n atMs: number\n event: Record<string, unknown>\n}\n\n/**\n * The long turn GTM recorded on 2026-10-10, reproduced in shape: a reasoning\n * model streaming three events per token (the harness's raw part update, a\n * model-processing heartbeat and the delta), with tool calls between runs of\n * reasoning and text. 59,659 events over about ten minutes, as that turn wrote\n * them before coalescing.\n */\nexport function recordedLongTurn(options: { tokens?: number; toolCalls?: number; tokenMs?: number } = {}): TimedTurnEvent[] {\n const tokens = options.tokens ?? 19_866\n const toolCalls = options.toolCalls ?? 30\n const tokenMs = options.tokenMs ?? 30\n const events: TimedTurnEvent[] = [{ atMs: 0, event: { type: 'turn', turnId: 'recorded-long-turn' } }]\n const toolEvery = Math.max(1, Math.floor(tokens / (toolCalls + 1)))\n let tool = 0\n let part = 0\n for (let index = 0; index < tokens; index += 1) {\n const atMs = (index + 1) * tokenMs\n if (index > 0 && index % toolEvery === 0 && tool < toolCalls) {\n tool += 1\n part += 1\n events.push({ atMs, event: { type: 'tool_call', id: `call_${tool}`, name: 'bash', input: { command: 'ls' } } })\n events.push({ atMs: atMs + 1, event: { type: 'tool_result', id: `call_${tool}`, output: 'ok' } })\n }\n const kind = part % 2 === 0 ? 'reasoning' : 'text'\n const partId = `prt_${part}`\n events.push({ atMs, event: { type: 'raw', data: { type: 'raw', backend: 'opencode', event: { type: kind, timestamp: atMs, part: { id: partId, type: kind, metadata: { at: atMs } } } } } })\n events.push({ atMs, event: { type: 'model-processing', data: { elapsedMs: atMs } } })\n events.push({ atMs, event: { type: kind, text: `t${index} ` } })\n }\n return events\n}\n\nexport interface CoalescedTurnOptions {\n subject: string\n /**\n * Start persisting one turn through the app's real turn persistence (its turn\n * store and buffer, as its chat route builds them). `detach` hands the turn\n * to a durable owner the way the route's completion handoff does; omit it when\n * the app has no detached lane.\n */\n open: (turnId: string) => Promise<{\n onEvent(event: unknown): Promise<void>\n detach?(): Promise<void>\n done(): Promise<void>\n }>\n /** Stored events for the turn. */\n count: (turnId: string) => Promise<number>\n maxEvents?: number\n fixture?: readonly TimedTurnEvent[]\n}\n\n/** The recorded long turn stores at most 5,000 events, attached and after a handoff. */\nexport async function checkCoalescedTurn(options: CoalescedTurnOptions): Promise<InvariantVerdict> {\n const maxEvents = options.maxEvents ?? LAUNCH_BUDGETS.turnEvents\n const fixture = options.fixture ?? recordedLongTurn()\n const findings: string[] = []\n const stored: Record<string, number> = {}\n const real = Date.now\n for (const lane of ['attached', 'detached'] as const) {\n const turnId = `invariant-long-turn-${lane}`\n const start = real()\n let clock = start\n Date.now = () => clock\n try {\n const tap = await options.open(turnId)\n if (lane === 'detached' && !tap.detach) continue\n for (const [index, item] of fixture.entries()) {\n clock = start + item.atMs\n await tap.onEvent(item.event)\n if (lane === 'detached' && index === 0) await tap.detach!()\n }\n clock = start + (fixture.at(-1)?.atMs ?? 0) + 1\n await tap.done()\n stored[lane] = await options.count(turnId)\n } finally {\n Date.now = real\n }\n if (stored[lane] === 0) findings.push(`${lane}: the turn stored no events; the check did not reach the app's turn store`)\n if (stored[lane]! > maxEvents) findings.push(`${lane}: the recorded long turn (${fixture.length.toLocaleString('en-US')} events) stored ${stored[lane]!.toLocaleString('en-US')}; the most is ${maxEvents.toLocaleString('en-US')}`)\n }\n return {\n invariant: 'coalesced-events',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : Object.entries(stored).map(([lane, count]) => `${lane}: ${fixture.length.toLocaleString('en-US')} events stored as ${count.toLocaleString('en-US')}`),\n data: { fixtureEvents: fixture.length, stored },\n }\n}\n\n// ── limit alarms ─────────────────────────────────────────────────────────────\n\n/** Hard platform limits a declared budget may not exceed. */\nexport const PLATFORM_LIMITS = {\n /** A Worker isolate's memory. */\n 'worker-memory': 128 * MB,\n /** Platform snapshots per sandbox; the cap GTM hit on 2026-10-10. */\n 'snapshot-count': 25,\n /** Requests per minute per operator key. */\n 'key-rate': 60,\n} as const\n\nexport interface LimitAlarmCheckOptions {\n subject: string\n /** Build the app's real limit alarms (its budgets and wiring) over a capturing sink. */\n create: (sink: AlertSink) => LimitAlarms | Promise<LimitAlarms>\n}\n\n/** Every resource alarms at 80% and not below, escalates at the limit, and no budget exceeds the platform's. */\nexport async function checkLimitAlarms(options: LimitAlarmCheckOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n for (const resource of LIMIT_RESOURCES) {\n const delivered: TurnHealthAlert[] = []\n const alarms = await options.create({ deliver: async (alert) => { delivered.push(alert) } })\n const limit = alarms.budgets[resource]\n const platform = (PLATFORM_LIMITS as Partial<Record<string, number>>)[resource]\n if (platform !== undefined && limit > platform) findings.push(`${resource}: the declared limit ${limit} is above the platform's ${platform}`)\n await alarms.observe(resource, limit * 0.79)\n if (delivered.length) findings.push(`${resource}: alarmed at 79% of its limit`)\n await alarms.observe(resource, limit * LAUNCH_BUDGETS.alarmRatio)\n if (delivered.length !== 1 || delivered[0]?.severity !== 'warning') findings.push(`${resource}: did not warn at 80% of its limit`)\n await alarms.observe(resource, limit)\n if (delivered.length !== 2 || delivered[1]?.severity !== 'critical') findings.push(`${resource}: did not raise a critical alert at its limit`)\n }\n return {\n invariant: 'limit-alarms',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [`${LIMIT_RESOURCES.join(', ')} warn at 80% and page at the limit`],\n }\n}\n\nexport {\n buildConformanceReport,\n formatConformanceReport,\n readDeploymentFacts,\n readVerdicts,\n type ConformanceReport,\n type DeploymentFacts,\n type InvariantReport,\n type InvariantStatus,\n type LaunchInvariantsConfig,\n} from './conformance.js'\n","/**\n * The conformance report: which launch invariants an app holds.\n *\n * `agent-app-invariants` runs the app's invariant tests with\n * `AGENT_APP_INVARIANTS_RESULTS` set, reads the verdicts they recorded, and\n * checks what it can see without the app's code: the crons each wrangler\n * environment configures, and whether the app has a D1 binding at all. An\n * invariant passes when at least one verdict was recorded for it and every\n * recorded verdict passed. Not applicable is accepted only where the\n * deployment shows it: no configured crons, or no D1 binding.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { LAUNCH_INVARIANTS, type InvariantVerdict, type LaunchInvariantId } from './catalog.js'\nimport { parseWranglerCrons } from './schedule.js'\n\n/** `launch-invariants.config.mjs` (or `.json`) at the app root. */\nexport interface LaunchInvariantsConfig {\n /** The app's name in the report. */\n product: string\n /** The command that runs the app's invariant tests, e.g. `pnpm exec vitest run tests/launch-invariants.test.ts`. */\n test: string\n /** Wrangler configs, relative to the app root. Default: the first of wrangler.toml, wrangler.jsonc, wrangler.json. */\n wrangler?: readonly string[]\n /** Invariants the deployment shows do not apply, with the reason. */\n notApplicable?: Partial<Record<LaunchInvariantId, string>>\n}\n\n/** What the deployment declares, read from its wrangler configs. */\nexport interface DeploymentFacts {\n wranglerFiles: string[]\n configuredCrons: string[]\n hasD1: boolean\n}\n\nexport type InvariantStatus = 'pass' | 'fail' | 'known-fail' | 'not-applicable'\n\nexport interface InvariantReport {\n id: LaunchInvariantId\n title: string\n status: InvariantStatus\n /** Why it failed or does not apply; on a pass, what was proven. */\n lines: string[]\n verdicts: number\n}\n\nexport interface ConformanceReport {\n product: string\n pass: boolean\n passed: number\n total: number\n testExitCode: number | null\n /** Invariants failing with a known-failing marker: not holding, but not failing the run. */\n knownFailing: number\n invariants: InvariantReport[]\n facts: DeploymentFacts\n}\n\n/** Read the crons and D1 bindings the app's wrangler configs declare. */\nexport function readDeploymentFacts(appDir: string, files?: readonly string[]): DeploymentFacts {\n const candidates = files ?? ['wrangler.toml', 'wrangler.jsonc', 'wrangler.json'].filter((file) => existsSync(join(appDir, file))).slice(0, 1)\n const crons = new Set<string>()\n let hasD1 = false\n for (const file of candidates) {\n const source = readFileSync(join(appDir, file), 'utf8')\n const json = /\\.jsonc?$/.test(file)\n const parsed = parseWranglerCrons(source, json ? 'json' : 'toml')\n for (const cron of [...parsed.top, ...Object.values(parsed.envs).flat()]) crons.add(cron)\n if (json ? /\"d1_databases\"\\s*:\\s*\\[\\s*\\{/.test(source) : /^\\s*\\[\\[(?:env\\.[^.\\]]+\\.)?d1_databases\\]\\]/m.test(source)) hasD1 = true\n }\n return { wranglerFiles: [...candidates], configuredCrons: [...crons], hasD1 }\n}\n\nconst NOT_APPLICABLE_WHEN: Partial<Record<LaunchInvariantId, { holds: (facts: DeploymentFacts) => boolean; condition: string }>> = {\n 'isolated-jobs': { holds: (facts) => facts.configuredCrons.length === 0, condition: 'no configured crons' },\n 'memory-budget': { holds: (facts) => facts.configuredCrons.length === 0, condition: 'no configured crons' },\n 'bounded-reads': { holds: (facts) => !facts.hasD1, condition: 'no D1 binding' },\n 'auth-survives-d1-stall': { holds: (facts) => !facts.hasD1, condition: 'no D1 binding' },\n}\n\n/** Parse the results file the invariant tests appended to. */\nexport function readVerdicts(source: string): InvariantVerdict[] {\n return source.split('\\n').filter((line) => line.trim()).flatMap((line) => {\n try {\n return [JSON.parse(line) as InvariantVerdict]\n } catch {\n return []\n }\n })\n}\n\n/** Judge each invariant from the recorded verdicts and the deployment facts. */\nexport function buildConformanceReport(input: {\n config: LaunchInvariantsConfig\n facts: DeploymentFacts\n verdicts: readonly InvariantVerdict[]\n testExitCode: number | null\n}): ConformanceReport {\n const { config, facts } = input\n const invariants = LAUNCH_INVARIANTS.map((invariant): InvariantReport => {\n const verdicts = input.verdicts.filter((verdict) => verdict.invariant === invariant.id)\n const reason = config.notApplicable?.[invariant.id]\n if (reason !== undefined) {\n const rule = NOT_APPLICABLE_WHEN[invariant.id]\n if (rule?.holds(facts)) return { id: invariant.id, title: invariant.title, status: 'not-applicable', lines: [`${reason} (verified: ${rule.condition})`], verdicts: verdicts.length }\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'fail',\n lines: [rule\n ? `declared not applicable (\"${reason}\"), but the deployment does not show ${rule.condition}`\n : `declared not applicable (\"${reason}\"), but this invariant applies to every agent app`],\n verdicts: verdicts.length,\n }\n }\n if (verdicts.length === 0) {\n return { id: invariant.id, title: invariant.title, status: 'fail', lines: [`no check recorded a verdict; ${invariant.rule}`], verdicts: 0 }\n }\n const failed = verdicts.filter((verdict) => !verdict.pass)\n const unknown = failed.filter((verdict) => !verdict.knownFailing)\n if (failed.length > 0 && unknown.length === 0) {\n const reasons = [...new Set(failed.map((verdict) => verdict.knownFailing!))]\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'known-fail',\n lines: [...reasons.map((reason) => `known failing: ${reason}`), ...failed.flatMap((verdict) => verdict.details.map((detail) => `${verdict.subject}: ${detail}`))],\n verdicts: verdicts.length,\n }\n }\n const lines = failed.length\n ? failed.flatMap((verdict) => verdict.details.map((detail) => `${verdict.subject}: ${detail}`))\n : verdicts.map((verdict) => `${verdict.subject}: ${verdict.details[0] ?? 'passed'}`)\n if (invariant.id === 'isolated-jobs' && failed.length === 0) {\n const checked = new Set(verdicts.flatMap((verdict) => (verdict.data?.configuredCrons as string[] | undefined) ?? []))\n const unchecked = facts.configuredCrons.filter((cron) => !checked.has(cron))\n if (unchecked.length) {\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'fail',\n lines: [`the check did not read every configured cron: ${unchecked.map((cron) => `\"${cron}\"`).join(', ')} (from ${facts.wranglerFiles.join(', ')})`],\n verdicts: verdicts.length,\n }\n }\n }\n return { id: invariant.id, title: invariant.title, status: failed.length ? 'fail' : 'pass', lines, verdicts: verdicts.length }\n })\n const passed = invariants.filter((invariant) => invariant.status === 'pass' || invariant.status === 'not-applicable').length\n const knownFailing = invariants.filter((invariant) => invariant.status === 'known-fail').length\n return {\n product: config.product,\n pass: passed + knownFailing === invariants.length && input.testExitCode === 0,\n passed,\n total: invariants.length,\n testExitCode: input.testExitCode,\n knownFailing,\n invariants,\n facts,\n }\n}\n\n/** The report as the CLI prints it. */\nexport function formatConformanceReport(report: ConformanceReport): string {\n const mark: Record<InvariantStatus, string> = { pass: 'PASS', fail: 'FAIL', 'known-fail': 'KNOWN', 'not-applicable': 'N/A ' }\n const lines = [`launch invariants — ${report.product}: ${report.passed} of ${report.total} hold${report.knownFailing ? `, ${report.knownFailing} known failing` : ''}`]\n for (const invariant of report.invariants) {\n lines.push(` ${mark[invariant.status]} ${invariant.id} — ${invariant.title}`)\n const shown = invariant.status === 'fail' || invariant.status === 'known-fail' ? invariant.lines : invariant.lines.slice(0, 3)\n for (const line of shown) lines.push(` ${line}`)\n if (invariant.status !== 'fail' && invariant.lines.length > shown.length) lines.push(` … ${invariant.lines.length - shown.length} more`)\n }\n if (report.testExitCode !== 0) lines.push(` the invariant test command exited ${report.testExitCode ?? 'by signal'}`)\n lines.push(report.passed === report.total && report.pass\n ? 'RESULT: launch-grade'\n : report.pass ? `RESULT: not launch-grade yet; ${report.knownFailing} known failing, no regressions` : 'RESULT: not launch-grade')\n return lines.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,sBAAsB;AAC/B,OAAO,QAAQ;AACf,OAAO,QAAQ;;;ACJf,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AA+Cd,SAAS,oBAAoB,QAAgB,OAA4C;AAC9F,QAAM,aAAa,SAAS,CAAC,iBAAiB,kBAAkB,eAAe,EAAE,OAAO,CAAC,SAAS,WAAW,KAAK,QAAQ,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC;AAC5I,QAAM,QAAQ,oBAAI,IAAY;AAC9B,MAAI,QAAQ;AACZ,aAAW,QAAQ,YAAY;AAC7B,UAAM,SAAS,aAAa,KAAK,QAAQ,IAAI,GAAG,MAAM;AACtD,UAAM,OAAO,YAAY,KAAK,IAAI;AAClC,UAAM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AS,MAAM,QAAQ,OAAO,EAAE,SAAS,OAAO,UAAU;AAAE,gBAAU,KAAK,KAAK;AAAA,IAAE,EAAE,CAAC;AAC3F,UAAM,QAAQ,OAAO,QAAQ,QAAQ;AACrC,UAAM,WAAY,gBAAoD,QAAQ;AAC9E,QAAI,aAAa,UAAa,QAAQ,SAAU,UAAS,KAAK,GAAG,QAAQ,wBAAwB,KAAK,4BAA4B,QAAQ,EAAE;AAC5I,UAAM,OAAO,QAAQ,UAAU,QAAQ,IAAI;AAC3C,QAAI,UAAU,OAAQ,UAAS,KAAK,GAAG,QAAQ,+BAA+B;AAC9E,UAAM,OAAO,QAAQ,UAAU,QAAQ,eAAe,UAAU;AAChE,QAAI,UAAU,WAAW,KAAK,UAAU,CAAC,GAAG,aAAa,UAAW,UAAS,KAAK,GAAG,QAAQ,oCAAoC;AACjI,UAAM,OAAO,QAAQ,UAAU,KAAK;AACpC,QAAI,UAAU,WAAW,KAAK,UAAU,CAAC,GAAG,aAAa,WAAY,UAAS,KAAK,GAAG,QAAQ,+CAA+C;AAAA,EAC/I;AACA,SAAO;AAAA,IACL,WAAW;AAAA,IACX,SAAS,QAAQ;AAAA,IACjB,MAAM,SAAS,WAAW;AAAA,IAC1B,SAAS,SAAS,SAAS,WAAW,CAAC,GAAG,gBAAgB,KAAK,IAAI,CAAC,oCAAoC;AAAA,EAC1G;AACF;","names":["reason"]}
|
|
@@ -2,5 +2,5 @@ export { HubConnectCallbackPage, type HubConnectCallbackPageProps } from './call
|
|
|
2
2
|
export { createHubIntegrationsClient, type HubIntegrationsClient, type HubIntegrationsIdentity, type HubSettingsRequest, type HubSettingsRequestFn } from './client';
|
|
3
3
|
export { HubIntegrationsPanel, type HubAccountStatus, type HubIntegrationsAccounts, type HubIntegrationsPanelProps } from './panel';
|
|
4
4
|
export { HUB_CONNECT_CHANNEL, HUB_CONNECTED_MESSAGE_TYPE, HUB_CONNECT_FAILED_MESSAGE_TYPE, POPUP_TIMEOUT_MS } from './popup';
|
|
5
|
-
export { useHubIntegrations, type HubWriteReceipt, type UseHubIntegrationsOptions } from './use-hub-integrations';
|
|
5
|
+
export { useHubIntegrations, type HubHostConnect, type HubWriteReceipt, type UseHubIntegrationsOptions } from './use-hub-integrations';
|
|
6
6
|
export { type HubIntegrationCapabilities, type HubIntegrationCapability } from './projection';
|
|
@@ -321,7 +321,7 @@ function contextKey(identity) {
|
|
|
321
321
|
function displayProvider(provider) {
|
|
322
322
|
return { providerId: provider.providerId, title: provider.title, category: provider.category };
|
|
323
323
|
}
|
|
324
|
-
function catalogRows(providers, connections, selectedIds, can, hasUnsupportedConnect = false) {
|
|
324
|
+
function catalogRows(providers, connections, selectedIds, can, hasUnsupportedConnect = false, hostConnectProviderIds = []) {
|
|
325
325
|
return providers.map((provider) => {
|
|
326
326
|
const accounts = connections.filter((connection) => connection.providerId === provider.providerId);
|
|
327
327
|
return {
|
|
@@ -329,7 +329,7 @@ function catalogRows(providers, connections, selectedIds, can, hasUnsupportedCon
|
|
|
329
329
|
kind: "provider",
|
|
330
330
|
authKind: provider.authKind,
|
|
331
331
|
selectedConnectionId: accounts.some((account) => account.id === selectedIds[provider.providerId]) ? selectedIds[provider.providerId] ?? null : null,
|
|
332
|
-
canConnect: provider.authKind === "oauth2" ? provider.configured && can({ operation: "oauth.start", providerId: provider.providerId }) : provider.authKind === "api_key" ? provider.configured && can({ operation: "api-key.connect", providerId: provider.providerId }) : hasUnsupportedConnect,
|
|
332
|
+
canConnect: hostConnectProviderIds.includes(provider.providerId) ? true : provider.authKind === "oauth2" ? provider.configured && can({ operation: "oauth.start", providerId: provider.providerId }) : provider.authKind === "api_key" ? provider.configured && can({ operation: "api-key.connect", providerId: provider.providerId }) : hasUnsupportedConnect,
|
|
333
333
|
connections: accounts.map((connection) => ({
|
|
334
334
|
id: connection.id,
|
|
335
335
|
accountDisplay: connection.accountDisplay ?? connection.displayName,
|
|
@@ -399,7 +399,7 @@ function updateUrl(providerId, connectionId) {
|
|
|
399
399
|
else url.searchParams.delete("connection");
|
|
400
400
|
window.history.pushState(window.history.state, "", url);
|
|
401
401
|
}
|
|
402
|
-
function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect }) {
|
|
402
|
+
function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect, hostConnect }) {
|
|
403
403
|
const scope = contextKey(identity);
|
|
404
404
|
const activeScope = useRef(scope);
|
|
405
405
|
activeScope.current = scope;
|
|
@@ -548,6 +548,10 @@ function useHubIntegrations({ identity, client, can, callbackPath, onUnsupported
|
|
|
548
548
|
return result;
|
|
549
549
|
}, [can, connections, client, identity, callbackPath, scope]);
|
|
550
550
|
const beginConnect = useCallback((target) => {
|
|
551
|
+
if (hostConnect?.providerIds.includes(target.providerId)) {
|
|
552
|
+
hostConnect.onConnect(target);
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
551
555
|
if (target.authKind !== "api_key" && target.authKind !== "oauth2") {
|
|
552
556
|
if (onUnsupportedConnect) onUnsupportedConnect(target);
|
|
553
557
|
else setConnectStatus({ scope, status: "failed", message: "This provider needs an app-specific connection flow." });
|
|
@@ -571,7 +575,7 @@ function useHubIntegrations({ identity, client, can, callbackPath, onUnsupported
|
|
|
571
575
|
else void startOAuth(target);
|
|
572
576
|
return;
|
|
573
577
|
}
|
|
574
|
-
}, [can, onUnsupportedConnect, scope, startOAuth]);
|
|
578
|
+
}, [can, onUnsupportedConnect, hostConnect, scope, startOAuth]);
|
|
575
579
|
const cancelConnect = useCallback(() => {
|
|
576
580
|
pendingPopup.current?.abort();
|
|
577
581
|
pendingPopup.current = null;
|
|
@@ -579,8 +583,15 @@ function useHubIntegrations({ identity, client, can, callbackPath, onUnsupported
|
|
|
579
583
|
setConnectStatus({ scope, status: "failed", message: "Connection was cancelled." });
|
|
580
584
|
}, [scope]);
|
|
581
585
|
const rows = useMemo(
|
|
582
|
-
() => catalogRows(
|
|
583
|
-
|
|
586
|
+
() => catalogRows(
|
|
587
|
+
providerList,
|
|
588
|
+
connectionList,
|
|
589
|
+
visibleSelection.providerId && visibleSelection.connectionId ? { [visibleSelection.providerId]: visibleSelection.connectionId } : {},
|
|
590
|
+
can,
|
|
591
|
+
!!onUnsupportedConnect,
|
|
592
|
+
hostConnect?.providerIds
|
|
593
|
+
),
|
|
594
|
+
[providerList, connectionList, visibleSelection.providerId, visibleSelection.connectionId, can, onUnsupportedConnect, hostConnect]
|
|
584
595
|
);
|
|
585
596
|
const details = detail.status === "ready" && connection ? permissionDetails(detail.value.tools, detail.value.policies, connection.id, can) : void 0;
|
|
586
597
|
return {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations-react/callback.tsx","../../src/integrations-react/popup.ts","../../src/integrations-react/client.ts","../../src/integrations-react/panel.tsx","../../src/integrations-react/projection.ts","../../src/integrations-react/use-hub-integrations.ts"],"sourcesContent":["import { useEffect, useState } from 'react'\nimport { HUB_CONNECTED_MESSAGE_TYPE, HUB_CONNECT_CHANNEL, HUB_CONNECT_FAILED_MESSAGE_TYPE, localAppUrl } from './popup'\n\nexport interface HubConnectCallbackPageProps {\n /** Local settings destination owned by the consuming app. */\n returnHref: string\n}\n\n/** The callback only signals completion; the opener verifies fresh Hub state. */\nexport function HubConnectCallbackPage({ returnHref }: HubConnectCallbackPageProps) {\n const [phase, setPhase] = useState<'checking' | 'returned' | 'failed'>('checking')\n const [reason, setReason] = useState('')\n\n useEffect(() => {\n const params = new URLSearchParams(window.location.search)\n const provider = params.get('provider')\n const nonce = params.get('nonce')\n const context = params.get('context')\n if (!provider || !nonce || !context) { setReason('This connection callback is incomplete.'); setPhase('failed'); return }\n const failure = params.get('error_description') || params.get('error')\n try {\n const channel = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n channel.postMessage({ type: failure ? HUB_CONNECT_FAILED_MESSAGE_TYPE : HUB_CONNECTED_MESSAGE_TYPE, provider, nonce, context })\n channel.close()\n } catch { /* The opener also polls the authoritative connection list. */ }\n if (failure) { setReason(failure.slice(0, 200)); setPhase('failed'); return }\n window.close()\n const timer = window.setTimeout(() => setPhase('returned'), 150)\n return () => window.clearTimeout(timer)\n }, [])\n\n const destination = localAppUrl(returnHref)\n const localReturn = destination ? `${destination.pathname}${destination.search}${destination.hash}` : '/'\n return <main aria-live=\"polite\" style={{ maxWidth: 560, margin: '20vh auto', padding: 24, textAlign: 'center' }}>\n {phase === 'checking' ? <p>Checking your connection…</p> : phase === 'returned'\n ? <p>Return to the app to check your connection. You can close this window.</p>\n : <p>Could not complete the connection. {reason}</p>}\n <a href={localReturn}>Return to integrations</a>\n </main>\n}\n","import type { HubConnection } from '@tangle-network/hub-sdk'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\n\nexport const HUB_CONNECT_CHANNEL = 'tangle:hub-connect'\nexport const HUB_CONNECTED_MESSAGE_TYPE = 'tangle:hub-connected'\nexport const HUB_CONNECT_FAILED_MESSAGE_TYPE = 'tangle:hub-connect-failed'\nexport const POPUP_TIMEOUT_MS = 5 * 60 * 1000\nconst PRE_REDIRECT_TIMEOUT_MS = 30_000\nconst POLL_INTERVAL_MS = 2500\nconst POPUP_FEATURES = 'popup=yes,width=520,height=680'\n\nexport type PopupConnectResult = 'connected' | 'blocked' | 'cancelled' | 'unverified' | 'unavailable'\n\nexport function localAppUrl(path: string): URL | null {\n if (!path.startsWith('/') || path.startsWith('//')) return null\n try {\n const origin = typeof window === 'undefined' ? 'https://local.invalid' : window.location.origin\n const url = new URL(path, origin)\n return url.origin === origin && !url.username && !url.password ? url : null\n } catch { return null }\n}\n\nfunction updatedConnection(providerId: string, before: readonly HubConnection[], after: readonly HubConnection[]): boolean {\n const previous = new Map(before.filter(connection => connection.providerId === providerId).map(connection => [connection.id, connection]))\n return after.some(connection => {\n if (connection.providerId !== providerId || connection.status !== 'active' || connection.health === 'unhealthy') return false\n const old = previous.get(connection.id)\n return !old || old.updatedAt !== connection.updatedAt || old.status !== connection.status\n })\n}\n\nfunction closePopup(popup: Window): void {\n try { if (!popup.closed) popup.close() } catch { /* COOP may sever the handle. */ }\n}\n\nfunction withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) { reject(new DOMException('Aborted', 'AbortError')); return }\n const onAbort = () => reject(new DOMException('Aborted', 'AbortError'))\n signal.addEventListener('abort', onAbort, { once: true })\n promise.then(value => { signal.removeEventListener('abort', onAbort); resolve(value) }, error => { signal.removeEventListener('abort', onAbort); reject(error) })\n })\n}\n\nfunction waitForConnection(input: {\n popup: Window\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n nonce: string\n contextToken: string\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n return new Promise(resolve => {\n let settled = false\n let checking = false\n let pollId: number | undefined\n let timeoutId: number | undefined\n let channel: BroadcastChannel | undefined\n const finish = (result: PopupConnectResult) => {\n if (settled) return\n settled = true\n if (pollId !== undefined) window.clearTimeout(pollId)\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n input.signal.removeEventListener('abort', onAbort)\n channel?.close()\n closePopup(input.popup)\n resolve(result)\n }\n const onAbort = () => finish('cancelled')\n const check = async () => {\n if (settled || checking) return\n checking = true\n if (!input.isCurrent() || input.signal.aborted) { finish('cancelled'); return }\n try {\n const after = await input.client.connections(input.identity, input.signal)\n if (input.isCurrent() && updatedConnection(input.providerId, input.before, after)) { finish('connected'); return }\n } catch { /* A lost read is never evidence of a connection. Keep polling. */ }\n checking = false\n if (!settled) pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n }\n if (input.signal.aborted) { finish('cancelled'); return }\n input.signal.addEventListener('abort', onAbort, { once: true })\n try {\n const candidate = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n candidate.onmessage = event => {\n const message = event.data as Record<string, unknown> | null\n if (!message || message.provider !== input.providerId || message.nonce !== input.nonce || message.context !== input.contextToken) return\n if (message.type === HUB_CONNECT_FAILED_MESSAGE_TYPE) finish('cancelled')\n if (message.type === HUB_CONNECTED_MESSAGE_TYPE) {\n if (pollId !== undefined) window.clearTimeout(pollId)\n void check()\n }\n }\n channel = candidate\n } catch { /* Polling covers browsers without BroadcastChannel. */ }\n pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n timeoutId = window.setTimeout(() => finish('unverified'), POPUP_TIMEOUT_MS)\n })\n}\n\n/** Opens before the first await, preserving the initiating user gesture. */\nexport async function connectWithPopup(input: {\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n callbackPath: string\n connectionParameters?: Record<string, string>\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n const callback = localAppUrl(input.callbackPath)\n if (!callback) throw new TypeError('Callback path must be local.')\n const popup = window.open('', '_blank', POPUP_FEATURES)\n if (!popup) return 'blocked'\n // Keep the parent handle for navigation while removing the provider page's opener.\n try { popup.opener = null } catch { /* Some browsers make this read-only. */ }\n const nonce = crypto.randomUUID()\n const contextToken = crypto.randomUUID()\n callback.searchParams.set('provider', input.providerId)\n callback.searchParams.set('nonce', nonce)\n callback.searchParams.set('context', contextToken)\n const timeout = new AbortController()\n const onAbort = () => timeout.abort()\n input.signal.addEventListener('abort', onAbort, { once: true })\n const preRedirectId = window.setTimeout(() => timeout.abort(), PRE_REDIRECT_TIMEOUT_MS)\n try {\n if (!input.isCurrent()) return 'cancelled'\n const start = await withAbort(input.client.startOAuth(input.identity, input.providerId, {\n returnUrl: callback.href,\n ...(input.connectionParameters === undefined ? {} : { connectionParameters: input.connectionParameters }),\n }, timeout.signal), timeout.signal)\n if (!input.isCurrent() || input.signal.aborted) return 'cancelled'\n let redirect: URL\n try { redirect = new URL(start.redirectUrl) } catch { return 'unavailable' }\n if (redirect.protocol !== 'https:' || redirect.username || redirect.password) return 'unavailable'\n window.clearTimeout(preRedirectId)\n const waitController = new AbortController()\n const abortWait = () => waitController.abort()\n input.signal.addEventListener('abort', abortWait, { once: true })\n if (input.signal.aborted) abortWait()\n const waiting = waitForConnection({ ...input, popup, nonce, contextToken, signal: waitController.signal })\n try {\n popup.location.href = redirect.href\n return await waiting\n } catch {\n waitController.abort()\n await waiting\n return 'unavailable'\n } finally {\n input.signal.removeEventListener('abort', abortWait)\n }\n } catch {\n return input.signal.aborted || timeout.signal.aborted ? 'cancelled' : 'unavailable'\n } finally {\n window.clearTimeout(preRedirectId)\n input.signal.removeEventListener('abort', onAbort)\n closePopup(popup)\n }\n}\n","import type {\n HubApiKeyConnectionMetadata,\n HubConnection,\n HubConnectionHealthResponse,\n HubOAuthStartResponse,\n HubPolicy,\n HubPolicyDecision,\n HubProvider,\n HubTool,\n} from '@tangle-network/hub-sdk'\n\n/** The host must bind each request to this server-verified identity. */\nexport interface HubIntegrationsIdentity {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsRequest {\n readonly identity: HubIntegrationsIdentity\n readonly path: string\n readonly init: RequestInit\n}\n\n/**\n * The host supplies its authenticated fetch, CSRF protection and expected\n * identity check. The browser never receives a Hub credential or SDK client.\n */\nexport type HubSettingsRequestFn = (request: HubSettingsRequest) => Promise<Response>\n\nexport interface HubIntegrationsClient {\n providers(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubProvider[]>\n connections(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubConnection[]>\n startOAuth(identity: HubIntegrationsIdentity, providerId: string, input: { returnUrl: string; connectionParameters?: Record<string, string> }, signal?: AbortSignal): Promise<HubOAuthStartResponse>\n connectApiKey(identity: HubIntegrationsIdentity, providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata, signal?: AbortSignal): Promise<HubConnection>\n revoke(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnection>\n health(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnectionHealthResponse>\n actions(identity: HubIntegrationsIdentity, providerId: string, limit: number, signal?: AbortSignal): Promise<HubTool[]>\n policies(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubPolicy[]>\n setPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, decision: HubPolicyDecision, signal?: AbortSignal): Promise<HubPolicy>\n resetPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, signal?: AbortSignal): Promise<void>\n}\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value as Record<string, unknown>\n}\n\nfunction array(value: unknown): unknown[] {\n if (!Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value\n}\n\nfunction namedArray<T>(value: unknown, key: string): T[] {\n const rows = array(object(value)[key])\n if (rows.some(row => row === null || typeof row !== 'object' || Array.isArray(row))) throw new Error('Invalid Hub settings response.')\n return rows as T[]\n}\n\nfunction namedObject<T>(value: unknown, key: string): T {\n return object(object(value)[key]) as T\n}\n\nfunction segment(value: string): string {\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value)) throw new TypeError('Invalid Hub settings identifier.')\n return encodeURIComponent(value)\n}\n\n/** Finite browser transport for the server-owned `createHubSettingsRoutes` API. */\nexport function createHubIntegrationsClient(request: HubSettingsRequestFn, basePath = '/api/hub/settings'): HubIntegrationsClient {\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath.')\n\n async function call(identity: HubIntegrationsIdentity, path: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', signal?: AbortSignal, body?: object): Promise<unknown> {\n if (![identity.userId, identity.sessionId, identity.workspaceId].every(part => typeof part === 'string' && part.trim())) {\n throw new TypeError('Hub settings identity is required.')\n }\n const response = await request({\n identity,\n path: `${basePath}${path}`,\n init: { method, signal, ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) },\n })\n if (!response.ok) {\n let code: string | undefined\n try {\n const error = object(await response.json())\n if (typeof error.code === 'string') code = error.code\n } catch { /* Status remains authoritative when a response is unreadable. */ }\n throw new Error(`Hub settings request failed (${response.status}${code ? `, ${code}` : ''}).`)\n }\n return response.json()\n }\n\n return {\n async providers(identity, signal) { return namedArray<HubProvider>(await call(identity, '/providers', 'GET', signal), 'providers') },\n async connections(identity, signal) { return namedArray<HubConnection>(await call(identity, '/connections', 'GET', signal), 'connections') },\n async startOAuth(identity, providerId, input, signal) {\n const response = object(await call(identity, `/connections/${segment(providerId)}/start`, 'POST', signal, input))\n if (typeof response.redirectUrl !== 'string') throw new Error('Invalid Hub OAuth response.')\n return response as unknown as HubOAuthStartResponse\n },\n async connectApiKey(identity, providerId, apiKey, metadata, signal) {\n return namedObject<HubConnection>(await call(identity, `/connections/${segment(providerId)}/connect-key`, 'POST', signal, { apiKey, ...(metadata === undefined ? {} : { metadata }) }), 'connection')\n },\n async revoke(identity, connectionId, signal) { return namedObject<HubConnection>(await call(identity, `/connections/${segment(connectionId)}`, 'DELETE', signal), 'connection') },\n async health(identity, connectionId, signal) {\n const response = object(await call(identity, `/connections/${segment(connectionId)}/health`, 'POST', signal))\n object(response.connection)\n object(response.health)\n return response as unknown as HubConnectionHealthResponse\n },\n async actions(identity, providerId, limit, signal) {\n if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new TypeError('Hub action limit must be 1–200.')\n const search = new URLSearchParams({ query: '', limit: String(limit) })\n return namedArray<HubTool>(await call(identity, `/providers/${segment(providerId)}/actions?${search}`, 'GET', signal), 'tools')\n },\n async policies(identity, connectionId, signal) {\n const search = new URLSearchParams({ connectionId })\n return namedArray<HubPolicy>(await call(identity, `/policies?${search}`, 'GET', signal), 'policies')\n },\n async setPolicy(identity, connectionId, actionPath, decision, signal) {\n return namedObject<HubPolicy>(await call(identity, '/policies', 'PUT', signal, { connectionId, actionPath, decision }), 'policy')\n },\n async resetPolicy(identity, connectionId, actionPath, signal) {\n const response = object(await call(identity, '/policies', 'DELETE', signal, { connectionId, actionPath }))\n if (response.connectionId !== connectionId || response.actionPath !== actionPath || typeof response.deleted !== 'boolean') {\n throw new Error('Invalid Hub policy reset response.')\n }\n },\n }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubProvider } from '@tangle-network/hub-sdk'\nimport {\n ApiKeyConnectDialog,\n IntegrationConnectionDetail,\n IntegrationsCatalog,\n OAuthConnectionParameterDialog,\n ProviderIcon,\n type IntegrationDisplayAction,\n type IntegrationsCatalogProps,\n type IntegrationSort,\n} from '@tangle-network/sandbox-ui/integrations'\nimport { Button, Card, Input, StatusPill, Tabs, TabsContent, TabsList, TabsTrigger, type StatusTone } from '@tangle-network/ui/primitives'\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { contextKey, displayProvider, type HubIntegrationCapabilities } from './projection'\nimport { useHubIntegrations } from './use-hub-integrations'\n\n/** Host-owned access state for one account, such as whether this agent can use it. */\nexport interface HubAccountStatus {\n label: string\n tone?: StatusTone\n}\n\n/**\n * Shows each connected account once, with its host status and one inline host\n * control. A separate tab offers providers without an account;\n * Manage opens permissions, Test, Disconnect and Connect another account.\n */\nexport interface HubIntegrationsAccounts {\n title: string\n description?: string\n /** Shown in the Accounts tab before any account exists. */\n emptyLabel?: string\n getStatus?: (connection: HubConnection) => HubAccountStatus | undefined\n /** The host authorizes this control and supplies its new status only after its server confirms. */\n getPrimaryAction?: (connection: HubConnection) => IntegrationDisplayAction | undefined\n /** Host-owned rows rendered after the accounts, such as access to an account that is no longer connected. */\n footer?: ReactNode\n}\n\nexport interface HubIntegrationsPanelProps {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n can: HubIntegrationCapabilities\n callbackPath: string\n title?: string\n /** Compact, icon-led tiles or descriptive cards. Defaults to cards. */\n layout?: IntegrationsCatalogProps['layout']\n className?: string\n onRequestIntegration?: (prefill: string) => void\n onUnsupportedConnect?: (provider: HubProvider) => void\n /** Host-owned context and actions; the host authorizes and confirms their effects. */\n getConnectionContext?: (connection: HubConnection) => string | undefined\n getConnectionActions?: (connection: HubConnection) => readonly IntegrationDisplayAction[]\n accounts?: HubIntegrationsAccounts\n /** Host-owned, transient fields for providers that require API-key metadata. */\n renderApiKeyMetadata?: (input: {\n provider: HubProvider\n value: HubApiKeyConnectionMetadata | undefined\n onChange: (value: HubApiKeyConnectionMetadata | undefined) => void\n }) => ReactNode\n}\n\nfunction catalogHref(): string {\n if (typeof window === 'undefined') return '/'\n const url = new URL(window.location.href)\n url.searchParams.delete('integration')\n url.searchParams.delete('connection')\n return `${url.pathname}${url.search}${url.hash}`\n}\n\nfunction accountName(connection: HubConnection, providerTitle: string): string {\n return connection.accountDisplay?.trim() || connection.displayName?.trim() || providerTitle\n}\n\nfunction AccountStatus({ connection, accounts }: { connection: HubConnection; accounts: HubIntegrationsAccounts }) {\n const status = accounts.getStatus?.(connection)\n return status ? <StatusPill tone={status.tone ?? 'neutral'} size=\"sm\" className=\"max-w-full whitespace-normal\">{status.label}</StatusPill> : null\n}\n\nfunction AccountPrimaryAction({ connection, accounts, busy }: { connection: HubConnection; accounts: HubIntegrationsAccounts; busy: boolean }) {\n const primary = accounts.getPrimaryAction?.(connection)\n return primary ? <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={busy || primary.disabled}\n onClick={primary.onSelect}>{primary.label}</Button> : null\n}\n\nfunction HubAccountList({ accounts, connections, providers, loading, error, busy, onRetry, onManage, canManage, onAdd }: {\n accounts: HubIntegrationsAccounts\n connections: readonly HubConnection[]\n providers: readonly HubProvider[]\n loading: boolean\n error: string | null\n busy: boolean\n onRetry: () => void\n onManage: (connection: HubConnection) => void\n canManage: (connection: HubConnection) => boolean\n onAdd: () => void\n}) {\n const [query, setQuery] = useState('')\n const titles = new Map(providers.map(provider => [provider.providerId, provider.title]))\n const title = (connection: HubConnection) => titles.get(connection.providerId) ?? connection.displayName ?? connection.providerId\n const rows = connections.filter(connection => connection.status !== 'revoked')\n .map(connection => ({ connection, provider: title(connection), name: accountName(connection, title(connection)) }))\n .sort((a, b) => a.provider.localeCompare(b.provider) || a.name.localeCompare(b.name) || a.connection.id.localeCompare(b.connection.id))\n const matching = rows.filter(row => `${row.provider} ${row.name}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()))\n return <section className=\"min-w-0 space-y-4\" aria-labelledby=\"hub-accounts-heading\" aria-busy={loading || undefined}>\n <header>\n <h2 id=\"hub-accounts-heading\" className=\"sr-only\">{accounts.title}</h2>\n {accounts.description ? <p className=\"text-sm text-muted-foreground\">{accounts.description}</p> : null}\n </header>\n {rows.length > 0 && !error ? <Input type=\"search\" aria-label=\"Search accounts\" placeholder=\"Search accounts…\" value={query} onChange={event => setQuery(event.target.value)} /> : null}\n {error ? <div role=\"alert\" className=\"flex flex-wrap items-center gap-3 rounded-xl border border-destructive/40 bg-card p-4 text-sm text-destructive\">\n <p className=\"min-w-0 flex-1 break-words\">{error}</p>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={onRetry}>Retry</Button>\n </div> : loading && rows.length === 0 ? <p role=\"status\" className=\"rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground\">Loading connected accounts…</p>\n : rows.length === 0 ? <div className=\"space-y-3 rounded-xl border border-border bg-card p-5\"><p className=\"text-sm text-muted-foreground\">{accounts.emptyLabel ?? 'No accounts connected yet.'}</p><Button type=\"button\" variant=\"outline\" onClick={onAdd}>Add integration</Button></div>\n : matching.length === 0 ? <p role=\"status\" className=\"py-6 text-sm text-muted-foreground\">No accounts match your search.</p>\n : <ul className=\"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3\" aria-label={accounts.title}>\n {matching.map(({ connection, provider, name }) => {\n const health = connection.status !== 'active' ? connection.status.replaceAll('_', ' ')\n : connection.health === 'unhealthy' ? 'needs attention' : null\n return <li key={connection.id} data-testid={`hub-account-${connection.id}`} className=\"min-w-0\">\n <Card className=\"flex h-full min-w-0 flex-col gap-4 p-4 shadow-none\">\n <div className=\"flex min-w-0 items-center gap-4\">\n <div className=\"flex size-16 shrink-0 items-center justify-center rounded-xl bg-muted/50\"><ProviderIcon id={connection.providerId} displayName={provider} size={48} className=\"shrink-0 rounded-lg\" /></div>\n <div className=\"min-w-0\">\n <p className=\"text-base font-semibold [overflow-wrap:anywhere]\">{provider}</p>\n {health ? <p className=\"mt-1 text-sm text-muted-foreground\">{health}</p> : null}\n </div>\n </div>\n <p className=\"text-sm font-medium [overflow-wrap:anywhere]\">{name}</p>\n <div className=\"mt-auto space-y-4\">\n <AccountStatus connection={connection} accounts={accounts} />\n <div className=\"flex flex-wrap items-center gap-2 border-t border-border pt-3\">\n <AccountPrimaryAction connection={connection} accounts={accounts} busy={busy} />\n {canManage(connection) ? <Button type=\"button\" variant=\"outline\" size=\"sm\" aria-label={`Manage ${provider} account ${name}`}\n onClick={() => onManage(connection)}>Manage</Button> : null}\n </div>\n </div>\n </Card>\n </li>\n })}\n </ul>}\n {accounts.footer}\n </section>\n}\n\n/** Embeddable settings surface. The app supplies authenticated transport and grants. */\nexport function HubIntegrationsPanel(props: HubIntegrationsPanelProps) {\n const hub = useHubIntegrations(props)\n const scope = contextKey(props.identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const activeDialog = useRef(hub.dialog)\n activeDialog.current = hub.dialog\n const [query, setQuery] = useState('')\n const [category, setCategory] = useState('')\n const [sort, setSort] = useState<IntegrationSort>('featured')\n const [view, setView] = useState<{ scope: string; value: 'accounts' | 'catalog' } | null>(null)\n const [catalogSelection, setCatalogSelection] = useState<{ scope: string; ids: Record<string, string | null> }>({ scope, ids: {} })\n const [keyInput, setKeyInput] = useState({ scope, value: '' })\n const apiKey = keyInput.scope === scope ? keyInput.value : ''\n const setApiKey = (value: string) => setKeyInput({ scope, value })\n const [metadataInput, setMetadataInput] = useState<{ scope: string; value: HubApiKeyConnectionMetadata | undefined }>({ scope, value: undefined })\n const metadata = metadataInput.scope === scope ? metadataInput.value : undefined\n const setMetadata = (value: HubApiKeyConnectionMetadata | undefined) => setMetadataInput({ scope, value })\n const [parameterInput, setParameterInput] = useState({ scope, values: {} as Record<string, string> })\n const parameters = parameterInput.scope === scope ? parameterInput.values : {}\n const setParameters = (values: Record<string, string>) => setParameterInput({ scope, values })\n\n useEffect(() => { setApiKey(''); setMetadata(undefined); setParameters({}) }, [scope])\n const pending = hub.writeState.status === 'pending' || hub.connectStatus.status === 'pending'\n const error = hub.providers.status === 'error' ? hub.providers.message\n : hub.connections.status === 'error' ? hub.connections.message : null\n const mutationError = hub.writeState.status === 'failed' ? hub.writeState.message : null\n const writeMessage = hub.writeState.status === 'succeeded' ? hub.writeState.value.message : null\n const writeWarning = hub.writeState.status === 'succeeded' && hub.writeState.value.reconciliation === 'refresh-failed'\n const rows = hub.rows.map(row => {\n const selectedId = catalogSelection.scope === scope ? catalogSelection.ids[row.providerId] : null\n return {\n ...row,\n selectedConnectionId: row.connections.some(connection => connection.id === selectedId) ? selectedId ?? null : null,\n connections: row.connections.map(connection => {\n const source = hub.connections.status === 'ready'\n ? hub.connections.value.find(item => item.id === connection.id) : undefined\n return source ? {\n ...connection,\n detail: props.getConnectionContext?.(source) ?? connection.detail,\n actions: props.getConnectionActions?.(source),\n } : connection\n }),\n }\n })\n const selectedRow = rows.find(row => row.providerId === hub.provider?.providerId)\n const connectionList = hub.connections.status === 'ready' ? hub.connections.value : []\n const accountCount = connectionList.filter(connection => connection.status !== 'revoked').length\n const activeView = view?.scope === scope ? view.value : hub.connections.status === 'ready' && accountCount === 0 ? 'catalog' : 'accounts'\n const showAccounts = () => setView({ scope, value: 'accounts' })\n useEffect(() => {\n if (hub.connectStatus.status === 'connected') showAccounts()\n }, [hub.connectStatus.status, scope])\n // With an account list, the catalog offers providers without a connected account.\n // The Hub keeps revoked connections listed; a provider with only those is connectable again.\n const connectedProviders = new Set(connectionList.filter(connection => connection.status !== 'revoked').map(connection => connection.providerId))\n const catalogRows = props.accounts && hub.connections.status === 'error' ? [] : props.accounts\n ? rows.filter(row => !connectedProviders.has(row.providerId)).map(row => ({ ...row, connections: [], selectedConnectionId: null }))\n : rows\n const selectedConnection = hub.connection\n const detailError = hub.detail.status === 'error' ? hub.detail.message\n : hub.detail.status === 'ready' && hub.detail.value.truncated\n ? `Showing at most ${hub.detail.value.tools.length} actions. The provider catalog may be incomplete.` : null\n const detailsByConnectionId = useMemo(() => hub.connection ? {\n [hub.connection.id]: {\n ...hub.details,\n loading: hub.detail.status === 'loading',\n busy: pending,\n error: detailError,\n },\n } : {}, [hub.connection, hub.details, hub.detail.status, pending, detailError])\n\n const closeDialog = () => {\n if (hub.connectStatus.status === 'pending') hub.cancelConnect()\n else hub.setDialog(null)\n setApiKey(''); setMetadata(undefined); setParameters({})\n }\n\n const catalog = <IntegrationsCatalog\n title={props.title ?? 'Integrations'} layout={props.layout} rows={catalogRows}\n query={query} onQueryChange={setQuery} categoryFilter={category} onCategoryFilterChange={setCategory}\n sort={sort} onSortChange={setSort}\n onSelectConnection={(providerId, connectionId) => setCatalogSelection(current => ({\n scope, ids: { ...(current.scope === scope ? current.ids : {}), [providerId]: connectionId },\n }))}\n onConnect={row => { const provider = hub.providers.status === 'ready' ? hub.providers.value.find(item => item.providerId === row.providerId) : null; if (provider) hub.beginConnect(provider) }}\n onManage={(connection, row) => hub.selectConnection(row.providerId, connection.id)}\n onDisconnect={connection => { void hub.revoke(connection.id) }}\n onRequestIntegration={props.onRequestIntegration} onRetry={() => hub.refresh()}\n loading={hub.providers.status === 'loading' || hub.connections.status === 'loading'} error={error}\n actionError={mutationError} connectError={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n busyProviderId={hub.connectStatus.status === 'pending' ? hub.connectStatus.providerId ?? null : null}\n reserveConnectionContext\n emptyCatalogLabel={props.accounts && rows.length > 0 ? 'Every available integration has a connected account. Manage an account to connect another.' : undefined}\n />\n\n return <section className={props.className}>\n {hub.connectStatus.status === 'pending' ? <div role=\"status\" className=\"mb-4 flex flex-wrap items-center gap-3\">\n <span>Finish connecting in the popup.</span>\n <Button type=\"button\" variant=\"outline\" onClick={hub.cancelConnect}>Cancel connection</Button>\n </div> : null}\n {hub.writeState.status === 'pending' ? <p role=\"status\">Saving Hub settings…</p> : null}\n {mutationError ? <p role=\"alert\">{mutationError}</p> : null}\n {writeMessage ? <p role={writeWarning ? 'alert' : 'status'}>{writeMessage}</p> : null}\n {hub.connectStatus.message && hub.provider ? <p role={hub.connectStatus.status === 'failed' ? 'alert' : 'status'}>{hub.connectStatus.message}</p> : null}\n {hub.provider ? <>\n {(props.accounts && selectedConnection) || selectedRow?.canConnect ? <div className=\"mb-4 flex min-w-0 flex-wrap items-center gap-2\">\n {props.accounts && selectedConnection ? <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-2\" data-testid=\"hub-account-access\"\n aria-label={`Access for ${accountName(selectedConnection, hub.provider.title)}`} role=\"group\">\n <span className=\"min-w-0 max-w-full truncate text-sm font-medium\">{accountName(selectedConnection, hub.provider.title)}</span>\n <AccountStatus connection={selectedConnection} accounts={props.accounts} />\n <AccountPrimaryAction connection={selectedConnection} accounts={props.accounts} busy={pending} />\n </div> : null}\n {selectedRow?.canConnect ? <Button type=\"button\" variant=\"outline\" className=\"ml-auto\" disabled={pending}\n onClick={() => hub.beginConnect(hub.provider!)}>Connect another account</Button> : null}\n </div> : null}\n <IntegrationConnectionDetail\n provider={displayProvider(hub.provider)}\n connections={selectedRow?.connections ?? []}\n selectedConnectionId={hub.connection?.id ?? null}\n onSelectConnection={connectionId => hub.selectConnection(hub.provider!.providerId, connectionId)}\n detailsByConnectionId={detailsByConnectionId}\n loading={hub.connections.status === 'loading' || hub.detail.status === 'loading'}\n error={detailError}\n backHref={catalogHref()}\n onRetry={() => hub.refresh()}\n onTestConnection={connectionId => { void hub.test(connectionId) }}\n onDisconnect={connectionId => { void hub.revoke(connectionId) }}\n onDecisionChange={(connectionId, actionPath, decision) => {\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') return\n void hub.setDecision(connectionId, actionPath, decision)\n }}\n onResetDecision={(connectionId, actionPath) => { void hub.resetDecision(connectionId, actionPath) }}\n />\n </> : <>\n {props.accounts ? <Tabs value={activeView} onValueChange={value => setView({ scope, value: value === 'catalog' ? 'catalog' : 'accounts' })}>\n <TabsList aria-label=\"Integration views\" className=\"mb-5 grid h-auto w-full grid-cols-2 sm:inline-flex sm:w-auto\">\n <TabsTrigger value=\"accounts\">Accounts{' '}{hub.connections.status === 'ready' ? <span className=\"ml-2 tabular-nums text-muted-foreground\">{accountCount}</span> : null}</TabsTrigger>\n <TabsTrigger value=\"catalog\">Add integration{' '}{hub.providers.status === 'ready' && hub.connections.status === 'ready' ? <span className=\"ml-2 tabular-nums text-muted-foreground\">{catalogRows.length}</span> : null}</TabsTrigger>\n </TabsList>\n <TabsContent value=\"accounts\">\n {hub.connectStatus.status === 'connected' && hub.connectStatus.message ? <p role=\"status\" className=\"mb-3 text-sm\">{hub.connectStatus.message}</p> : null}\n <HubAccountList key={scope} accounts={props.accounts} connections={connectionList} providers={hub.providers.status === 'ready' ? hub.providers.value : []}\n loading={hub.connections.status === 'loading'} error={hub.connections.status === 'error' ? hub.connections.message : null} busy={pending}\n onRetry={() => hub.refresh()} onManage={connection => hub.selectConnection(connection.providerId, connection.id)}\n canManage={connection => props.can({ operation: 'policies.list', connectionId: connection.id })}\n onAdd={() => setView({ scope, value: 'catalog' })} />\n </TabsContent>\n <TabsContent value=\"catalog\">{catalog}</TabsContent>\n </Tabs> : catalog}\n </>}\n {hub.dialog?.kind === 'api-key' ? <ApiKeyConnectDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n description={hub.dialog.provider.authHint}\n value={apiKey}\n onValueChange={setApiKey}\n busy={pending}\n error={mutationError}\n canSubmit={apiKey.trim().length > 0 && !pending}\n onSubmit={() => {\n const secret = apiKey\n const target = hub.dialog?.provider.providerId\n const submittedDialog = hub.dialog\n setApiKey('')\n if (target) void hub.submitApiKey(target, secret, metadata).then(result => {\n if (result.succeeded && activeScope.current === scope && activeDialog.current === submittedDialog) {\n hub.setDialog(null); setMetadata(undefined); showAccounts()\n }\n })\n }}\n >{props.renderApiKeyMetadata?.({ provider: hub.dialog.provider, value: metadata, onChange: setMetadata })}</ApiKeyConnectDialog> : null}\n {hub.dialog?.kind === 'oauth' ? <OAuthConnectionParameterDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n parameters={hub.dialog.provider.connectionParameters ?? []}\n values={parameters}\n onValueChange={(key, value) => setParameters({ ...parameters, [key]: value })}\n busy={pending}\n error={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n canSubmit={!pending && (hub.dialog.provider.connectionParameters ?? []).every(field => !field.required || !!parameters[field.key]?.trim())}\n onSubmit={() => {\n const target = hub.dialog?.provider\n const submittedDialog = hub.dialog\n if (target) void hub.startOAuth(target, parameters).then(result => {\n if (result === 'connected' && activeScope.current === scope && activeDialog.current === submittedDialog) setParameters({})\n })\n }}\n /> : null}\n </section>\n}\n","import type { HubConnection, HubPolicy, HubProvider, HubTool } from '@tangle-network/hub-sdk'\nimport type {\n IntegrationConnectionDetails,\n IntegrationDisplayProvider,\n IntegrationPermissionDisplay,\n IntegrationPermissionGroup,\n IntegrationsProviderRow,\n} from '@tangle-network/sandbox-ui/integrations'\n\nexport type HubIntegrationCapability =\n | { operation: 'oauth.start' | 'api-key.connect'; providerId: string }\n | { operation: 'connection.revoke' | 'connection.health' | 'policies.list'; connectionId: string }\n | { operation: 'policy.set' | 'policy.reset'; connectionId: string; actionPath: string }\n\n/** Display hints only. `createHubSettingsRoutes.authorize` remains authoritative. */\nexport type HubIntegrationCapabilities = (intent: HubIntegrationCapability) => boolean\n\nexport const ACTION_LIMIT = 200\n\nexport function contextKey(identity: { userId: string; sessionId: string; workspaceId: string }): string {\n return JSON.stringify([identity.userId, identity.sessionId, identity.workspaceId])\n}\n\nexport function displayProvider(provider: HubProvider): IntegrationDisplayProvider {\n return { providerId: provider.providerId, title: provider.title, category: provider.category }\n}\n\nexport function catalogRows(\n providers: readonly HubProvider[],\n connections: readonly HubConnection[],\n selectedIds: Readonly<Record<string, string | null>>,\n can: HubIntegrationCapabilities,\n hasUnsupportedConnect = false,\n): IntegrationsProviderRow[] {\n return providers.map(provider => {\n const accounts = connections.filter(connection => connection.providerId === provider.providerId)\n return {\n ...displayProvider(provider),\n kind: 'provider',\n authKind: provider.authKind,\n selectedConnectionId: accounts.some(account => account.id === selectedIds[provider.providerId])\n ? selectedIds[provider.providerId] ?? null : null,\n canConnect: provider.authKind === 'oauth2'\n ? provider.configured && can({ operation: 'oauth.start', providerId: provider.providerId })\n : provider.authKind === 'api_key'\n ? provider.configured && can({ operation: 'api-key.connect', providerId: provider.providerId })\n : hasUnsupportedConnect,\n connections: accounts.map(connection => ({\n id: connection.id,\n accountDisplay: connection.accountDisplay ?? connection.displayName,\n statusLabel: connection.status === 'active' ? 'Connected' : connection.status.replaceAll('_', ' '),\n statusTone: connection.status === 'active' && connection.health !== 'unhealthy' ? 'success' : 'warning',\n detail: connection.providerAccountId ?? undefined,\n capabilities: {\n manage: can({ operation: 'policies.list', connectionId: connection.id }),\n disconnect: can({ operation: 'connection.revoke', connectionId: connection.id }),\n test: can({ operation: 'connection.health', connectionId: connection.id }),\n editPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n resetPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n },\n })),\n }\n })\n}\n\nconst OPTIONS = [\n { value: 'allow', label: 'Allow' },\n { value: 'ask', label: 'Ask' },\n { value: 'deny', label: 'Deny' },\n] as const\n\n/** Stored overrides are shown; app-specific effective policy is never guessed. */\nexport function permissionDetails(\n tools: readonly HubTool[],\n policies: readonly HubPolicy[],\n connectionId: string,\n can: HubIntegrationCapabilities,\n): IntegrationConnectionDetails {\n const overrides = new Map(policies.filter(policy => policy.connectionId === connectionId).map(policy => [policy.actionPath, policy.decision]))\n const groups: IntegrationPermissionGroup[] = [\n { id: 'writes', title: 'Write and unknown actions', rows: [] },\n { id: 'reads', title: 'Read actions', collapsed: true, rows: [] },\n ]\n const writes: IntegrationPermissionDisplay[] = []\n const reads: IntegrationPermissionDisplay[] = []\n for (const tool of tools) {\n const override = overrides.get(tool.path)\n const row = {\n actionPath: tool.path,\n title: tool.title ?? tool.path,\n riskLabel: tool.risk ?? 'unknown',\n riskTone: tool.risk === 'destructive' ? 'error' : tool.risk === 'write' || tool.risk === undefined ? 'warning' : 'neutral',\n decision: override ?? null,\n decisionOptions: OPTIONS,\n sourceLabel: override ? 'Stored override' : 'No stored override',\n canReset: override !== undefined && can({ operation: 'policy.reset', connectionId, actionPath: tool.path }),\n disabled: !can({ operation: 'policy.set', connectionId, actionPath: tool.path }),\n } as const\n if (tool.risk === 'read') reads.push(row)\n else writes.push(row)\n }\n writes.sort((a, b) => a.title.localeCompare(b.title))\n reads.sort((a, b) => a.title.localeCompare(b.title))\n groups[0] = { ...groups[0]!, rows: writes }\n groups[1] = { ...groups[1]!, rows: reads }\n return { permissionGroups: groups }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubPolicyDecision, HubProvider } from '@tangle-network/hub-sdk'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { confirmWrite, useAsyncResource, useConfirmedMutation } from '../web-react/async'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { connectWithPopup, type PopupConnectResult } from './popup'\nimport { ACTION_LIMIT, catalogRows, contextKey, permissionDetails, type HubIntegrationCapabilities } from './projection'\n\ntype Selection = { scope: string; providerId: string | null; connectionId: string | null }\ntype Dialog = { scope: string; kind: 'api-key' | 'oauth'; provider: HubProvider } | null\n\nexport interface UseHubIntegrationsOptions {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n /** Display only. The host server must authorize every exact operation. */\n can: HubIntegrationCapabilities\n /** Local app route that renders `HubConnectCallbackPage`. */\n callbackPath: string\n /** Optional host handler for custom/native signup. No Platform redirect is assumed. */\n onUnsupportedConnect?: (provider: HubProvider) => void\n}\n\ntype WriteInput =\n | { kind: 'api-key'; identity: HubIntegrationsIdentity; scope: string; providerId: string; apiKey: string; metadata?: HubApiKeyConnectionMetadata }\n | { kind: 'revoke'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'health'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'set'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string; decision: HubPolicyDecision }\n | { kind: 'reset'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string }\n\nexport interface HubWriteReceipt {\n scope: string\n kind: WriteInput['kind']\n reconciliation: 'verified' | 'refresh-failed'\n message: string\n}\n\nfunction initialSelection(scope: string): Selection {\n if (typeof window === 'undefined') return { scope, providerId: null, connectionId: null }\n const query = new URL(window.location.href).searchParams\n return { scope, providerId: query.get('integration'), connectionId: query.get('connection') }\n}\n\nfunction updateUrl(providerId: string | null, connectionId: string | null): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n if (providerId) url.searchParams.set('integration', providerId)\n else url.searchParams.delete('integration')\n if (connectionId) url.searchParams.set('connection', connectionId)\n else url.searchParams.delete('connection')\n window.history.pushState(window.history.state, '', url)\n}\n\n/** Identity-bound Hub settings controller; connection state is always server-read. */\nexport function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect }: UseHubIntegrationsOptions) {\n const scope = contextKey(identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const [selection, setSelection] = useState<Selection>(() => initialSelection(scope))\n const visibleSelection = selection.scope === scope ? selection : { scope, providerId: null, connectionId: null }\n const [dialog, setDialog] = useState<Dialog>(null)\n const visibleDialog = dialog?.scope === scope ? dialog : null\n const [connectStatus, setConnectStatus] = useState<{ scope: string; status: 'idle' | 'pending' | 'connected' | 'failed'; providerId?: string; message?: string }>({ scope, status: 'idle' })\n const [writeScope, setWriteScope] = useState(scope)\n const pendingPopup = useRef<AbortController | null>(null)\n\n useEffect(() => {\n const onPop = () => setSelection(initialSelection(scope))\n window.addEventListener('popstate', onPop)\n return () => window.removeEventListener('popstate', onPop)\n }, [scope])\n\n const providers = useAsyncResource({ load: ({ signal }) => client.providers(identity, signal), deps: [client, scope], isEmpty: () => false })\n const connections = useAsyncResource({ load: ({ signal }) => client.connections(identity, signal), deps: [client, scope], isEmpty: () => false })\n const providerList = providers.status === 'ready' ? providers.value : []\n const connectionList = connections.status === 'ready' ? connections.value : []\n const provider = providerList.find(item => item.providerId === visibleSelection.providerId) ?? null\n const connection = connectionList.find(item => item.id === visibleSelection.connectionId && item.providerId === provider?.providerId) ?? null\n const canReadPolicies = connection !== null && can({ operation: 'policies.list', connectionId: connection.id })\n const detail = useAsyncResource({\n enabled: canReadPolicies && connection?.status === 'active',\n deps: [client, scope, provider?.providerId, connection?.id, canReadPolicies],\n isEmpty: () => false,\n load: async ({ signal }) => {\n if (!provider || !connection) throw new Error('Choose a connection.')\n const [tools, policies] = await Promise.all([\n client.actions(identity, provider.providerId, ACTION_LIMIT, signal),\n client.policies(identity, connection.id, signal),\n ])\n if (tools.some(tool => !tool.path.startsWith(`${provider.providerId}.`)) || policies.some(policy => policy.connectionId !== connection.id)) {\n throw new Error('Hub settings response changed connection or provider.')\n }\n return { tools, policies, truncated: tools.length >= ACTION_LIMIT }\n },\n })\n\n const write = useConfirmedMutation<WriteInput, HubWriteReceipt>({\n concurrency: 'reject',\n mutate: async (input, { signal }) => {\n if (input.scope !== activeScope.current) throw new Error('Integration context changed. Retry in the current workspace.')\n const origin = input.identity\n const receipt = (reconciliation: HubWriteReceipt['reconciliation'], message: string) => confirmWrite<HubWriteReceipt>({ scope: input.scope, kind: input.kind, reconciliation, message })\n if (input.kind === 'api-key') {\n if (!can({ operation: 'api-key.connect', providerId: input.providerId })) throw new Error('Connection setup is unavailable.')\n const created = await client.connectApiKey(origin, input.providerId, input.apiKey, input.metadata, signal)\n if (created.providerId !== input.providerId || created.status !== 'active') throw new Error('Hub did not confirm the requested connection.')\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === created.id && item.status === 'active')\n ? receipt('verified', 'Connection saved and verified.') : receipt('refresh-failed', 'Connection saved; current account state could not be confirmed.')\n } catch { return receipt('refresh-failed', 'Connection saved; refresh failed.') }\n }\n if (input.kind === 'revoke') {\n if (!can({ operation: 'connection.revoke', connectionId: input.connectionId })) throw new Error('Disconnect is unavailable.')\n await client.revoke(origin, input.connectionId, signal)\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === input.connectionId && item.status === 'active')\n ? receipt('refresh-failed', 'Disconnected, but the current account state disagrees.') : receipt('verified', 'Connection disconnected and verified.')\n } catch { return receipt('refresh-failed', 'Disconnected; refresh failed.') }\n }\n if (input.kind === 'health') {\n if (!can({ operation: 'connection.health', connectionId: input.connectionId })) throw new Error('Connection test is unavailable.')\n const result = await client.health(origin, input.connectionId, signal)\n if (result.connection.id !== input.connectionId) throw new Error('Hub returned another connection.')\n return receipt('verified', `Connection test: ${result.health.status.replaceAll('_', ' ')}.`)\n }\n if (!can({ operation: input.kind === 'set' ? 'policy.set' : 'policy.reset', connectionId: input.connectionId, actionPath: input.actionPath })) {\n throw new Error('Permission editing is unavailable.')\n }\n if (input.kind === 'set') {\n const stored = await client.setPolicy(origin, input.connectionId, input.actionPath, input.decision, signal)\n if (stored.connectionId !== input.connectionId || stored.actionPath !== input.actionPath || stored.decision !== input.decision) {\n throw new Error('Hub did not confirm the requested permission.')\n }\n } else await client.resetPolicy(origin, input.connectionId, input.actionPath, signal)\n try {\n const current = await client.policies(origin, input.connectionId, signal)\n const override = current.find(policy => policy.actionPath === input.actionPath)\n const matches = input.kind === 'set' ? override?.decision === input.decision : override === undefined\n return matches\n ? receipt('verified', 'Permission saved and verified.') : receipt('refresh-failed', 'Permission write was accepted; current policy state disagrees.')\n } catch { return receipt('refresh-failed', 'Permission write was accepted; refresh failed.') }\n },\n onSucceeded: value => { if (value.scope === activeScope.current) { connections.retry(); detail.retry() } },\n })\n\n useEffect(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'idle' })\n setWriteScope(scope)\n write.reset()\n return () => { pendingPopup.current?.abort(); pendingPopup.current = null }\n }, [scope, client, write.reset])\n\n const selectProvider = useCallback((providerId: string | null) => {\n const next = { scope, providerId, connectionId: null }\n setSelection(next)\n updateUrl(providerId, null)\n }, [scope])\n\n const selectConnection = useCallback((providerId: string, connectionId: string | null) => {\n if (connectionId && !connectionList.some(item => item.id === connectionId && item.providerId === providerId)) return\n setSelection({ scope, providerId, connectionId })\n updateUrl(providerId, connectionId)\n }, [scope, connectionList])\n\n const startOAuth = useCallback(async (target: HubProvider, connectionParameters?: Record<string, string>): Promise<PopupConnectResult> => {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) return 'unavailable'\n if (connections.status !== 'ready') { setConnectStatus({ scope, status: 'failed', message: 'Load connections before connecting.' }); return 'unavailable' }\n pendingPopup.current?.abort()\n const controller = new AbortController()\n pendingPopup.current = controller\n setConnectStatus({ scope, status: 'pending', providerId: target.providerId })\n const result = await connectWithPopup({\n client, identity, providerId: target.providerId, before: connections.value,\n callbackPath, connectionParameters, signal: controller.signal,\n isCurrent: () => activeScope.current === scope && !controller.signal.aborted,\n })\n if (pendingPopup.current !== controller || activeScope.current !== scope) return result\n pendingPopup.current = null\n if (result === 'connected') {\n connections.retry()\n setDialog(null)\n setConnectStatus({ scope, status: 'connected', message: 'Connection verified.' })\n } else setConnectStatus({ scope, status: 'failed', message: result === 'blocked' ? 'Allow the popup and try again.' : result === 'unverified' ? 'Could not verify a new connection. Refresh and try again.' : result === 'cancelled' ? 'Connection was cancelled.' : 'This connection flow is unavailable.' })\n return result\n }, [can, connections, client, identity, callbackPath, scope])\n\n const beginConnect = useCallback((target: HubProvider) => {\n if (target.authKind !== 'api_key' && target.authKind !== 'oauth2') {\n if (onUnsupportedConnect) onUnsupportedConnect(target)\n else setConnectStatus({ scope, status: 'failed', message: 'This provider needs an app-specific connection flow.' })\n return\n }\n if (!target.configured) {\n setConnectStatus({ scope, status: 'failed', message: 'This provider is not configured for connection.' })\n return\n }\n if (target.authKind === 'api_key') {\n if (can({ operation: 'api-key.connect', providerId: target.providerId })) setDialog({ scope, kind: 'api-key', provider: target })\n else setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' })\n return\n }\n if (target.authKind === 'oauth2') {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) {\n setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' }); return\n }\n if (target.connectionParameters?.length) setDialog({ scope, kind: 'oauth', provider: target })\n else void startOAuth(target)\n return\n }\n }, [can, onUnsupportedConnect, scope, startOAuth])\n\n const cancelConnect = useCallback(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'failed', message: 'Connection was cancelled.' })\n }, [scope])\n\n const rows = useMemo(() => catalogRows(providerList, connectionList, visibleSelection.providerId && visibleSelection.connectionId\n ? { [visibleSelection.providerId]: visibleSelection.connectionId } : {}, can, !!onUnsupportedConnect),\n [providerList, connectionList, visibleSelection.providerId, visibleSelection.connectionId, can, onUnsupportedConnect])\n const details = detail.status === 'ready' && connection\n ? permissionDetails(detail.value.tools, detail.value.policies, connection.id, can) : undefined\n\n return {\n providers, connections, detail, rows, provider, connection, dialog: visibleDialog, setDialog,\n connectStatus: connectStatus.scope === scope ? connectStatus : { scope, status: 'idle' as const, providerId: undefined },\n selection: visibleSelection, selectProvider, selectConnection, beginConnect, startOAuth, cancelConnect,\n write, writeState: writeScope === scope ? write.state : { status: 'idle' as const }, details,\n refresh: () => { providers.retry(); connections.retry(); detail.retry() },\n submitApiKey: (providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata) => { setWriteScope(scope); return write.run({ kind: 'api-key', identity, scope, providerId, apiKey, metadata }) },\n revoke: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'revoke', identity, scope, connectionId }) },\n test: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'health', identity, scope, connectionId }) },\n setDecision: (connectionId: string, actionPath: string, decision: HubPolicyDecision) => { setWriteScope(scope); return write.run({ kind: 'set', identity, scope, connectionId, actionPath, decision }) },\n resetDecision: (connectionId: string, actionPath: string) => { setWriteScope(scope); return write.run({ kind: 'reset', identity, scope, connectionId, actionPath }) },\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,WAAW,gBAAgB;;;ACG7B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,kCAAkC;AACxC,IAAM,mBAAmB,IAAI,KAAK;AACzC,IAAM,0BAA0B;AAChC,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AAIhB,SAAS,YAAY,MAA0B;AACpD,MAAI,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,EAAG,QAAO;AAC3D,MAAI;AACF,UAAM,SAAS,OAAO,WAAW,cAAc,0BAA0B,OAAO,SAAS;AACzF,UAAM,MAAM,IAAI,IAAI,MAAM,MAAM;AAChC,WAAO,IAAI,WAAW,UAAU,CAAC,IAAI,YAAY,CAAC,IAAI,WAAW,MAAM;AAAA,EACzE,QAAQ;AAAE,WAAO;AAAA,EAAK;AACxB;AAEA,SAAS,kBAAkB,YAAoB,QAAkC,OAA0C;AACzH,QAAM,WAAW,IAAI,IAAI,OAAO,OAAO,gBAAc,WAAW,eAAe,UAAU,EAAE,IAAI,gBAAc,CAAC,WAAW,IAAI,UAAU,CAAC,CAAC;AACzI,SAAO,MAAM,KAAK,gBAAc;AAC9B,QAAI,WAAW,eAAe,cAAc,WAAW,WAAW,YAAY,WAAW,WAAW,YAAa,QAAO;AACxH,UAAM,MAAM,SAAS,IAAI,WAAW,EAAE;AACtC,WAAO,CAAC,OAAO,IAAI,cAAc,WAAW,aAAa,IAAI,WAAW,WAAW;AAAA,EACrF,CAAC;AACH;AAEA,SAAS,WAAW,OAAqB;AACvC,MAAI;AA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,IAAI,WAAW,QAAQ,UAAU,EAAE,KAAK,YAAU;AACjE,gBAAI,WAAW,eAAe,YAAY,YAAY,SAAS,aAAa,YAAY,gBAAiB,eAAc,CAAC,CAAC;AAAA,UAC3H,CAAC;AAAA,QACH;AAAA;AAAA,IACF,IAAK;AAAA,KACP;AACF;","names":["useEffect","useMemo","useRef","useState","useEffect","useState","useState","useEffect","jsx","jsxs","useState","useRef","useEffect","catalogRows","useMemo"]}
|
|
1
|
+
{"version":3,"sources":["../../src/integrations-react/callback.tsx","../../src/integrations-react/popup.ts","../../src/integrations-react/client.ts","../../src/integrations-react/panel.tsx","../../src/integrations-react/projection.ts","../../src/integrations-react/use-hub-integrations.ts"],"sourcesContent":["import { useEffect, useState } from 'react'\nimport { HUB_CONNECTED_MESSAGE_TYPE, HUB_CONNECT_CHANNEL, HUB_CONNECT_FAILED_MESSAGE_TYPE, localAppUrl } from './popup'\n\nexport interface HubConnectCallbackPageProps {\n /** Local settings destination owned by the consuming app. */\n returnHref: string\n}\n\n/** The callback only signals completion; the opener verifies fresh Hub state. */\nexport function HubConnectCallbackPage({ returnHref }: HubConnectCallbackPageProps) {\n const [phase, setPhase] = useState<'checking' | 'returned' | 'failed'>('checking')\n const [reason, setReason] = useState('')\n\n useEffect(() => {\n const params = new URLSearchParams(window.location.search)\n const provider = params.get('provider')\n const nonce = params.get('nonce')\n const context = params.get('context')\n if (!provider || !nonce || !context) { setReason('This connection callback is incomplete.'); setPhase('failed'); return }\n const failure = params.get('error_description') || params.get('error')\n try {\n const channel = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n channel.postMessage({ type: failure ? HUB_CONNECT_FAILED_MESSAGE_TYPE : HUB_CONNECTED_MESSAGE_TYPE, provider, nonce, context })\n channel.close()\n } catch { /* The opener also polls the authoritative connection list. */ }\n if (failure) { setReason(failure.slice(0, 200)); setPhase('failed'); return }\n window.close()\n const timer = window.setTimeout(() => setPhase('returned'), 150)\n return () => window.clearTimeout(timer)\n }, [])\n\n const destination = localAppUrl(returnHref)\n const localReturn = destination ? `${destination.pathname}${destination.search}${destination.hash}` : '/'\n return <main aria-live=\"polite\" style={{ maxWidth: 560, margin: '20vh auto', padding: 24, textAlign: 'center' }}>\n {phase === 'checking' ? <p>Checking your connection…</p> : phase === 'returned'\n ? <p>Return to the app to check your connection. You can close this window.</p>\n : <p>Could not complete the connection. {reason}</p>}\n <a href={localReturn}>Return to integrations</a>\n </main>\n}\n","import type { HubConnection } from '@tangle-network/hub-sdk'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\n\nexport const HUB_CONNECT_CHANNEL = 'tangle:hub-connect'\nexport const HUB_CONNECTED_MESSAGE_TYPE = 'tangle:hub-connected'\nexport const HUB_CONNECT_FAILED_MESSAGE_TYPE = 'tangle:hub-connect-failed'\nexport const POPUP_TIMEOUT_MS = 5 * 60 * 1000\nconst PRE_REDIRECT_TIMEOUT_MS = 30_000\nconst POLL_INTERVAL_MS = 2500\nconst POPUP_FEATURES = 'popup=yes,width=520,height=680'\n\nexport type PopupConnectResult = 'connected' | 'blocked' | 'cancelled' | 'unverified' | 'unavailable'\n\nexport function localAppUrl(path: string): URL | null {\n if (!path.startsWith('/') || path.startsWith('//')) return null\n try {\n const origin = typeof window === 'undefined' ? 'https://local.invalid' : window.location.origin\n const url = new URL(path, origin)\n return url.origin === origin && !url.username && !url.password ? url : null\n } catch { return null }\n}\n\nfunction updatedConnection(providerId: string, before: readonly HubConnection[], after: readonly HubConnection[]): boolean {\n const previous = new Map(before.filter(connection => connection.providerId === providerId).map(connection => [connection.id, connection]))\n return after.some(connection => {\n if (connection.providerId !== providerId || connection.status !== 'active' || connection.health === 'unhealthy') return false\n const old = previous.get(connection.id)\n return !old || old.updatedAt !== connection.updatedAt || old.status !== connection.status\n })\n}\n\nfunction closePopup(popup: Window): void {\n try { if (!popup.closed) popup.close() } catch { /* COOP may sever the handle. */ }\n}\n\nfunction withAbort<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) { reject(new DOMException('Aborted', 'AbortError')); return }\n const onAbort = () => reject(new DOMException('Aborted', 'AbortError'))\n signal.addEventListener('abort', onAbort, { once: true })\n promise.then(value => { signal.removeEventListener('abort', onAbort); resolve(value) }, error => { signal.removeEventListener('abort', onAbort); reject(error) })\n })\n}\n\nfunction waitForConnection(input: {\n popup: Window\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n nonce: string\n contextToken: string\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n return new Promise(resolve => {\n let settled = false\n let checking = false\n let pollId: number | undefined\n let timeoutId: number | undefined\n let channel: BroadcastChannel | undefined\n const finish = (result: PopupConnectResult) => {\n if (settled) return\n settled = true\n if (pollId !== undefined) window.clearTimeout(pollId)\n if (timeoutId !== undefined) window.clearTimeout(timeoutId)\n input.signal.removeEventListener('abort', onAbort)\n channel?.close()\n closePopup(input.popup)\n resolve(result)\n }\n const onAbort = () => finish('cancelled')\n const check = async () => {\n if (settled || checking) return\n checking = true\n if (!input.isCurrent() || input.signal.aborted) { finish('cancelled'); return }\n try {\n const after = await input.client.connections(input.identity, input.signal)\n if (input.isCurrent() && updatedConnection(input.providerId, input.before, after)) { finish('connected'); return }\n } catch { /* A lost read is never evidence of a connection. Keep polling. */ }\n checking = false\n if (!settled) pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n }\n if (input.signal.aborted) { finish('cancelled'); return }\n input.signal.addEventListener('abort', onAbort, { once: true })\n try {\n const candidate = new BroadcastChannel(HUB_CONNECT_CHANNEL)\n candidate.onmessage = event => {\n const message = event.data as Record<string, unknown> | null\n if (!message || message.provider !== input.providerId || message.nonce !== input.nonce || message.context !== input.contextToken) return\n if (message.type === HUB_CONNECT_FAILED_MESSAGE_TYPE) finish('cancelled')\n if (message.type === HUB_CONNECTED_MESSAGE_TYPE) {\n if (pollId !== undefined) window.clearTimeout(pollId)\n void check()\n }\n }\n channel = candidate\n } catch { /* Polling covers browsers without BroadcastChannel. */ }\n pollId = window.setTimeout(check, POLL_INTERVAL_MS)\n timeoutId = window.setTimeout(() => finish('unverified'), POPUP_TIMEOUT_MS)\n })\n}\n\n/** Opens before the first await, preserving the initiating user gesture. */\nexport async function connectWithPopup(input: {\n client: HubIntegrationsClient\n identity: HubIntegrationsIdentity\n providerId: string\n before: readonly HubConnection[]\n callbackPath: string\n connectionParameters?: Record<string, string>\n signal: AbortSignal\n isCurrent: () => boolean\n}): Promise<PopupConnectResult> {\n const callback = localAppUrl(input.callbackPath)\n if (!callback) throw new TypeError('Callback path must be local.')\n const popup = window.open('', '_blank', POPUP_FEATURES)\n if (!popup) return 'blocked'\n // Keep the parent handle for navigation while removing the provider page's opener.\n try { popup.opener = null } catch { /* Some browsers make this read-only. */ }\n const nonce = crypto.randomUUID()\n const contextToken = crypto.randomUUID()\n callback.searchParams.set('provider', input.providerId)\n callback.searchParams.set('nonce', nonce)\n callback.searchParams.set('context', contextToken)\n const timeout = new AbortController()\n const onAbort = () => timeout.abort()\n input.signal.addEventListener('abort', onAbort, { once: true })\n const preRedirectId = window.setTimeout(() => timeout.abort(), PRE_REDIRECT_TIMEOUT_MS)\n try {\n if (!input.isCurrent()) return 'cancelled'\n const start = await withAbort(input.client.startOAuth(input.identity, input.providerId, {\n returnUrl: callback.href,\n ...(input.connectionParameters === undefined ? {} : { connectionParameters: input.connectionParameters }),\n }, timeout.signal), timeout.signal)\n if (!input.isCurrent() || input.signal.aborted) return 'cancelled'\n let redirect: URL\n try { redirect = new URL(start.redirectUrl) } catch { return 'unavailable' }\n if (redirect.protocol !== 'https:' || redirect.username || redirect.password) return 'unavailable'\n window.clearTimeout(preRedirectId)\n const waitController = new AbortController()\n const abortWait = () => waitController.abort()\n input.signal.addEventListener('abort', abortWait, { once: true })\n if (input.signal.aborted) abortWait()\n const waiting = waitForConnection({ ...input, popup, nonce, contextToken, signal: waitController.signal })\n try {\n popup.location.href = redirect.href\n return await waiting\n } catch {\n waitController.abort()\n await waiting\n return 'unavailable'\n } finally {\n input.signal.removeEventListener('abort', abortWait)\n }\n } catch {\n return input.signal.aborted || timeout.signal.aborted ? 'cancelled' : 'unavailable'\n } finally {\n window.clearTimeout(preRedirectId)\n input.signal.removeEventListener('abort', onAbort)\n closePopup(popup)\n }\n}\n","import type {\n HubApiKeyConnectionMetadata,\n HubConnection,\n HubConnectionHealthResponse,\n HubOAuthStartResponse,\n HubPolicy,\n HubPolicyDecision,\n HubProvider,\n HubTool,\n} from '@tangle-network/hub-sdk'\n\n/** The host must bind each request to this server-verified identity. */\nexport interface HubIntegrationsIdentity {\n readonly userId: string\n readonly sessionId: string\n readonly workspaceId: string\n}\n\nexport interface HubSettingsRequest {\n readonly identity: HubIntegrationsIdentity\n readonly path: string\n readonly init: RequestInit\n}\n\n/**\n * The host supplies its authenticated fetch, CSRF protection and expected\n * identity check. The browser never receives a Hub credential or SDK client.\n */\nexport type HubSettingsRequestFn = (request: HubSettingsRequest) => Promise<Response>\n\nexport interface HubIntegrationsClient {\n providers(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubProvider[]>\n connections(identity: HubIntegrationsIdentity, signal?: AbortSignal): Promise<HubConnection[]>\n startOAuth(identity: HubIntegrationsIdentity, providerId: string, input: { returnUrl: string; connectionParameters?: Record<string, string> }, signal?: AbortSignal): Promise<HubOAuthStartResponse>\n connectApiKey(identity: HubIntegrationsIdentity, providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata, signal?: AbortSignal): Promise<HubConnection>\n revoke(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnection>\n health(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubConnectionHealthResponse>\n actions(identity: HubIntegrationsIdentity, providerId: string, limit: number, signal?: AbortSignal): Promise<HubTool[]>\n policies(identity: HubIntegrationsIdentity, connectionId: string, signal?: AbortSignal): Promise<HubPolicy[]>\n setPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, decision: HubPolicyDecision, signal?: AbortSignal): Promise<HubPolicy>\n resetPolicy(identity: HubIntegrationsIdentity, connectionId: string, actionPath: string, signal?: AbortSignal): Promise<void>\n}\n\nfunction object(value: unknown): Record<string, unknown> {\n if (value === null || typeof value !== 'object' || Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value as Record<string, unknown>\n}\n\nfunction array(value: unknown): unknown[] {\n if (!Array.isArray(value)) throw new Error('Invalid Hub settings response.')\n return value\n}\n\nfunction namedArray<T>(value: unknown, key: string): T[] {\n const rows = array(object(value)[key])\n if (rows.some(row => row === null || typeof row !== 'object' || Array.isArray(row))) throw new Error('Invalid Hub settings response.')\n return rows as T[]\n}\n\nfunction namedObject<T>(value: unknown, key: string): T {\n return object(object(value)[key]) as T\n}\n\nfunction segment(value: string): string {\n if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(value)) throw new TypeError('Invalid Hub settings identifier.')\n return encodeURIComponent(value)\n}\n\n/** Finite browser transport for the server-owned `createHubSettingsRoutes` API. */\nexport function createHubIntegrationsClient(request: HubSettingsRequestFn, basePath = '/api/hub/settings'): HubIntegrationsClient {\n if (!/^\\/(?:[A-Za-z0-9_-]+\\/)*[A-Za-z0-9_-]+$/.test(basePath)) throw new TypeError('Invalid Hub settings basePath.')\n\n async function call(identity: HubIntegrationsIdentity, path: string, method: 'GET' | 'POST' | 'PUT' | 'DELETE', signal?: AbortSignal, body?: object): Promise<unknown> {\n if (![identity.userId, identity.sessionId, identity.workspaceId].every(part => typeof part === 'string' && part.trim())) {\n throw new TypeError('Hub settings identity is required.')\n }\n const response = await request({\n identity,\n path: `${basePath}${path}`,\n init: { method, signal, ...(body === undefined ? {} : { headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }) },\n })\n if (!response.ok) {\n let code: string | undefined\n try {\n const error = object(await response.json())\n if (typeof error.code === 'string') code = error.code\n } catch { /* Status remains authoritative when a response is unreadable. */ }\n throw new Error(`Hub settings request failed (${response.status}${code ? `, ${code}` : ''}).`)\n }\n return response.json()\n }\n\n return {\n async providers(identity, signal) { return namedArray<HubProvider>(await call(identity, '/providers', 'GET', signal), 'providers') },\n async connections(identity, signal) { return namedArray<HubConnection>(await call(identity, '/connections', 'GET', signal), 'connections') },\n async startOAuth(identity, providerId, input, signal) {\n const response = object(await call(identity, `/connections/${segment(providerId)}/start`, 'POST', signal, input))\n if (typeof response.redirectUrl !== 'string') throw new Error('Invalid Hub OAuth response.')\n return response as unknown as HubOAuthStartResponse\n },\n async connectApiKey(identity, providerId, apiKey, metadata, signal) {\n return namedObject<HubConnection>(await call(identity, `/connections/${segment(providerId)}/connect-key`, 'POST', signal, { apiKey, ...(metadata === undefined ? {} : { metadata }) }), 'connection')\n },\n async revoke(identity, connectionId, signal) { return namedObject<HubConnection>(await call(identity, `/connections/${segment(connectionId)}`, 'DELETE', signal), 'connection') },\n async health(identity, connectionId, signal) {\n const response = object(await call(identity, `/connections/${segment(connectionId)}/health`, 'POST', signal))\n object(response.connection)\n object(response.health)\n return response as unknown as HubConnectionHealthResponse\n },\n async actions(identity, providerId, limit, signal) {\n if (!Number.isInteger(limit) || limit < 1 || limit > 200) throw new TypeError('Hub action limit must be 1–200.')\n const search = new URLSearchParams({ query: '', limit: String(limit) })\n return namedArray<HubTool>(await call(identity, `/providers/${segment(providerId)}/actions?${search}`, 'GET', signal), 'tools')\n },\n async policies(identity, connectionId, signal) {\n const search = new URLSearchParams({ connectionId })\n return namedArray<HubPolicy>(await call(identity, `/policies?${search}`, 'GET', signal), 'policies')\n },\n async setPolicy(identity, connectionId, actionPath, decision, signal) {\n return namedObject<HubPolicy>(await call(identity, '/policies', 'PUT', signal, { connectionId, actionPath, decision }), 'policy')\n },\n async resetPolicy(identity, connectionId, actionPath, signal) {\n const response = object(await call(identity, '/policies', 'DELETE', signal, { connectionId, actionPath }))\n if (response.connectionId !== connectionId || response.actionPath !== actionPath || typeof response.deleted !== 'boolean') {\n throw new Error('Invalid Hub policy reset response.')\n }\n },\n }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubProvider } from '@tangle-network/hub-sdk'\nimport {\n ApiKeyConnectDialog,\n IntegrationConnectionDetail,\n IntegrationsCatalog,\n OAuthConnectionParameterDialog,\n ProviderIcon,\n type IntegrationDisplayAction,\n type IntegrationsCatalogProps,\n type IntegrationSort,\n} from '@tangle-network/sandbox-ui/integrations'\nimport { Button, Card, Input, StatusPill, Tabs, TabsContent, TabsList, TabsTrigger, type StatusTone } from '@tangle-network/ui/primitives'\nimport { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { contextKey, displayProvider, type HubIntegrationCapabilities } from './projection'\nimport { type HubHostConnect, useHubIntegrations } from './use-hub-integrations'\n\n/** Host-owned access state for one account, such as whether this agent can use it. */\nexport interface HubAccountStatus {\n label: string\n tone?: StatusTone\n}\n\n/**\n * Shows each connected account once, with its host status and one inline host\n * control. A separate tab offers providers without an account;\n * Manage opens permissions, Test, Disconnect and Connect another account.\n */\nexport interface HubIntegrationsAccounts {\n title: string\n description?: string\n /** Shown in the Accounts tab before any account exists. */\n emptyLabel?: string\n getStatus?: (connection: HubConnection) => HubAccountStatus | undefined\n /** The host authorizes this control and supplies its new status only after its server confirms. */\n getPrimaryAction?: (connection: HubConnection) => IntegrationDisplayAction | undefined\n /** Host-owned rows rendered after the accounts, such as access to an account that is no longer connected. */\n footer?: ReactNode\n}\n\nexport interface HubIntegrationsPanelProps {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n can: HubIntegrationCapabilities\n callbackPath: string\n title?: string\n /** Compact, icon-led tiles or descriptive cards. Defaults to cards. */\n layout?: IntegrationsCatalogProps['layout']\n className?: string\n onRequestIntegration?: (prefill: string) => void\n onUnsupportedConnect?: (provider: HubProvider) => void\n /**\n * App-owned connection for these providers, such as a number the app\n * provisions itself. Their catalog rows stay visible and connectable, and\n * choosing one calls `onConnect` instead of running a Hub flow.\n */\n hostConnect?: HubHostConnect\n /** Host-owned context and actions; the host authorizes and confirms their effects. */\n getConnectionContext?: (connection: HubConnection) => string | undefined\n getConnectionActions?: (connection: HubConnection) => readonly IntegrationDisplayAction[]\n accounts?: HubIntegrationsAccounts\n /** Host-owned, transient fields for providers that require API-key metadata. */\n renderApiKeyMetadata?: (input: {\n provider: HubProvider\n value: HubApiKeyConnectionMetadata | undefined\n onChange: (value: HubApiKeyConnectionMetadata | undefined) => void\n }) => ReactNode\n}\n\nfunction catalogHref(): string {\n if (typeof window === 'undefined') return '/'\n const url = new URL(window.location.href)\n url.searchParams.delete('integration')\n url.searchParams.delete('connection')\n return `${url.pathname}${url.search}${url.hash}`\n}\n\nfunction accountName(connection: HubConnection, providerTitle: string): string {\n return connection.accountDisplay?.trim() || connection.displayName?.trim() || providerTitle\n}\n\nfunction AccountStatus({ connection, accounts }: { connection: HubConnection; accounts: HubIntegrationsAccounts }) {\n const status = accounts.getStatus?.(connection)\n return status ? <StatusPill tone={status.tone ?? 'neutral'} size=\"sm\" className=\"max-w-full whitespace-normal\">{status.label}</StatusPill> : null\n}\n\nfunction AccountPrimaryAction({ connection, accounts, busy }: { connection: HubConnection; accounts: HubIntegrationsAccounts; busy: boolean }) {\n const primary = accounts.getPrimaryAction?.(connection)\n return primary ? <Button type=\"button\" variant=\"outline\" size=\"sm\" disabled={busy || primary.disabled}\n onClick={primary.onSelect}>{primary.label}</Button> : null\n}\n\nfunction HubAccountList({ accounts, connections, providers, loading, error, busy, onRetry, onManage, canManage, onAdd }: {\n accounts: HubIntegrationsAccounts\n connections: readonly HubConnection[]\n providers: readonly HubProvider[]\n loading: boolean\n error: string | null\n busy: boolean\n onRetry: () => void\n onManage: (connection: HubConnection) => void\n canManage: (connection: HubConnection) => boolean\n onAdd: () => void\n}) {\n const [query, setQuery] = useState('')\n const titles = new Map(providers.map(provider => [provider.providerId, provider.title]))\n const title = (connection: HubConnection) => titles.get(connection.providerId) ?? connection.displayName ?? connection.providerId\n const rows = connections.filter(connection => connection.status !== 'revoked')\n .map(connection => ({ connection, provider: title(connection), name: accountName(connection, title(connection)) }))\n .sort((a, b) => a.provider.localeCompare(b.provider) || a.name.localeCompare(b.name) || a.connection.id.localeCompare(b.connection.id))\n const matching = rows.filter(row => `${row.provider} ${row.name}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()))\n return <section className=\"min-w-0 space-y-4\" aria-labelledby=\"hub-accounts-heading\" aria-busy={loading || undefined}>\n <header>\n <h2 id=\"hub-accounts-heading\" className=\"sr-only\">{accounts.title}</h2>\n {accounts.description ? <p className=\"text-sm text-muted-foreground\">{accounts.description}</p> : null}\n </header>\n {rows.length > 0 && !error ? <Input type=\"search\" aria-label=\"Search accounts\" placeholder=\"Search accounts…\" value={query} onChange={event => setQuery(event.target.value)} /> : null}\n {error ? <div role=\"alert\" className=\"flex flex-wrap items-center gap-3 rounded-xl border border-destructive/40 bg-card p-4 text-sm text-destructive\">\n <p className=\"min-w-0 flex-1 break-words\">{error}</p>\n <Button type=\"button\" variant=\"outline\" size=\"sm\" onClick={onRetry}>Retry</Button>\n </div> : loading && rows.length === 0 ? <p role=\"status\" className=\"rounded-xl border border-border bg-card p-4 text-sm text-muted-foreground\">Loading connected accounts…</p>\n : rows.length === 0 ? <div className=\"space-y-3 rounded-xl border border-border bg-card p-5\"><p className=\"text-sm text-muted-foreground\">{accounts.emptyLabel ?? 'No accounts connected yet.'}</p><Button type=\"button\" variant=\"outline\" onClick={onAdd}>Add integration</Button></div>\n : matching.length === 0 ? <p role=\"status\" className=\"py-6 text-sm text-muted-foreground\">No accounts match your search.</p>\n : <ul className=\"grid grid-cols-1 gap-4 md:grid-cols-2 xl:grid-cols-3\" aria-label={accounts.title}>\n {matching.map(({ connection, provider, name }) => {\n const health = connection.status !== 'active' ? connection.status.replaceAll('_', ' ')\n : connection.health === 'unhealthy' ? 'needs attention' : null\n return <li key={connection.id} data-testid={`hub-account-${connection.id}`} className=\"min-w-0\">\n <Card className=\"flex h-full min-w-0 flex-col gap-4 p-4 shadow-none\">\n <div className=\"flex min-w-0 items-center gap-4\">\n <div className=\"flex size-16 shrink-0 items-center justify-center rounded-xl bg-muted/50\"><ProviderIcon id={connection.providerId} displayName={provider} size={48} className=\"shrink-0 rounded-lg\" /></div>\n <div className=\"min-w-0\">\n <p className=\"text-base font-semibold [overflow-wrap:anywhere]\">{provider}</p>\n {health ? <p className=\"mt-1 text-sm text-muted-foreground\">{health}</p> : null}\n </div>\n </div>\n <p className=\"text-sm font-medium [overflow-wrap:anywhere]\">{name}</p>\n <div className=\"mt-auto space-y-4\">\n <AccountStatus connection={connection} accounts={accounts} />\n <div className=\"flex flex-wrap items-center gap-2 border-t border-border pt-3\">\n <AccountPrimaryAction connection={connection} accounts={accounts} busy={busy} />\n {canManage(connection) ? <Button type=\"button\" variant=\"outline\" size=\"sm\" aria-label={`Manage ${provider} account ${name}`}\n onClick={() => onManage(connection)}>Manage</Button> : null}\n </div>\n </div>\n </Card>\n </li>\n })}\n </ul>}\n {accounts.footer}\n </section>\n}\n\n/** Embeddable settings surface. The app supplies authenticated transport and grants. */\nexport function HubIntegrationsPanel(props: HubIntegrationsPanelProps) {\n const hub = useHubIntegrations(props)\n const scope = contextKey(props.identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const activeDialog = useRef(hub.dialog)\n activeDialog.current = hub.dialog\n const [query, setQuery] = useState('')\n const [category, setCategory] = useState('')\n const [sort, setSort] = useState<IntegrationSort>('featured')\n const [view, setView] = useState<{ scope: string; value: 'accounts' | 'catalog' } | null>(null)\n const [catalogSelection, setCatalogSelection] = useState<{ scope: string; ids: Record<string, string | null> }>({ scope, ids: {} })\n const [keyInput, setKeyInput] = useState({ scope, value: '' })\n const apiKey = keyInput.scope === scope ? keyInput.value : ''\n const setApiKey = (value: string) => setKeyInput({ scope, value })\n const [metadataInput, setMetadataInput] = useState<{ scope: string; value: HubApiKeyConnectionMetadata | undefined }>({ scope, value: undefined })\n const metadata = metadataInput.scope === scope ? metadataInput.value : undefined\n const setMetadata = (value: HubApiKeyConnectionMetadata | undefined) => setMetadataInput({ scope, value })\n const [parameterInput, setParameterInput] = useState({ scope, values: {} as Record<string, string> })\n const parameters = parameterInput.scope === scope ? parameterInput.values : {}\n const setParameters = (values: Record<string, string>) => setParameterInput({ scope, values })\n\n useEffect(() => { setApiKey(''); setMetadata(undefined); setParameters({}) }, [scope])\n const pending = hub.writeState.status === 'pending' || hub.connectStatus.status === 'pending'\n const error = hub.providers.status === 'error' ? hub.providers.message\n : hub.connections.status === 'error' ? hub.connections.message : null\n const mutationError = hub.writeState.status === 'failed' ? hub.writeState.message : null\n const writeMessage = hub.writeState.status === 'succeeded' ? hub.writeState.value.message : null\n const writeWarning = hub.writeState.status === 'succeeded' && hub.writeState.value.reconciliation === 'refresh-failed'\n const rows = hub.rows.map(row => {\n const selectedId = catalogSelection.scope === scope ? catalogSelection.ids[row.providerId] : null\n return {\n ...row,\n selectedConnectionId: row.connections.some(connection => connection.id === selectedId) ? selectedId ?? null : null,\n connections: row.connections.map(connection => {\n const source = hub.connections.status === 'ready'\n ? hub.connections.value.find(item => item.id === connection.id) : undefined\n return source ? {\n ...connection,\n detail: props.getConnectionContext?.(source) ?? connection.detail,\n actions: props.getConnectionActions?.(source),\n } : connection\n }),\n }\n })\n const selectedRow = rows.find(row => row.providerId === hub.provider?.providerId)\n const connectionList = hub.connections.status === 'ready' ? hub.connections.value : []\n const accountCount = connectionList.filter(connection => connection.status !== 'revoked').length\n const activeView = view?.scope === scope ? view.value : hub.connections.status === 'ready' && accountCount === 0 ? 'catalog' : 'accounts'\n const showAccounts = () => setView({ scope, value: 'accounts' })\n useEffect(() => {\n if (hub.connectStatus.status === 'connected') showAccounts()\n }, [hub.connectStatus.status, scope])\n // With an account list, the catalog offers providers without a connected account.\n // The Hub keeps revoked connections listed; a provider with only those is connectable again.\n const connectedProviders = new Set(connectionList.filter(connection => connection.status !== 'revoked').map(connection => connection.providerId))\n const catalogRows = props.accounts && hub.connections.status === 'error' ? [] : props.accounts\n ? rows.filter(row => !connectedProviders.has(row.providerId)).map(row => ({ ...row, connections: [], selectedConnectionId: null }))\n : rows\n const selectedConnection = hub.connection\n const detailError = hub.detail.status === 'error' ? hub.detail.message\n : hub.detail.status === 'ready' && hub.detail.value.truncated\n ? `Showing at most ${hub.detail.value.tools.length} actions. The provider catalog may be incomplete.` : null\n const detailsByConnectionId = useMemo(() => hub.connection ? {\n [hub.connection.id]: {\n ...hub.details,\n loading: hub.detail.status === 'loading',\n busy: pending,\n error: detailError,\n },\n } : {}, [hub.connection, hub.details, hub.detail.status, pending, detailError])\n\n const closeDialog = () => {\n if (hub.connectStatus.status === 'pending') hub.cancelConnect()\n else hub.setDialog(null)\n setApiKey(''); setMetadata(undefined); setParameters({})\n }\n\n const catalog = <IntegrationsCatalog\n title={props.title ?? 'Integrations'} layout={props.layout} rows={catalogRows}\n query={query} onQueryChange={setQuery} categoryFilter={category} onCategoryFilterChange={setCategory}\n sort={sort} onSortChange={setSort}\n onSelectConnection={(providerId, connectionId) => setCatalogSelection(current => ({\n scope, ids: { ...(current.scope === scope ? current.ids : {}), [providerId]: connectionId },\n }))}\n onConnect={row => { const provider = hub.providers.status === 'ready' ? hub.providers.value.find(item => item.providerId === row.providerId) : null; if (provider) hub.beginConnect(provider) }}\n onManage={(connection, row) => hub.selectConnection(row.providerId, connection.id)}\n onDisconnect={connection => { void hub.revoke(connection.id) }}\n onRequestIntegration={props.onRequestIntegration} onRetry={() => hub.refresh()}\n loading={hub.providers.status === 'loading' || hub.connections.status === 'loading'} error={error}\n actionError={mutationError} connectError={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n busyProviderId={hub.connectStatus.status === 'pending' ? hub.connectStatus.providerId ?? null : null}\n reserveConnectionContext\n emptyCatalogLabel={props.accounts && rows.length > 0 ? 'Every available integration has a connected account. Manage an account to connect another.' : undefined}\n />\n\n return <section className={props.className}>\n {hub.connectStatus.status === 'pending' ? <div role=\"status\" className=\"mb-4 flex flex-wrap items-center gap-3\">\n <span>Finish connecting in the popup.</span>\n <Button type=\"button\" variant=\"outline\" onClick={hub.cancelConnect}>Cancel connection</Button>\n </div> : null}\n {hub.writeState.status === 'pending' ? <p role=\"status\">Saving Hub settings…</p> : null}\n {mutationError ? <p role=\"alert\">{mutationError}</p> : null}\n {writeMessage ? <p role={writeWarning ? 'alert' : 'status'}>{writeMessage}</p> : null}\n {hub.connectStatus.message && hub.provider ? <p role={hub.connectStatus.status === 'failed' ? 'alert' : 'status'}>{hub.connectStatus.message}</p> : null}\n {hub.provider ? <>\n {(props.accounts && selectedConnection) || selectedRow?.canConnect ? <div className=\"mb-4 flex min-w-0 flex-wrap items-center gap-2\">\n {props.accounts && selectedConnection ? <div className=\"flex min-w-0 flex-1 flex-wrap items-center gap-2\" data-testid=\"hub-account-access\"\n aria-label={`Access for ${accountName(selectedConnection, hub.provider.title)}`} role=\"group\">\n <span className=\"min-w-0 max-w-full truncate text-sm font-medium\">{accountName(selectedConnection, hub.provider.title)}</span>\n <AccountStatus connection={selectedConnection} accounts={props.accounts} />\n <AccountPrimaryAction connection={selectedConnection} accounts={props.accounts} busy={pending} />\n </div> : null}\n {selectedRow?.canConnect ? <Button type=\"button\" variant=\"outline\" className=\"ml-auto\" disabled={pending}\n onClick={() => hub.beginConnect(hub.provider!)}>Connect another account</Button> : null}\n </div> : null}\n <IntegrationConnectionDetail\n provider={displayProvider(hub.provider)}\n connections={selectedRow?.connections ?? []}\n selectedConnectionId={hub.connection?.id ?? null}\n onSelectConnection={connectionId => hub.selectConnection(hub.provider!.providerId, connectionId)}\n detailsByConnectionId={detailsByConnectionId}\n loading={hub.connections.status === 'loading' || hub.detail.status === 'loading'}\n error={detailError}\n backHref={catalogHref()}\n onRetry={() => hub.refresh()}\n onTestConnection={connectionId => { void hub.test(connectionId) }}\n onDisconnect={connectionId => { void hub.revoke(connectionId) }}\n onDecisionChange={(connectionId, actionPath, decision) => {\n if (decision !== 'allow' && decision !== 'ask' && decision !== 'deny') return\n void hub.setDecision(connectionId, actionPath, decision)\n }}\n onResetDecision={(connectionId, actionPath) => { void hub.resetDecision(connectionId, actionPath) }}\n />\n </> : <>\n {props.accounts ? <Tabs value={activeView} onValueChange={value => setView({ scope, value: value === 'catalog' ? 'catalog' : 'accounts' })}>\n <TabsList aria-label=\"Integration views\" className=\"mb-5 grid h-auto w-full grid-cols-2 sm:inline-flex sm:w-auto\">\n <TabsTrigger value=\"accounts\">Accounts{' '}{hub.connections.status === 'ready' ? <span className=\"ml-2 tabular-nums text-muted-foreground\">{accountCount}</span> : null}</TabsTrigger>\n <TabsTrigger value=\"catalog\">Add integration{' '}{hub.providers.status === 'ready' && hub.connections.status === 'ready' ? <span className=\"ml-2 tabular-nums text-muted-foreground\">{catalogRows.length}</span> : null}</TabsTrigger>\n </TabsList>\n <TabsContent value=\"accounts\">\n {hub.connectStatus.status === 'connected' && hub.connectStatus.message ? <p role=\"status\" className=\"mb-3 text-sm\">{hub.connectStatus.message}</p> : null}\n <HubAccountList key={scope} accounts={props.accounts} connections={connectionList} providers={hub.providers.status === 'ready' ? hub.providers.value : []}\n loading={hub.connections.status === 'loading'} error={hub.connections.status === 'error' ? hub.connections.message : null} busy={pending}\n onRetry={() => hub.refresh()} onManage={connection => hub.selectConnection(connection.providerId, connection.id)}\n canManage={connection => props.can({ operation: 'policies.list', connectionId: connection.id })}\n onAdd={() => setView({ scope, value: 'catalog' })} />\n </TabsContent>\n <TabsContent value=\"catalog\">{catalog}</TabsContent>\n </Tabs> : catalog}\n </>}\n {hub.dialog?.kind === 'api-key' ? <ApiKeyConnectDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n description={hub.dialog.provider.authHint}\n value={apiKey}\n onValueChange={setApiKey}\n busy={pending}\n error={mutationError}\n canSubmit={apiKey.trim().length > 0 && !pending}\n onSubmit={() => {\n const secret = apiKey\n const target = hub.dialog?.provider.providerId\n const submittedDialog = hub.dialog\n setApiKey('')\n if (target) void hub.submitApiKey(target, secret, metadata).then(result => {\n if (result.succeeded && activeScope.current === scope && activeDialog.current === submittedDialog) {\n hub.setDialog(null); setMetadata(undefined); showAccounts()\n }\n })\n }}\n >{props.renderApiKeyMetadata?.({ provider: hub.dialog.provider, value: metadata, onChange: setMetadata })}</ApiKeyConnectDialog> : null}\n {hub.dialog?.kind === 'oauth' ? <OAuthConnectionParameterDialog\n open\n onOpenChange={open => { if (!open) closeDialog() }}\n providerId={hub.dialog.provider.providerId}\n title={hub.dialog.provider.title}\n parameters={hub.dialog.provider.connectionParameters ?? []}\n values={parameters}\n onValueChange={(key, value) => setParameters({ ...parameters, [key]: value })}\n busy={pending}\n error={hub.connectStatus.status === 'failed' ? hub.connectStatus.message : null}\n canSubmit={!pending && (hub.dialog.provider.connectionParameters ?? []).every(field => !field.required || !!parameters[field.key]?.trim())}\n onSubmit={() => {\n const target = hub.dialog?.provider\n const submittedDialog = hub.dialog\n if (target) void hub.startOAuth(target, parameters).then(result => {\n if (result === 'connected' && activeScope.current === scope && activeDialog.current === submittedDialog) setParameters({})\n })\n }}\n /> : null}\n </section>\n}\n","import type { HubConnection, HubPolicy, HubProvider, HubTool } from '@tangle-network/hub-sdk'\nimport type {\n IntegrationConnectionDetails,\n IntegrationDisplayProvider,\n IntegrationPermissionDisplay,\n IntegrationPermissionGroup,\n IntegrationsProviderRow,\n} from '@tangle-network/sandbox-ui/integrations'\n\nexport type HubIntegrationCapability =\n | { operation: 'oauth.start' | 'api-key.connect'; providerId: string }\n | { operation: 'connection.revoke' | 'connection.health' | 'policies.list'; connectionId: string }\n | { operation: 'policy.set' | 'policy.reset'; connectionId: string; actionPath: string }\n\n/** Display hints only. `createHubSettingsRoutes.authorize` remains authoritative. */\nexport type HubIntegrationCapabilities = (intent: HubIntegrationCapability) => boolean\n\nexport const ACTION_LIMIT = 200\n\nexport function contextKey(identity: { userId: string; sessionId: string; workspaceId: string }): string {\n return JSON.stringify([identity.userId, identity.sessionId, identity.workspaceId])\n}\n\nexport function displayProvider(provider: HubProvider): IntegrationDisplayProvider {\n return { providerId: provider.providerId, title: provider.title, category: provider.category }\n}\n\nexport function catalogRows(\n providers: readonly HubProvider[],\n connections: readonly HubConnection[],\n selectedIds: Readonly<Record<string, string | null>>,\n can: HubIntegrationCapabilities,\n hasUnsupportedConnect = false,\n hostConnectProviderIds: readonly string[] = [],\n): IntegrationsProviderRow[] {\n return providers.map(provider => {\n const accounts = connections.filter(connection => connection.providerId === provider.providerId)\n return {\n ...displayProvider(provider),\n kind: 'provider',\n authKind: provider.authKind,\n selectedConnectionId: accounts.some(account => account.id === selectedIds[provider.providerId])\n ? selectedIds[provider.providerId] ?? null : null,\n canConnect: hostConnectProviderIds.includes(provider.providerId) ? true : provider.authKind === 'oauth2'\n ? provider.configured && can({ operation: 'oauth.start', providerId: provider.providerId })\n : provider.authKind === 'api_key'\n ? provider.configured && can({ operation: 'api-key.connect', providerId: provider.providerId })\n : hasUnsupportedConnect,\n connections: accounts.map(connection => ({\n id: connection.id,\n accountDisplay: connection.accountDisplay ?? connection.displayName,\n statusLabel: connection.status === 'active' ? 'Connected' : connection.status.replaceAll('_', ' '),\n statusTone: connection.status === 'active' && connection.health !== 'unhealthy' ? 'success' : 'warning',\n detail: connection.providerAccountId ?? undefined,\n capabilities: {\n manage: can({ operation: 'policies.list', connectionId: connection.id }),\n disconnect: can({ operation: 'connection.revoke', connectionId: connection.id }),\n test: can({ operation: 'connection.health', connectionId: connection.id }),\n editPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n resetPermissions: can({ operation: 'policies.list', connectionId: connection.id }),\n },\n })),\n }\n })\n}\n\nconst OPTIONS = [\n { value: 'allow', label: 'Allow' },\n { value: 'ask', label: 'Ask' },\n { value: 'deny', label: 'Deny' },\n] as const\n\n/** Stored overrides are shown; app-specific effective policy is never guessed. */\nexport function permissionDetails(\n tools: readonly HubTool[],\n policies: readonly HubPolicy[],\n connectionId: string,\n can: HubIntegrationCapabilities,\n): IntegrationConnectionDetails {\n const overrides = new Map(policies.filter(policy => policy.connectionId === connectionId).map(policy => [policy.actionPath, policy.decision]))\n const groups: IntegrationPermissionGroup[] = [\n { id: 'writes', title: 'Write and unknown actions', rows: [] },\n { id: 'reads', title: 'Read actions', collapsed: true, rows: [] },\n ]\n const writes: IntegrationPermissionDisplay[] = []\n const reads: IntegrationPermissionDisplay[] = []\n for (const tool of tools) {\n const override = overrides.get(tool.path)\n const row = {\n actionPath: tool.path,\n title: tool.title ?? tool.path,\n riskLabel: tool.risk ?? 'unknown',\n riskTone: tool.risk === 'destructive' ? 'error' : tool.risk === 'write' || tool.risk === undefined ? 'warning' : 'neutral',\n decision: override ?? null,\n decisionOptions: OPTIONS,\n sourceLabel: override ? 'Stored override' : 'No stored override',\n canReset: override !== undefined && can({ operation: 'policy.reset', connectionId, actionPath: tool.path }),\n disabled: !can({ operation: 'policy.set', connectionId, actionPath: tool.path }),\n } as const\n if (tool.risk === 'read') reads.push(row)\n else writes.push(row)\n }\n writes.sort((a, b) => a.title.localeCompare(b.title))\n reads.sort((a, b) => a.title.localeCompare(b.title))\n groups[0] = { ...groups[0]!, rows: writes }\n groups[1] = { ...groups[1]!, rows: reads }\n return { permissionGroups: groups }\n}\n","import type { HubApiKeyConnectionMetadata, HubConnection, HubPolicyDecision, HubProvider } from '@tangle-network/hub-sdk'\nimport { useCallback, useEffect, useMemo, useRef, useState } from 'react'\nimport { confirmWrite, useAsyncResource, useConfirmedMutation } from '../web-react/async'\nimport type { HubIntegrationsClient, HubIntegrationsIdentity } from './client'\nimport { connectWithPopup, type PopupConnectResult } from './popup'\nimport { ACTION_LIMIT, catalogRows, contextKey, permissionDetails, type HubIntegrationCapabilities } from './projection'\n\ntype Selection = { scope: string; providerId: string | null; connectionId: string | null }\ntype Dialog = { scope: string; kind: 'api-key' | 'oauth'; provider: HubProvider } | null\n\nexport interface UseHubIntegrationsOptions {\n identity: HubIntegrationsIdentity\n client: HubIntegrationsClient\n /** Display only. The host server must authorize every exact operation. */\n can: HubIntegrationCapabilities\n /** Local app route that renders `HubConnectCallbackPage`. */\n callbackPath: string\n /** Optional host handler for custom/native signup. No Platform redirect is assumed. */\n onUnsupportedConnect?: (provider: HubProvider) => void\n /**\n * App-owned connection for these providers, such as a number the app\n * provisions itself. Their catalog rows stay visible and connectable, and\n * choosing one calls `onConnect` instead of running a Hub flow.\n */\n hostConnect?: HubHostConnect\n}\n\nexport interface HubHostConnect {\n providerIds: readonly string[]\n onConnect: (provider: HubProvider) => void\n}\n\ntype WriteInput =\n | { kind: 'api-key'; identity: HubIntegrationsIdentity; scope: string; providerId: string; apiKey: string; metadata?: HubApiKeyConnectionMetadata }\n | { kind: 'revoke'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'health'; identity: HubIntegrationsIdentity; scope: string; connectionId: string }\n | { kind: 'set'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string; decision: HubPolicyDecision }\n | { kind: 'reset'; identity: HubIntegrationsIdentity; scope: string; connectionId: string; actionPath: string }\n\nexport interface HubWriteReceipt {\n scope: string\n kind: WriteInput['kind']\n reconciliation: 'verified' | 'refresh-failed'\n message: string\n}\n\nfunction initialSelection(scope: string): Selection {\n if (typeof window === 'undefined') return { scope, providerId: null, connectionId: null }\n const query = new URL(window.location.href).searchParams\n return { scope, providerId: query.get('integration'), connectionId: query.get('connection') }\n}\n\nfunction updateUrl(providerId: string | null, connectionId: string | null): void {\n if (typeof window === 'undefined') return\n const url = new URL(window.location.href)\n if (providerId) url.searchParams.set('integration', providerId)\n else url.searchParams.delete('integration')\n if (connectionId) url.searchParams.set('connection', connectionId)\n else url.searchParams.delete('connection')\n window.history.pushState(window.history.state, '', url)\n}\n\n/** Identity-bound Hub settings controller; connection state is always server-read. */\nexport function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect, hostConnect }: UseHubIntegrationsOptions) {\n const scope = contextKey(identity)\n const activeScope = useRef(scope)\n activeScope.current = scope\n const [selection, setSelection] = useState<Selection>(() => initialSelection(scope))\n const visibleSelection = selection.scope === scope ? selection : { scope, providerId: null, connectionId: null }\n const [dialog, setDialog] = useState<Dialog>(null)\n const visibleDialog = dialog?.scope === scope ? dialog : null\n const [connectStatus, setConnectStatus] = useState<{ scope: string; status: 'idle' | 'pending' | 'connected' | 'failed'; providerId?: string; message?: string }>({ scope, status: 'idle' })\n const [writeScope, setWriteScope] = useState(scope)\n const pendingPopup = useRef<AbortController | null>(null)\n\n useEffect(() => {\n const onPop = () => setSelection(initialSelection(scope))\n window.addEventListener('popstate', onPop)\n return () => window.removeEventListener('popstate', onPop)\n }, [scope])\n\n const providers = useAsyncResource({ load: ({ signal }) => client.providers(identity, signal), deps: [client, scope], isEmpty: () => false })\n const connections = useAsyncResource({ load: ({ signal }) => client.connections(identity, signal), deps: [client, scope], isEmpty: () => false })\n const providerList = providers.status === 'ready' ? providers.value : []\n const connectionList = connections.status === 'ready' ? connections.value : []\n const provider = providerList.find(item => item.providerId === visibleSelection.providerId) ?? null\n const connection = connectionList.find(item => item.id === visibleSelection.connectionId && item.providerId === provider?.providerId) ?? null\n const canReadPolicies = connection !== null && can({ operation: 'policies.list', connectionId: connection.id })\n const detail = useAsyncResource({\n enabled: canReadPolicies && connection?.status === 'active',\n deps: [client, scope, provider?.providerId, connection?.id, canReadPolicies],\n isEmpty: () => false,\n load: async ({ signal }) => {\n if (!provider || !connection) throw new Error('Choose a connection.')\n const [tools, policies] = await Promise.all([\n client.actions(identity, provider.providerId, ACTION_LIMIT, signal),\n client.policies(identity, connection.id, signal),\n ])\n if (tools.some(tool => !tool.path.startsWith(`${provider.providerId}.`)) || policies.some(policy => policy.connectionId !== connection.id)) {\n throw new Error('Hub settings response changed connection or provider.')\n }\n return { tools, policies, truncated: tools.length >= ACTION_LIMIT }\n },\n })\n\n const write = useConfirmedMutation<WriteInput, HubWriteReceipt>({\n concurrency: 'reject',\n mutate: async (input, { signal }) => {\n if (input.scope !== activeScope.current) throw new Error('Integration context changed. Retry in the current workspace.')\n const origin = input.identity\n const receipt = (reconciliation: HubWriteReceipt['reconciliation'], message: string) => confirmWrite<HubWriteReceipt>({ scope: input.scope, kind: input.kind, reconciliation, message })\n if (input.kind === 'api-key') {\n if (!can({ operation: 'api-key.connect', providerId: input.providerId })) throw new Error('Connection setup is unavailable.')\n const created = await client.connectApiKey(origin, input.providerId, input.apiKey, input.metadata, signal)\n if (created.providerId !== input.providerId || created.status !== 'active') throw new Error('Hub did not confirm the requested connection.')\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === created.id && item.status === 'active')\n ? receipt('verified', 'Connection saved and verified.') : receipt('refresh-failed', 'Connection saved; current account state could not be confirmed.')\n } catch { return receipt('refresh-failed', 'Connection saved; refresh failed.') }\n }\n if (input.kind === 'revoke') {\n if (!can({ operation: 'connection.revoke', connectionId: input.connectionId })) throw new Error('Disconnect is unavailable.')\n await client.revoke(origin, input.connectionId, signal)\n try {\n const current = await client.connections(origin, signal)\n return current.some(item => item.id === input.connectionId && item.status === 'active')\n ? receipt('refresh-failed', 'Disconnected, but the current account state disagrees.') : receipt('verified', 'Connection disconnected and verified.')\n } catch { return receipt('refresh-failed', 'Disconnected; refresh failed.') }\n }\n if (input.kind === 'health') {\n if (!can({ operation: 'connection.health', connectionId: input.connectionId })) throw new Error('Connection test is unavailable.')\n const result = await client.health(origin, input.connectionId, signal)\n if (result.connection.id !== input.connectionId) throw new Error('Hub returned another connection.')\n return receipt('verified', `Connection test: ${result.health.status.replaceAll('_', ' ')}.`)\n }\n if (!can({ operation: input.kind === 'set' ? 'policy.set' : 'policy.reset', connectionId: input.connectionId, actionPath: input.actionPath })) {\n throw new Error('Permission editing is unavailable.')\n }\n if (input.kind === 'set') {\n const stored = await client.setPolicy(origin, input.connectionId, input.actionPath, input.decision, signal)\n if (stored.connectionId !== input.connectionId || stored.actionPath !== input.actionPath || stored.decision !== input.decision) {\n throw new Error('Hub did not confirm the requested permission.')\n }\n } else await client.resetPolicy(origin, input.connectionId, input.actionPath, signal)\n try {\n const current = await client.policies(origin, input.connectionId, signal)\n const override = current.find(policy => policy.actionPath === input.actionPath)\n const matches = input.kind === 'set' ? override?.decision === input.decision : override === undefined\n return matches\n ? receipt('verified', 'Permission saved and verified.') : receipt('refresh-failed', 'Permission write was accepted; current policy state disagrees.')\n } catch { return receipt('refresh-failed', 'Permission write was accepted; refresh failed.') }\n },\n onSucceeded: value => { if (value.scope === activeScope.current) { connections.retry(); detail.retry() } },\n })\n\n useEffect(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'idle' })\n setWriteScope(scope)\n write.reset()\n return () => { pendingPopup.current?.abort(); pendingPopup.current = null }\n }, [scope, client, write.reset])\n\n const selectProvider = useCallback((providerId: string | null) => {\n const next = { scope, providerId, connectionId: null }\n setSelection(next)\n updateUrl(providerId, null)\n }, [scope])\n\n const selectConnection = useCallback((providerId: string, connectionId: string | null) => {\n if (connectionId && !connectionList.some(item => item.id === connectionId && item.providerId === providerId)) return\n setSelection({ scope, providerId, connectionId })\n updateUrl(providerId, connectionId)\n }, [scope, connectionList])\n\n const startOAuth = useCallback(async (target: HubProvider, connectionParameters?: Record<string, string>): Promise<PopupConnectResult> => {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) return 'unavailable'\n if (connections.status !== 'ready') { setConnectStatus({ scope, status: 'failed', message: 'Load connections before connecting.' }); return 'unavailable' }\n pendingPopup.current?.abort()\n const controller = new AbortController()\n pendingPopup.current = controller\n setConnectStatus({ scope, status: 'pending', providerId: target.providerId })\n const result = await connectWithPopup({\n client, identity, providerId: target.providerId, before: connections.value,\n callbackPath, connectionParameters, signal: controller.signal,\n isCurrent: () => activeScope.current === scope && !controller.signal.aborted,\n })\n if (pendingPopup.current !== controller || activeScope.current !== scope) return result\n pendingPopup.current = null\n if (result === 'connected') {\n connections.retry()\n setDialog(null)\n setConnectStatus({ scope, status: 'connected', message: 'Connection verified.' })\n } else setConnectStatus({ scope, status: 'failed', message: result === 'blocked' ? 'Allow the popup and try again.' : result === 'unverified' ? 'Could not verify a new connection. Refresh and try again.' : result === 'cancelled' ? 'Connection was cancelled.' : 'This connection flow is unavailable.' })\n return result\n }, [can, connections, client, identity, callbackPath, scope])\n\n const beginConnect = useCallback((target: HubProvider) => {\n if (hostConnect?.providerIds.includes(target.providerId)) {\n hostConnect.onConnect(target)\n return\n }\n if (target.authKind !== 'api_key' && target.authKind !== 'oauth2') {\n if (onUnsupportedConnect) onUnsupportedConnect(target)\n else setConnectStatus({ scope, status: 'failed', message: 'This provider needs an app-specific connection flow.' })\n return\n }\n if (!target.configured) {\n setConnectStatus({ scope, status: 'failed', message: 'This provider is not configured for connection.' })\n return\n }\n if (target.authKind === 'api_key') {\n if (can({ operation: 'api-key.connect', providerId: target.providerId })) setDialog({ scope, kind: 'api-key', provider: target })\n else setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' })\n return\n }\n if (target.authKind === 'oauth2') {\n if (!can({ operation: 'oauth.start', providerId: target.providerId })) {\n setConnectStatus({ scope, status: 'failed', message: 'Connection setup is unavailable.' }); return\n }\n if (target.connectionParameters?.length) setDialog({ scope, kind: 'oauth', provider: target })\n else void startOAuth(target)\n return\n }\n }, [can, onUnsupportedConnect, hostConnect, scope, startOAuth])\n\n const cancelConnect = useCallback(() => {\n pendingPopup.current?.abort()\n pendingPopup.current = null\n setDialog(null)\n setConnectStatus({ scope, status: 'failed', message: 'Connection was cancelled.' })\n }, [scope])\n\n const rows = useMemo(() => catalogRows(providerList, connectionList, visibleSelection.providerId && visibleSelection.connectionId\n ? { [visibleSelection.providerId]: visibleSelection.connectionId } : {}, can, !!onUnsupportedConnect,\n hostConnect?.providerIds),\n [providerList, connectionList, visibleSelection.providerId, visibleSelection.connectionId, can, onUnsupportedConnect, hostConnect])\n const details = detail.status === 'ready' && connection\n ? permissionDetails(detail.value.tools, detail.value.policies, connection.id, can) : undefined\n\n return {\n providers, connections, detail, rows, provider, connection, dialog: visibleDialog, setDialog,\n connectStatus: connectStatus.scope === scope ? connectStatus : { scope, status: 'idle' as const, providerId: undefined },\n selection: visibleSelection, selectProvider, selectConnection, beginConnect, startOAuth, cancelConnect,\n write, writeState: writeScope === scope ? write.state : { status: 'idle' as const }, details,\n refresh: () => { providers.retry(); connections.retry(); detail.retry() },\n submitApiKey: (providerId: string, apiKey: string, metadata?: HubApiKeyConnectionMetadata) => { setWriteScope(scope); return write.run({ kind: 'api-key', identity, scope, providerId, apiKey, metadata }) },\n revoke: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'revoke', identity, scope, connectionId }) },\n test: (connectionId: string) => { setWriteScope(scope); return write.run({ kind: 'health', identity, scope, connectionId }) },\n setDecision: (connectionId: string, actionPath: string, decision: HubPolicyDecision) => { setWriteScope(scope); return write.run({ kind: 'set', identity, scope, connectionId, actionPath, decision }) },\n resetDecision: (connectionId: string, actionPath: string) => { setWriteScope(scope); return write.run({ kind: 'reset', identity, scope, connectionId, actionPath }) },\n }\n}\n"],"mappings":";;;;;;;AAAA,SAAS,WAAW,gBAAgB;;;ACG7B,IAAM,sBAAsB;AAC5B,IAAM,6BAA6B;AACnC,IAAM,kCAAkC;AACxC,IAAM,mBAAmB,IAAI,KAAK;AACzC,IAAM,0BAA0B;AAChC,IAAM,mBAAmB;AACzB,IAAM,iBAAiB;AAIhB,SAAS,YAAY,MAA0B;AACpD,MAAI,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,EAAG,QAAO;AAC3D,MAAI;AACF,UAAM,SAAS,OAAO,WAAW,cAAc,0BAA0B,OAAO,SAAS;AACzF,UAAM,MAAM,IAAI,IAAI,MAAM,MAAM;AAChC,WAAO,IAAI,WAAW,UAAU,CAAC,IAAI,YAAY,CAAC,IAAI,WAAW,MAAM;AAAA,EACzE,QAAQ;AAAE,WAAO;AAAA,EAAK;AACxB;AAEA,SAAS,kBAAkB,YAAoB,QAAkC,OAA0C;AACzH,QAAM,WAAW,IAAI,IAA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AAM,aAAY;AAAA,QAAE;AAAA,QACjD,YAAY,IAAI,OAAO,SAAS;AAAA,QAChC,OAAO,IAAI,OAAO,SAAS;AAAA,QAC3B,YAAY,IAAI,OAAO,SAAS,wBAAwB,CAAC;AAAA,QACzD,QAAQ;AAAA,QACR,eAAe,CAAC,KAAK,UAAU,cAAc,EAAE,GAAG,YAAY,CAAC,GAAG,GAAG,MAAM,CAAC;AAAA,QAC5E,MAAM;AAAA,QACN,OAAO,IAAI,cAAc,WAAW,WAAW,IAAI,cAAc,UAAU;AAAA,QAC3E,WAAW,CAAC,YAAY,IAAI,OAAO,SAAS,wBAAwB,CAAC,GAAG,MAAM,WAAS,CAAC,MAAM,YAAY,CAAC,CAAC,WAAW,MAAM,GAAG,GAAG,KAAK,CAAC;AAAA,QACzI,UAAU,MAAM;AACd,gBAAM,SAAS,IAAI,QAAQ;AAC3B,gBAAM,kBAAkB,IAAI;AAC5B,cAAI,OAAQ,MAAK,IAAI,WAAW,QAAQ,UAAU,EAAE,KAAK,YAAU;AACjE,gBAAI,WAAW,eAAe,YAAY,YAAY,SAAS,aAAa,YAAY,gBAAiB,eAAc,CAAC,CAAC;AAAA,UAC3H,CAAC;AAAA,QACH;AAAA;AAAA,IACF,IAAK;AAAA,KACP;AACF;","names":["useEffect","useMemo","useRef","useState","useEffect","useState","useState","useEffect","jsx","jsxs","useState","useRef","useEffect","catalogRows","useMemo"]}
|
|
@@ -4,6 +4,7 @@ import { type StatusTone } from '@tangle-network/ui/primitives';
|
|
|
4
4
|
import { type ReactNode } from 'react';
|
|
5
5
|
import type { HubIntegrationsClient, HubIntegrationsIdentity } from './client';
|
|
6
6
|
import { type HubIntegrationCapabilities } from './projection';
|
|
7
|
+
import { type HubHostConnect } from './use-hub-integrations';
|
|
7
8
|
/** Host-owned access state for one account, such as whether this agent can use it. */
|
|
8
9
|
export interface HubAccountStatus {
|
|
9
10
|
label: string;
|
|
@@ -36,6 +37,12 @@ export interface HubIntegrationsPanelProps {
|
|
|
36
37
|
className?: string;
|
|
37
38
|
onRequestIntegration?: (prefill: string) => void;
|
|
38
39
|
onUnsupportedConnect?: (provider: HubProvider) => void;
|
|
40
|
+
/**
|
|
41
|
+
* App-owned connection for these providers, such as a number the app
|
|
42
|
+
* provisions itself. Their catalog rows stay visible and connectable, and
|
|
43
|
+
* choosing one calls `onConnect` instead of running a Hub flow.
|
|
44
|
+
*/
|
|
45
|
+
hostConnect?: HubHostConnect;
|
|
39
46
|
/** Host-owned context and actions; the host authorizes and confirms their effects. */
|
|
40
47
|
getConnectionContext?: (connection: HubConnection) => string | undefined;
|
|
41
48
|
getConnectionActions?: (connection: HubConnection) => readonly IntegrationDisplayAction[];
|
|
@@ -20,6 +20,6 @@ export declare function contextKey(identity: {
|
|
|
20
20
|
workspaceId: string;
|
|
21
21
|
}): string;
|
|
22
22
|
export declare function displayProvider(provider: HubProvider): IntegrationDisplayProvider;
|
|
23
|
-
export declare function catalogRows(providers: readonly HubProvider[], connections: readonly HubConnection[], selectedIds: Readonly<Record<string, string | null>>, can: HubIntegrationCapabilities, hasUnsupportedConnect?: boolean): IntegrationsProviderRow[];
|
|
23
|
+
export declare function catalogRows(providers: readonly HubProvider[], connections: readonly HubConnection[], selectedIds: Readonly<Record<string, string | null>>, can: HubIntegrationCapabilities, hasUnsupportedConnect?: boolean, hostConnectProviderIds?: readonly string[]): IntegrationsProviderRow[];
|
|
24
24
|
/** Stored overrides are shown; app-specific effective policy is never guessed. */
|
|
25
25
|
export declare function permissionDetails(tools: readonly HubTool[], policies: readonly HubPolicy[], connectionId: string, can: HubIntegrationCapabilities): IntegrationConnectionDetails;
|
|
@@ -21,6 +21,16 @@ export interface UseHubIntegrationsOptions {
|
|
|
21
21
|
callbackPath: string;
|
|
22
22
|
/** Optional host handler for custom/native signup. No Platform redirect is assumed. */
|
|
23
23
|
onUnsupportedConnect?: (provider: HubProvider) => void;
|
|
24
|
+
/**
|
|
25
|
+
* App-owned connection for these providers, such as a number the app
|
|
26
|
+
* provisions itself. Their catalog rows stay visible and connectable, and
|
|
27
|
+
* choosing one calls `onConnect` instead of running a Hub flow.
|
|
28
|
+
*/
|
|
29
|
+
hostConnect?: HubHostConnect;
|
|
30
|
+
}
|
|
31
|
+
export interface HubHostConnect {
|
|
32
|
+
providerIds: readonly string[];
|
|
33
|
+
onConnect: (provider: HubProvider) => void;
|
|
24
34
|
}
|
|
25
35
|
type WriteInput = {
|
|
26
36
|
kind: 'api-key';
|
|
@@ -60,7 +70,7 @@ export interface HubWriteReceipt {
|
|
|
60
70
|
message: string;
|
|
61
71
|
}
|
|
62
72
|
/** Identity-bound Hub settings controller; connection state is always server-read. */
|
|
63
|
-
export declare function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect }: UseHubIntegrationsOptions): {
|
|
73
|
+
export declare function useHubIntegrations({ identity, client, can, callbackPath, onUnsupportedConnect, hostConnect }: UseHubIntegrationsOptions): {
|
|
64
74
|
providers: import("../web-react/async").AsyncResourceState<HubProvider[]>;
|
|
65
75
|
connections: import("../web-react/async").AsyncResourceState<HubConnection[]>;
|
|
66
76
|
detail: import("../web-react/async").AsyncResourceState<{
|
|
@@ -33,16 +33,24 @@ export interface D1Reads {
|
|
|
33
33
|
/** The query running when the heap peaked: where a job holds what it read. */
|
|
34
34
|
peakSql: string;
|
|
35
35
|
}
|
|
36
|
+
export interface MeasureD1Options {
|
|
37
|
+
/** Sample the live heap at all. Default true. */
|
|
38
|
+
sampleHeap?: boolean;
|
|
39
|
+
/** Sample after every response at least this large. Default 64 KB. */
|
|
40
|
+
sampleAfterBytes?: number;
|
|
41
|
+
/** Also sample every this-many queries, so what a job keeps from small reads still shows. Default 50. */
|
|
42
|
+
sampleEvery?: number;
|
|
43
|
+
}
|
|
36
44
|
/**
|
|
37
45
|
* The D1 binding with every response measured (serialized bytes) and the live
|
|
38
|
-
* heap sampled after a collection
|
|
39
|
-
*
|
|
40
|
-
*
|
|
41
|
-
*
|
|
46
|
+
* heap sampled after a forced collection. A collection costs about 50 ms on a
|
|
47
|
+
* test heap and a job runs hundreds of small queries, so the heap is sampled
|
|
48
|
+
* after each large read and every 50th query (GTM's sweeps budget took 170 s
|
|
49
|
+
* sampling around every query). Works over Cloudflare D1 and the sqlite-backed
|
|
50
|
+
* D1 shims apps test with. A database engine that keeps its pages off the JS
|
|
51
|
+
* heap (node:sqlite, better-sqlite3) leaves heap growth to the job's own objects.
|
|
42
52
|
*/
|
|
43
|
-
export declare function measureD1<D extends object>(d1: D, reads?: D1Reads, options?: {
|
|
44
|
-
sampleHeap?: boolean;
|
|
45
|
-
}): {
|
|
53
|
+
export declare function measureD1<D extends object>(d1: D, reads?: D1Reads, options?: MeasureD1Options): {
|
|
46
54
|
d1: D;
|
|
47
55
|
reads: D1Reads;
|
|
48
56
|
};
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/launch-invariants/testing.ts","../src/launch-invariants/conformance.ts"],"sourcesContent":["/**\n * `/launch-invariants/testing` — the checks an app runs in its own test suite.\n *\n * Each check drives the app's real code through a small adapter and returns an\n * {@link InvariantVerdict}. {@link recordInvariant} fails the calling test with\n * the verdict's findings and, when `agent-app-invariants` runs the suite,\n * records the verdict so the conformance report can say which invariant\n * passed. The checks need no test runner: vitest, node:test and plain scripts\n * all work.\n *\n * Node-only (`node:v8`, `node:vm`, `node:fs`): import it from tests, never from\n * a Worker.\n */\nimport { appendFileSync } from 'node:fs'\nimport v8 from 'node:v8'\nimport vm from 'node:vm'\nimport type { AlertSink, TurnHealthAlert } from '../turn-health/sink.js'\nimport { describeVerdict, LAUNCH_BUDGETS, type InvariantVerdict } from './catalog.js'\nimport { LIMIT_RESOURCES, type LimitAlarms } from './limit-alarms.js'\nimport { isEdgeBlock, PASTED_CODE_SAMPLES } from './pasted-code.js'\n\nexport { describeVerdict } from './catalog.js'\n\n/** Set by `agent-app-invariants` to the file it reads verdicts from. */\nexport const INVARIANT_RESULTS_ENV = 'AGENT_APP_INVARIANTS_RESULTS'\n\nexport interface RecordInvariantOptions {\n /**\n * The app knows this check fails today: why, who owns the fix and the next\n * check. The failure is recorded (the report counts the invariant as not\n * holding) without failing the suite, so an app adopts the kit before every\n * invariant holds. Once the check passes, this fails the caller until the\n * marker is removed, so a fixed invariant cannot regress silently.\n */\n knownFailing?: string\n}\n\n/**\n * Record a verdict for the conformance report and fail the caller when it did\n * not pass. Returns the verdict on a pass.\n */\nexport function recordInvariant(verdict: InvariantVerdict, options: RecordInvariantOptions = {}): InvariantVerdict {\n const known = options.knownFailing?.trim()\n const recorded = known && !verdict.pass ? { ...verdict, knownFailing: known } : verdict\n const file = process.env[INVARIANT_RESULTS_ENV]\n if (file) appendFileSync(file, `${JSON.stringify({ ...recorded, at: new Date().toISOString() })}\\n`)\n if (known && verdict.pass) {\n throw new Error(`${describeVerdict(verdict)}\\n this invariant now holds; remove its knownFailing marker (\"${known}\") so it cannot regress silently`)\n }\n if (!verdict.pass && !known) throw new Error(describeVerdict(verdict))\n return recorded\n}\n\n/** Record several verdicts; fails after recording all of them. */\nexport function recordInvariants(verdicts: readonly InvariantVerdict[], options: RecordInvariantOptions = {}): InvariantVerdict[] {\n const failures: string[] = []\n for (const verdict of verdicts) {\n try {\n recordInvariant(verdict, options)\n } catch (error) {\n failures.push(error instanceof Error ? error.message : String(error))\n }\n }\n if (failures.length) throw new Error(failures.join('\\n'))\n return [...verdicts]\n}\n\n// ── heap ─────────────────────────────────────────────────────────────────────\n\nlet gc: (() => void) | undefined\n\n/** Run a full garbage collection, so a heap reading counts only live objects. */\nexport function forceGc(): void {\n if (!gc) {\n v8.setFlagsFromString('--expose_gc')\n gc = vm.runInNewContext('gc') as () => void\n }\n gc()\n}\n\n// ── measured D1 ──────────────────────────────────────────────────────────────\n\nconst MB = 1024 * 1024\n\n/** What a measured binding saw while one job ran. */\nexport interface D1Reads {\n queries: number\n maxQueryBytes: number\n /** The query that returned the most bytes. */\n largestSql: string\n peakHeapBytes: number\n /** The query running when the heap peaked: where a job holds what it read. */\n peakSql: string\n}\n\nfunction emptyReads(): D1Reads {\n return { queries: 0, maxQueryBytes: 0, largestSql: '', peakHeapBytes: 0, peakSql: '' }\n}\n\n/**\n * The D1 binding with every response measured (serialized bytes) and the live\n * heap sampled after a collection before and after every query. Works over\n * Cloudflare D1 and the sqlite-backed D1 shims apps test with. A database\n * engine that keeps its pages off the JS heap (node:sqlite, better-sqlite3)\n * leaves heap growth to the job's own objects.\n */\nexport function measureD1<D extends object>(d1: D, reads: D1Reads = emptyReads(), options: { sampleHeap?: boolean } = {}): { d1: D; reads: D1Reads } {\n const sampleHeap = options.sampleHeap ?? true\n const sample = (sql: string) => {\n if (!sampleHeap) return\n forceGc()\n const heap = process.memoryUsage().heapUsed\n if (heap > reads.peakHeapBytes) {\n reads.peakHeapBytes = heap\n reads.peakSql = sql\n }\n }\n const measure = (sql: string, result: unknown) => {\n reads.queries += 1\n const bytes = Buffer.byteLength(JSON.stringify(result) ?? '')\n if (bytes > reads.maxQueryBytes) {\n reads.maxQueryBytes = bytes\n reads.largestSql = sql\n }\n }\n const statement = (target: object, sql: string): object => new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object, sql)\n if (key === 'all' || key === 'raw' || key === 'first' || key === 'run') {\n return async (...args: unknown[]) => {\n sample(sql)\n const result: unknown = await value.apply(stmt, args)\n measure(sql, result)\n sample(sql)\n return result\n }\n }\n return value.bind(stmt)\n },\n })\n const unwrap = new WeakMap<object, object>()\n const proxy = new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') {\n return (sql: string) => {\n const stmt = (value as (sql: string) => object).call(binding, sql)\n const wrapped = statement(stmt, sql.replace(/\\s+/g, ' ').trim().slice(0, 200))\n unwrap.set(wrapped, stmt)\n return wrapped\n }\n }\n if (key === 'batch') {\n return async (statements: object[]) => {\n sample('batch')\n const result: unknown = await (value as (s: object[]) => Promise<unknown>).call(binding, statements.map((stmt) => unwrap.get(stmt) ?? stmt))\n measure('batch', result)\n sample('batch')\n return result\n }\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n return { d1: proxy, reads }\n}\n\n/** One scheduled job (or report route) as the budget check runs it. */\nexport interface BudgetedJob {\n name: string\n run: () => Promise<unknown>\n /** False for a job that reads nothing from D1 (it then passes bounded reads vacuously). Default true. */\n readsD1?: boolean\n}\n\nexport interface JobMeasurement {\n name: string\n reads: D1Reads\n heapGrowthBytes: number\n error?: string\n}\n\nexport interface ScheduledJobBudgetOptions {\n /** The app's D1 over its day-sized fixture. */\n d1: object\n /** Point the app's database accessor at the measured binding (`setD1`, `setDatabase(drizzle(...))`). */\n install: (measured: object) => void\n jobs: readonly BudgetedJob[]\n /** Every job the app schedules, by the names {@link jobs} uses. Each must be measured. */\n scheduled: readonly string[]\n maxQueryBytes?: number\n maxHeapGrowthBytes?: number\n /** Silence the jobs' own logging while they run. Default true. */\n quiet?: boolean\n}\n\n/** Run one job against a measured binding. */\nexport async function measureJob(job: BudgetedJob, d1: object, install: (measured: object) => void, quiet = true): Promise<JobMeasurement> {\n const { d1: measured, reads } = measureD1(d1)\n install(measured)\n forceGc()\n const baseline = process.memoryUsage().heapUsed\n reads.peakHeapBytes = baseline\n const restore = quiet ? silenceConsole() : () => {}\n let error: string | undefined\n try {\n await job.run()\n } catch (caught) {\n error = caught instanceof Error ? caught.message : String(caught)\n } finally {\n restore()\n }\n forceGc()\n const after = process.memoryUsage().heapUsed\n if (after > reads.peakHeapBytes) {\n reads.peakHeapBytes = after\n reads.peakSql = reads.peakSql ? `${reads.peakSql} (still held when the job returned)` : '(after the job returned)'\n }\n return { name: job.name, reads, heapGrowthBytes: reads.peakHeapBytes - baseline, ...(error ? { error } : {}) }\n}\n\nfunction silenceConsole(): () => void {\n const saved = { log: console.log, info: console.info, warn: console.warn, error: console.error }\n console.log = console.info = console.warn = console.error = () => {}\n return () => Object.assign(console, saved)\n}\n\n/**\n * Bounded reads and the memory budget for every scheduled job, on the app's\n * day-sized fixture. Returns a bounded-reads and a memory-budget verdict per\n * job, and a coverage verdict naming any scheduled job that was not run.\n */\nexport async function checkScheduledJobBudgets(options: ScheduledJobBudgetOptions): Promise<InvariantVerdict[]> {\n const maxQueryBytes = options.maxQueryBytes ?? LAUNCH_BUDGETS.queryBytes\n const maxHeap = options.maxHeapGrowthBytes ?? LAUNCH_BUDGETS.heapGrowthBytes\n const verdicts: InvariantVerdict[] = []\n const measured = new Set<string>()\n for (const job of options.jobs) {\n const m = await measureJob(job, options.d1, options.install, options.quiet ?? true)\n measured.add(job.name)\n const failed = m.error ? [`the job threw on the fixture: ${m.error}`] : []\n const readFindings = [...failed]\n if ((job.readsD1 ?? true) && m.reads.queries === 0) readFindings.push('made no D1 query on the fixture; the fixture does not reach it, or it reads through another binding')\n if (m.reads.maxQueryBytes > maxQueryBytes) {\n readFindings.push(`one query returned ${(m.reads.maxQueryBytes / MB).toFixed(1)} MB (the most is ${(maxQueryBytes / MB).toFixed(0)} MB): ${m.reads.largestSql}`)\n }\n verdicts.push({\n invariant: 'bounded-reads',\n subject: job.name,\n pass: readFindings.length === 0,\n details: readFindings.length ? readFindings : [`${m.reads.queries} queries, largest ${(m.reads.maxQueryBytes / MB).toFixed(2)} MB`],\n data: { queries: m.reads.queries, maxQueryBytes: m.reads.maxQueryBytes, largestSql: m.reads.largestSql },\n })\n const heapFindings = [...failed]\n if (m.heapGrowthBytes > maxHeap) {\n heapFindings.push(`the live heap grew ${(m.heapGrowthBytes / MB).toFixed(1)} MB (the most is ${(maxHeap / MB).toFixed(0)} MB), at its peak around: ${m.reads.peakSql}`)\n }\n verdicts.push({\n invariant: 'memory-budget',\n subject: job.name,\n pass: heapFindings.length === 0,\n details: heapFindings.length ? heapFindings : [`heap grew ${(m.heapGrowthBytes / MB).toFixed(1)} MB`],\n data: { heapGrowthBytes: m.heapGrowthBytes, peakSql: m.reads.peakSql },\n })\n }\n const missing = options.scheduled.filter((name) => !measured.has(name))\n verdicts.push({\n invariant: 'memory-budget',\n subject: 'coverage',\n pass: missing.length === 0 && options.scheduled.length > 0,\n details: missing.length\n ? missing.map((name) => `${name} is scheduled but not run on the fixture`)\n : options.scheduled.length === 0\n ? ['no scheduled jobs were named; pass every job the app schedules']\n : [`all ${options.scheduled.length} scheduled jobs ran on the fixture`],\n data: { scheduled: [...options.scheduled], measured: [...measured] },\n })\n return verdicts\n}\n\n// ── a D1 that stalls ─────────────────────────────────────────────────────────\n\nexport type StallMode = 'ok' | 'error' | 'hang'\n\n/** The D1 binding with a switch that makes every query fail or never answer, as an overloaded D1 did. */\nexport function stallingD1<D extends object>(d1: D): { d1: D; stall(mode: StallMode): void; readonly mode: StallMode } {\n let mode: StallMode = 'ok'\n const fail = (): Promise<never> => mode === 'hang'\n ? new Promise<never>(() => {})\n : Promise.reject(new Error('D1_ERROR: Network connection lost.'))\n const unwrapped = new WeakMap<object, object>()\n const statement = (target: object): object => {\n const wrapped = new Proxy(target, {\n get(stmt, key) {\n const value = Reflect.get(stmt, key) as unknown\n if (typeof value !== 'function') return value\n if (key === 'bind') return (...params: unknown[]) => statement(value.apply(stmt, params) as object)\n if (key === 'all' || key === 'raw' || key === 'first' || key === 'run') {\n return (...args: unknown[]) => (mode === 'ok' ? value.apply(stmt, args) : fail())\n }\n return value.bind(stmt)\n },\n })\n unwrapped.set(wrapped, target)\n return wrapped\n }\n const proxy = new Proxy(d1, {\n get(binding, key) {\n const value = Reflect.get(binding, key) as unknown\n if (key === 'prepare') return (sql: string) => statement((value as (sql: string) => object).call(binding, sql))\n if (key === 'batch') {\n return (statements: object[]) => (mode === 'ok'\n ? (value as (s: object[]) => unknown).call(binding, statements.map((stmt) => unwrapped.get(stmt) ?? stmt))\n : fail())\n }\n return typeof value === 'function' ? value.bind(binding) : value\n },\n })\n return {\n d1: proxy,\n stall(next) {\n mode = next\n },\n get mode() {\n return mode\n },\n }\n}\n\n/** Move `Date.now` forward for the duration of a check; returns the restore. */\nfunction shiftableClock(): { advance(ms: number): void; restore(): void } {\n const real = Date.now\n let offset = 0\n Date.now = () => real() + offset\n return {\n advance(ms) {\n offset += ms\n },\n restore() {\n Date.now = real\n },\n }\n}\n\n// ── auth survives a D1 stall ─────────────────────────────────────────────────\n\nexport interface AuthStallOptions {\n /** A label for the lookup: \"session\", \"API key\". */\n subject: string\n /** Three distinct valid credentials the app's store accepts. */\n credentials: { cached: string; revoked: string; aged: string }\n /** The app's real lookup: truthy when the credential is accepted. A throw or a falsy value is a refusal. */\n verify: (credential: string) => Promise<unknown>\n /** The app's real revoke path (revoke the key, sign the session out). */\n revoke: (credential: string) => Promise<void>\n /** Switch the D1 the lookup reads. */\n stall: (mode: StallMode) => void\n /** The keys the app's auth caches hold. */\n cacheKeys: () => string[]\n /** Include a stall that never answers (costs one lookup deadline, 2.5 s). Default true. */\n hang?: boolean\n}\n\n/**\n * A verified credential keeps working while D1 errors or stalls; it is refused\n * once revoked, and once its last verification is more than 60 s old; and the\n * cache holds SHA-256 keys, not secrets. Uses the app's real lookup, revoke\n * path and D1, with `Date.now` moved forward to age the cache.\n */\nexport async function checkAuthSurvivesStall(options: AuthStallOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n const accepted = async (credential: string): Promise<boolean> => {\n try {\n return Boolean(await options.verify(credential))\n } catch {\n return false\n }\n }\n const { cached, revoked, aged } = options.credentials\n const clock = shiftableClock()\n try {\n options.stall('ok')\n for (const credential of [cached, revoked, aged]) {\n if (!(await accepted(credential))) findings.push(`a valid credential was refused while D1 was healthy (${options.subject})`)\n }\n for (const key of options.cacheKeys()) {\n if (!/^[0-9a-f]{64}$/.test(key) || [cached, revoked, aged].some((credential) => key.includes(credential))) {\n findings.push(`the auth cache holds a key that is not a SHA-256 digest: ${key.slice(0, 12)}…`)\n }\n }\n await options.revoke(revoked)\n if (await accepted(revoked)) findings.push('a revoked credential was accepted while D1 was healthy')\n\n options.stall('error')\n if (!(await accepted(cached))) findings.push('a credential verified moments before was refused while D1 errored')\n if (await accepted(revoked)) findings.push('a revoked credential was accepted from the cache while D1 errored')\n if (options.hang ?? true) {\n options.stall('hang')\n if (!(await accepted(cached))) findings.push('a credential verified moments before was refused while D1 did not answer')\n }\n\n clock.advance(LAUNCH_BUDGETS.authCacheTtlMs + 1_000)\n options.stall('error')\n if (await accepted(aged)) findings.push(`a credential last verified more than ${LAUNCH_BUDGETS.authCacheTtlMs / 1000} s ago was accepted from the cache while D1 errored`)\n } finally {\n options.stall('ok')\n clock.restore()\n }\n return {\n invariant: 'auth-survives-d1-stall',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [\n 'served while D1 errored and while it stalled; refused after revoke and after the 60 s cache window; keys are SHA-256',\n ],\n }\n}\n\n// ── authorization before any stream ──────────────────────────────────────────\n\nexport interface AuthorizeBeforeStreamOptions {\n subject: string\n /** The app's real route handler, as its router mounts it. */\n handle: (request: Request) => Promise<Response>\n /** Requests the route must refuse: no session, another workspace's thread, a revoked key. */\n refused: ReadonlyArray<{ name: string; request: () => Request; status?: readonly number[] }>\n /** Product state the route touched (rows written, producers started); empty after every refusal. */\n touched?: () => readonly string[]\n}\n\nconst STREAM_TYPES = /event-stream|ndjson|x-turn-progress/i\n\n/** Each refused request gets a plain 4xx, opens no stream and touches nothing. */\nexport async function checkAuthorizeBeforeStream(options: AuthorizeBeforeStreamOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n for (const probe of options.refused) {\n const before = options.touched?.().length ?? 0\n const response = await options.handle(probe.request())\n const allowed = probe.status ?? [401, 403, 404]\n if (!allowed.includes(response.status)) findings.push(`${probe.name}: answered ${response.status}, expected ${allowed.join(' or ')}`)\n const type = response.headers.get('content-type') ?? ''\n if (STREAM_TYPES.test(type)) findings.push(`${probe.name}: opened a ${type} stream before refusing`)\n for (const [name] of response.headers) {\n if (/turn-progress|x-turn-id/i.test(name)) findings.push(`${probe.name}: refusal carries turn header ${name}`)\n }\n await response.body?.cancel().catch(() => undefined)\n const after = options.touched?.() ?? []\n if (after.length > before) findings.push(`${probe.name}: touched ${after.slice(before).join(', ')} before refusing`)\n }\n return {\n invariant: 'authorize-before-stream',\n subject: options.subject,\n pass: findings.length === 0 && options.refused.length > 0,\n details: findings.length ? findings : options.refused.length\n ? [`${options.refused.length} refused requests answered plainly with nothing touched`]\n : ['no refused requests were probed'],\n }\n}\n\n// ── pasted code reaches the chat ─────────────────────────────────────────────\n\nexport interface ChatAcceptsCodeOptions {\n subject: string\n /** The app's real chat route handler, as its router mounts it. */\n handle: (request: Request) => Promise<Response>\n /** An authenticated chat request carrying `text` as the message. */\n request: (text: string) => Request\n /** Statuses the route answers an accepted message with. Default any 2xx. */\n accepted?: (status: number) => boolean\n samples?: readonly { name: string; text: string }[]\n}\n\n/** Each pasted-code sample gets the route's normal response, never a refusal or an edge block. Cancels any stream it opens. */\nexport async function checkChatAcceptsCode(options: ChatAcceptsCodeOptions): Promise<InvariantVerdict> {\n const accepted = options.accepted ?? ((status: number) => status >= 200 && status < 300)\n const samples = options.samples ?? PASTED_CODE_SAMPLES\n const findings: string[] = []\n for (const sample of samples) {\n const response = await options.handle(options.request(sample.text))\n if (await isEdgeBlock(response)) findings.push(`${sample.name}: an edge rule blocked it (${response.status})`)\n else if (!accepted(response.status)) {\n const body = (await response.clone().text().catch(() => '')).slice(0, 160)\n findings.push(`${sample.name}: answered ${response.status}${body ? `: ${body}` : ''}`)\n }\n await response.body?.cancel().catch(() => undefined)\n }\n return {\n invariant: 'pasted-code-reaches-chat',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [`${samples.length} pasted-code messages reached the chat and got its normal response`],\n }\n}\n\n// ── coalesced turn events ────────────────────────────────────────────────────\n\n/** One event of the recorded long turn and the turn-relative time it arrived. */\nexport interface TimedTurnEvent {\n atMs: number\n event: Record<string, unknown>\n}\n\n/**\n * The long turn GTM recorded on 2026-10-10, reproduced in shape: a reasoning\n * model streaming three events per token (the harness's raw part update, a\n * model-processing heartbeat and the delta), with tool calls between runs of\n * reasoning and text. 59,659 events over about ten minutes, as that turn wrote\n * them before coalescing.\n */\nexport function recordedLongTurn(options: { tokens?: number; toolCalls?: number; tokenMs?: number } = {}): TimedTurnEvent[] {\n const tokens = options.tokens ?? 19_866\n const toolCalls = options.toolCalls ?? 30\n const tokenMs = options.tokenMs ?? 30\n const events: TimedTurnEvent[] = [{ atMs: 0, event: { type: 'turn', turnId: 'recorded-long-turn' } }]\n const toolEvery = Math.max(1, Math.floor(tokens / (toolCalls + 1)))\n let tool = 0\n let part = 0\n for (let index = 0; index < tokens; index += 1) {\n const atMs = (index + 1) * tokenMs\n if (index > 0 && index % toolEvery === 0 && tool < toolCalls) {\n tool += 1\n part += 1\n events.push({ atMs, event: { type: 'tool_call', id: `call_${tool}`, name: 'bash', input: { command: 'ls' } } })\n events.push({ atMs: atMs + 1, event: { type: 'tool_result', id: `call_${tool}`, output: 'ok' } })\n }\n const kind = part % 2 === 0 ? 'reasoning' : 'text'\n const partId = `prt_${part}`\n events.push({ atMs, event: { type: 'raw', data: { type: 'raw', backend: 'opencode', event: { type: kind, timestamp: atMs, part: { id: partId, type: kind, metadata: { at: atMs } } } } } })\n events.push({ atMs, event: { type: 'model-processing', data: { elapsedMs: atMs } } })\n events.push({ atMs, event: { type: kind, text: `t${index} ` } })\n }\n return events\n}\n\nexport interface CoalescedTurnOptions {\n subject: string\n /**\n * Start persisting one turn through the app's real turn persistence (its turn\n * store and buffer, as its chat route builds them). `detach` hands the turn\n * to a durable owner the way the route's completion handoff does; omit it when\n * the app has no detached lane.\n */\n open: (turnId: string) => Promise<{\n onEvent(event: unknown): Promise<void>\n detach?(): Promise<void>\n done(): Promise<void>\n }>\n /** Stored events for the turn. */\n count: (turnId: string) => Promise<number>\n maxEvents?: number\n fixture?: readonly TimedTurnEvent[]\n}\n\n/** The recorded long turn stores at most 5,000 events, attached and after a handoff. */\nexport async function checkCoalescedTurn(options: CoalescedTurnOptions): Promise<InvariantVerdict> {\n const maxEvents = options.maxEvents ?? LAUNCH_BUDGETS.turnEvents\n const fixture = options.fixture ?? recordedLongTurn()\n const findings: string[] = []\n const stored: Record<string, number> = {}\n const real = Date.now\n for (const lane of ['attached', 'detached'] as const) {\n const turnId = `invariant-long-turn-${lane}`\n const start = real()\n let clock = start\n Date.now = () => clock\n try {\n const tap = await options.open(turnId)\n if (lane === 'detached' && !tap.detach) continue\n for (const [index, item] of fixture.entries()) {\n clock = start + item.atMs\n await tap.onEvent(item.event)\n if (lane === 'detached' && index === 0) await tap.detach!()\n }\n clock = start + (fixture.at(-1)?.atMs ?? 0) + 1\n await tap.done()\n stored[lane] = await options.count(turnId)\n } finally {\n Date.now = real\n }\n if (stored[lane] === 0) findings.push(`${lane}: the turn stored no events; the check did not reach the app's turn store`)\n if (stored[lane]! > maxEvents) findings.push(`${lane}: the recorded long turn (${fixture.length.toLocaleString('en-US')} events) stored ${stored[lane]!.toLocaleString('en-US')}; the most is ${maxEvents.toLocaleString('en-US')}`)\n }\n return {\n invariant: 'coalesced-events',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : Object.entries(stored).map(([lane, count]) => `${lane}: ${fixture.length.toLocaleString('en-US')} events stored as ${count.toLocaleString('en-US')}`),\n data: { fixtureEvents: fixture.length, stored },\n }\n}\n\n// ── limit alarms ─────────────────────────────────────────────────────────────\n\n/** Hard platform limits a declared budget may not exceed. */\nexport const PLATFORM_LIMITS = {\n /** A Worker isolate's memory. */\n 'worker-memory': 128 * MB,\n /** Platform snapshots per sandbox; the cap GTM hit on 2026-10-10. */\n 'snapshot-count': 25,\n /** Requests per minute per operator key. */\n 'key-rate': 60,\n} as const\n\nexport interface LimitAlarmCheckOptions {\n subject: string\n /** Build the app's real limit alarms (its budgets and wiring) over a capturing sink. */\n create: (sink: AlertSink) => LimitAlarms | Promise<LimitAlarms>\n}\n\n/** Every resource alarms at 80% and not below, escalates at the limit, and no budget exceeds the platform's. */\nexport async function checkLimitAlarms(options: LimitAlarmCheckOptions): Promise<InvariantVerdict> {\n const findings: string[] = []\n for (const resource of LIMIT_RESOURCES) {\n const delivered: TurnHealthAlert[] = []\n const alarms = await options.create({ deliver: async (alert) => { delivered.push(alert) } })\n const limit = alarms.budgets[resource]\n const platform = (PLATFORM_LIMITS as Partial<Record<string, number>>)[resource]\n if (platform !== undefined && limit > platform) findings.push(`${resource}: the declared limit ${limit} is above the platform's ${platform}`)\n await alarms.observe(resource, limit * 0.79)\n if (delivered.length) findings.push(`${resource}: alarmed at 79% of its limit`)\n await alarms.observe(resource, limit * LAUNCH_BUDGETS.alarmRatio)\n if (delivered.length !== 1 || delivered[0]?.severity !== 'warning') findings.push(`${resource}: did not warn at 80% of its limit`)\n await alarms.observe(resource, limit)\n if (delivered.length !== 2 || delivered[1]?.severity !== 'critical') findings.push(`${resource}: did not raise a critical alert at its limit`)\n }\n return {\n invariant: 'limit-alarms',\n subject: options.subject,\n pass: findings.length === 0,\n details: findings.length ? findings : [`${LIMIT_RESOURCES.join(', ')} warn at 80% and page at the limit`],\n }\n}\n\nexport {\n buildConformanceReport,\n formatConformanceReport,\n readDeploymentFacts,\n readVerdicts,\n type ConformanceReport,\n type DeploymentFacts,\n type InvariantReport,\n type InvariantStatus,\n type LaunchInvariantsConfig,\n} from './conformance.js'\n","/**\n * The conformance report: which launch invariants an app holds.\n *\n * `agent-app-invariants` runs the app's invariant tests with\n * `AGENT_APP_INVARIANTS_RESULTS` set, reads the verdicts they recorded, and\n * checks what it can see without the app's code: the crons each wrangler\n * environment configures, and whether the app has a D1 binding at all. An\n * invariant passes when at least one verdict was recorded for it and every\n * recorded verdict passed. Not applicable is accepted only where the\n * deployment shows it: no configured crons, or no D1 binding.\n */\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport { LAUNCH_INVARIANTS, type InvariantVerdict, type LaunchInvariantId } from './catalog.js'\nimport { parseWranglerCrons } from './schedule.js'\n\n/** `launch-invariants.config.mjs` (or `.json`) at the app root. */\nexport interface LaunchInvariantsConfig {\n /** The app's name in the report. */\n product: string\n /** The command that runs the app's invariant tests, e.g. `pnpm exec vitest run tests/launch-invariants.test.ts`. */\n test: string\n /** Wrangler configs, relative to the app root. Default: the first of wrangler.toml, wrangler.jsonc, wrangler.json. */\n wrangler?: readonly string[]\n /** Invariants the deployment shows do not apply, with the reason. */\n notApplicable?: Partial<Record<LaunchInvariantId, string>>\n}\n\n/** What the deployment declares, read from its wrangler configs. */\nexport interface DeploymentFacts {\n wranglerFiles: string[]\n configuredCrons: string[]\n hasD1: boolean\n}\n\nexport type InvariantStatus = 'pass' | 'fail' | 'known-fail' | 'not-applicable'\n\nexport interface InvariantReport {\n id: LaunchInvariantId\n title: string\n status: InvariantStatus\n /** Why it failed or does not apply; on a pass, what was proven. */\n lines: string[]\n verdicts: number\n}\n\nexport interface ConformanceReport {\n product: string\n pass: boolean\n passed: number\n total: number\n testExitCode: number | null\n /** Invariants failing with a known-failing marker: not holding, but not failing the run. */\n knownFailing: number\n invariants: InvariantReport[]\n facts: DeploymentFacts\n}\n\n/** Read the crons and D1 bindings the app's wrangler configs declare. */\nexport function readDeploymentFacts(appDir: string, files?: readonly string[]): DeploymentFacts {\n const candidates = files ?? ['wrangler.toml', 'wrangler.jsonc', 'wrangler.json'].filter((file) => existsSync(join(appDir, file))).slice(0, 1)\n const crons = new Set<string>()\n let hasD1 = false\n for (const file of candidates) {\n const source = readFileSync(join(appDir, file), 'utf8')\n const json = /\\.jsonc?$/.test(file)\n const parsed = parseWranglerCrons(source, json ? 'json' : 'toml')\n for (const cron of [...parsed.top, ...Object.values(parsed.envs).flat()]) crons.add(cron)\n if (json ? /\"d1_databases\"\\s*:\\s*\\[\\s*\\{/.test(source) : /^\\s*\\[\\[(?:env\\.[^.\\]]+\\.)?d1_databases\\]\\]/m.test(source)) hasD1 = true\n }\n return { wranglerFiles: [...candidates], configuredCrons: [...crons], hasD1 }\n}\n\nconst NOT_APPLICABLE_WHEN: Partial<Record<LaunchInvariantId, { holds: (facts: DeploymentFacts) => boolean; condition: string }>> = {\n 'isolated-jobs': { holds: (facts) => facts.configuredCrons.length === 0, condition: 'no configured crons' },\n 'memory-budget': { holds: (facts) => facts.configuredCrons.length === 0, condition: 'no configured crons' },\n 'bounded-reads': { holds: (facts) => !facts.hasD1, condition: 'no D1 binding' },\n 'auth-survives-d1-stall': { holds: (facts) => !facts.hasD1, condition: 'no D1 binding' },\n}\n\n/** Parse the results file the invariant tests appended to. */\nexport function readVerdicts(source: string): InvariantVerdict[] {\n return source.split('\\n').filter((line) => line.trim()).flatMap((line) => {\n try {\n return [JSON.parse(line) as InvariantVerdict]\n } catch {\n return []\n }\n })\n}\n\n/** Judge each invariant from the recorded verdicts and the deployment facts. */\nexport function buildConformanceReport(input: {\n config: LaunchInvariantsConfig\n facts: DeploymentFacts\n verdicts: readonly InvariantVerdict[]\n testExitCode: number | null\n}): ConformanceReport {\n const { config, facts } = input\n const invariants = LAUNCH_INVARIANTS.map((invariant): InvariantReport => {\n const verdicts = input.verdicts.filter((verdict) => verdict.invariant === invariant.id)\n const reason = config.notApplicable?.[invariant.id]\n if (reason !== undefined) {\n const rule = NOT_APPLICABLE_WHEN[invariant.id]\n if (rule?.holds(facts)) return { id: invariant.id, title: invariant.title, status: 'not-applicable', lines: [`${reason} (verified: ${rule.condition})`], verdicts: verdicts.length }\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'fail',\n lines: [rule\n ? `declared not applicable (\"${reason}\"), but the deployment does not show ${rule.condition}`\n : `declared not applicable (\"${reason}\"), but this invariant applies to every agent app`],\n verdicts: verdicts.length,\n }\n }\n if (verdicts.length === 0) {\n return { id: invariant.id, title: invariant.title, status: 'fail', lines: [`no check recorded a verdict; ${invariant.rule}`], verdicts: 0 }\n }\n const failed = verdicts.filter((verdict) => !verdict.pass)\n const unknown = failed.filter((verdict) => !verdict.knownFailing)\n if (failed.length > 0 && unknown.length === 0) {\n const reasons = [...new Set(failed.map((verdict) => verdict.knownFailing!))]\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'known-fail',\n lines: [...reasons.map((reason) => `known failing: ${reason}`), ...failed.flatMap((verdict) => verdict.details.map((detail) => `${verdict.subject}: ${detail}`))],\n verdicts: verdicts.length,\n }\n }\n const lines = failed.length\n ? failed.flatMap((verdict) => verdict.details.map((detail) => `${verdict.subject}: ${detail}`))\n : verdicts.map((verdict) => `${verdict.subject}: ${verdict.details[0] ?? 'passed'}`)\n if (invariant.id === 'isolated-jobs' && failed.length === 0) {\n const checked = new Set(verdicts.flatMap((verdict) => (verdict.data?.configuredCrons as string[] | undefined) ?? []))\n const unchecked = facts.configuredCrons.filter((cron) => !checked.has(cron))\n if (unchecked.length) {\n return {\n id: invariant.id,\n title: invariant.title,\n status: 'fail',\n lines: [`the check did not read every configured cron: ${unchecked.map((cron) => `\"${cron}\"`).join(', ')} (from ${facts.wranglerFiles.join(', ')})`],\n verdicts: verdicts.length,\n }\n }\n }\n return { id: invariant.id, title: invariant.title, status: failed.length ? 'fail' : 'pass', lines, verdicts: verdicts.length }\n })\n const passed = invariants.filter((invariant) => invariant.status === 'pass' || invariant.status === 'not-applicable').length\n const knownFailing = invariants.filter((invariant) => invariant.status === 'known-fail').length\n return {\n product: config.product,\n pass: passed + knownFailing === invariants.length && input.testExitCode === 0,\n passed,\n total: invariants.length,\n testExitCode: input.testExitCode,\n knownFailing,\n invariants,\n facts,\n }\n}\n\n/** The report as the CLI prints it. */\nexport function formatConformanceReport(report: ConformanceReport): string {\n const mark: Record<InvariantStatus, string> = { pass: 'PASS', fail: 'FAIL', 'known-fail': 'KNOWN', 'not-applicable': 'N/A ' }\n const lines = [`launch invariants — ${report.product}: ${report.passed} of ${report.total} hold${report.knownFailing ? `, ${report.knownFailing} known failing` : ''}`]\n for (const invariant of report.invariants) {\n lines.push(` ${mark[invariant.status]} ${invariant.id} — ${invariant.title}`)\n const shown = invariant.status === 'fail' || invariant.status === 'known-fail' ? invariant.lines : invariant.lines.slice(0, 3)\n for (const line of shown) lines.push(` ${line}`)\n if (invariant.status !== 'fail' && invariant.lines.length > shown.length) lines.push(` … ${invariant.lines.length - shown.length} more`)\n }\n if (report.testExitCode !== 0) lines.push(` the invariant test command exited ${report.testExitCode ?? 'by signal'}`)\n lines.push(report.passed === report.total && report.pass\n ? 'RESULT: launch-grade'\n : report.pass ? `RESULT: not launch-grade yet; ${report.knownFailing} known failing, no regressions` : 'RESULT: not launch-grade')\n return lines.join('\\n')\n}\n"],"mappings":";;;;;;;;;;;AAaA,SAAS,sBAAsB;AAC/B,OAAO,QAAQ;AACf,OAAO,QAAQ;;;ACJf,SAAS,YAAY,oBAAoB;AACzC,SAAS,YAAY;AA+Cd,SAAS,oBAAoB,QAAgB,OAA4C;AAC9F,QAAM,aAAa,SAAS,CAAC,iBAAiB,kBAAkB,eAAe,EAAE,OAAO,CAAC,SAAS,WAAW,KAAK,QAAQ,IAAI,CAAC,CAAC,EAAE,MAAM,GAAG,CAAC;AAC5I,QAAM,QAAQ,oBAAI,IAAY;AAC9B,MAAI,QAAQ;AACZ,aAAW,QAAQ,YAAY;AAC7B,UAAM,SAAS,aAAa,KAAK,QAAQ,IAAI,GAAG,MAAM;AACtD,UAAM,OAAO,YAAY,KAAK,IAAI;AAClC,UAAM,SAAS,mBAAmB,QAAQ,OAAO,SAAS,MAAM;AAChE,eAAW,QAAQ,CAAC,GAAG,OAAO,KAAK,GAAG,OAAO,OAAO,OAAO,IAAI,EAAE,KAAK,CAAC,EAAG,OAAM,IAAI,IAAI;AACxF,QAAI,OAAO,+BAA+B,KAAK,MAAM,IAAI,+CAA+C,KAAK,MAAM,EAAG,SAAQ;AAAA,EAChI;AACA,SAAO,EAAE,eAAe,CAAC,GAAG,UAAU,GAAG,iBAAiB,CAAC,GAAG,KAAK,GAAG,MAAM;AAC9E;AAEA,IAAM,sBAA6H;AAAA,EACjI,iBAAiB,EAAE,OAAO,CAAC,UAAU,MAAM,gBAAgB,WAAW,GAAG,WAAW,sBAAsB;AAAA,EAC1G,iBAAiB,EAAE,OAAO,CAAC,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