@tangle-network/agent-app 0.44.55 → 0.44.56

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.
@@ -2,7 +2,7 @@ import { C as ChatMessagePart } from '../parts-F8W3-iry.js';
2
2
  export { a as ChatAttachmentPart, b as ChatFilePart, c as ChatImagePart, d as ChatInteractionPart, e as ChatMentionPart, f as ChatNoticePart, g as ChatPartTime, h as ChatPlanPart, i as ChatReasoningPart, j as ChatStepFinishPart, k as ChatStepStartPart, l as ChatSubtaskPart, m as ChatTextPart, n as ChatToolPart, o as ChatToolState, p as ChatToolStatus, q as ChatUsageTokens, r as ChatWorkProductPart, D as DEFAULT_ATTACHMENT_PROMPT_HEADER, S as StorableHarnessPartKind, s as attachmentInputToPart, t as attachmentKindForMime, u as attachmentPartsFromMessageParts, v as buildAttachmentPromptBlock, w as historyContentWithAttachments, x as isChatAttachmentPart, y as isChatInteractionPart, z as isChatMentionPart, A as isChatPlanPart, B as isChatStepFinishPart, E as isChatTextPart, F as isChatToolPart, G as isChatWorkProductPart, H as mentionInputToPart, I as mentionPartsFromMessageParts, J as toChatMessageParts } from '../parts-F8W3-iry.js';
3
3
  import * as drizzle_orm from 'drizzle-orm';
4
4
  import * as drizzle_orm_sqlite_core from 'drizzle-orm/sqlite-core';
5
- import { SQLiteColumnBuilderBase, AnySQLiteTable, AnySQLiteColumn, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
5
+ import { AnySQLiteColumn, SQLiteColumnBuilderBase, AnySQLiteTable, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core';
6
6
  import { SqliteBatchDatabase } from '../store/index.js';
7
7
  export { a as ChatAttachmentKind, C as ChatMentionKind } from '../wire-DOZ-O6hD.js';
8
8
  export { a as attachmentPartKey } from '../stream-normalizer-CnPnMaTp.js';
@@ -52,7 +52,28 @@ interface CreateChatTablesOptions<TThreadExtras extends Record<string, SQLiteCol
52
52
  /** Product columns merged into the message table — e.g. legal's
53
53
  * `vault_files`. */
54
54
  messageExtraColumns?: TMessageExtras;
55
+ /**
56
+ * Product indexes appended to the thread table's own, given the built
57
+ * columns (extras included) so a product can index what it added.
58
+ *
59
+ * Names are used VERBATIM — `tablePrefix` is not applied — because these
60
+ * have to byte-match indexes the product's migrations already created.
61
+ *
62
+ * Without this a product with one extra index cannot adopt the factory at
63
+ * all: it keeps a hand-rolled duplicate of the same physical table, and the
64
+ * two drift on the next factory change.
65
+ */
66
+ threadExtraIndexes?: ChatExtraIndexes;
67
+ /** Product indexes appended to the message table's own. Same rules as
68
+ * `threadExtraIndexes`. */
69
+ messageExtraIndexes?: ChatExtraIndexes;
55
70
  }
71
+ /**
72
+ * Builds product indexes from a table's columns. Returns drizzle's
73
+ * `index(...)`/`uniqueIndex(...)` results; the column map is passed through
74
+ * untyped because its shape depends on the product's own extras.
75
+ */
76
+ type ChatExtraIndexes = (columns: Record<string, AnySQLiteColumn>) => unknown[];
56
77
  /** Build chat-related SQLite tables with customizable thread and message columns */
57
78
  declare function createChatTables<TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {}, TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {}>(options?: CreateChatTablesOptions<TThreadExtras, TMessageExtras>): {
58
79
  threads: drizzle_orm_sqlite_core.SQLiteTableWithColumns<{
@@ -275,4 +296,4 @@ interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {
275
296
  /** Create a chat store managing threads and messages based on the provided database and tables */
276
297
  declare function createChatStore<TTables extends ChatTables>(db: ChatDatabase, tables: TTables): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']>;
277
298
 
278
- export { type AppendMessageInput, BULK_DELETE_MAX_THREADS, type BulkDeleteThreadsInput, type ChatDatabase, ChatMessagePart, type ChatMessageRow, type ChatParentTable, type ChatStore, ChatStoreInputError, type ChatTables, type ChatThreadRow, type CreateChatTablesOptions, type CreateThreadInput, type ListMessagesOptions, type ListThreadsInput, type ListThreadsResult, type NewChatMessageRow, type NewChatThreadRow, type UpdateMessageInput, type WorkspaceAccessCheck, createChatStore, createChatTables, threadTitleFromMessage };
299
+ export { type AppendMessageInput, BULK_DELETE_MAX_THREADS, type BulkDeleteThreadsInput, type ChatDatabase, type ChatExtraIndexes, ChatMessagePart, type ChatMessageRow, type ChatParentTable, type ChatStore, ChatStoreInputError, type ChatTables, type ChatThreadRow, type CreateChatTablesOptions, type CreateThreadInput, type ListMessagesOptions, type ListThreadsInput, type ListThreadsResult, type NewChatMessageRow, type NewChatThreadRow, type UpdateMessageInput, type WorkspaceAccessCheck, createChatStore, createChatTables, threadTitleFromMessage };
@@ -52,6 +52,7 @@ function createChatTables(options = {}) {
52
52
  const { workspaceTable, tablePrefix = "" } = options;
53
53
  const threadExtras = options.threadExtraColumns ?? {};
54
54
  const messageExtras = options.messageExtraColumns ?? {};
55
+ const extraIndexes = (build, table) => build?.(table) ?? [];
55
56
  const threads = sqliteTable(`${tablePrefix}thread`, {
56
57
  id: hexId(),
57
58
  workspaceId: workspaceTable ? text("workspace_id").notNull().references(() => workspaceTable.id, { onDelete: "cascade" }) : text("workspace_id").notNull(),
@@ -64,7 +65,8 @@ function createChatTables(options = {}) {
64
65
  }, (table) => [
65
66
  index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),
66
67
  // Supports the store's list ordering (updatedAt desc within a workspace).
67
- index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt)
68
+ index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt),
69
+ ...extraIndexes(options.threadExtraIndexes, table)
68
70
  ]);
69
71
  const messages = sqliteTable(`${tablePrefix}message`, {
70
72
  id: hexId(),
@@ -90,7 +92,8 @@ function createChatTables(options = {}) {
90
92
  ...messageExtras
91
93
  }, (table) => [
92
94
  index(`idx_${tablePrefix}message_thread`).on(table.threadId),
93
- index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt)
95
+ index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt),
96
+ ...extraIndexes(options.messageExtraIndexes, table)
94
97
  ]);
95
98
  return { threads, messages };
96
99
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/chat-store/core.ts","../../src/chat-store/schema.ts","../../src/chat-store/store.ts"],"sourcesContent":["/**\n * Pure (drizzle-free) pieces of the chat store: thread-title derivation, the\n * bulk-delete bound, and the typed input error. Split from `./schema`/`./store`\n * so the root barrel can re-export them without dragging the optional\n * drizzle-orm peer into every root-entry consumer.\n */\n\n/** Bounds a single bulk-delete request's write set; product surfaces cap\n * thread lists at far fewer, so a larger batch is a malformed or hostile\n * request. (Lifted from legal's api.threads.bulk-delete route.) */\nexport const BULK_DELETE_MAX_THREADS = 200\n\n/** Invalid caller input (missing/oversized ids, empty title). Products map it\n * to a 400; anything else out of the store is a real failure. */\nexport class ChatStoreInputError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ChatStoreInputError'\n }\n}\n\n/** Thread titles come from the first message — keep the list scannable by\n * storing only its first non-empty line, capped at 80 chars, never the whole\n * multi-page prompt. (Lifted verbatim from legal's chat.new route.) */\nexport function threadTitleFromMessage(message: string): string {\n const firstLine = message.split('\\n').find((l) => l.trim().length > 0)?.trim() ?? ''\n if (!firstLine) return 'New Thread'\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine\n}\n","/**\n * Drizzle schema factory for the chat thread/message tables — the same\n * injection pattern as `createTeamTables`: the product owns the workspace\n * table; the factory wires the thread FK into it so the whole graph lives in\n * one drizzle schema with real cascade semantics. Column names, types,\n * defaults, enums, and indexes mirror legal's and gtm's hand-rolled `thread`/\n * `message` tables so a product with those tables adopts the factory without\n * rewriting rows; `tablePrefix` covers products that namespace (tax's\n * `chat_messages` style).\n *\n * The core is the superset the three products agree on. Divergences dropped,\n * and why:\n * - `thread.status` ('active'|'archived', legal+gtm) — archive semantics\n * diverge (tax uses `archivedAt`); product-domain lifecycle → extra column.\n * - `thread.scopeKind`/`scopeKey`/`harness` (gtm) — artifact anchoring and\n * harness pinning are product-domain → extra columns.\n * - tax's `tax_sessions` session columns (`taxYear`, `projectRef`,\n * `agentSessionId`, `agentRuntime`, `agentHarness`, `profile`, `error`,\n * `userId`) — sandbox-session state, not chat state → extra columns.\n * - `message.toolInput`/`toolOutput` (legal+gtm) — duplicate of the tool\n * part's `state.input`/`state.output` inside `parts` (the shape `/stream`'s\n * `normalizePersistedPart` owns); keeping both invites drift.\n * - `message.vaultFiles` (legal+gtm) — vault is product-domain → extra column.\n * - tax's re-declared `turn_events`/`turn_status` DDL — deliberately NOT here;\n * `/stream`'s turn-buffer owns that DDL (`TURN_BUFFER_D1_SCHEMA_SQL`).\n *\n * Kept beyond the intersection: tax's per-message `model`/`inputTokens`/\n * `outputTokens`, extended to the full usage receipt the harness actually\n * reports in `step-finish` parts (`tokens {input, output, reasoning,\n * cache{read, write}}` + `cost`) — see `./parts`.\n *\n * `threadExtraColumns`/`messageExtraColumns` merge product columns into the\n * table definitions (the `/missions` opaque-extras pattern: the store writes\n * `extras` values verbatim in the SAME insert statement and never reads,\n * validates, or defaults them).\n *\n * SERVER-side module (D1/libsql/better-sqlite3 behind a worker or server\n * route) — but free of `node:` builtins on purpose: D1 workers have none.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable, SQLiteColumnBuilderBase } from 'drizzle-orm/sqlite-core'\nimport type { ChatMessagePart } from './parts'\n\n/** A product table referenced by FK — only the `id` column is touched. */\nexport type ChatParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/** Define options to customize chat thread and message table creation including workspace and naming prefixes */\nexport interface CreateChatTablesOptions<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n> {\n /** The product's workspace table — threads reference `workspaceTable.id`\n * with cascade. Omitted: `workspace_id` stays a plain indexed text column\n * (products whose tenant table lives in another database). */\n workspaceTable?: ChatParentTable\n /** Prefixes table AND index names (`'chat_'` → `chat_thread`,\n * `idx_chat_thread_workspace`) for products that namespace chat tables in a\n * shared database. Default: unprefixed `thread`/`message` (legal/gtm row\n * compatibility). */\n tablePrefix?: string\n /** Product columns merged into the thread table (the `/missions` extras\n * pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */\n threadExtraColumns?: TThreadExtras\n /** Product columns merged into the message table — e.g. legal's\n * `vault_files`. */\n messageExtraColumns?: TMessageExtras\n}\n\nconst hexId = () => text('id').primaryKey().default(sql`(lower(hex(randomblob(16))))`)\n\nconst createdAt = () => integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nconst updatedAt = () => integer('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\n/** Build chat-related SQLite tables with customizable thread and message columns */\nexport function createChatTables<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n>(options: CreateChatTablesOptions<TThreadExtras, TMessageExtras> = {}) {\n const { workspaceTable, tablePrefix = '' } = options\n const threadExtras = options.threadExtraColumns ?? ({} as TThreadExtras)\n const messageExtras = options.messageExtraColumns ?? ({} as TMessageExtras)\n\n const threads = sqliteTable(`${tablePrefix}thread`, {\n id: hexId(),\n workspaceId: workspaceTable\n ? text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' })\n : text('workspace_id').notNull(),\n title: text('title').notNull(),\n category: text('category'),\n isPinned: integer('is_pinned', { mode: 'boolean' }).notNull().default(false),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n ...threadExtras,\n }, (table) => [\n index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),\n // Supports the store's list ordering (updatedAt desc within a workspace).\n index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt),\n ])\n\n const messages = sqliteTable(`${tablePrefix}message`, {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threads.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['user', 'assistant', 'system', 'tool'] }).notNull(),\n content: text('content').notNull(),\n parts: text('parts', { mode: 'json' }).$type<ChatMessagePart[]>().default([]),\n toolName: text('tool_name'),\n model: text('model'),\n requestedModel: text('requested_model'),\n servedModel: text('served_model'),\n servedProvider: text('served_provider'),\n servedSource: text('served_model_source'),\n // Usage receipt, flattened from the harness's `step-finish` shape\n // (`tokens {input, output, reasoning, cache{read, write}}` + `cost`).\n inputTokens: integer('input_tokens'),\n outputTokens: integer('output_tokens'),\n reasoningTokens: integer('reasoning_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n cacheWriteTokens: integer('cache_write_tokens'),\n costUsd: real('cost_usd'),\n createdAt: createdAt(),\n ...messageExtras,\n }, (table) => [\n index(`idx_${tablePrefix}message_thread`).on(table.threadId),\n index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt),\n ])\n\n return { threads, messages }\n}\n\n/**\n * The base (no-extras) table pair, pinned via an instantiation expression:\n * `ReturnType<typeof createChatTables>` on the bare generic substitutes the\n * extras params with their CONSTRAINT (`Record<string,\n * SQLiteColumnBuilderBase>`), stamping an index signature into the column map\n * that widens every concrete column to `unknown`/`notNull: false` — concrete\n * factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`\n * is non-generic, so its plain `ReturnType` never hits this.)\n */\nexport type ChatTables = ReturnType<typeof createChatTables<{}, {}>>\n\n/** Resolve the selected fields of a chat thread row from the chat threads table */\nexport type ChatThreadRow = ChatTables['threads']['$inferSelect']\n/** Resolve the selected structure of a chat message row from the messages table */\nexport type ChatMessageRow = ChatTables['messages']['$inferSelect']\n/** Resolve the type for inserting a new chat thread row into the threads table */\nexport type NewChatThreadRow = ChatTables['threads']['$inferInsert']\n/** Resolve the type for inserting a new chat message row into the messages table */\nexport type NewChatMessageRow = ChatTables['messages']['$inferInsert']\n","/**\n * Typed CRUD over the tables from `createChatTables`. Works against any\n * SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,\n * never `.run()`/`.all()`, so sync and async drivers behave identically.\n *\n * Access control is an injected seam, never an import: single-thread routes\n * check workspace access themselves (they know the thread), while\n * `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request\n * can span workspaces — it is called once per distinct workspace and any\n * throw rejects the whole request before a single delete runs (fail-closed;\n * legal's bulk-delete semantics).\n *\n * Deletes run messages-first in ONE `db.batch` round trip when the driver has\n * one (D1, libsql), so a partial failure never leaves orphaned rows behind a\n * deleted thread; drivers without `batch` (better-sqlite3) fall back to\n * sequential awaits in the same order.\n */\n\nimport { asc, desc, eq, inArray, sql } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessagePart } from './parts'\nimport type { ChatMessageRow, ChatTables, ChatThreadRow, NewChatMessageRow, NewChatThreadRow } from './schema'\n\n/** Any SQLite drizzle database — `any` erases the driver-specific run-result\n * and schema generics so better-sqlite3, D1, and libsql handles all fit.\n * `batch` is structural: present on D1/libsql drizzle instances. */\nexport type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> &\n SqliteBatchDatabase\n\n/** Product-injected access check. Throw to deny; the store never interprets\n * users or roles itself. */\nexport type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>\n\n/** Define input parameters for listing threads within a workspace with pagination options */\nexport interface ListThreadsInput {\n workspaceId: string\n /** Clamped to 1..200; default 50 (legal's list route semantics). */\n limit?: number\n /** Clamped to >= 0; default 0. */\n offset?: number\n}\n\n/** Represent a paginated collection of chat threads with total count and pagination details */\nexport interface ListThreadsResult<TThread = ChatThreadRow> {\n threads: TThread[]\n total: number\n limit: number\n offset: number\n}\n\n/** Define input parameters required to create a new thread in a workspace */\nexport interface CreateThreadInput {\n workspaceId: string\n /** Title source when `title` is absent: first non-empty line, 80-char cap\n * (`threadTitleFromMessage`). */\n firstMessage?: string\n /** Explicit title; still normalized through `threadTitleFromMessage` so a\n * multi-page paste never becomes a sidebar entry. */\n title?: string\n category?: string | null\n isPinned?: boolean\n /** Opaque product-column values written verbatim in the SAME insert (the\n * `/missions` extras pattern). Never read, validated, or defaulted here. */\n extras?: Record<string, unknown>\n}\n\n/** Define input parameters for appending a message to a chat thread with optional metadata */\nexport interface AppendMessageInput {\n /** Caller-assigned primary key. Omitted, the column default assigns a random\n * hex id (today's behavior). Incremental assistant persistence passes a\n * DETERMINISTIC id derived from the turn's own identity, so a re-entered\n * turn (crashed worker, durable-driver retry) finds and updates the row a\n * previous attempt started instead of inserting a second one. */\n id?: string\n threadId: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[]\n toolName?: string | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n /** Opaque product-column values written verbatim in the SAME insert. */\n extras?: Record<string, unknown>\n}\n\n/** Fields an existing message row may be patched with. Every field is\n * optional and only DEFINED fields are written, so a partial patch never\n * clears a column it does not mention. `threadId` and `role` are absent on\n * purpose: a message never moves thread or changes speaker.\n *\n * Exists for incremental assistant persistence — the streaming turn writes\n * the row once and then patches it as content accumulates, so the durable\n * transcript is at most one cadence interval behind the live stream. */\nexport interface UpdateMessageInput {\n content?: string\n parts?: ChatMessagePart[]\n toolName?: string | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n /** Opaque product-column values written verbatim in the SAME update. */\n extras?: Record<string, unknown>\n}\n\n/** Define options to configure message listing with optional limit and offset parameters */\nexport interface ListMessagesOptions {\n limit?: number\n offset?: number\n}\n\n/** Define input for bulk deleting threads with access checks per workspace */\nexport interface BulkDeleteThreadsInput {\n ids: string[]\n /** Called once per distinct workspace the ids touch, before ANY delete. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Manage chat threads and messages with operations for listing, creating, updating, and deleting data */\nexport interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {\n listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>\n getThread(threadId: string): Promise<TThread | null>\n createThread(input: CreateThreadInput): Promise<TThread>\n renameThread(threadId: string, title: string): Promise<TThread | null>\n pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>\n /** Messages + thread in one batch. Resolves false when the thread does not\n * exist. `assertAccess` (optional) receives the thread's workspaceId before\n * the delete — single-thread callers usually check access themselves. */\n deleteThread(threadId: string, options?: { assertAccess?: WorkspaceAccessCheck }): Promise<boolean>\n bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{ deleted: number }>\n /** Ordered oldest-first: `created_at`, then rowid (insertion order within a\n * same-second burst — a user+assistant pair lands in one epoch second). */\n listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>\n /** Inserts the message and bumps the thread's `updatedAt` in one batch so\n * workspace recency sorts stay truthful. */\n appendMessage(input: AppendMessageInput): Promise<TMessage>\n /** Patches an existing message and bumps its thread's `updatedAt` in the\n * same batch. Resolves `null` when the id does not exist. Only defined\n * patch fields are written. */\n updateMessage(id: string, patch: UpdateMessageInput): Promise<TMessage | null>\n /** Removes one message. Resolves false when the id does not exist. Used by\n * incremental persistence to retract a draft row for a turn that ended\n * producing nothing, so an empty assistant row is never left behind. */\n deleteMessage(id: string): Promise<boolean>\n}\n\nfunction clampLimit(limit: number | undefined, fallback: number, max: number): number {\n const value = Number.isFinite(limit) ? Math.trunc(limit as number) : fallback\n return Math.min(Math.max(value, 1), max)\n}\n\nfunction clampOffset(offset: number | undefined): number {\n const value = Number.isFinite(offset) ? Math.trunc(offset as number) : 0\n return Math.max(value, 0)\n}\n\n/** Create a chat store managing threads and messages based on the provided database and tables */\nexport function createChatStore<TTables extends ChatTables>(\n db: ChatDatabase,\n tables: TTables,\n): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']> {\n type TThread = TTables['threads']['$inferSelect']\n type TMessage = TTables['messages']['$inferSelect']\n const threads = tables.threads as ChatTables['threads']\n const messages = tables.messages as ChatTables['messages']\n\n return {\n async listThreads(input) {\n const limit = clampLimit(input.limit, 50, 200)\n const offset = clampOffset(input.offset)\n const scope = eq(threads.workspaceId, input.workspaceId)\n const [list, [countRow]] = await Promise.all([\n db.select().from(threads).where(scope)\n // `id` tiebreak keeps pagination stable across same-second updates.\n .orderBy(desc(threads.updatedAt), asc(threads.id))\n .limit(limit)\n .offset(offset),\n db.select({ total: sql<number>`count(*)` }).from(threads).where(scope),\n ])\n return { threads: list as TThread[], total: countRow?.total ?? 0, limit, offset }\n },\n\n async getThread(threadId) {\n const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1)\n return (row as TThread | undefined) ?? null\n },\n\n async createThread(input) {\n const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? '')\n const values = {\n workspaceId: input.workspaceId,\n title,\n ...(input.category !== undefined ? { category: input.category } : {}),\n ...(input.isPinned !== undefined ? { isPinned: input.isPinned } : {}),\n ...(input.extras ?? {}),\n } as NewChatThreadRow\n const [row] = await db.insert(threads).values(values).returning()\n if (!row) throw new Error('thread insert returned no row')\n return row as TThread\n },\n\n async renameThread(threadId, title) {\n const trimmed = title.trim()\n if (!trimmed) throw new ChatStoreInputError('Missing title')\n const [row] = await db.update(threads)\n .set({ title: trimmed, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async pinThread(threadId, isPinned) {\n const [row] = await db.update(threads)\n .set({ isPinned, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async deleteThread(threadId, options) {\n const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(eq(threads.id, threadId))\n .limit(1)\n if (!existing) return false\n if (options?.assertAccess) await options.assertAccess(existing.workspaceId)\n // Messages first so a partial failure never leaves orphaned rows behind\n // a deleted thread.\n await runSqliteStatements(db, [\n db.delete(messages).where(eq(messages.threadId, threadId)),\n db.delete(threads).where(eq(threads.id, threadId)),\n ])\n return true\n },\n\n async bulkDeleteThreads(input) {\n const { ids, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ChatStoreInputError('Missing ids')\n }\n if (ids.length > BULK_DELETE_MAX_THREADS) {\n throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`)\n }\n\n const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(inArray(threads.id, ids))\n if (rows.length === 0) return { deleted: 0 }\n\n // Access is verified once per workspace the ids touch. Fail-closed: one\n // inaccessible workspace rejects the whole request before any delete.\n // Sorted so the check order (and therefore which denial surfaces) is\n // deterministic — row order follows random hex ids and varies per run.\n const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort()\n for (const workspaceId of workspaceIds) {\n await assertAccess(workspaceId)\n }\n\n const foundIds = rows.map((row) => row.id)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, foundIds)),\n db.delete(threads).where(inArray(threads.id, foundIds)),\n ])\n return { deleted: foundIds.length }\n },\n\n async listMessages(threadId, options) {\n const query = db.select().from(messages)\n .where(eq(messages.threadId, threadId))\n .orderBy(asc(messages.createdAt), sql`rowid`)\n .$dynamic()\n if (options?.limit !== undefined) query.limit(clampLimit(options.limit, 1, 1000))\n if (options?.offset !== undefined) query.offset(clampOffset(options.offset))\n return await query as TMessage[]\n },\n\n async appendMessage(input) {\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n ...(input.parts !== undefined ? { parts: input.parts } : {}),\n ...(input.toolName !== undefined ? { toolName: input.toolName } : {}),\n ...(input.model !== undefined ? { model: input.model } : {}),\n ...(input.requestedModel !== undefined ? { requestedModel: input.requestedModel } : {}),\n ...(input.servedModel !== undefined ? { servedModel: input.servedModel } : {}),\n ...(input.servedProvider !== undefined ? { servedProvider: input.servedProvider } : {}),\n ...(input.servedSource !== undefined ? { servedSource: input.servedSource } : {}),\n ...(input.inputTokens !== undefined ? { inputTokens: input.inputTokens } : {}),\n ...(input.outputTokens !== undefined ? { outputTokens: input.outputTokens } : {}),\n ...(input.reasoningTokens !== undefined ? { reasoningTokens: input.reasoningTokens } : {}),\n ...(input.cacheReadTokens !== undefined ? { cacheReadTokens: input.cacheReadTokens } : {}),\n ...(input.cacheWriteTokens !== undefined ? { cacheWriteTokens: input.cacheWriteTokens } : {}),\n ...(input.costUsd !== undefined ? { costUsd: input.costUsd } : {}),\n ...(input.extras ?? {}),\n } as NewChatMessageRow\n const [insertResult] = await runSqliteStatements(db, [\n db.insert(messages).values(values).returning(),\n db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, input.threadId)),\n ])\n const row = (insertResult as TMessage[] | undefined)?.[0]\n if (!row) throw new Error('message insert returned no row')\n return row\n },\n\n async updateMessage(id, patch) {\n const values = {\n ...(patch.content !== undefined ? { content: patch.content } : {}),\n ...(patch.parts !== undefined ? { parts: patch.parts } : {}),\n ...(patch.toolName !== undefined ? { toolName: patch.toolName } : {}),\n ...(patch.model !== undefined ? { model: patch.model } : {}),\n ...(patch.requestedModel !== undefined ? { requestedModel: patch.requestedModel } : {}),\n ...(patch.servedModel !== undefined ? { servedModel: patch.servedModel } : {}),\n ...(patch.servedProvider !== undefined ? { servedProvider: patch.servedProvider } : {}),\n ...(patch.servedSource !== undefined ? { servedSource: patch.servedSource } : {}),\n ...(patch.inputTokens !== undefined ? { inputTokens: patch.inputTokens } : {}),\n ...(patch.outputTokens !== undefined ? { outputTokens: patch.outputTokens } : {}),\n ...(patch.reasoningTokens !== undefined ? { reasoningTokens: patch.reasoningTokens } : {}),\n ...(patch.cacheReadTokens !== undefined ? { cacheReadTokens: patch.cacheReadTokens } : {}),\n ...(patch.cacheWriteTokens !== undefined ? { cacheWriteTokens: patch.cacheWriteTokens } : {}),\n ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}),\n ...(patch.extras ?? {}),\n }\n if (Object.keys(values).length === 0) {\n const [current] = await db.select().from(messages).where(eq(messages.id, id))\n return (current as TMessage | undefined) ?? null\n }\n // The thread bump reads the row's own `thread_id` rather than trusting a\n // caller-supplied one: a message never moves thread, so the subquery is\n // the authoritative source and one fewer parameter to get wrong.\n const [updateResult] = await runSqliteStatements(db, [\n db.update(messages).set(values).where(eq(messages.id, id)).returning(),\n db.update(threads).set({ updatedAt: new Date() })\n .where(eq(threads.id, sql`(select ${messages.threadId} from ${messages} where ${messages.id} = ${id})`)),\n ])\n return (updateResult as TMessage[] | undefined)?.[0] ?? null\n },\n\n async deleteMessage(id) {\n const deleted = await db.delete(messages).where(eq(messages.id, id)).returning()\n return (deleted as unknown[]).length > 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,IAAM,0BAA0B;AAIhC,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,YAAY,QAAQ,MAAM,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,KAAK,KAAK;AAClF,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,UAAU,SAAS,KAAK,GAAG,UAAU,MAAM,GAAG,EAAE,CA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,MAAM,GAAG,OAAO,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAC/E,aAAQ,QAAsB,SAAS;AAAA,IACzC;AAAA,EACF;AACF;","names":["sql","sql"]}
1
+ {"version":3,"sources":["../../src/chat-store/core.ts","../../src/chat-store/schema.ts","../../src/chat-store/store.ts"],"sourcesContent":["/**\n * Pure (drizzle-free) pieces of the chat store: thread-title derivation, the\n * bulk-delete bound, and the typed input error. Split from `./schema`/`./store`\n * so the root barrel can re-export them without dragging the optional\n * drizzle-orm peer into every root-entry consumer.\n */\n\n/** Bounds a single bulk-delete request's write set; product surfaces cap\n * thread lists at far fewer, so a larger batch is a malformed or hostile\n * request. (Lifted from legal's api.threads.bulk-delete route.) */\nexport const BULK_DELETE_MAX_THREADS = 200\n\n/** Invalid caller input (missing/oversized ids, empty title). Products map it\n * to a 400; anything else out of the store is a real failure. */\nexport class ChatStoreInputError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'ChatStoreInputError'\n }\n}\n\n/** Thread titles come from the first message — keep the list scannable by\n * storing only its first non-empty line, capped at 80 chars, never the whole\n * multi-page prompt. (Lifted verbatim from legal's chat.new route.) */\nexport function threadTitleFromMessage(message: string): string {\n const firstLine = message.split('\\n').find((l) => l.trim().length > 0)?.trim() ?? ''\n if (!firstLine) return 'New Thread'\n return firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine\n}\n","/**\n * Drizzle schema factory for the chat thread/message tables — the same\n * injection pattern as `createTeamTables`: the product owns the workspace\n * table; the factory wires the thread FK into it so the whole graph lives in\n * one drizzle schema with real cascade semantics. Column names, types,\n * defaults, enums, and indexes mirror legal's and gtm's hand-rolled `thread`/\n * `message` tables so a product with those tables adopts the factory without\n * rewriting rows; `tablePrefix` covers products that namespace (tax's\n * `chat_messages` style).\n *\n * The core is the superset the three products agree on. Divergences dropped,\n * and why:\n * - `thread.status` ('active'|'archived', legal+gtm) — archive semantics\n * diverge (tax uses `archivedAt`); product-domain lifecycle → extra column.\n * - `thread.scopeKind`/`scopeKey`/`harness` (gtm) — artifact anchoring and\n * harness pinning are product-domain → extra columns.\n * - tax's `tax_sessions` session columns (`taxYear`, `projectRef`,\n * `agentSessionId`, `agentRuntime`, `agentHarness`, `profile`, `error`,\n * `userId`) — sandbox-session state, not chat state → extra columns.\n * - `message.toolInput`/`toolOutput` (legal+gtm) — duplicate of the tool\n * part's `state.input`/`state.output` inside `parts` (the shape `/stream`'s\n * `normalizePersistedPart` owns); keeping both invites drift.\n * - `message.vaultFiles` (legal+gtm) — vault is product-domain → extra column.\n * - tax's re-declared `turn_events`/`turn_status` DDL — deliberately NOT here;\n * `/stream`'s turn-buffer owns that DDL (`TURN_BUFFER_D1_SCHEMA_SQL`).\n *\n * Kept beyond the intersection: tax's per-message `model`/`inputTokens`/\n * `outputTokens`, extended to the full usage receipt the harness actually\n * reports in `step-finish` parts (`tokens {input, output, reasoning,\n * cache{read, write}}` + `cost`) — see `./parts`.\n *\n * `threadExtraColumns`/`messageExtraColumns` merge product columns into the\n * table definitions (the `/missions` opaque-extras pattern: the store writes\n * `extras` values verbatim in the SAME insert statement and never reads,\n * validates, or defaults them).\n *\n * SERVER-side module (D1/libsql/better-sqlite3 behind a worker or server\n * route) — but free of `node:` builtins on purpose: D1 workers have none.\n */\n\nimport { sql } from 'drizzle-orm'\nimport { index, integer, real, sqliteTable, text } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable, SQLiteColumnBuilderBase } from 'drizzle-orm/sqlite-core'\nimport type { ChatMessagePart } from './parts'\n\n/** A product table referenced by FK — only the `id` column is touched. */\nexport type ChatParentTable = AnySQLiteTable & { id: AnySQLiteColumn }\n\n/** Define options to customize chat thread and message table creation including workspace and naming prefixes */\nexport interface CreateChatTablesOptions<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n> {\n /** The product's workspace table — threads reference `workspaceTable.id`\n * with cascade. Omitted: `workspace_id` stays a plain indexed text column\n * (products whose tenant table lives in another database). */\n workspaceTable?: ChatParentTable\n /** Prefixes table AND index names (`'chat_'` → `chat_thread`,\n * `idx_chat_thread_workspace`) for products that namespace chat tables in a\n * shared database. Default: unprefixed `thread`/`message` (legal/gtm row\n * compatibility). */\n tablePrefix?: string\n /** Product columns merged into the thread table (the `/missions` extras\n * pattern) — e.g. a `status` lifecycle enum or gtm's scope columns. */\n threadExtraColumns?: TThreadExtras\n /** Product columns merged into the message table — e.g. legal's\n * `vault_files`. */\n messageExtraColumns?: TMessageExtras\n /**\n * Product indexes appended to the thread table's own, given the built\n * columns (extras included) so a product can index what it added.\n *\n * Names are used VERBATIM — `tablePrefix` is not applied — because these\n * have to byte-match indexes the product's migrations already created.\n *\n * Without this a product with one extra index cannot adopt the factory at\n * all: it keeps a hand-rolled duplicate of the same physical table, and the\n * two drift on the next factory change.\n */\n threadExtraIndexes?: ChatExtraIndexes\n /** Product indexes appended to the message table's own. Same rules as\n * `threadExtraIndexes`. */\n messageExtraIndexes?: ChatExtraIndexes\n}\n\n/**\n * Builds product indexes from a table's columns. Returns drizzle's\n * `index(...)`/`uniqueIndex(...)` results; the column map is passed through\n * untyped because its shape depends on the product's own extras.\n */\nexport type ChatExtraIndexes = (columns: Record<string, AnySQLiteColumn>) => unknown[]\n\nconst hexId = () => text('id').primaryKey().default(sql`(lower(hex(randomblob(16))))`)\n\nconst createdAt = () => integer('created_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\nconst updatedAt = () => integer('updated_at', { mode: 'timestamp' }).notNull().default(sql`(unixepoch())`)\n\n/** Build chat-related SQLite tables with customizable thread and message columns */\nexport function createChatTables<\n TThreadExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n TMessageExtras extends Record<string, SQLiteColumnBuilderBase> = {},\n>(options: CreateChatTablesOptions<TThreadExtras, TMessageExtras> = {}) {\n const { workspaceTable, tablePrefix = '' } = options\n const threadExtras = options.threadExtraColumns ?? ({} as TThreadExtras)\n const messageExtras = options.messageExtraColumns ?? ({} as TMessageExtras)\n const extraIndexes = (\n build: ChatExtraIndexes | undefined,\n table: Record<string, AnySQLiteColumn>,\n ): unknown[] => build?.(table) ?? []\n\n const threads = sqliteTable(`${tablePrefix}thread`, {\n id: hexId(),\n workspaceId: workspaceTable\n ? text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' })\n : text('workspace_id').notNull(),\n title: text('title').notNull(),\n category: text('category'),\n isPinned: integer('is_pinned', { mode: 'boolean' }).notNull().default(false),\n createdAt: createdAt(),\n updatedAt: updatedAt(),\n ...threadExtras,\n }, (table) => [\n index(`idx_${tablePrefix}thread_workspace`).on(table.workspaceId),\n // Supports the store's list ordering (updatedAt desc within a workspace).\n index(`idx_${tablePrefix}thread_workspace_updated`).on(table.workspaceId, table.updatedAt),\n ...extraIndexes(options.threadExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ] as never)\n\n const messages = sqliteTable(`${tablePrefix}message`, {\n id: hexId(),\n threadId: text('thread_id').notNull().references(() => threads.id, { onDelete: 'cascade' }),\n role: text('role', { enum: ['user', 'assistant', 'system', 'tool'] }).notNull(),\n content: text('content').notNull(),\n parts: text('parts', { mode: 'json' }).$type<ChatMessagePart[]>().default([]),\n toolName: text('tool_name'),\n model: text('model'),\n requestedModel: text('requested_model'),\n servedModel: text('served_model'),\n servedProvider: text('served_provider'),\n servedSource: text('served_model_source'),\n // Usage receipt, flattened from the harness's `step-finish` shape\n // (`tokens {input, output, reasoning, cache{read, write}}` + `cost`).\n inputTokens: integer('input_tokens'),\n outputTokens: integer('output_tokens'),\n reasoningTokens: integer('reasoning_tokens'),\n cacheReadTokens: integer('cache_read_tokens'),\n cacheWriteTokens: integer('cache_write_tokens'),\n costUsd: real('cost_usd'),\n createdAt: createdAt(),\n ...messageExtras,\n }, (table) => [\n index(`idx_${tablePrefix}message_thread`).on(table.threadId),\n index(`idx_${tablePrefix}message_thread_created`).on(table.threadId, table.createdAt),\n ...extraIndexes(options.messageExtraIndexes, table as unknown as Record<string, AnySQLiteColumn>),\n ] as never)\n\n return { threads, messages }\n}\n\n/**\n * The base (no-extras) table pair, pinned via an instantiation expression:\n * `ReturnType<typeof createChatTables>` on the bare generic substitutes the\n * extras params with their CONSTRAINT (`Record<string,\n * SQLiteColumnBuilderBase>`), stamping an index signature into the column map\n * that widens every concrete column to `unknown`/`notNull: false` — concrete\n * factory results then fail `extends ChatTables`. (`teams`' `createTeamTables`\n * is non-generic, so its plain `ReturnType` never hits this.)\n */\nexport type ChatTables = ReturnType<typeof createChatTables<{}, {}>>\n\n/** Resolve the selected fields of a chat thread row from the chat threads table */\nexport type ChatThreadRow = ChatTables['threads']['$inferSelect']\n/** Resolve the selected structure of a chat message row from the messages table */\nexport type ChatMessageRow = ChatTables['messages']['$inferSelect']\n/** Resolve the type for inserting a new chat thread row into the threads table */\nexport type NewChatThreadRow = ChatTables['threads']['$inferInsert']\n/** Resolve the type for inserting a new chat message row into the messages table */\nexport type NewChatMessageRow = ChatTables['messages']['$inferInsert']\n","/**\n * Typed CRUD over the tables from `createChatTables`. Works against any\n * SQLite drizzle driver (D1, libsql, better-sqlite3) — builders are awaited,\n * never `.run()`/`.all()`, so sync and async drivers behave identically.\n *\n * Access control is an injected seam, never an import: single-thread routes\n * check workspace access themselves (they know the thread), while\n * `bulkDeleteThreads` REQUIRES an `assertAccess` callback because one request\n * can span workspaces — it is called once per distinct workspace and any\n * throw rejects the whole request before a single delete runs (fail-closed;\n * legal's bulk-delete semantics).\n *\n * Deletes run messages-first in ONE `db.batch` round trip when the driver has\n * one (D1, libsql), so a partial failure never leaves orphaned rows behind a\n * deleted thread; drivers without `batch` (better-sqlite3) fall back to\n * sequential awaits in the same order.\n */\n\nimport { asc, desc, eq, inArray, sql } from 'drizzle-orm'\nimport type { BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport {\n runSqliteStatements,\n type SqliteBatchDatabase,\n} from '../store'\nimport { BULK_DELETE_MAX_THREADS, ChatStoreInputError, threadTitleFromMessage } from './core'\nimport type { ChatMessagePart } from './parts'\nimport type { ChatMessageRow, ChatTables, ChatThreadRow, NewChatMessageRow, NewChatThreadRow } from './schema'\n\n/** Any SQLite drizzle database — `any` erases the driver-specific run-result\n * and schema generics so better-sqlite3, D1, and libsql handles all fit.\n * `batch` is structural: present on D1/libsql drizzle instances. */\nexport type ChatDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any> &\n SqliteBatchDatabase\n\n/** Product-injected access check. Throw to deny; the store never interprets\n * users or roles itself. */\nexport type WorkspaceAccessCheck = (workspaceId: string) => void | Promise<void>\n\n/** Define input parameters for listing threads within a workspace with pagination options */\nexport interface ListThreadsInput {\n workspaceId: string\n /** Clamped to 1..200; default 50 (legal's list route semantics). */\n limit?: number\n /** Clamped to >= 0; default 0. */\n offset?: number\n}\n\n/** Represent a paginated collection of chat threads with total count and pagination details */\nexport interface ListThreadsResult<TThread = ChatThreadRow> {\n threads: TThread[]\n total: number\n limit: number\n offset: number\n}\n\n/** Define input parameters required to create a new thread in a workspace */\nexport interface CreateThreadInput {\n workspaceId: string\n /** Title source when `title` is absent: first non-empty line, 80-char cap\n * (`threadTitleFromMessage`). */\n firstMessage?: string\n /** Explicit title; still normalized through `threadTitleFromMessage` so a\n * multi-page paste never becomes a sidebar entry. */\n title?: string\n category?: string | null\n isPinned?: boolean\n /** Opaque product-column values written verbatim in the SAME insert (the\n * `/missions` extras pattern). Never read, validated, or defaulted here. */\n extras?: Record<string, unknown>\n}\n\n/** Define input parameters for appending a message to a chat thread with optional metadata */\nexport interface AppendMessageInput {\n /** Caller-assigned primary key. Omitted, the column default assigns a random\n * hex id (today's behavior). Incremental assistant persistence passes a\n * DETERMINISTIC id derived from the turn's own identity, so a re-entered\n * turn (crashed worker, durable-driver retry) finds and updates the row a\n * previous attempt started instead of inserting a second one. */\n id?: string\n threadId: string\n role: 'user' | 'assistant' | 'system' | 'tool'\n content: string\n parts?: ChatMessagePart[]\n toolName?: string | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n /** Opaque product-column values written verbatim in the SAME insert. */\n extras?: Record<string, unknown>\n}\n\n/** Fields an existing message row may be patched with. Every field is\n * optional and only DEFINED fields are written, so a partial patch never\n * clears a column it does not mention. `threadId` and `role` are absent on\n * purpose: a message never moves thread or changes speaker.\n *\n * Exists for incremental assistant persistence — the streaming turn writes\n * the row once and then patches it as content accumulates, so the durable\n * transcript is at most one cadence interval behind the live stream. */\nexport interface UpdateMessageInput {\n content?: string\n parts?: ChatMessagePart[]\n toolName?: string | null\n model?: string | null\n requestedModel?: string | null\n servedModel?: string | null\n servedProvider?: string | null\n servedSource?: string | null\n inputTokens?: number | null\n outputTokens?: number | null\n reasoningTokens?: number | null\n cacheReadTokens?: number | null\n cacheWriteTokens?: number | null\n costUsd?: number | null\n /** Opaque product-column values written verbatim in the SAME update. */\n extras?: Record<string, unknown>\n}\n\n/** Define options to configure message listing with optional limit and offset parameters */\nexport interface ListMessagesOptions {\n limit?: number\n offset?: number\n}\n\n/** Define input for bulk deleting threads with access checks per workspace */\nexport interface BulkDeleteThreadsInput {\n ids: string[]\n /** Called once per distinct workspace the ids touch, before ANY delete. */\n assertAccess: WorkspaceAccessCheck\n}\n\n/** Manage chat threads and messages with operations for listing, creating, updating, and deleting data */\nexport interface ChatStore<TThread = ChatThreadRow, TMessage = ChatMessageRow> {\n listThreads(input: ListThreadsInput): Promise<ListThreadsResult<TThread>>\n getThread(threadId: string): Promise<TThread | null>\n createThread(input: CreateThreadInput): Promise<TThread>\n renameThread(threadId: string, title: string): Promise<TThread | null>\n pinThread(threadId: string, isPinned: boolean): Promise<TThread | null>\n /** Messages + thread in one batch. Resolves false when the thread does not\n * exist. `assertAccess` (optional) receives the thread's workspaceId before\n * the delete — single-thread callers usually check access themselves. */\n deleteThread(threadId: string, options?: { assertAccess?: WorkspaceAccessCheck }): Promise<boolean>\n bulkDeleteThreads(input: BulkDeleteThreadsInput): Promise<{ deleted: number }>\n /** Ordered oldest-first: `created_at`, then rowid (insertion order within a\n * same-second burst — a user+assistant pair lands in one epoch second). */\n listMessages(threadId: string, options?: ListMessagesOptions): Promise<TMessage[]>\n /** Inserts the message and bumps the thread's `updatedAt` in one batch so\n * workspace recency sorts stay truthful. */\n appendMessage(input: AppendMessageInput): Promise<TMessage>\n /** Patches an existing message and bumps its thread's `updatedAt` in the\n * same batch. Resolves `null` when the id does not exist. Only defined\n * patch fields are written. */\n updateMessage(id: string, patch: UpdateMessageInput): Promise<TMessage | null>\n /** Removes one message. Resolves false when the id does not exist. Used by\n * incremental persistence to retract a draft row for a turn that ended\n * producing nothing, so an empty assistant row is never left behind. */\n deleteMessage(id: string): Promise<boolean>\n}\n\nfunction clampLimit(limit: number | undefined, fallback: number, max: number): number {\n const value = Number.isFinite(limit) ? Math.trunc(limit as number) : fallback\n return Math.min(Math.max(value, 1), max)\n}\n\nfunction clampOffset(offset: number | undefined): number {\n const value = Number.isFinite(offset) ? Math.trunc(offset as number) : 0\n return Math.max(value, 0)\n}\n\n/** Create a chat store managing threads and messages based on the provided database and tables */\nexport function createChatStore<TTables extends ChatTables>(\n db: ChatDatabase,\n tables: TTables,\n): ChatStore<TTables['threads']['$inferSelect'], TTables['messages']['$inferSelect']> {\n type TThread = TTables['threads']['$inferSelect']\n type TMessage = TTables['messages']['$inferSelect']\n const threads = tables.threads as ChatTables['threads']\n const messages = tables.messages as ChatTables['messages']\n\n return {\n async listThreads(input) {\n const limit = clampLimit(input.limit, 50, 200)\n const offset = clampOffset(input.offset)\n const scope = eq(threads.workspaceId, input.workspaceId)\n const [list, [countRow]] = await Promise.all([\n db.select().from(threads).where(scope)\n // `id` tiebreak keeps pagination stable across same-second updates.\n .orderBy(desc(threads.updatedAt), asc(threads.id))\n .limit(limit)\n .offset(offset),\n db.select({ total: sql<number>`count(*)` }).from(threads).where(scope),\n ])\n return { threads: list as TThread[], total: countRow?.total ?? 0, limit, offset }\n },\n\n async getThread(threadId) {\n const [row] = await db.select().from(threads).where(eq(threads.id, threadId)).limit(1)\n return (row as TThread | undefined) ?? null\n },\n\n async createThread(input) {\n const title = threadTitleFromMessage(input.title ?? input.firstMessage ?? '')\n const values = {\n workspaceId: input.workspaceId,\n title,\n ...(input.category !== undefined ? { category: input.category } : {}),\n ...(input.isPinned !== undefined ? { isPinned: input.isPinned } : {}),\n ...(input.extras ?? {}),\n } as NewChatThreadRow\n const [row] = await db.insert(threads).values(values).returning()\n if (!row) throw new Error('thread insert returned no row')\n return row as TThread\n },\n\n async renameThread(threadId, title) {\n const trimmed = title.trim()\n if (!trimmed) throw new ChatStoreInputError('Missing title')\n const [row] = await db.update(threads)\n .set({ title: trimmed, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async pinThread(threadId, isPinned) {\n const [row] = await db.update(threads)\n .set({ isPinned, updatedAt: new Date() })\n .where(eq(threads.id, threadId))\n .returning()\n return (row as TThread | undefined) ?? null\n },\n\n async deleteThread(threadId, options) {\n const [existing] = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(eq(threads.id, threadId))\n .limit(1)\n if (!existing) return false\n if (options?.assertAccess) await options.assertAccess(existing.workspaceId)\n // Messages first so a partial failure never leaves orphaned rows behind\n // a deleted thread.\n await runSqliteStatements(db, [\n db.delete(messages).where(eq(messages.threadId, threadId)),\n db.delete(threads).where(eq(threads.id, threadId)),\n ])\n return true\n },\n\n async bulkDeleteThreads(input) {\n const { ids, assertAccess } = input\n if (typeof assertAccess !== 'function') throw new ChatStoreInputError('Missing assertAccess')\n if (!Array.isArray(ids) || ids.length === 0 || !ids.every((id) => typeof id === 'string' && id.length > 0)) {\n throw new ChatStoreInputError('Missing ids')\n }\n if (ids.length > BULK_DELETE_MAX_THREADS) {\n throw new ChatStoreInputError(`Too many ids (max ${BULK_DELETE_MAX_THREADS})`)\n }\n\n const rows = await db.select({ id: threads.id, workspaceId: threads.workspaceId })\n .from(threads)\n .where(inArray(threads.id, ids))\n if (rows.length === 0) return { deleted: 0 }\n\n // Access is verified once per workspace the ids touch. Fail-closed: one\n // inaccessible workspace rejects the whole request before any delete.\n // Sorted so the check order (and therefore which denial surfaces) is\n // deterministic — row order follows random hex ids and varies per run.\n const workspaceIds = [...new Set(rows.map((row) => row.workspaceId))].sort()\n for (const workspaceId of workspaceIds) {\n await assertAccess(workspaceId)\n }\n\n const foundIds = rows.map((row) => row.id)\n await runSqliteStatements(db, [\n db.delete(messages).where(inArray(messages.threadId, foundIds)),\n db.delete(threads).where(inArray(threads.id, foundIds)),\n ])\n return { deleted: foundIds.length }\n },\n\n async listMessages(threadId, options) {\n const query = db.select().from(messages)\n .where(eq(messages.threadId, threadId))\n .orderBy(asc(messages.createdAt), sql`rowid`)\n .$dynamic()\n if (options?.limit !== undefined) query.limit(clampLimit(options.limit, 1, 1000))\n if (options?.offset !== undefined) query.offset(clampOffset(options.offset))\n return await query as TMessage[]\n },\n\n async appendMessage(input) {\n const values = {\n ...(input.id !== undefined ? { id: input.id } : {}),\n threadId: input.threadId,\n role: input.role,\n content: input.content,\n ...(input.parts !== undefined ? { parts: input.parts } : {}),\n ...(input.toolName !== undefined ? { toolName: input.toolName } : {}),\n ...(input.model !== undefined ? { model: input.model } : {}),\n ...(input.requestedModel !== undefined ? { requestedModel: input.requestedModel } : {}),\n ...(input.servedModel !== undefined ? { servedModel: input.servedModel } : {}),\n ...(input.servedProvider !== undefined ? { servedProvider: input.servedProvider } : {}),\n ...(input.servedSource !== undefined ? { servedSource: input.servedSource } : {}),\n ...(input.inputTokens !== undefined ? { inputTokens: input.inputTokens } : {}),\n ...(input.outputTokens !== undefined ? { outputTokens: input.outputTokens } : {}),\n ...(input.reasoningTokens !== undefined ? { reasoningTokens: input.reasoningTokens } : {}),\n ...(input.cacheReadTokens !== undefined ? { cacheReadTokens: input.cacheReadTokens } : {}),\n ...(input.cacheWriteTokens !== undefined ? { cacheWriteTokens: input.cacheWriteTokens } : {}),\n ...(input.costUsd !== undefined ? { costUsd: input.costUsd } : {}),\n ...(input.extras ?? {}),\n } as NewChatMessageRow\n const [insertResult] = await runSqliteStatements(db, [\n db.insert(messages).values(values).returning(),\n db.update(threads).set({ updatedAt: new Date() }).where(eq(threads.id, input.threadId)),\n ])\n const row = (insertResult as TMessage[] | undefined)?.[0]\n if (!row) throw new Error('message insert returned no row')\n return row\n },\n\n async updateMessage(id, patch) {\n const values = {\n ...(patch.content !== undefined ? { content: patch.content } : {}),\n ...(patch.parts !== undefined ? { parts: patch.parts } : {}),\n ...(patch.toolName !== undefined ? { toolName: patch.toolName } : {}),\n ...(patch.model !== undefined ? { model: patch.model } : {}),\n ...(patch.requestedModel !== undefined ? { requestedModel: patch.requestedModel } : {}),\n ...(patch.servedModel !== undefined ? { servedModel: patch.servedModel } : {}),\n ...(patch.servedProvider !== undefined ? { servedProvider: patch.servedProvider } : {}),\n ...(patch.servedSource !== undefined ? { servedSource: patch.servedSource } : {}),\n ...(patch.inputTokens !== undefined ? { inputTokens: patch.inputTokens } : {}),\n ...(patch.outputTokens !== undefined ? { outputTokens: patch.outputTokens } : {}),\n ...(patch.reasoningTokens !== undefined ? { reasoningTokens: patch.reasoningTokens } : {}),\n ...(patch.cacheReadTokens !== undefined ? { cacheReadTokens: patch.cacheReadTokens } : {}),\n ...(patch.cacheWriteTokens !== undefined ? { cacheWriteTokens: patch.cacheWriteTokens } : {}),\n ...(patch.costUsd !== undefined ? { costUsd: patch.costUsd } : {}),\n ...(patch.extras ?? {}),\n }\n if (Object.keys(values).length === 0) {\n const [current] = await db.select().from(messages).where(eq(messages.id, id))\n return (current as TMessage | undefined) ?? null\n }\n // The thread bump reads the row's own `thread_id` rather than trusting a\n // caller-supplied one: a message never moves thread, so the subquery is\n // the authoritative source and one fewer parameter to get wrong.\n const [updateResult] = await runSqliteStatements(db, [\n db.update(messages).set(values).where(eq(messages.id, id)).returning(),\n db.update(threads).set({ updatedAt: new Date() })\n .where(eq(threads.id, sql`(select ${messages.threadId} from ${messages} where ${messages.id} = ${id})`)),\n ])\n return (updateResult as TMessage[] | undefined)?.[0] ?? null\n },\n\n async deleteMessage(id) {\n const deleted = await db.delete(messages).where(eq(messages.id, id)).returning()\n return (deleted as unknown[]).length > 0\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,IAAM,0BAA0B;AAIhC,IAAM,sBAAN,cAAkC,MAAM;AAAA,EAC7C,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAKO,SAAS,uBAAuB,SAAyB;AAC9D,QAAM,YAAY,QAAQ,MAAM,IAAI,EAAE,KAAK,CAAC,MAAM,EAAE,KAAK,EAAE,SAAS,CAAC,GAAG,KAAK,KAAK;AAClF,MAAI,CAAC,UAAW,QAAO;AACvB,SAAO,UAAU,SAAS,KAAK,GAAG,UAAU,MAAM,GAAG,EAAE,CAAC,WAAM;AAChE;;;ACYA,SAAS,WAAW;AACpB,SAAS,OAAO,SAAS,MAAM,aAAa,YAAY;AAmDxD,IAAM,QAAQ,MAAM,KAAK,IAAI,EAAE,WAAW,EAAE,QAAQ,iCAAiC;AAErF,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAEzG,IAAM,YAAY,MAAM,QAAQ,cAAc,EAAE,MAAM,YAAY,CAAC,EAAE,QAAQ,EAAE,QAAQ,kBAAkB;AAGlG,SAAS,iBAGd,UAAkE,CAAC,GAAG;AACtE,QAAM,EAAE,gBAAgB,cAAc,GAAG,IAAI;AAC7C,QAAM,eAAe,QAAQ,sBAAuB,CAAC;AACrD,QAAM,gBAAgB,QAAQ,uBAAwB,CAAC;AACvD,QAAM,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AgB,IAAI,CAAC;AAAA,QACxF,GAAI,MAAM,qBAAqB,SAAY,EAAE,kBAAkB,MAAM,iBAAiB,IAAI,CAAC;AAAA,QAC3F,GAAI,MAAM,YAAY,SAAY,EAAE,SAAS,MAAM,QAAQ,IAAI,CAAC;AAAA,QAChE,GAAI,MAAM,UAAU,CAAC;AAAA,MACvB;AACA,UAAI,OAAO,KAAK,MAAM,EAAE,WAAW,GAAG;AACpC,cAAM,CAAC,OAAO,IAAI,MAAM,GAAG,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC;AAC5E,eAAQ,WAAoC;AAAA,MAC9C;AAIA,YAAM,CAAC,YAAY,IAAI,MAAM,oBAAoB,IAAI;AAAA,QACnD,GAAG,OAAO,QAAQ,EAAE,IAAI,MAAM,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAAA,QACrE,GAAG,OAAO,OAAO,EAAE,IAAI,EAAE,WAAW,oBAAI,KAAK,EAAE,CAAC,EAC7C,MAAM,GAAG,QAAQ,IAAIA,eAAc,SAAS,QAAQ,SAAS,QAAQ,UAAU,SAAS,EAAE,MAAM,EAAE,GAAG,CAAC;AAAA,MAC3G,CAAC;AACD,aAAQ,eAA0C,CAAC,KAAK;AAAA,IAC1D;AAAA,IAEA,MAAM,cAAc,IAAI;AACtB,YAAM,UAAU,MAAM,GAAG,OAAO,QAAQ,EAAE,MAAM,GAAG,SAAS,IAAI,EAAE,CAAC,EAAE,UAAU;AAC/E,aAAQ,QAAsB,SAAS;AAAA,IACzC;AAAA,EACF;AACF;","names":["sql","sql"]}
@@ -71,6 +71,16 @@ function classifyAuthed(outcome, ctx) {
71
71
  function trimTrailingSlash(url) {
72
72
  return url.replace(/\/+$/, "");
73
73
  }
74
+ function requiredValueProbe(config) {
75
+ return {
76
+ name: `required:${config.name}`,
77
+ critical: config.critical,
78
+ run: async () => {
79
+ const ok = typeof config.value === "string" && config.value.trim().length > 0;
80
+ return { ok, detail: ok ? void 0 : config.missingDetail ?? `${config.name} is unset` };
81
+ }
82
+ };
83
+ }
74
84
  function routerChatProbe(config) {
75
85
  const keyLabel = config.keySecret ?? "the router API key";
76
86
  const urlLabel = config.urlSecret ?? "the router base URL";
@@ -231,10 +241,11 @@ function formatPreflightReport(report) {
231
241
  }
232
242
 
233
243
  export {
244
+ requiredValueProbe,
234
245
  routerChatProbe,
235
246
  sandboxAuthProbe,
236
247
  httpHeadProbe,
237
248
  runPreflight,
238
249
  formatPreflightReport
239
250
  };
240
- //# sourceMappingURL=chunk-JTLYXUEV.js.map
251
+ //# sourceMappingURL=chunk-5FAKBTCK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/preflight/index.ts"],"sourcesContent":["/**\n * `/preflight` — deploy-time secret-liveness probes.\n *\n * WHY THIS EXISTS: on 2026-07-15 four secrets were simultaneously dead in one\n * production day — a dead `SANDBOX_API_KEY`, a stale `SANDBOX_API_URL`, and a\n * dead LiteLLM router key + URL. Each one was present in `wrangler secret list`\n * (so nothing looked wrong) yet invalid against its live endpoint, and nothing\n * anywhere checked liveness. CI cannot hold production secrets, so this binds\n * at DEPLOY time instead: a product declares a handful of probes built from its\n * real env, the deploy workflow runs `agent-app-preflight` as a step, and a\n * dead secret fails the deploy with a message that names exactly which secret\n * to rotate.\n *\n * A probe is `{ name, run, critical? }`; `run()` returns `{ ok, detail? }`.\n * The standard builders (`requiredValueProbe`, `routerChatProbe`,\n * `sandboxAuthProbe`, `httpHeadProbe`) each take explicit config — they read\n * nothing global — so the same probe runs identically in a deploy step, a test,\n * or a local check. `runPreflight` fans\n * the probes out, times each, and folds them into a pass/fail report: any\n * failed CRITICAL probe fails the whole run (probes are critical by default).\n *\n * Server-only: probes carry live API keys and hit live endpoints. This subpath\n * must never reach a browser bundle.\n */\n\n/** One probe's outcome. `detail` should name the secret to rotate on failure. */\nexport interface PreflightProbeResult {\n ok: boolean\n detail?: string\n}\n\n/**\n * A liveness probe. `run` performs one cheap live call and maps the result to\n * `{ ok, detail }`. `critical` defaults to `true` — a failed critical probe\n * fails the whole preflight (and the deploy).\n */\nexport interface PreflightProbe {\n name: string\n run: () => Promise<PreflightProbeResult>\n critical?: boolean\n}\n\n/** Per-probe verdict enriched with the resolved criticality and measured latency. */\nexport interface PreflightProbeVerdict {\n name: string\n ok: boolean\n critical: boolean\n latencyMs: number\n detail?: string\n}\n\n/** Aggregate of every probe verdict plus the overall pass/fail decision. */\nexport interface PreflightReport {\n /** `false` if any critical probe failed. */\n ok: boolean\n probes: PreflightProbeVerdict[]\n passed: number\n failed: number\n criticalFailures: number\n durationMs: number\n}\n\n/** Deploy-time deadline for a single probe. Cold upstreams are slow; a dead\n * endpoint should still fail fast, so 10s is the ceiling, not the target. */\nconst DEFAULT_TIMEOUT_MS = 10_000\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now()\n}\n\nfunction isAbortLike(err: unknown): boolean {\n return err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')\n}\n\n/** Strip bearer tokens / key material before an upstream string is surfaced in\n * a report (deploy logs are not always private). */\nfunction sanitizeUpstreamMessage(input: unknown): string {\n const message = input instanceof Error ? input.message : String(input)\n return message\n .replace(/Bearer\\s+[^\\s]+/gi, 'Bearer [redacted]')\n .replace(/\\b(?:sk|pk|tc)[_-][A-Za-z0-9_-]{8,}\\b/g, '[redacted-key]')\n}\n\nfunction snippet(body: string): string {\n const trimmed = body.trim()\n if (!trimmed) return ''\n const clipped = trimmed.length > 180 ? `${trimmed.slice(0, 180)}…` : trimmed\n return `: ${sanitizeUpstreamMessage(clipped)}`\n}\n\ntype ProbeOutcome =\n | { kind: 'status'; status: number; bodyText: string }\n | { kind: 'timeout'; timeoutMs: number }\n | { kind: 'network'; message: string }\n\ninterface HttpProbeCall {\n fetchImpl: typeof fetch\n url: string\n method: string\n headers?: Record<string, string>\n body?: string\n timeoutMs: number\n}\n\n/** One live HTTP call, folded to a probe outcome. Never throws: a timeout, a\n * DNS/connection failure, and any thrown error all become an outcome so the\n * probe can classify them into an actionable detail. */\nasync function runHttp(call: HttpProbeCall): Promise<ProbeOutcome> {\n let response: Response\n try {\n response = await call.fetchImpl(call.url, {\n method: call.method,\n headers: call.headers,\n body: call.body,\n signal: AbortSignal.timeout(call.timeoutMs),\n })\n } catch (err) {\n if (isAbortLike(err)) return { kind: 'timeout', timeoutMs: call.timeoutMs }\n return { kind: 'network', message: sanitizeUpstreamMessage(err) }\n }\n let bodyText = ''\n try {\n bodyText = await response.text()\n } catch {\n bodyText = ''\n }\n return { kind: 'status', status: response.status, bodyText }\n}\n\ninterface AuthedClassifyContext {\n /** Full endpoint reached, for the message. */\n endpoint: string\n /** How to name the API-key secret when the endpoint reports auth failure. */\n keyLabel: string\n /** How to name the URL secret when the endpoint is unreachable. */\n urlLabel: string\n}\n\n/**\n * Shared classification for an authed liveness endpoint (router, sandbox):\n * 2xx → live; 401/403 → the KEY is dead, name it; 503 → the UPSTREAM is down,\n * the key still looks valid, don't rotate; timeout / unreachable → the URL is\n * likely stale, name it; anything else → an unexpected status with a snippet.\n */\nfunction classifyAuthed(outcome: ProbeOutcome, ctx: AuthedClassifyContext): PreflightProbeResult {\n switch (outcome.kind) {\n case 'status': {\n const { status, bodyText } = outcome\n if (status >= 200 && status < 300) return { ok: true, detail: `${status} OK` }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n detail: `DEAD KEY — ${ctx.endpoint} returned ${status}; rotate ${ctx.keyLabel}`,\n }\n }\n if (status === 503) {\n return {\n ok: false,\n detail: `UPSTREAM DOWN — ${ctx.endpoint} returned 503; ${ctx.keyLabel} still looks valid, retry or check the provider (do NOT rotate)`,\n }\n }\n return { ok: false, detail: `UNEXPECTED ${status} from ${ctx.endpoint}${snippet(bodyText)}` }\n }\n case 'timeout':\n return {\n ok: false,\n detail: `TIMEOUT after ${outcome.timeoutMs}ms reaching ${ctx.endpoint} — check ${ctx.urlLabel}`,\n }\n case 'network':\n return {\n ok: false,\n detail: `UNREACHABLE ${ctx.endpoint} (${outcome.message}) — check ${ctx.urlLabel}`,\n }\n }\n}\n\nfunction trimTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\n// --- Standard probe builders --------------------------------------------------\n\n/** Configuration for a required non-empty production value. */\nexport interface RequiredValueProbeConfig {\n /** Human-readable value name, normally the environment variable name. */\n name: string\n /** Value supplied by the caller. It is checked but never included in output. */\n value: string | null | undefined\n /** Default `true`. */\n critical?: boolean\n /** Failure detail. Defaults to `NAME is unset`. */\n missingDetail?: string\n}\n\n/**\n * Require a non-empty string without ever printing its value.\n *\n * This covers local signing keys and other values that have no external\n * endpoint to probe. Credentials with a live API should use a liveness probe\n * instead, because presence alone cannot detect an expired key.\n */\nexport function requiredValueProbe(config: RequiredValueProbeConfig): PreflightProbe {\n return {\n name: `required:${config.name}`,\n critical: config.critical,\n run: async () => {\n const ok = typeof config.value === 'string' && config.value.trim().length > 0\n return { ok, detail: ok ? undefined : (config.missingDetail ?? `${config.name} is unset`) }\n },\n }\n}\n\n/** Define configuration options for probing an LLM router with authentication and model details */\nexport interface RouterChatProbeConfig {\n /** LLM router base URL (LiteLLM / OpenAI-compatible), e.g. `https://router…`. */\n baseUrl: string\n apiKey: string\n /** A cheap model id available on the router. */\n model: string\n /** Probe name in the report. Default `'router-chat'`. */\n name?: string\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the API key, named verbatim in a dead-key failure. */\n keySecret?: string\n /** Env-var name of the base URL, named verbatim in an unreachable failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Probe an OpenAI-compatible LLM router with one cheap `POST /chat/completions`\n * (`max_tokens: 1`). 200 → live; 401/403 → dead router key; 503 → upstream\n * provider down (key still valid); timeout / unreachable → check the router URL.\n */\nexport function routerChatProbe(config: RouterChatProbeConfig): PreflightProbe {\n const keyLabel = config.keySecret ?? 'the router API key'\n const urlLabel = config.urlSecret ?? 'the router base URL'\n return {\n name: config.name ?? 'router-chat',\n critical: config.critical,\n run: async () => {\n const base = trimTrailingSlash(config.baseUrl)\n const endpoint = `${base}/chat/completions`\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: endpoint,\n method: 'POST',\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: config.model,\n messages: [{ role: 'user', content: 'ping' }],\n max_tokens: 1,\n }),\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n return classifyAuthed(outcome, { endpoint, keyLabel, urlLabel })\n },\n }\n}\n\n/** Define configuration options for probing sandbox authentication endpoints */\nexport interface SandboxAuthProbeConfig {\n /** Sandbox API base URL. */\n baseUrl: string\n apiKey: string\n /** Probe name in the report. Default `'sandbox-auth'`. */\n name?: string\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the API key, named verbatim in a dead-key failure. */\n keySecret?: string\n /** Env-var name of the base URL, named verbatim in an unreachable failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Probe the sandbox API with a cheap authed `GET /v1/sandboxes?limit=1`.\n * 200 → live; 401/403 → dead sandbox key; 503 → sandbox platform down (key\n * still valid); timeout / unreachable → check the sandbox URL.\n */\nexport function sandboxAuthProbe(config: SandboxAuthProbeConfig): PreflightProbe {\n const keyLabel = config.keySecret ?? 'the sandbox API key'\n const urlLabel = config.urlSecret ?? 'the sandbox base URL'\n return {\n name: config.name ?? 'sandbox-auth',\n critical: config.critical,\n run: async () => {\n const base = trimTrailingSlash(config.baseUrl)\n const endpoint = `${base}/v1/sandboxes?limit=1`\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: endpoint,\n method: 'GET',\n headers: { Authorization: `Bearer ${config.apiKey}` },\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n return classifyAuthed(outcome, { endpoint, keyLabel, urlLabel })\n },\n }\n}\n\n/** Define configuration options for performing an HTTP HEAD probe to check URL availability */\nexport interface HttpHeadProbeConfig {\n /** Probe name in the report. */\n name: string\n /** URL to `HEAD`. */\n url: string\n /**\n * Accepted status(es). A single number requires an exact match; an array\n * requires membership. Omitted → any 2xx/3xx (the host is up and the path\n * resolves) counts as live.\n */\n expectStatus?: number | number[]\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the URL, named verbatim in a failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\nfunction statusMatches(status: number, expect?: number | number[]): boolean {\n if (expect === undefined) return status >= 200 && status < 400\n if (Array.isArray(expect)) return expect.includes(status)\n return status === expect\n}\n\nfunction describeExpected(expect?: number | number[]): string {\n if (expect === undefined) return '2xx/3xx'\n if (Array.isArray(expect)) return expect.join(' or ')\n return String(expect)\n}\n\n/**\n * Probe a plain reachability endpoint (e.g. a platform base URL) with a `HEAD`.\n * Confirms the URL is live and resolving — the class of failure behind a stale\n * platform URL that still sits in the secret store.\n */\nexport function httpHeadProbe(config: HttpHeadProbeConfig): PreflightProbe {\n const urlLabel = config.urlSecret ?? `the URL for ${config.name}`\n return {\n name: config.name,\n critical: config.critical,\n run: async () => {\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: config.url,\n method: 'HEAD',\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n switch (outcome.kind) {\n case 'status': {\n if (statusMatches(outcome.status, config.expectStatus)) {\n return { ok: true, detail: `${outcome.status} OK` }\n }\n return {\n ok: false,\n detail: `UNEXPECTED ${outcome.status} from ${config.url} (expected ${describeExpected(config.expectStatus)}) — check ${urlLabel}`,\n }\n }\n case 'timeout':\n return {\n ok: false,\n detail: `TIMEOUT after ${outcome.timeoutMs}ms reaching ${config.url} — check ${urlLabel}`,\n }\n case 'network':\n return {\n ok: false,\n detail: `UNREACHABLE ${config.url} (${outcome.message}) — check ${urlLabel}`,\n }\n }\n },\n }\n}\n\n// --- Runner + report ----------------------------------------------------------\n\nasync function runOne(probe: PreflightProbe): Promise<PreflightProbeVerdict> {\n const critical = probe.critical ?? true\n const start = nowMs()\n try {\n const result = await probe.run()\n return {\n name: probe.name,\n ok: result.ok,\n critical,\n latencyMs: Math.round(nowMs() - start),\n detail: result.detail,\n }\n } catch (err) {\n return {\n name: probe.name,\n ok: false,\n critical,\n latencyMs: Math.round(nowMs() - start),\n detail: `probe threw: ${sanitizeUpstreamMessage(err)}`,\n }\n }\n}\n\n/**\n * Run every probe (concurrently), time each, and fold into a report. The run\n * fails (`ok: false`) iff a critical probe fails; a failed non-critical probe\n * is a warning that does not block the deploy.\n */\nexport async function runPreflight(probes: PreflightProbe[]): Promise<PreflightReport> {\n const start = nowMs()\n const verdicts = await Promise.all(probes.map(runOne))\n const failed = verdicts.filter((v) => !v.ok)\n const criticalFailures = failed.filter((v) => v.critical).length\n return {\n ok: criticalFailures === 0,\n probes: verdicts,\n passed: verdicts.length - failed.length,\n failed: failed.length,\n criticalFailures,\n durationMs: Math.round(nowMs() - start),\n }\n}\n\ninterface FormatRow {\n status: string\n name: string\n latency: string\n detail: string\n}\n\n/** Render a report as an aligned, operator-readable table + verdict line. Pure\n * (no I/O) so it is trivially testable and reusable by the bin. */\nexport function formatPreflightReport(report: PreflightReport): string {\n const header: FormatRow = { status: 'STATUS', name: 'PROBE', latency: 'LATENCY', detail: 'DETAIL' }\n const rows: FormatRow[] = report.probes.map((p) => ({\n status: p.ok ? 'PASS' : p.critical ? 'FAIL' : 'WARN',\n name: p.name,\n latency: `${p.latencyMs}ms`,\n detail: p.detail ?? '',\n }))\n const statusW = Math.max(header.status.length, ...rows.map((r) => r.status.length))\n const nameW = Math.max(header.name.length, ...rows.map((r) => r.name.length))\n const latencyW = Math.max(header.latency.length, ...rows.map((r) => r.latency.length))\n const line = (r: FormatRow): string =>\n `${r.status.padEnd(statusW)} ${r.name.padEnd(nameW)} ${r.latency.padStart(latencyW)} ${r.detail}`.trimEnd()\n\n const out: string[] = [\n line(header),\n `${'-'.repeat(statusW)} ${'-'.repeat(nameW)} ${'-'.repeat(latencyW)} ------`,\n ...rows.map(line),\n '',\n ]\n if (report.ok) {\n const warn = report.failed > 0 ? ` (${report.failed} non-critical warning(s))` : ''\n out.push(`Preflight PASSED — ${report.passed}/${report.probes.length} probe(s) live${warn}`)\n } else {\n const dead = report.probes\n .filter((p) => !p.ok && p.critical)\n .map((p) => p.name)\n .join(', ')\n out.push(`Preflight FAILED — ${report.criticalFailures} critical probe(s) dead: ${dead}`)\n out.push('Rotate the secret named in each FAIL row above, then redeploy.')\n }\n return out.join('\\n')\n}\n"],"mappings":";AAgEA,IAAM,qBAAqB;AAE3B,SAAS,QAAgB;AACvB,SAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AAEA,SAAS,YAAY,KAAuB;AAC1C,SAAO,eAAe,UAAU,IAAI,SAAS,kBAAkB,IAAI,SAAS;AAC9E;AAIA,SAAS,wBAAwB,OAAwB;AACvD,QAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AACrE,SAAO,QACJ,QAAQ,qBAAqB,mBAAmB,EAChD,QAAQ,0CAA0C,gBAAgB;AACvE;AAEA,SAAS,QAAQ,MAAsB;AACrC,QAAM,UAAU,KAAK,KAAK;AAC1B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,UAAU,QAAQ,SAAS,MAAM,GAAG,QAAQ,MAAM,GAAG,GAAG,CAAC,WAAM;AACrE,SAAO,KAAK,wBAAwB,OAAO,CAAC;AAC9C;AAmBA,eAAe,QAAQ,MAA4C;AACjE,MAAI;AACJ,MAAI;AACF,eAAW,MAAM,KAAK,UAAU,KAAK,KAAK;AAA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AAA,IAChB;AAAA,EACF;AACA,MAAI,OAAO,IAAI;AACb,UAAM,OAAO,OAAO,SAAS,IAAI,KAAK,OAAO,MAAM,8BAA8B;AACjF,QAAI,KAAK,2BAAsB,OAAO,MAAM,IAAI,OAAO,OAAO,MAAM,iBAAiB,IAAI,EAAE;AAAA,EAC7F,OAAO;AACL,UAAM,OAAO,OAAO,OACjB,OAAO,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,QAAQ,EACjC,IAAI,CAAC,MAAM,EAAE,IAAI,EACjB,KAAK,IAAI;AACZ,QAAI,KAAK,2BAAsB,OAAO,gBAAgB,4BAA4B,IAAI,EAAE;AACxF,QAAI,KAAK,gEAAgE;AAAA,EAC3E;AACA,SAAO,IAAI,KAAK,IAAI;AACtB;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  formatPreflightReport,
4
4
  runPreflight
5
- } from "../chunk-JTLYXUEV.js";
5
+ } from "../chunk-5FAKBTCK.js";
6
6
 
7
7
  // src/preflight/cli.ts
8
8
  import { pathToFileURL } from "url";
@@ -12,9 +12,10 @@
12
12
  * to rotate.
13
13
  *
14
14
  * A probe is `{ name, run, critical? }`; `run()` returns `{ ok, detail? }`.
15
- * The standard builders (`routerChatProbe`, `sandboxAuthProbe`, `httpHeadProbe`)
16
- * each take explicit config — they read nothing global — so the same probe runs
17
- * identically in a deploy step, a test, or a local check. `runPreflight` fans
15
+ * The standard builders (`requiredValueProbe`, `routerChatProbe`,
16
+ * `sandboxAuthProbe`, `httpHeadProbe`) each take explicit config — they read
17
+ * nothing global — so the same probe runs identically in a deploy step, a test,
18
+ * or a local check. `runPreflight` fans
18
19
  * the probes out, times each, and folds them into a pass/fail report: any
19
20
  * failed CRITICAL probe fails the whole run (probes are critical by default).
20
21
  *
@@ -54,6 +55,25 @@ interface PreflightReport {
54
55
  criticalFailures: number;
55
56
  durationMs: number;
56
57
  }
58
+ /** Configuration for a required non-empty production value. */
59
+ interface RequiredValueProbeConfig {
60
+ /** Human-readable value name, normally the environment variable name. */
61
+ name: string;
62
+ /** Value supplied by the caller. It is checked but never included in output. */
63
+ value: string | null | undefined;
64
+ /** Default `true`. */
65
+ critical?: boolean;
66
+ /** Failure detail. Defaults to `NAME is unset`. */
67
+ missingDetail?: string;
68
+ }
69
+ /**
70
+ * Require a non-empty string without ever printing its value.
71
+ *
72
+ * This covers local signing keys and other values that have no external
73
+ * endpoint to probe. Credentials with a live API should use a liveness probe
74
+ * instead, because presence alone cannot detect an expired key.
75
+ */
76
+ declare function requiredValueProbe(config: RequiredValueProbeConfig): PreflightProbe;
57
77
  /** Define configuration options for probing an LLM router with authentication and model details */
58
78
  interface RouterChatProbeConfig {
59
79
  /** LLM router base URL (LiteLLM / OpenAI-compatible), e.g. `https://router…`. */
@@ -141,4 +161,4 @@ declare function runPreflight(probes: PreflightProbe[]): Promise<PreflightReport
141
161
  * (no I/O) so it is trivially testable and reusable by the bin. */
142
162
  declare function formatPreflightReport(report: PreflightReport): string;
143
163
 
144
- export { type HttpHeadProbeConfig, type PreflightProbe, type PreflightProbeResult, type PreflightProbeVerdict, type PreflightReport, type RouterChatProbeConfig, type SandboxAuthProbeConfig, formatPreflightReport, httpHeadProbe, routerChatProbe, runPreflight, sandboxAuthProbe };
164
+ export { type HttpHeadProbeConfig, type PreflightProbe, type PreflightProbeResult, type PreflightProbeVerdict, type PreflightReport, type RequiredValueProbeConfig, type RouterChatProbeConfig, type SandboxAuthProbeConfig, formatPreflightReport, httpHeadProbe, requiredValueProbe, routerChatProbe, runPreflight, sandboxAuthProbe };
@@ -1,13 +1,15 @@
1
1
  import {
2
2
  formatPreflightReport,
3
3
  httpHeadProbe,
4
+ requiredValueProbe,
4
5
  routerChatProbe,
5
6
  runPreflight,
6
7
  sandboxAuthProbe
7
- } from "../chunk-JTLYXUEV.js";
8
+ } from "../chunk-5FAKBTCK.js";
8
9
  export {
9
10
  formatPreflightReport,
10
11
  httpHeadProbe,
12
+ requiredValueProbe,
11
13
  routerChatProbe,
12
14
  runPreflight,
13
15
  sandboxAuthProbe
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tangle-network/agent-app",
3
- "version": "0.44.55",
3
+ "version": "0.44.56",
4
4
  "packageManager": "pnpm@11.17.0",
5
5
  "description": "Build agent applications with typed chat, tools, sandboxes, integrations, billing, and evaluation.",
6
6
  "keywords": [
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/preflight/index.ts"],"sourcesContent":["/**\n * `/preflight` — deploy-time secret-liveness probes.\n *\n * WHY THIS EXISTS: on 2026-07-15 four secrets were simultaneously dead in one\n * production day — a dead `SANDBOX_API_KEY`, a stale `SANDBOX_API_URL`, and a\n * dead LiteLLM router key + URL. Each one was present in `wrangler secret list`\n * (so nothing looked wrong) yet invalid against its live endpoint, and nothing\n * anywhere checked liveness. CI cannot hold production secrets, so this binds\n * at DEPLOY time instead: a product declares a handful of probes built from its\n * real env, the deploy workflow runs `agent-app-preflight` as a step, and a\n * dead secret fails the deploy with a message that names exactly which secret\n * to rotate.\n *\n * A probe is `{ name, run, critical? }`; `run()` returns `{ ok, detail? }`.\n * The standard builders (`routerChatProbe`, `sandboxAuthProbe`, `httpHeadProbe`)\n * each take explicit config — they read nothing global — so the same probe runs\n * identically in a deploy step, a test, or a local check. `runPreflight` fans\n * the probes out, times each, and folds them into a pass/fail report: any\n * failed CRITICAL probe fails the whole run (probes are critical by default).\n *\n * Server-only: probes carry live API keys and hit live endpoints. This subpath\n * must never reach a browser bundle.\n */\n\n/** One probe's outcome. `detail` should name the secret to rotate on failure. */\nexport interface PreflightProbeResult {\n ok: boolean\n detail?: string\n}\n\n/**\n * A liveness probe. `run` performs one cheap live call and maps the result to\n * `{ ok, detail }`. `critical` defaults to `true` — a failed critical probe\n * fails the whole preflight (and the deploy).\n */\nexport interface PreflightProbe {\n name: string\n run: () => Promise<PreflightProbeResult>\n critical?: boolean\n}\n\n/** Per-probe verdict enriched with the resolved criticality and measured latency. */\nexport interface PreflightProbeVerdict {\n name: string\n ok: boolean\n critical: boolean\n latencyMs: number\n detail?: string\n}\n\n/** Aggregate of every probe verdict plus the overall pass/fail decision. */\nexport interface PreflightReport {\n /** `false` if any critical probe failed. */\n ok: boolean\n probes: PreflightProbeVerdict[]\n passed: number\n failed: number\n criticalFailures: number\n durationMs: number\n}\n\n/** Deploy-time deadline for a single probe. Cold upstreams are slow; a dead\n * endpoint should still fail fast, so 10s is the ceiling, not the target. */\nconst DEFAULT_TIMEOUT_MS = 10_000\n\nfunction nowMs(): number {\n return typeof performance !== 'undefined' ? performance.now() : Date.now()\n}\n\nfunction isAbortLike(err: unknown): boolean {\n return err instanceof Error && (err.name === 'TimeoutError' || err.name === 'AbortError')\n}\n\n/** Strip bearer tokens / key material before an upstream string is surfaced in\n * a report (deploy logs are not always private). */\nfunction sanitizeUpstreamMessage(input: unknown): string {\n const message = input instanceof Error ? input.message : String(input)\n return message\n .replace(/Bearer\\s+[^\\s]+/gi, 'Bearer [redacted]')\n .replace(/\\b(?:sk|pk|tc)[_-][A-Za-z0-9_-]{8,}\\b/g, '[redacted-key]')\n}\n\nfunction snippet(body: string): string {\n const trimmed = body.trim()\n if (!trimmed) return ''\n const clipped = trimmed.length > 180 ? `${trimmed.slice(0, 180)}…` : trimmed\n return `: ${sanitizeUpstreamMessage(clipped)}`\n}\n\ntype ProbeOutcome =\n | { kind: 'status'; status: number; bodyText: string }\n | { kind: 'timeout'; timeoutMs: number }\n | { kind: 'network'; message: string }\n\ninterface HttpProbeCall {\n fetchImpl: typeof fetch\n url: string\n method: string\n headers?: Record<string, string>\n body?: string\n timeoutMs: number\n}\n\n/** One live HTTP call, folded to a probe outcome. Never throws: a timeout, a\n * DNS/connection failure, and any thrown error all become an outcome so the\n * probe can classify them into an actionable detail. */\nasync function runHttp(call: HttpProbeCall): Promise<ProbeOutcome> {\n let response: Response\n try {\n response = await call.fetchImpl(call.url, {\n method: call.method,\n headers: call.headers,\n body: call.body,\n signal: AbortSignal.timeout(call.timeoutMs),\n })\n } catch (err) {\n if (isAbortLike(err)) return { kind: 'timeout', timeoutMs: call.timeoutMs }\n return { kind: 'network', message: sanitizeUpstreamMessage(err) }\n }\n let bodyText = ''\n try {\n bodyText = await response.text()\n } catch {\n bodyText = ''\n }\n return { kind: 'status', status: response.status, bodyText }\n}\n\ninterface AuthedClassifyContext {\n /** Full endpoint reached, for the message. */\n endpoint: string\n /** How to name the API-key secret when the endpoint reports auth failure. */\n keyLabel: string\n /** How to name the URL secret when the endpoint is unreachable. */\n urlLabel: string\n}\n\n/**\n * Shared classification for an authed liveness endpoint (router, sandbox):\n * 2xx → live; 401/403 → the KEY is dead, name it; 503 → the UPSTREAM is down,\n * the key still looks valid, don't rotate; timeout / unreachable → the URL is\n * likely stale, name it; anything else → an unexpected status with a snippet.\n */\nfunction classifyAuthed(outcome: ProbeOutcome, ctx: AuthedClassifyContext): PreflightProbeResult {\n switch (outcome.kind) {\n case 'status': {\n const { status, bodyText } = outcome\n if (status >= 200 && status < 300) return { ok: true, detail: `${status} OK` }\n if (status === 401 || status === 403) {\n return {\n ok: false,\n detail: `DEAD KEY — ${ctx.endpoint} returned ${status}; rotate ${ctx.keyLabel}`,\n }\n }\n if (status === 503) {\n return {\n ok: false,\n detail: `UPSTREAM DOWN — ${ctx.endpoint} returned 503; ${ctx.keyLabel} still looks valid, retry or check the provider (do NOT rotate)`,\n }\n }\n return { ok: false, detail: `UNEXPECTED ${status} from ${ctx.endpoint}${snippet(bodyText)}` }\n }\n case 'timeout':\n return {\n ok: false,\n detail: `TIMEOUT after ${outcome.timeoutMs}ms reaching ${ctx.endpoint} — check ${ctx.urlLabel}`,\n }\n case 'network':\n return {\n ok: false,\n detail: `UNREACHABLE ${ctx.endpoint} (${outcome.message}) — check ${ctx.urlLabel}`,\n }\n }\n}\n\nfunction trimTrailingSlash(url: string): string {\n return url.replace(/\\/+$/, '')\n}\n\n// --- Standard probe builders --------------------------------------------------\n\n/** Define configuration options for probing an LLM router with authentication and model details */\nexport interface RouterChatProbeConfig {\n /** LLM router base URL (LiteLLM / OpenAI-compatible), e.g. `https://router…`. */\n baseUrl: string\n apiKey: string\n /** A cheap model id available on the router. */\n model: string\n /** Probe name in the report. Default `'router-chat'`. */\n name?: string\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the API key, named verbatim in a dead-key failure. */\n keySecret?: string\n /** Env-var name of the base URL, named verbatim in an unreachable failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Probe an OpenAI-compatible LLM router with one cheap `POST /chat/completions`\n * (`max_tokens: 1`). 200 → live; 401/403 → dead router key; 503 → upstream\n * provider down (key still valid); timeout / unreachable → check the router URL.\n */\nexport function routerChatProbe(config: RouterChatProbeConfig): PreflightProbe {\n const keyLabel = config.keySecret ?? 'the router API key'\n const urlLabel = config.urlSecret ?? 'the router base URL'\n return {\n name: config.name ?? 'router-chat',\n critical: config.critical,\n run: async () => {\n const base = trimTrailingSlash(config.baseUrl)\n const endpoint = `${base}/chat/completions`\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: endpoint,\n method: 'POST',\n headers: {\n Authorization: `Bearer ${config.apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: config.model,\n messages: [{ role: 'user', content: 'ping' }],\n max_tokens: 1,\n }),\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n return classifyAuthed(outcome, { endpoint, keyLabel, urlLabel })\n },\n }\n}\n\n/** Define configuration options for probing sandbox authentication endpoints */\nexport interface SandboxAuthProbeConfig {\n /** Sandbox API base URL. */\n baseUrl: string\n apiKey: string\n /** Probe name in the report. Default `'sandbox-auth'`. */\n name?: string\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the API key, named verbatim in a dead-key failure. */\n keySecret?: string\n /** Env-var name of the base URL, named verbatim in an unreachable failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\n/**\n * Probe the sandbox API with a cheap authed `GET /v1/sandboxes?limit=1`.\n * 200 → live; 401/403 → dead sandbox key; 503 → sandbox platform down (key\n * still valid); timeout / unreachable → check the sandbox URL.\n */\nexport function sandboxAuthProbe(config: SandboxAuthProbeConfig): PreflightProbe {\n const keyLabel = config.keySecret ?? 'the sandbox API key'\n const urlLabel = config.urlSecret ?? 'the sandbox base URL'\n return {\n name: config.name ?? 'sandbox-auth',\n critical: config.critical,\n run: async () => {\n const base = trimTrailingSlash(config.baseUrl)\n const endpoint = `${base}/v1/sandboxes?limit=1`\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: endpoint,\n method: 'GET',\n headers: { Authorization: `Bearer ${config.apiKey}` },\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n return classifyAuthed(outcome, { endpoint, keyLabel, urlLabel })\n },\n }\n}\n\n/** Define configuration options for performing an HTTP HEAD probe to check URL availability */\nexport interface HttpHeadProbeConfig {\n /** Probe name in the report. */\n name: string\n /** URL to `HEAD`. */\n url: string\n /**\n * Accepted status(es). A single number requires an exact match; an array\n * requires membership. Omitted → any 2xx/3xx (the host is up and the path\n * resolves) counts as live.\n */\n expectStatus?: number | number[]\n /** Default `true`. */\n critical?: boolean\n /** Env-var name of the URL, named verbatim in a failure. */\n urlSecret?: string\n /** Per-probe deadline. Default 10s. */\n timeoutMs?: number\n /** Injection seam for tests; defaults to global `fetch`. */\n fetchImpl?: typeof fetch\n}\n\nfunction statusMatches(status: number, expect?: number | number[]): boolean {\n if (expect === undefined) return status >= 200 && status < 400\n if (Array.isArray(expect)) return expect.includes(status)\n return status === expect\n}\n\nfunction describeExpected(expect?: number | number[]): string {\n if (expect === undefined) return '2xx/3xx'\n if (Array.isArray(expect)) return expect.join(' or ')\n return String(expect)\n}\n\n/**\n * Probe a plain reachability endpoint (e.g. a platform base URL) with a `HEAD`.\n * Confirms the URL is live and resolving — the class of failure behind a stale\n * platform URL that still sits in the secret store.\n */\nexport function httpHeadProbe(config: HttpHeadProbeConfig): PreflightProbe {\n const urlLabel = config.urlSecret ?? `the URL for ${config.name}`\n return {\n name: config.name,\n critical: config.critical,\n run: async () => {\n const outcome = await runHttp({\n fetchImpl: config.fetchImpl ?? fetch,\n url: config.url,\n method: 'HEAD',\n timeoutMs: config.timeoutMs ?? DEFAULT_TIMEOUT_MS,\n })\n switch (outcome.kind) {\n case 'status': {\n if (statusMatches(outcome.status, config.expectStatus)) {\n return { ok: true, detail: `${outcome.status} OK` }\n }\n return {\n ok: false,\n detail: `UNEXPECTED ${outcome.status} from ${config.url} (expected ${describeExpected(config.expectStatus)}) — check ${urlLabel}`,\n }\n }\n case 'timeout':\n return {\n ok: false,\n detail: `TIMEOUT after ${outcome.timeoutMs}ms reaching ${config.url} — check ${urlLabel}`,\n }\n case 'network':\n return {\n ok: false,\n detail: `UNREACHABLE ${config.url} (${outcome.message}) — check ${urlLabel}`,\n }\n }\n },\n }\n}\n\n// --- Runner + report ----------------------------------------------------------\n\nasync function runOne(probe: PreflightProbe): Promise<PreflightProbeVerdict> {\n const critical = probe.critical ?? true\n const start = nowMs()\n try {\n const result = await probe.run()\n return {\n name: probe.name,\n ok: result.ok,\n critical,\n latencyMs: Math.round(nowMs() - start),\n detail: result.detail,\n }\n } catch (err) {\n return {\n name: probe.name,\n ok: false,\n critical,\n latencyMs: Math.round(nowMs() - start),\n detail: `probe threw: ${sanitizeUpstreamMessage(err)}`,\n }\n }\n}\n\n/**\n * Run every probe (concurrently), time each, and fold into a report. The run\n * fails (`ok: false`) iff a critical probe fails; a failed non-critical probe\n * is a warning that does not block the deploy.\n */\nexport async function runPreflight(probes: PreflightProbe[]): Promise<PreflightReport> {\n const start = nowMs()\n const verdicts = await Promise.all(probes.map(runOne))\n const failed = verdicts.filter((v) => !v.ok)\n const criticalFailures = failed.filter((v) => v.critical).length\n return {\n ok: criticalFailures === 0,\n probes: verdicts,\n passed: verdicts.length - failed.length,\n failed: failed.length,\n criticalFailures,\n durationMs: Math.round(nowMs() - start),\n }\n}\n\ninterface FormatRow {\n status: string\n name: string\n latency: string\n detail: string\n}\n\n/** Render a report as an aligned, operator-readable table + verdict line. Pure\n * (no I/O) so it is trivially testable and reusable by the bin. */\nexport function formatPreflightReport(report: PreflightReport): string {\n const header: FormatRow = { status: 'STATUS', name: 'PROBE', latency: 'LATENCY', detail: 'DETAIL' }\n const rows: FormatRow[] = report.probes.map((p) => ({\n status: p.ok ? 'PASS' : p.critical ? 'FAIL' : 'WARN',\n name: p.name,\n latency: `${p.latencyMs}ms`,\n detail: p.detail ?? '',\n }))\n const statusW = Math.max(header.status.length, ...rows.map((r) => r.status.length))\n const nameW = Math.max(header.name.length, ...rows.map((r) => r.name.length))\n const latencyW = Math.max(header.latency.length, ...rows.map((r) => r.latency.length))\n const line = (r: FormatRow): string =>\n `${r.status.padEnd(statusW)} ${r.name.padEnd(nameW)} ${r.latency.padStart(latencyW)} ${r.detail}`.trimEnd()\n\n const out: string[] = [\n line(header),\n `${'-'.repeat(statusW)} ${'-'.repeat(nameW)} ${'-'.repeat(latencyW)} ------`,\n ...rows.map(line),\n '',\n ]\n if (report.ok) {\n const warn = report.failed > 0 ? ` (${report.failed} non-critical warning(s))` : ''\n out.push(`Preflight PASSED — ${report.passed}/${report.probes.length} probe(s) live${warn}`)\n } else {\n const dead = report.probes\n .filter((p) => !p.ok && p.critical)\n .map((p) => p.name)\n .join(', ')\n out.push(`Preflight FAILED — ${report.criticalFailures} critical probe(s) dead: ${dead}`)\n out.push('Rotate the secret named in each FAIL row above, then redeploy.')\n }\n return out.join('\\n')\n}\n"],"mappings":";AA+DA,IAAM,qBAAqB;AAE3B,SAAS,QAAgB;AACvB,SAAO,OAAO,gBAAgB,cAAc,YAAY,IAAI,IAAI,KAAK,IAAI;AAC3E;AAEA,SAAS,YAAY,KAAuB;AA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