@tangle-network/agent-app 0.63.30 → 0.63.32

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.
Files changed (133) hide show
  1. package/dist/{DesignCanvas-3DGZQOD7.js → DesignCanvas-VKZ7Y3JU.js} +2 -3
  2. package/dist/{DesignCanvasEditor-OG4QY5WJ.js → DesignCanvasEditor-3V53YLLZ.js} +2 -3
  3. package/dist/agent-profiles/d1.js +4 -3
  4. package/dist/agent-profiles/d1.js.map +1 -1
  5. package/dist/agent-profiles/index.js +4 -3
  6. package/dist/alerting/github.d.ts +33 -0
  7. package/dist/alerting/index.d.ts +1 -0
  8. package/dist/alerting/index.js +47 -0
  9. package/dist/alerting/index.js.map +1 -1
  10. package/dist/app-auth/index.js +1 -2
  11. package/dist/app-auth/index.js.map +1 -1
  12. package/dist/assistant/index.js +4 -4
  13. package/dist/billing/index.d.ts +15 -0
  14. package/dist/billing/index.js +5 -3
  15. package/dist/chat-routes/index.js +15 -14
  16. package/dist/chat-routes/index.js.map +1 -1
  17. package/dist/chat-store/index.js +34 -4
  18. package/dist/chat-store/index.js.map +1 -1
  19. package/dist/chat-store/schema.d.ts +286 -0
  20. package/dist/{chunk-6JEDSKFH.js → chunk-2SDX3OC4.js} +32 -24
  21. package/dist/{chunk-6JEDSKFH.js.map → chunk-2SDX3OC4.js.map} +1 -1
  22. package/dist/{chunk-QLZ6A73E.js → chunk-4CEIZZTH.js} +9 -9
  23. package/dist/{chunk-WL7PZK7Q.js → chunk-4PIN6QYQ.js} +43 -1
  24. package/dist/chunk-4PIN6QYQ.js.map +1 -0
  25. package/dist/{chunk-6UMIOEDR.js → chunk-AZRPDSRQ.js} +3 -3
  26. package/dist/{chunk-6LMM3OVX.js → chunk-BMCC2BUP.js} +3 -3
  27. package/dist/{chunk-36HSG7HU.js → chunk-CRZXEKCX.js} +2 -2
  28. package/dist/chunk-F4XBNR5L.js +16 -0
  29. package/dist/chunk-F4XBNR5L.js.map +1 -0
  30. package/dist/chunk-GY4IPYG4.js +40 -0
  31. package/dist/chunk-GY4IPYG4.js.map +1 -0
  32. package/dist/{chunk-6OG4244Y.js → chunk-MTKD2FN5.js} +2 -251
  33. package/dist/chunk-MTKD2FN5.js.map +1 -0
  34. package/dist/{chunk-5AUZR655.js → chunk-NDXQFEZQ.js} +51 -48
  35. package/dist/chunk-NDXQFEZQ.js.map +1 -0
  36. package/dist/chunk-NSWLZTJX.js +645 -0
  37. package/dist/chunk-NSWLZTJX.js.map +1 -0
  38. package/dist/chunk-PU6AWIRE.js +252 -0
  39. package/dist/chunk-PU6AWIRE.js.map +1 -0
  40. package/dist/{chunk-JKECSYDB.js → chunk-PV3GSLUY.js} +3 -3
  41. package/dist/{chunk-7Y7U7U7X.js → chunk-Q7RSHLEV.js} +5 -3
  42. package/dist/{chunk-7Y7U7U7X.js.map → chunk-Q7RSHLEV.js.map} +1 -1
  43. package/dist/{chunk-HRBF4B5L.js → chunk-TUJ4277Q.js} +1 -14
  44. package/dist/chunk-TUJ4277Q.js.map +1 -0
  45. package/dist/{chunk-57XPEL7X.js → chunk-V42C72V5.js} +25 -2
  46. package/dist/chunk-V42C72V5.js.map +1 -0
  47. package/dist/{chunk-FCYHDENJ.js → chunk-VOIVDEAV.js} +2 -2
  48. package/dist/{chunk-ACB7KOQ6.js → chunk-WSQSKYXP.js} +4 -4
  49. package/dist/{chunk-F6J5J4H6.js → chunk-WYQTPFPI.js} +26 -2
  50. package/dist/chunk-WYQTPFPI.js.map +1 -0
  51. package/dist/{chunk-PFTOGTHH.js → chunk-Z3IJ7XEW.js} +3 -3
  52. package/dist/{chunk-ZD2AUFIT.js → chunk-ZGGEYYEQ.js} +3 -3
  53. package/dist/{chunk-O5AUJQIA.js → chunk-ZNWJJRHP.js} +2 -2
  54. package/dist/design-canvas/index.js +1 -2
  55. package/dist/design-canvas/index.js.map +1 -1
  56. package/dist/design-canvas-react/engine.js +1 -2
  57. package/dist/design-canvas-react/index.js +2 -3
  58. package/dist/design-canvas-react/index.js.map +1 -1
  59. package/dist/design-canvas-react/lazy.js +1 -1
  60. package/dist/media/generate-request.d.ts +27 -1
  61. package/dist/media/index.js +36 -426
  62. package/dist/media/index.js.map +1 -1
  63. package/dist/media/router-generation.d.ts +7 -0
  64. package/dist/operator/gateway-keys.d.ts +44 -0
  65. package/dist/operator/index.d.ts +1 -0
  66. package/dist/operator/index.js +55 -1
  67. package/dist/operator/index.js.map +1 -1
  68. package/dist/plans/decision.d.ts +31 -0
  69. package/dist/plans/drizzle.js +1 -1
  70. package/dist/plans/index.js +5 -1
  71. package/dist/platform/billing.d.ts +3 -2
  72. package/dist/platform/deployment.d.ts +21 -0
  73. package/dist/platform/index.d.ts +1 -0
  74. package/dist/platform/index.js +30 -10
  75. package/dist/platform/index.js.map +1 -1
  76. package/dist/preset-cloudflare/index.js +9 -8
  77. package/dist/preset-cloudflare/index.js.map +1 -1
  78. package/dist/public-consultation/index.d.ts +1 -1
  79. package/dist/public-consultation/index.js +13 -12
  80. package/dist/public-consultation/index.js.map +1 -1
  81. package/dist/sandbox/computer-receipts.d.ts +1 -1
  82. package/dist/sandbox/index.d.ts +1 -0
  83. package/dist/sandbox/index.js +15 -8
  84. package/dist/sandbox/router-model-policy.d.ts +31 -0
  85. package/dist/sequences/index.js +1 -2
  86. package/dist/sequences/index.js.map +1 -1
  87. package/dist/spend/drizzle.d.ts +195 -0
  88. package/dist/spend/drizzle.js +22 -0
  89. package/dist/spend/drizzle.js.map +1 -1
  90. package/dist/stream/index.js +2 -2
  91. package/dist/studio/generated-media/flows.d.ts +240 -0
  92. package/dist/studio/generated-media/index.d.ts +3 -1
  93. package/dist/studio/generated-media/index.js +357 -138
  94. package/dist/studio/generated-media/index.js.map +1 -1
  95. package/dist/studio/index.js +18 -16
  96. package/dist/studio-react/index.js +28 -26
  97. package/dist/studio-react/index.js.map +1 -1
  98. package/dist/teams/index.d.ts +1 -0
  99. package/dist/teams/index.js +16 -0
  100. package/dist/teams/index.js.map +1 -1
  101. package/dist/teams/invitations-api.js +1 -1
  102. package/dist/teams/members-api.d.ts +5 -3
  103. package/dist/teams/members-api.js +1 -1
  104. package/dist/teams/thread-access.d.ts +22 -0
  105. package/dist/tools/index.js +5 -4
  106. package/dist/web/index.js +4 -6
  107. package/dist/web-react/index.js +4 -4
  108. package/dist/work-product/index.js +3 -2
  109. package/dist/work-product/index.js.map +1 -1
  110. package/dist/workspace-export/d1.d.ts +1 -1
  111. package/dist/workspace-export/index.js +9 -2
  112. package/dist/workspace-export/index.js.map +1 -1
  113. package/package.json +1 -1
  114. package/dist/chunk-57XPEL7X.js.map +0 -1
  115. package/dist/chunk-5AUZR655.js.map +0 -1
  116. package/dist/chunk-6OG4244Y.js.map +0 -1
  117. package/dist/chunk-6Z7TZVKZ.js +0 -26
  118. package/dist/chunk-6Z7TZVKZ.js.map +0 -1
  119. package/dist/chunk-F6J5J4H6.js.map +0 -1
  120. package/dist/chunk-HRBF4B5L.js.map +0 -1
  121. package/dist/chunk-WL7PZK7Q.js.map +0 -1
  122. /package/dist/{DesignCanvas-3DGZQOD7.js.map → DesignCanvas-VKZ7Y3JU.js.map} +0 -0
  123. /package/dist/{DesignCanvasEditor-OG4QY5WJ.js.map → DesignCanvasEditor-3V53YLLZ.js.map} +0 -0
  124. /package/dist/{chunk-QLZ6A73E.js.map → chunk-4CEIZZTH.js.map} +0 -0
  125. /package/dist/{chunk-6UMIOEDR.js.map → chunk-AZRPDSRQ.js.map} +0 -0
  126. /package/dist/{chunk-6LMM3OVX.js.map → chunk-BMCC2BUP.js.map} +0 -0
  127. /package/dist/{chunk-36HSG7HU.js.map → chunk-CRZXEKCX.js.map} +0 -0
  128. /package/dist/{chunk-JKECSYDB.js.map → chunk-PV3GSLUY.js.map} +0 -0
  129. /package/dist/{chunk-FCYHDENJ.js.map → chunk-VOIVDEAV.js.map} +0 -0
  130. /package/dist/{chunk-ACB7KOQ6.js.map → chunk-WSQSKYXP.js.map} +0 -0
  131. /package/dist/{chunk-PFTOGTHH.js.map → chunk-Z3IJ7XEW.js.map} +0 -0
  132. /package/dist/{chunk-ZD2AUFIT.js.map → chunk-ZGGEYYEQ.js.map} +0 -0
  133. /package/dist/{chunk-O5AUJQIA.js.map → chunk-ZNWJJRHP.js.map} +0 -0
@@ -17,6 +17,201 @@ export type SpendBoxLedgerTable = AnySQLiteTable & {
17
17
  deletedAt: AnySQLiteColumn;
18
18
  extras: AnySQLiteColumn;
19
19
  };
20
+ /**
21
+ * Build the standard `spend_box_ledger` table. With `workspaceTable`, a box row
22
+ * cascades with its workspace; without it, `workspace_id` is a plain column so
23
+ * the ledger outlives a deleted workspace whose boxes may still be on the
24
+ * platform's books.
25
+ */
26
+ export declare function createSpendBoxLedgerTable(options?: {
27
+ workspaceTable?: AnySQLiteTable & {
28
+ id: AnySQLiteColumn;
29
+ };
30
+ }): import("drizzle-orm/sqlite-core").SQLiteTableWithColumns<{
31
+ name: "spend_box_ledger";
32
+ schema: undefined;
33
+ columns: {
34
+ sandboxId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
35
+ name: "sandbox_id";
36
+ tableName: "spend_box_ledger";
37
+ dataType: "string";
38
+ columnType: "SQLiteText";
39
+ data: string;
40
+ driverParam: string;
41
+ notNull: true;
42
+ hasDefault: false;
43
+ isPrimaryKey: true;
44
+ isAutoincrement: false;
45
+ hasRuntimeDefault: false;
46
+ enumValues: [string, ...string[]];
47
+ baseColumn: never;
48
+ identity: undefined;
49
+ generated: undefined;
50
+ }, {}, {
51
+ length: number | undefined;
52
+ }>;
53
+ workspaceId: import("drizzle-orm/sqlite-core").SQLiteColumn<{
54
+ name: "workspace_id";
55
+ tableName: "spend_box_ledger";
56
+ dataType: "string";
57
+ columnType: "SQLiteText";
58
+ data: string;
59
+ driverParam: string;
60
+ notNull: true;
61
+ hasDefault: false;
62
+ isPrimaryKey: false;
63
+ isAutoincrement: false;
64
+ hasRuntimeDefault: false;
65
+ enumValues: [string, ...string[]];
66
+ baseColumn: never;
67
+ identity: undefined;
68
+ generated: undefined;
69
+ }, {}, {
70
+ length: number | undefined;
71
+ }>;
72
+ createdAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
73
+ name: "created_at";
74
+ tableName: "spend_box_ledger";
75
+ dataType: "number";
76
+ columnType: "SQLiteInteger";
77
+ data: number;
78
+ driverParam: number;
79
+ notNull: true;
80
+ hasDefault: false;
81
+ isPrimaryKey: false;
82
+ isAutoincrement: false;
83
+ hasRuntimeDefault: false;
84
+ enumValues: undefined;
85
+ baseColumn: never;
86
+ identity: undefined;
87
+ generated: undefined;
88
+ }, {}, {}>;
89
+ idleTimeoutSeconds: import("drizzle-orm/sqlite-core").SQLiteColumn<{
90
+ name: "idle_timeout_seconds";
91
+ tableName: "spend_box_ledger";
92
+ dataType: "number";
93
+ columnType: "SQLiteInteger";
94
+ data: number;
95
+ driverParam: number;
96
+ notNull: true;
97
+ hasDefault: false;
98
+ isPrimaryKey: false;
99
+ isAutoincrement: false;
100
+ hasRuntimeDefault: false;
101
+ enumValues: undefined;
102
+ baseColumn: never;
103
+ identity: undefined;
104
+ generated: undefined;
105
+ }, {}, {}>;
106
+ maxLifetimeSeconds: import("drizzle-orm/sqlite-core").SQLiteColumn<{
107
+ name: "max_lifetime_seconds";
108
+ tableName: "spend_box_ledger";
109
+ dataType: "number";
110
+ columnType: "SQLiteInteger";
111
+ data: number;
112
+ driverParam: number;
113
+ notNull: false;
114
+ hasDefault: false;
115
+ isPrimaryKey: false;
116
+ isAutoincrement: false;
117
+ hasRuntimeDefault: false;
118
+ enumValues: undefined;
119
+ baseColumn: never;
120
+ identity: undefined;
121
+ generated: undefined;
122
+ }, {}, {}>;
123
+ lastActivityAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
124
+ name: "last_activity_at";
125
+ tableName: "spend_box_ledger";
126
+ dataType: "number";
127
+ columnType: "SQLiteInteger";
128
+ data: number;
129
+ driverParam: number;
130
+ notNull: true;
131
+ hasDefault: false;
132
+ isPrimaryKey: false;
133
+ isAutoincrement: false;
134
+ hasRuntimeDefault: false;
135
+ enumValues: undefined;
136
+ baseColumn: never;
137
+ identity: undefined;
138
+ generated: undefined;
139
+ }, {}, {}>;
140
+ openDetachedRunIds: import("drizzle-orm/sqlite-core").SQLiteColumn<{
141
+ name: "open_detached_run_ids";
142
+ tableName: "spend_box_ledger";
143
+ dataType: "json";
144
+ columnType: "SQLiteTextJson";
145
+ data: string[];
146
+ driverParam: string;
147
+ notNull: true;
148
+ hasDefault: true;
149
+ isPrimaryKey: false;
150
+ isAutoincrement: false;
151
+ hasRuntimeDefault: false;
152
+ enumValues: undefined;
153
+ baseColumn: never;
154
+ identity: undefined;
155
+ generated: undefined;
156
+ }, {}, {
157
+ $type: string[];
158
+ }>;
159
+ stoppedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
160
+ name: "stopped_at";
161
+ tableName: "spend_box_ledger";
162
+ dataType: "number";
163
+ columnType: "SQLiteInteger";
164
+ data: number;
165
+ driverParam: number;
166
+ notNull: false;
167
+ hasDefault: false;
168
+ isPrimaryKey: false;
169
+ isAutoincrement: false;
170
+ hasRuntimeDefault: false;
171
+ enumValues: undefined;
172
+ baseColumn: never;
173
+ identity: undefined;
174
+ generated: undefined;
175
+ }, {}, {}>;
176
+ deletedAt: import("drizzle-orm/sqlite-core").SQLiteColumn<{
177
+ name: "deleted_at";
178
+ tableName: "spend_box_ledger";
179
+ dataType: "number";
180
+ columnType: "SQLiteInteger";
181
+ data: number;
182
+ driverParam: number;
183
+ notNull: false;
184
+ hasDefault: false;
185
+ isPrimaryKey: false;
186
+ isAutoincrement: false;
187
+ hasRuntimeDefault: false;
188
+ enumValues: undefined;
189
+ baseColumn: never;
190
+ identity: undefined;
191
+ generated: undefined;
192
+ }, {}, {}>;
193
+ extras: import("drizzle-orm/sqlite-core").SQLiteColumn<{
194
+ name: "extras";
195
+ tableName: "spend_box_ledger";
196
+ dataType: "json";
197
+ columnType: "SQLiteTextJson";
198
+ data: Record<string, unknown>;
199
+ driverParam: string;
200
+ notNull: false;
201
+ hasDefault: false;
202
+ isPrimaryKey: false;
203
+ isAutoincrement: false;
204
+ hasRuntimeDefault: false;
205
+ enumValues: undefined;
206
+ baseColumn: never;
207
+ identity: undefined;
208
+ generated: undefined;
209
+ }, {}, {
210
+ $type: Record<string, unknown>;
211
+ }>;
212
+ };
213
+ dialect: 'sqlite';
214
+ }>;
20
215
  /** The ledger a store or query reads: a database and the product's table. */
21
216
  export interface SpendLedgerTableOptions {
22
217
  readonly db: SpendDatabase;
@@ -4,6 +4,27 @@ import {
4
4
 
5
5
  // src/spend/drizzle.ts
6
6
  import { and, eq, gte, isNull, lte, or, sql } from "drizzle-orm";
7
+ import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
8
+ function createSpendBoxLedgerTable(options = {}) {
9
+ const { workspaceTable } = options;
10
+ return sqliteTable("spend_box_ledger", {
11
+ sandboxId: text("sandbox_id").primaryKey(),
12
+ workspaceId: workspaceTable ? text("workspace_id").notNull().references(() => workspaceTable.id, { onDelete: "cascade" }) : text("workspace_id").notNull(),
13
+ createdAt: integer("created_at").notNull(),
14
+ idleTimeoutSeconds: integer("idle_timeout_seconds").notNull(),
15
+ maxLifetimeSeconds: integer("max_lifetime_seconds"),
16
+ lastActivityAt: integer("last_activity_at").notNull(),
17
+ openDetachedRunIds: text("open_detached_run_ids", { mode: "json" }).$type().notNull().default([]),
18
+ stoppedAt: integer("stopped_at"),
19
+ deletedAt: integer("deleted_at"),
20
+ // Opaque product columns written verbatim on insert: `billingOwnerId`, the
21
+ // platform user whose wallet the box bills, which the platform's own
22
+ // settlement row does not name.
23
+ extras: text("extras", { mode: "json" }).$type()
24
+ }, (table) => [
25
+ index("idx_spend_box_ledger_workspace").on(table.workspaceId)
26
+ ]);
27
+ }
7
28
  function rowToRecord(row) {
8
29
  return {
9
30
  sandboxId: row.sandboxId,
@@ -124,6 +145,7 @@ async function loadWorkspaceSpendBudgetConfig(options) {
124
145
  }
125
146
  export {
126
147
  createDrizzleSpendStore,
148
+ createSpendBoxLedgerTable,
127
149
  listLedgerBillingOwnerIds,
128
150
  listWorkspaceSandboxIds,
129
151
  loadWorkspaceSpendBudgetConfig
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/spend/drizzle.ts"],"sourcesContent":["/**\n * Drizzle (SQLite / D1) implementations of the spend module's persistence:\n * the expectation-ledger `SpendLedgerStorePort`, the ledger reads a settlement\n * sweep needs, and the per-workspace budget opt-in. This optional subpath keeps\n * the core `./spend` entry free of Drizzle.\n *\n * The product owns the tables and their migration. The ledger table needs the\n * columns of {@link SpendBoxLedgerTable}; every timestamp is epoch\n * MILLISECONDS, matching `SpendBoxRecord`, so declare them as plain `integer`\n * (a drizzle `{ mode: 'timestamp' }` column would silently divide by 1000).\n * `openDetachedRunIds` is a JSON-mode text column defaulting to `[]`; `extras`\n * is a nullable JSON-mode text column carrying `{ billingOwnerId }`.\n *\n * `update()` is deliberately NOT a read-modify-write. It runs on the live turn\n * path from a Worker, where two isolates recording activity for the same box\n * are ordinary, so every column is computed in ONE atomic SQL statement using\n * the exact merge rule `foldSpendBoxRecord` states for that field (moves\n * forward only / latest-wins-but-never-behind-activity / set-once). A lost race\n * under a read-modify-write could rewind the ceiling; under this fold a lost\n * race can only tighten it, which surfaces as a false alarm rather than a\n * missed charge.\n */\nimport { and, eq, gte, isNull, lte, or, sql, type SQL } from 'drizzle-orm'\nimport type { AnySQLiteColumn, AnySQLiteTable, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport { DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD } from './budget'\nimport type { SpendLedgerStorePort } from './store'\nimport type { SpendBoxPatch, SpendBoxRecord, SpendWindow } from './types'\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. */\nexport type SpendDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any>\n\n/** Required Drizzle column properties of the expectation ledger; SQL column\n * names, foreign keys and indexes remain product-owned. */\nexport type SpendBoxLedgerTable = AnySQLiteTable & {\n sandboxId: AnySQLiteColumn\n workspaceId: AnySQLiteColumn\n createdAt: AnySQLiteColumn\n idleTimeoutSeconds: AnySQLiteColumn\n maxLifetimeSeconds: AnySQLiteColumn\n lastActivityAt: AnySQLiteColumn\n openDetachedRunIds: AnySQLiteColumn\n stoppedAt: AnySQLiteColumn\n deletedAt: AnySQLiteColumn\n extras: AnySQLiteColumn\n}\n\n/** The ledger a store or query reads: a database and the product's table. */\nexport interface SpendLedgerTableOptions {\n readonly db: SpendDatabase\n readonly table: SpendBoxLedgerTable\n}\n\ninterface SpendBoxLedgerRow {\n sandboxId: string\n workspaceId: string\n createdAt: number\n idleTimeoutSeconds: number\n maxLifetimeSeconds: number | null\n lastActivityAt: number\n openDetachedRunIds: string[] | null\n stoppedAt: number | null\n deletedAt: number | null\n extras: Record<string, unknown> | null\n}\n\nfunction rowToRecord(row: SpendBoxLedgerRow): SpendBoxRecord {\n return {\n sandboxId: row.sandboxId,\n workspaceId: row.workspaceId,\n createdAt: row.createdAt,\n idleTimeoutSeconds: row.idleTimeoutSeconds,\n maxLifetimeSeconds: row.maxLifetimeSeconds,\n lastActivityAt: row.lastActivityAt,\n openDetachedRunIds: row.openDetachedRunIds ?? [],\n stoppedAt: row.stoppedAt,\n deletedAt: row.deletedAt,\n ...(row.extras ? { extras: row.extras } : {}),\n }\n}\n\n/** Build the expectation-ledger store over the product's drizzle table. */\nexport function createDrizzleSpendStore(options: SpendLedgerTableOptions): SpendLedgerStorePort {\n const { db, table } = options\n\n async function load(sandboxId: string): Promise<SpendBoxRecord | null> {\n const [row] = await db.select().from(table).where(eq(table.sandboxId, sandboxId)).limit(1)\n return row ? rowToRecord(row as SpendBoxLedgerRow) : null\n }\n\n return {\n load,\n\n /**\n * Every box that could have been live at some point inside `window`.\n *\n * Deliberately COARSE: the box existed by the window's end and was not\n * recorded deleted before it began. The reconciler re-derives liveness from\n * the same fold `computeExpectedCeiling` uses (delete, stop, open detached\n * run, last activity plus idle timeout, capped by max lifetime), so this\n * only has to be a superset it can filter down. Encoding the real rule here\n * would put a second definition of \"live\" in SQL, free to drift from the one\n * the ceiling check uses. `stopped_at` is therefore not a filter: later\n * activity can clear a stop, and the fold decides which stop closed the box.\n *\n * Over-returning is correct; under-returning is the only real failure — a\n * box this query omits is a box the pass never notices went unbilled.\n */\n async listLiveBetween(window: SpendWindow): Promise<readonly SpendBoxRecord[]> {\n const rows = await db\n .select()\n .from(table)\n .where(and(lte(table.createdAt, window.endAt), or(isNull(table.deletedAt), gte(table.deletedAt, window.startAt))))\n return rows.map((row) => rowToRecord(row as SpendBoxLedgerRow))\n },\n\n async insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord> {\n const [row] = await db\n .insert(table)\n .values({\n sandboxId: record.sandboxId,\n workspaceId: record.workspaceId,\n createdAt: record.createdAt,\n idleTimeoutSeconds: record.idleTimeoutSeconds,\n maxLifetimeSeconds: record.maxLifetimeSeconds,\n lastActivityAt: record.lastActivityAt,\n openDetachedRunIds: [...record.openDetachedRunIds],\n stoppedAt: record.stoppedAt,\n deletedAt: record.deletedAt,\n // Written in the SAME statement — a second UPDATE to attach extras\n // would leave a window where the reconciler cannot tell whose wallet\n // this box bills.\n extras: extras ?? null,\n } as never)\n .returning()\n return rowToRecord(row as SpendBoxLedgerRow)\n },\n\n async update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null> {\n const hasActivity = patch.observedActivityAt !== undefined\n const hasStop = patch.stoppedAt !== undefined\n const activityValue = patch.observedActivityAt\n const stopValue = patch.stoppedAt\n\n const set: Partial<Record<keyof SpendBoxLedgerRow, SQL>> = {}\n\n // last_activity_at moves forward only. SQLite's two-argument MAX() is the\n // SCALAR max, not the aggregate, so this needs no GROUP BY — and a\n // replayed or out-of-order event therefore cannot rewind the ceiling.\n if (hasActivity) {\n set.lastActivityAt = sql`MAX(${table.lastActivityAt}, ${activityValue})`\n }\n\n // stopped_at is touched whenever activity might CLEAR it (work observed\n // after a recorded stop means the box is running again, and keeping the\n // stale stop would invent an over-ceiling finding out of the product's\n // own bookkeeping) or a new stop is being recorded (latest-wins, but never\n // behind the newly computed activity — a stop reported behind observed\n // work is not the stop that closed this box, so it does not move the column).\n //\n // The \"new last_activity_at\" sub-expression is repeated verbatim rather\n // than referenced, because SQLite evaluates every SET-clause expression\n // against the row's PRE-update values: one clause can never see\n // another's result.\n if (hasActivity || hasStop) {\n const newLastActivityAtExpr = hasActivity\n ? sql`MAX(${table.lastActivityAt}, ${activityValue})`\n : sql`${table.lastActivityAt}`\n const afterActivityClearExpr = hasActivity\n ? sql`(CASE WHEN ${table.stoppedAt} IS NOT NULL AND ${activityValue} > ${table.stoppedAt} THEN NULL ELSE ${table.stoppedAt} END)`\n : sql`${table.stoppedAt}`\n set.stoppedAt = hasStop\n ? sql`(CASE WHEN ${stopValue} >= (${newLastActivityAtExpr}) THEN ${stopValue} ELSE ${afterActivityClearExpr} END)`\n : afterActivityClearExpr\n }\n\n // deleted_at is set-once: a deleted sandbox id never returns, so a second\n // observation is duplicate delivery, not a second deletion.\n if (patch.deletedAt !== undefined) {\n set.deletedAt = sql`COALESCE(${table.deletedAt}, ${patch.deletedAt})`\n }\n\n // open_detached_run_ids is a SET encoded as a JSON array. Add is\n // insert-if-absent; remove rebuilds the array excluding the value. Both\n // read and write the same column expression inside one statement, and the\n // remove chains off whatever the add branch produced so the fold's own\n // field order holds: a patch that both adds and removes the same id nets\n // to removed.\n let runIdsExpr: SQL | undefined\n if (patch.openDetachedRunAdd !== undefined) {\n runIdsExpr = sql`(\n CASE\n WHEN EXISTS (SELECT 1 FROM json_each(${table.openDetachedRunIds}) WHERE value = ${patch.openDetachedRunAdd})\n THEN ${table.openDetachedRunIds}\n ELSE json_insert(${table.openDetachedRunIds}, '$[#]', ${patch.openDetachedRunAdd})\n END\n )`\n }\n if (patch.openDetachedRunRemove !== undefined) {\n const source = runIdsExpr ?? sql`${table.openDetachedRunIds}`\n runIdsExpr = sql`(\n SELECT COALESCE(json_group_array(value), '[]') FROM json_each(${source}) WHERE value != ${patch.openDetachedRunRemove}\n )`\n }\n if (runIdsExpr) set.openDetachedRunIds = runIdsExpr\n\n // A patch with every field undefined is a no-op — return the current row\n // rather than issuing an empty UPDATE.\n if (Object.keys(set).length === 0) return await load(sandboxId)\n\n const rows = await db\n .update(table)\n .set(set as never)\n .where(eq(table.sandboxId, sandboxId))\n .returning()\n // Absent row returns null, never a throw: the ledger legitimately does\n // not know every box (see the `unknown-box` finding class).\n const [row] = rows as SpendBoxLedgerRow[]\n return row ? rowToRecord(row) : null\n },\n }\n}\n\n/** Every distinct platform-user id the ledger has recorded as a box's\n * `extras.billingOwnerId` — the set of wallets a full pass needs to read. */\nexport async function listLedgerBillingOwnerIds(options: SpendLedgerTableOptions): Promise<string[]> {\n const { db, table } = options\n const rows = await db\n .select({ billingOwnerId: sql<string | null>`json_extract(${table.extras}, '$.billingOwnerId')` })\n .from(table)\n .where(sql`json_extract(${table.extras}, '$.billingOwnerId') IS NOT NULL`)\n return [...new Set(rows.map((row) => row.billingOwnerId).filter((id): id is string => Boolean(id)))]\n}\n\n/** Every sandbox id the ledger attributes to this workspace — the only place\n * the workspace-to-sandbox mapping exists; the platform does not model a workspace. */\nexport async function listWorkspaceSandboxIds(\n options: SpendLedgerTableOptions & { readonly workspaceId: string },\n): Promise<Set<string>> {\n const { db, table, workspaceId } = options\n const rows = await db.select({ sandboxId: table.sandboxId }).from(table).where(eq(table.workspaceId, workspaceId))\n return new Set(rows.map((row) => row.sandboxId as string))\n}\n\n/** The product's workspace table columns holding the compute-budget opt-in. */\nexport type SpendBudgetWorkspaceTable = AnySQLiteTable & {\n id: AnySQLiteColumn\n spendBudgetEnabled: AnySQLiteColumn\n spendBudgetLimitNanoUsd: AnySQLiteColumn\n}\n\nexport interface WorkspaceSpendBudgetConfig {\n readonly enabled: boolean\n readonly limitNanoUsd: number\n}\n\n/**\n * Opt-in per-workspace budget read. Absent or disabled — the default for every\n * workspace until it opts in — short-circuits the caller before any settlement\n * read runs, so an unopted workspace's provisioning path makes no extra network\n * call. A null limit falls back to {@link DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD}.\n */\nexport async function loadWorkspaceSpendBudgetConfig(options: {\n readonly db: SpendDatabase\n readonly workspaces: SpendBudgetWorkspaceTable\n readonly workspaceId: string\n}): Promise<WorkspaceSpendBudgetConfig> {\n const { db, workspaces, workspaceId } = options\n const [row] = await db\n .select({ enabled: workspaces.spendBudgetEnabled, limit: workspaces.spendBudgetLimitNanoUsd })\n .from(workspaces)\n .where(eq(workspaces.id, workspaceId))\n .limit(1)\n return {\n enabled: (row?.enabled as boolean | null | undefined) ?? false,\n limitNanoUsd: (row?.limit as number | null | undefined) ?? DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD,\n }\n}\n"],"mappings":";;;;;AAsBA,SAAS,KAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,WAAqB;AA4C7D,SAAS,YAAY,KAAwC;AAC3D,SAAO;AAAA,IACL,WAAW,IAAI;AAAA,IACf,aAAa,IAAI;AAAA,IACjB,WAAW,IAAI;AAAA,IACf,oBAAoB,IAAI;AAAA,IACxB,oBAAoB,IAAI;AAAA,IACxB,gBAAgB,IAAI;AAAA,IACpB,oBAAoB,IAAI,sBAAsB,CAAC;AAAA,IAC/C,WAAW,IAAI;AAAA,IACf,WAAW,IAAI;AAAA,IACf,GAAI,IAAI,SAAS,EAAE,QAAQ,IAAI,OAAO,IAAI,CAAC;AAAA,EAC7C;AACF;AAGO,SAAS,wBAAwB,SAAwD;AAC9F,QAAM,EAAE,IAAI,MAAM,IAAI;AAEtB,iBAAe,KAAK,WAAmD;AACrE,UAAM,CAAC,GAAG,IAAI,MAAM,GAAG,OAAO,EAAE,KAAK,KAAK,EAAE,MAAM,GAAG,MAAM,WAAW,SAAS,CAAC,EAAE,MAAM,CAAC;AACzF,WAAO,MAAM,YAAY,GAAwB,IAAI;AAAA,EACvD;AAEA,SAAO;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AAI,KAAK,IAAI,CAAC,QAAQ,IAAI,cAAc,EAAE,OAAO,CAAC,OAAqB,QAAQ,EAAE,CAAC,CAAC,CAAC;AACrG;AAIA,eAAsB,wBACpB,SACsB;AACtB,QAAM,EAAE,IAAI,OAAO,YAAY,IAAI;AACnC,QAAM,OAAO,MAAM,GAAG,OAAO,EAAE,WAAW,MAAM,UAAU,CAAC,EAAE,KAAK,KAAK,EAAE,MAAM,GAAG,MAAM,aAAa,WAAW,CAAC;AACjH,SAAO,IAAI,IAAI,KAAK,IAAI,CAAC,QAAQ,IAAI,SAAmB,CAAC;AAC3D;AAoBA,eAAsB,+BAA+B,SAIb;AACtC,QAAM,EAAE,IAAI,YAAY,YAAY,IAAI;AACxC,QAAM,CAAC,GAAG,IAAI,MAAM,GACjB,OAAO,EAAE,SAAS,WAAW,oBAAoB,OAAO,WAAW,wBAAwB,CAAC,EAC5F,KAAK,UAAU,EACf,MAAM,GAAG,WAAW,IAAI,WAAW,CAAC,EACpC,MAAM,CAAC;AACV,SAAO;AAAA,IACL,SAAU,KAAK,WAA0C;AAAA,IACzD,cAAe,KAAK,SAAuC;AAAA,EAC7D;AACF;","names":[]}
1
+ {"version":3,"sources":["../../src/spend/drizzle.ts"],"sourcesContent":["/**\n * Drizzle (SQLite / D1) implementations of the spend module's persistence:\n * the expectation-ledger `SpendLedgerStorePort`, the ledger reads a settlement\n * sweep needs, and the per-workspace budget opt-in. This optional subpath keeps\n * the core `./spend` entry free of Drizzle.\n *\n * The product owns its migration. {@link createSpendBoxLedgerTable} builds the\n * standard `spend_box_ledger` table; a product with its own table needs the\n * columns of {@link SpendBoxLedgerTable}. Every timestamp is epoch\n * MILLISECONDS, matching `SpendBoxRecord`, so they are plain `integer` columns\n * (a drizzle `{ mode: 'timestamp' }` column would silently divide by 1000).\n * `openDetachedRunIds` is a JSON-mode text column defaulting to `[]`; `extras`\n * is a nullable JSON-mode text column carrying `{ billingOwnerId }`.\n *\n * `update()` is deliberately NOT a read-modify-write. It runs on the live turn\n * path from a Worker, where two isolates recording activity for the same box\n * are ordinary, so every column is computed in ONE atomic SQL statement using\n * the exact merge rule `foldSpendBoxRecord` states for that field (moves\n * forward only / latest-wins-but-never-behind-activity / set-once). A lost race\n * under a read-modify-write could rewind the ceiling; under this fold a lost\n * race can only tighten it, which surfaces as a false alarm rather than a\n * missed charge.\n */\nimport { and, eq, gte, isNull, lte, or, sql, type SQL } from 'drizzle-orm'\nimport { index, integer, sqliteTable, text } from 'drizzle-orm/sqlite-core'\nimport type { AnySQLiteColumn, AnySQLiteTable, BaseSQLiteDatabase } from 'drizzle-orm/sqlite-core'\nimport { DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD } from './budget'\nimport type { SpendLedgerStorePort } from './store'\nimport type { SpendBoxPatch, SpendBoxRecord, SpendWindow } from './types'\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. */\nexport type SpendDatabase = BaseSQLiteDatabase<'sync' | 'async', any, any>\n\n/** Required Drizzle column properties of the expectation ledger; SQL column\n * names, foreign keys and indexes remain product-owned. */\nexport type SpendBoxLedgerTable = AnySQLiteTable & {\n sandboxId: AnySQLiteColumn\n workspaceId: AnySQLiteColumn\n createdAt: AnySQLiteColumn\n idleTimeoutSeconds: AnySQLiteColumn\n maxLifetimeSeconds: AnySQLiteColumn\n lastActivityAt: AnySQLiteColumn\n openDetachedRunIds: AnySQLiteColumn\n stoppedAt: AnySQLiteColumn\n deletedAt: AnySQLiteColumn\n extras: AnySQLiteColumn\n}\n\n/**\n * Build the standard `spend_box_ledger` table. With `workspaceTable`, a box row\n * cascades with its workspace; without it, `workspace_id` is a plain column so\n * the ledger outlives a deleted workspace whose boxes may still be on the\n * platform's books.\n */\nexport function createSpendBoxLedgerTable(options: { workspaceTable?: AnySQLiteTable & { id: AnySQLiteColumn } } = {}) {\n const { workspaceTable } = options\n return sqliteTable('spend_box_ledger', {\n sandboxId: text('sandbox_id').primaryKey(),\n workspaceId: workspaceTable\n ? text('workspace_id').notNull().references(() => workspaceTable.id, { onDelete: 'cascade' })\n : text('workspace_id').notNull(),\n createdAt: integer('created_at').notNull(),\n idleTimeoutSeconds: integer('idle_timeout_seconds').notNull(),\n maxLifetimeSeconds: integer('max_lifetime_seconds'),\n lastActivityAt: integer('last_activity_at').notNull(),\n openDetachedRunIds: text('open_detached_run_ids', { mode: 'json' }).$type<string[]>().notNull().default([]),\n stoppedAt: integer('stopped_at'),\n deletedAt: integer('deleted_at'),\n // Opaque product columns written verbatim on insert: `billingOwnerId`, the\n // platform user whose wallet the box bills, which the platform's own\n // settlement row does not name.\n extras: text('extras', { mode: 'json' }).$type<Record<string, unknown>>(),\n }, (table) => [\n index('idx_spend_box_ledger_workspace').on(table.workspaceId),\n ])\n}\n\n/** The ledger a store or query reads: a database and the product's table. */\nexport interface SpendLedgerTableOptions {\n readonly db: SpendDatabase\n readonly table: SpendBoxLedgerTable\n}\n\ninterface SpendBoxLedgerRow {\n sandboxId: string\n workspaceId: string\n createdAt: number\n idleTimeoutSeconds: number\n maxLifetimeSeconds: number | null\n lastActivityAt: number\n openDetachedRunIds: string[] | null\n stoppedAt: number | null\n deletedAt: number | null\n extras: Record<string, unknown> | null\n}\n\nfunction rowToRecord(row: SpendBoxLedgerRow): SpendBoxRecord {\n return {\n sandboxId: row.sandboxId,\n workspaceId: row.workspaceId,\n createdAt: row.createdAt,\n idleTimeoutSeconds: row.idleTimeoutSeconds,\n maxLifetimeSeconds: row.maxLifetimeSeconds,\n lastActivityAt: row.lastActivityAt,\n openDetachedRunIds: row.openDetachedRunIds ?? [],\n stoppedAt: row.stoppedAt,\n deletedAt: row.deletedAt,\n ...(row.extras ? { extras: row.extras } : {}),\n }\n}\n\n/** Build the expectation-ledger store over the product's drizzle table. */\nexport function createDrizzleSpendStore(options: SpendLedgerTableOptions): SpendLedgerStorePort {\n const { db, table } = options\n\n async function load(sandboxId: string): Promise<SpendBoxRecord | null> {\n const [row] = await db.select().from(table).where(eq(table.sandboxId, sandboxId)).limit(1)\n return row ? rowToRecord(row as SpendBoxLedgerRow) : null\n }\n\n return {\n load,\n\n /**\n * Every box that could have been live at some point inside `window`.\n *\n * Deliberately COARSE: the box existed by the window's end and was not\n * recorded deleted before it began. The reconciler re-derives liveness from\n * the same fold `computeExpectedCeiling` uses (delete, stop, open detached\n * run, last activity plus idle timeout, capped by max lifetime), so this\n * only has to be a superset it can filter down. Encoding the real rule here\n * would put a second definition of \"live\" in SQL, free to drift from the one\n * the ceiling check uses. `stopped_at` is therefore not a filter: later\n * activity can clear a stop, and the fold decides which stop closed the box.\n *\n * Over-returning is correct; under-returning is the only real failure — a\n * box this query omits is a box the pass never notices went unbilled.\n */\n async listLiveBetween(window: SpendWindow): Promise<readonly SpendBoxRecord[]> {\n const rows = await db\n .select()\n .from(table)\n .where(and(lte(table.createdAt, window.endAt), or(isNull(table.deletedAt), gte(table.deletedAt, window.startAt))))\n return rows.map((row) => rowToRecord(row as SpendBoxLedgerRow))\n },\n\n async insert(record: SpendBoxRecord, extras?: Record<string, unknown>): Promise<SpendBoxRecord> {\n const [row] = await db\n .insert(table)\n .values({\n sandboxId: record.sandboxId,\n workspaceId: record.workspaceId,\n createdAt: record.createdAt,\n idleTimeoutSeconds: record.idleTimeoutSeconds,\n maxLifetimeSeconds: record.maxLifetimeSeconds,\n lastActivityAt: record.lastActivityAt,\n openDetachedRunIds: [...record.openDetachedRunIds],\n stoppedAt: record.stoppedAt,\n deletedAt: record.deletedAt,\n // Written in the SAME statement — a second UPDATE to attach extras\n // would leave a window where the reconciler cannot tell whose wallet\n // this box bills.\n extras: extras ?? null,\n } as never)\n .returning()\n return rowToRecord(row as SpendBoxLedgerRow)\n },\n\n async update(sandboxId: string, patch: SpendBoxPatch): Promise<SpendBoxRecord | null> {\n const hasActivity = patch.observedActivityAt !== undefined\n const hasStop = patch.stoppedAt !== undefined\n const activityValue = patch.observedActivityAt\n const stopValue = patch.stoppedAt\n\n const set: Partial<Record<keyof SpendBoxLedgerRow, SQL>> = {}\n\n // last_activity_at moves forward only. SQLite's two-argument MAX() is the\n // SCALAR max, not the aggregate, so this needs no GROUP BY — and a\n // replayed or out-of-order event therefore cannot rewind the ceiling.\n if (hasActivity) {\n set.lastActivityAt = sql`MAX(${table.lastActivityAt}, ${activityValue})`\n }\n\n // stopped_at is touched whenever activity might CLEAR it (work observed\n // after a recorded stop means the box is running again, and keeping the\n // stale stop would invent an over-ceiling finding out of the product's\n // own bookkeeping) or a new stop is being recorded (latest-wins, but never\n // behind the newly computed activity — a stop reported behind observed\n // work is not the stop that closed this box, so it does not move the column).\n //\n // The \"new last_activity_at\" sub-expression is repeated verbatim rather\n // than referenced, because SQLite evaluates every SET-clause expression\n // against the row's PRE-update values: one clause can never see\n // another's result.\n if (hasActivity || hasStop) {\n const newLastActivityAtExpr = hasActivity\n ? sql`MAX(${table.lastActivityAt}, ${activityValue})`\n : sql`${table.lastActivityAt}`\n const afterActivityClearExpr = hasActivity\n ? sql`(CASE WHEN ${table.stoppedAt} IS NOT NULL AND ${activityValue} > ${table.stoppedAt} THEN NULL ELSE ${table.stoppedAt} END)`\n : sql`${table.stoppedAt}`\n set.stoppedAt = hasStop\n ? sql`(CASE WHEN ${stopValue} >= (${newLastActivityAtExpr}) THEN ${stopValue} ELSE ${afterActivityClearExpr} END)`\n : afterActivityClearExpr\n }\n\n // deleted_at is set-once: a deleted sandbox id never returns, so a second\n // observation is duplicate delivery, not a second deletion.\n if (patch.deletedAt !== undefined) {\n set.deletedAt = sql`COALESCE(${table.deletedAt}, ${patch.deletedAt})`\n }\n\n // open_detached_run_ids is a SET encoded as a JSON array. Add is\n // insert-if-absent; remove rebuilds the array excluding the value. Both\n // read and write the same column expression inside one statement, and the\n // remove chains off whatever the add branch produced so the fold's own\n // field order holds: a patch that both adds and removes the same id nets\n // to removed.\n let runIdsExpr: SQL | undefined\n if (patch.openDetachedRunAdd !== undefined) {\n runIdsExpr = sql`(\n CASE\n WHEN EXISTS (SELECT 1 FROM json_each(${table.openDetachedRunIds}) WHERE value = ${patch.openDetachedRunAdd})\n THEN ${table.openDetachedRunIds}\n ELSE json_insert(${table.openDetachedRunIds}, '$[#]', ${patch.openDetachedRunAdd})\n END\n )`\n }\n if (patch.openDetachedRunRemove !== undefined) {\n const source = runIdsExpr ?? sql`${table.openDetachedRunIds}`\n runIdsExpr = sql`(\n SELECT COALESCE(json_group_array(value), '[]') FROM json_each(${source}) WHERE value != ${patch.openDetachedRunRemove}\n )`\n }\n if (runIdsExpr) set.openDetachedRunIds = runIdsExpr\n\n // A patch with every field undefined is a no-op — return the current row\n // rather than issuing an empty UPDATE.\n if (Object.keys(set).length === 0) return await load(sandboxId)\n\n const rows = await db\n .update(table)\n .set(set as never)\n .where(eq(table.sandboxId, sandboxId))\n .returning()\n // Absent row returns null, never a throw: the ledger legitimately does\n // not know every box (see the `unknown-box` finding class).\n const [row] = rows as SpendBoxLedgerRow[]\n return row ? rowToRecord(row) : null\n },\n }\n}\n\n/** Every distinct platform-user id the ledger has recorded as a box's\n * `extras.billingOwnerId` — the set of wallets a full pass needs to read. */\nexport async function listLedgerBillingOwnerIds(options: SpendLedgerTableOptions): Promise<string[]> {\n const { db, table } = options\n const rows = await db\n .select({ billingOwnerId: sql<string | null>`json_extract(${table.extras}, '$.billingOwnerId')` })\n .from(table)\n .where(sql`json_extract(${table.extras}, '$.billingOwnerId') IS NOT NULL`)\n return [...new Set(rows.map((row) => row.billingOwnerId).filter((id): id is string => Boolean(id)))]\n}\n\n/** Every sandbox id the ledger attributes to this workspace — the only place\n * the workspace-to-sandbox mapping exists; the platform does not model a workspace. */\nexport async function listWorkspaceSandboxIds(\n options: SpendLedgerTableOptions & { readonly workspaceId: string },\n): Promise<Set<string>> {\n const { db, table, workspaceId } = options\n const rows = await db.select({ sandboxId: table.sandboxId }).from(table).where(eq(table.workspaceId, workspaceId))\n return new Set(rows.map((row) => row.sandboxId as string))\n}\n\n/** The product's workspace table columns holding the compute-budget opt-in. */\nexport type SpendBudgetWorkspaceTable = AnySQLiteTable & {\n id: AnySQLiteColumn\n spendBudgetEnabled: AnySQLiteColumn\n spendBudgetLimitNanoUsd: AnySQLiteColumn\n}\n\nexport interface WorkspaceSpendBudgetConfig {\n readonly enabled: boolean\n readonly limitNanoUsd: number\n}\n\n/**\n * Opt-in per-workspace budget read. Absent or disabled — the default for every\n * workspace until it opts in — short-circuits the caller before any settlement\n * read runs, so an unopted workspace's provisioning path makes no extra network\n * call. A null limit falls back to {@link DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD}.\n */\nexport async function loadWorkspaceSpendBudgetConfig(options: {\n readonly db: SpendDatabase\n readonly workspaces: SpendBudgetWorkspaceTable\n readonly workspaceId: string\n}): Promise<WorkspaceSpendBudgetConfig> {\n const { db, workspaces, workspaceId } = options\n const [row] = await db\n .select({ enabled: workspaces.spendBudgetEnabled, limit: workspaces.spendBudgetLimitNanoUsd })\n .from(workspaces)\n .where(eq(workspaces.id, workspaceId))\n .limit(1)\n return {\n enabled: (row?.enabled as boolean | null | undefined) ?? false,\n limitNanoUsd: (row?.limit as number | null | undefined) ?? DEFAULT_WORKSPACE_SPEND_BUDGET_NANO_USD,\n }\n}\n"],"mappings":";;;;;AAuBA,SAAS,KAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,WAAqB;AAC7D,SAAS,OAAO,SAAS,aAAa,YAAY;AA+B3C,SAAS,0BAA0B,UAAyE,CAAC,GAAG;AACrH,QAAM,EAAE,eAAe,IAAI;AAC3B,SAAO,YAAY,oBAAoB;AAAA,IACrC,WAAW,KAAK,YAAY,EAAE,WAAW;AAAA,IACzC,aAAa,iBACT,KAAK,cAAc,EAAE,QAAQ,EAAE,WAAW,MAAM,eAAe,IAAI,EAAE,UAAU,UAAU,CAAC,IAC1F,KAAK,cAAc,EAAE,QAAQ;AAAA,IACjC,WAAW,QAAQ,YAAY,EAAE,QAAQ;AAAA,IACzC,oBAAoB,QAAQ,sBAAsB,EAAE,QAAQ;AAAA,IAC5D,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,IAAI,OAAO,YAAY,IAAI;AACnC,QAAM,OAAO,MAAM,GAAG,OAAO,EAAE,WAAW,MAAM,UAAU,CAAC,EAAE,KAAK,KAAK,EAAE,MAAM,GAAG,MAAM,aAAa,WAAW,CAAC;AACjH,SAAO,IAAI,IAAI,KAAK,IAAI,CAAC,QAAQ,IAAI,SAAmB,CAAC;AAC3D;AAoBA,eAAsB,+BAA+B,SAIb;AACtC,QAAM,EAAE,IAAI,YAAY,YAAY,IAAI;AACxC,QAAM,CAAC,GAAG,IAAI,MAAM,GACjB,OAAO,EAAE,SAAS,WAAW,oBAAoB,OAAO,WAAW,wBAAwB,CAAC,EAC5F,KAAK,UAAU,EACf,MAAM,GAAG,WAAW,IAAI,WAAW,CAAC,EACpC,MAAM,CAAC;AACV,SAAO;AAAA,IACL,SAAU,KAAK,WAA0C;AAAA,IACzD,cAAe,KAAK,SAAuC;AAAA,EAC7D;AACF;","names":[]}
@@ -33,7 +33,7 @@ import {
33
33
  terminalizeDanglingAssistantToolUpdates,
34
34
  terminalizeDanglingToolPart,
35
35
  terminalizeDanglingToolParts
36
- } from "../chunk-O5AUJQIA.js";
36
+ } from "../chunk-ZNWJJRHP.js";
37
37
  import "../chunk-SRZTL3Z5.js";
38
38
  import {
39
39
  DEFAULT_RUNNING_TURN_LEASE_MS,
@@ -52,7 +52,7 @@ import {
52
52
  replayTurnEvents,
53
53
  stampReplaySeq
54
54
  } from "../chunk-3Q3UEWKK.js";
55
- import "../chunk-WL7PZK7Q.js";
55
+ import "../chunk-4PIN6QYQ.js";
56
56
  export {
57
57
  DEFAULT_RUNNING_TURN_LEASE_MS,
58
58
  DEFAULT_RUNNING_TURN_RENEW_INTERVAL_MS,
@@ -0,0 +1,240 @@
1
+ /**
2
+ * The provider-side steps of a direct media generation, over a product's
3
+ * generated-media store and its bound Router client: ingesting a provider
4
+ * result into the workspace, settling a video or avatar job, persisting
5
+ * provider images, speech and transcripts, and advancing a running job when
6
+ * it is polled. The product keeps its routes, rows, billing, costs and
7
+ * approvals; each step returns the stored-metadata fields it produced so the
8
+ * product writes them through `generationMetadata`.
9
+ */
10
+ import { type GenerateInputs } from '../../media/generate-request';
11
+ import { type GenerationMetadataFields } from '../../media/generation-record';
12
+ import type { RouterMediaSource } from '../../media/router-client';
13
+ import { type RouterAvatarRequest, type RouterTranscriptionRequest } from '../../media/router-generation';
14
+ import type { SpeechInput } from '../../media/speech-script';
15
+ import type { GenerationStatus } from '../generation';
16
+ import type { GeneratedMediaStore, PersistedGeneratedMedia } from './store';
17
+ /** How long ingesting a provider result into the workspace may take. */
18
+ export declare const GENERATED_MEDIA_INGEST_TIMEOUT_MS = 30000;
19
+ /** How long a pending generation may wait for a provider job id before polling fails it. */
20
+ export declare const STALE_PENDING_GENERATION_MS: number;
21
+ /** The generation types whose provider returns a job that may finish later. */
22
+ export type ProviderJobMediaType = 'video' | 'avatar';
23
+ /** A video or avatar provider's submit response. */
24
+ export interface ProviderMediaJobResponse {
25
+ job_id?: string;
26
+ id?: string;
27
+ status?: string;
28
+ video_url?: string;
29
+ url?: string;
30
+ polling_url?: string;
31
+ }
32
+ /** A provider result ingested into the workspace, or the reason it was not. */
33
+ export interface GeneratedMediaIngestion {
34
+ media: PersistedGeneratedMedia | null;
35
+ storageStatus: 'saved' | 'failed';
36
+ storageError?: string;
37
+ }
38
+ /** The stored-metadata fields that describe one persisted media file. */
39
+ export type PersistedMediaFields = Pick<GenerationMetadataFields, 'assetId' | 'assetVersionId' | 'vaultPath' | 'savedToVaultAt' | 'r2Key' | 'mimeType' | 'sizeBytes'>;
40
+ /** A persisted provider image: its workspace file, or the provider URL kept as the result. */
41
+ export type PersistedProviderImage = {
42
+ url: string;
43
+ } & Partial<Omit<PersistedGeneratedMedia, 'url'>>;
44
+ /** The settled state of a video or avatar job and the metadata fields it adds to the row. */
45
+ export interface SettledProviderJob {
46
+ /** The browser-usable result: the ingested file, else a public provider URL, else null while the job runs. */
47
+ result: string | null;
48
+ media: PersistedGeneratedMedia | null;
49
+ fields: Pick<GenerationMetadataFields, 'status' | 'provider' | 'providerJobId' | 'providerStatus' | 'resultUrl' | 'providerResultUrl' | 'pollingUrl' | 'storageStatus' | 'storageError'> & PersistedMediaFields;
50
+ }
51
+ /** The generation row fields a provider-job poll reads. */
52
+ export interface PolledGenerationRow {
53
+ workspaceId: string;
54
+ prompt: string;
55
+ model: string | null;
56
+ result: string | null;
57
+ createdAt: Date;
58
+ metadata: unknown;
59
+ }
60
+ /** What a poll decided for a generation row; the product writes the row. */
61
+ export type ProviderJobRefresh =
62
+ /** Nothing to write: the row is settled, not a provider job, or unchanged since the last poll. */
63
+ {
64
+ kind: 'unchanged';
65
+ }
66
+ /** A pending row never received a provider job id before the deadline; `metadata` fails it. */
67
+ | {
68
+ kind: 'stale';
69
+ metadata: Record<string, unknown>;
70
+ }
71
+ /** The provider job moved; write `result` and `metadata`. */
72
+ | {
73
+ kind: 'update';
74
+ status: GenerationStatus;
75
+ resultUrl?: string;
76
+ result: string | null;
77
+ metadata: Record<string, unknown>;
78
+ }
79
+ /** The poll itself failed; `metadata` records the error so the next poll retries. */
80
+ | {
81
+ kind: 'poll-failed';
82
+ metadata: Record<string, unknown>;
83
+ };
84
+ export interface GeneratedMediaFlowsConfig<Context> {
85
+ store: Pick<GeneratedMediaStore<Context>, 'persistGeneratedMediaAsset' | 'persistGeneratedMediaFromUrl' | 'cleanupGeneratedMediaAsset' | 'writeGeneratedTranscriptVaultFile'>;
86
+ /** The bound Router media client's source resolution and job poll. */
87
+ router: {
88
+ resolveRouterMediaSource(value: string, apiKey?: string): RouterMediaSource;
89
+ routerMediaStatus(id: string, signal?: AbortSignal, apiKey?: string): Promise<Record<string, unknown>>;
90
+ };
91
+ /** The bound Router generation calls. */
92
+ generation: {
93
+ generateAvatarViaRouter(body: RouterAvatarRequest, signal: AbortSignal | undefined, apiKey: string): Promise<Record<string, unknown>>;
94
+ transcribeViaRouter(request: RouterTranscriptionRequest): Promise<{
95
+ text?: string;
96
+ }>;
97
+ };
98
+ /**
99
+ * Products with an explicit save-to-Vault step record `savedToVaultAt: null`
100
+ * on media they store, so the library can tell stored media from saved media.
101
+ */
102
+ recordVaultSave?: boolean;
103
+ /** The provider error stored on a row; defaults to the message, capped at 500 characters. */
104
+ sanitizeProviderError?: (message: string) => string;
105
+ /**
106
+ * A result URL the store rejects as tool input fails the generation by default.
107
+ * False records it as a storage failure instead, keeping the provider's result row.
108
+ */
109
+ failOnRejectedResultUrl?: boolean;
110
+ }
111
+ interface MediaActor<Context> {
112
+ context: Context;
113
+ workspaceId: string;
114
+ userId: string;
115
+ prompt: string;
116
+ model: string;
117
+ outputPath: string | null;
118
+ /** Rechecks the caller's live authorization before persistence. */
119
+ recheck?: () => Promise<void>;
120
+ }
121
+ /** Bind the provider-side generation steps to a product's store and Router client. */
122
+ export declare function createGeneratedMediaFlows<Context>(config: GeneratedMediaFlowsConfig<Context>): {
123
+ mediaFields: (media: Parameters<typeof mediaFields>[1]) => PersistedMediaFields;
124
+ ingestFromUrl: (input: Parameters<typeof ingestFromUrl<Context>>[1]) => Promise<GeneratedMediaIngestion>;
125
+ settleProviderJob: (response: ProviderMediaJobResponse, providerJobId: string | null, input: Parameters<typeof settleProviderJob<Context>>[3]) => Promise<SettledProviderJob>;
126
+ generateAvatar: (input: Parameters<typeof generateAvatar<Context>>[1]) => Promise<SettledProviderJob>;
127
+ generateSpeech: (input: Parameters<typeof generateSpeech<Context>>[1]) => Promise<{
128
+ media: PersistedGeneratedMedia;
129
+ speechInput: SpeechInput;
130
+ fields: GenerationMetadataFields;
131
+ }>;
132
+ transcribe: (input: Parameters<typeof transcribe<Context>>[1]) => Promise<{
133
+ text: string;
134
+ fields: GenerationMetadataFields;
135
+ }>;
136
+ persistProviderImage: (input: Parameters<typeof persistProviderImage<Context>>[1]) => Promise<PersistedProviderImage>;
137
+ cleanupPersistedImages: (context: Context, images: readonly PersistedProviderImage[]) => Promise<void>;
138
+ refreshProviderJob: (row: PolledGenerationRow, input: Parameters<typeof refreshProviderJob<Context>>[2]) => Promise<ProviderJobRefresh>;
139
+ };
140
+ /** The stored-metadata fields of one persisted media file. */
141
+ declare function mediaFields<Context>(config: GeneratedMediaFlowsConfig<Context>, media: Omit<PersistedGeneratedMedia, 'url'> | Partial<Omit<PersistedGeneratedMedia, 'url'>> | null): PersistedMediaFields;
142
+ /**
143
+ * Ingest a provider result URL into the workspace. A storage failure is
144
+ * reported rather than thrown, so the provider's work is not discarded; an
145
+ * authorization failure still throws, and so does a rejected result URL unless
146
+ * `failOnRejectedResultUrl` is false.
147
+ */
148
+ declare function ingestFromUrl<Context>(config: GeneratedMediaFlowsConfig<Context>, input: {
149
+ context: Context;
150
+ workspaceId: string;
151
+ userId: string;
152
+ generationType: ProviderJobMediaType;
153
+ prompt: string;
154
+ model: string | null;
155
+ outputPath: string | null | undefined;
156
+ sourceUrl: string;
157
+ sourceAuthorization?: string;
158
+ metadata: Record<string, unknown>;
159
+ recheck?: () => Promise<void>;
160
+ }): Promise<GeneratedMediaIngestion>;
161
+ /**
162
+ * Settle a video or avatar provider response: ingest the video when the
163
+ * provider already returned it, else leave the job running. Router-proxied
164
+ * URLs need the Bearer key, so only the ingested file or a public provider
165
+ * URL becomes the result; a null result keeps the row running so a poll
166
+ * retries ingestion.
167
+ */
168
+ declare function settleProviderJob<Context>(config: GeneratedMediaFlowsConfig<Context>, response: ProviderMediaJobResponse, providerJobId: string | null, input: MediaActor<Context> & {
169
+ generationType: ProviderJobMediaType;
170
+ apiKey: string;
171
+ /** Request fields recorded on the ingested asset. */
172
+ sourceMetadata: Record<string, unknown>;
173
+ }): Promise<SettledProviderJob>;
174
+ /** Submit an avatar job through the Router and settle its response. */
175
+ declare function generateAvatar<Context>(config: GeneratedMediaFlowsConfig<Context>, input: MediaActor<Context> & {
176
+ effectivePrompt: string;
177
+ inputs: GenerateInputs;
178
+ apiKey: string;
179
+ callbackUrl?: string;
180
+ }): Promise<SettledProviderJob>;
181
+ /**
182
+ * Speak a prompt and store the audio. `resolveSpeechInput` decides whether the
183
+ * prompt is read literally or scripted first; `speak` is the product's
184
+ * text-to-speech call, bounded but not cancelled by the timeout.
185
+ */
186
+ declare function generateSpeech<Context>(config: GeneratedMediaFlowsConfig<Context>, input: MediaActor<Context> & {
187
+ voice: string;
188
+ apiKey: string;
189
+ /** The request's checked inputs; the stored record adds how the spoken text was produced. */
190
+ inputs: GenerateInputs;
191
+ resolveSpeechInput(prompt: string, apiKey: string): Promise<SpeechInput>;
192
+ speak(request: {
193
+ input: string;
194
+ model: string;
195
+ voice: string;
196
+ }): Promise<unknown>;
197
+ }): Promise<{
198
+ media: PersistedGeneratedMedia;
199
+ speechInput: SpeechInput;
200
+ fields: GenerationMetadataFields;
201
+ }>;
202
+ /** Transcribe the request's audio URL and write the transcript into the Vault. */
203
+ declare function transcribe<Context>(config: GeneratedMediaFlowsConfig<Context>, input: {
204
+ workspaceId: string;
205
+ generationId: string;
206
+ prompt: string;
207
+ model: string;
208
+ outputPath: string | null;
209
+ inputs: GenerateInputs;
210
+ apiKey: string;
211
+ createdAt: Date;
212
+ }): Promise<{
213
+ text: string;
214
+ fields: GenerationMetadataFields;
215
+ }>;
216
+ /**
217
+ * Persist one provider image. Inline bytes and data URIs are stored in the
218
+ * workspace; a remote URL is ingested when `remoteUrl` is `'ingest'`, or kept
219
+ * as the result when it is `'link'`.
220
+ */
221
+ declare function persistProviderImage<Context>(config: GeneratedMediaFlowsConfig<Context>, input: Omit<MediaActor<Context>, 'recheck'> & {
222
+ size: string;
223
+ quality: string;
224
+ url?: string;
225
+ b64Json?: string;
226
+ remoteUrl: 'ingest' | 'link';
227
+ recheck?: () => Promise<void>;
228
+ }): Promise<PersistedProviderImage>;
229
+ /**
230
+ * Advance a running video or avatar generation from its provider job: a
231
+ * succeeded job's video is ingested once, a no-op poll writes nothing, and a
232
+ * pending row that never received a job id fails after the deadline.
233
+ */
234
+ declare function refreshProviderJob<Context>(config: GeneratedMediaFlowsConfig<Context>, row: PolledGenerationRow, input: {
235
+ context: Context;
236
+ userId: string;
237
+ apiKey: string;
238
+ }): Promise<ProviderJobRefresh>;
239
+ export type GeneratedMediaFlows<Context> = ReturnType<typeof createGeneratedMediaFlows<Context>>;
240
+ export {};
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Server-only: studio-generated media as Vault files over a product's
3
- * `asset`, `asset_version` and `generation` tables (`drizzle-orm` peer).
3
+ * `asset`, `asset_version` and `generation` tables (`drizzle-orm` peer), and
4
+ * the provider-side generation steps bound to that store.
4
5
  */
5
6
  export * from './output';
6
7
  export * from './store';
8
+ export * from './flows';