@powerhousedao/clint 6.3.0-dev.9 → 6.4.0-next.1

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 (93) hide show
  1. package/dist/build-DZIv63eB.mjs +77 -0
  2. package/dist/build-DZIv63eB.mjs.map +1 -0
  3. package/dist/{build-skills-BnqGyuCH.mjs → build-skills-XkfkDhWl.mjs} +15 -6
  4. package/dist/build-skills-XkfkDhWl.mjs.map +1 -0
  5. package/dist/dist-Bd6hUl0J.mjs +655 -0
  6. package/dist/dist-Bd6hUl0J.mjs.map +1 -0
  7. package/dist/glob-CGjvhxgW.mjs +48 -0
  8. package/dist/glob-CGjvhxgW.mjs.map +1 -0
  9. package/dist/index-C3-HSfKb.d.mts +389 -0
  10. package/dist/index-C3-HSfKb.d.mts.map +1 -0
  11. package/dist/index.d.mts +55 -303
  12. package/dist/index.d.mts.map +1 -1
  13. package/dist/index.mjs +7 -8
  14. package/dist/integrations/mastra/index.d.mts +248 -0
  15. package/dist/integrations/mastra/index.d.mts.map +1 -0
  16. package/dist/integrations/mastra/index.mjs +509 -0
  17. package/dist/integrations/mastra/index.mjs.map +1 -0
  18. package/dist/integrations/powerhouse/index.d.mts +4 -0
  19. package/dist/integrations/powerhouse/index.mjs +3 -0
  20. package/dist/markdown-BUeGwhbR.mjs +1588 -0
  21. package/dist/markdown-BUeGwhbR.mjs.map +1 -0
  22. package/dist/powerhouse-3XZmdY3_.mjs +1922 -0
  23. package/dist/powerhouse-3XZmdY3_.mjs.map +1 -0
  24. package/dist/{proxy-BFR8GScT.mjs → proxy-ji3EHzLn.mjs} +128 -28
  25. package/dist/proxy-ji3EHzLn.mjs.map +1 -0
  26. package/dist/remote-reactor-oBsHphPT.mjs +69 -0
  27. package/dist/remote-reactor-oBsHphPT.mjs.map +1 -0
  28. package/dist/{start-b7Mn2cxB.mjs → repl-Czb7u0x_.mjs} +6 -29
  29. package/dist/repl-Czb7u0x_.mjs.map +1 -0
  30. package/dist/runners/cli-runner.d.mts +339 -0
  31. package/dist/runners/cli-runner.d.mts.map +1 -0
  32. package/dist/runners/cli-runner.mjs +324 -0
  33. package/dist/runners/cli-runner.mjs.map +1 -0
  34. package/dist/runners/mastra-runner.d.mts +5 -3
  35. package/dist/runners/mastra-runner.d.mts.map +1 -1
  36. package/dist/runners/mastra-runner.mjs +10 -60
  37. package/dist/runners/mastra-runner.mjs.map +1 -1
  38. package/dist/runners/proxy-runner.d.mts +281 -0
  39. package/dist/runners/proxy-runner.d.mts.map +1 -0
  40. package/dist/runners/proxy-runner.mjs +91 -0
  41. package/dist/runners/proxy-runner.mjs.map +1 -0
  42. package/dist/schema-BEKAZGyT.mjs +47 -0
  43. package/dist/schema-BEKAZGyT.mjs.map +1 -0
  44. package/dist/{src-BebNN3xc.mjs → src-055YwI8s.mjs} +395 -1481
  45. package/dist/src-055YwI8s.mjs.map +1 -0
  46. package/dist/start-BHn9LIyX.mjs +37 -0
  47. package/dist/start-BHn9LIyX.mjs.map +1 -0
  48. package/dist/store-CxqB-OrX.mjs +101 -0
  49. package/dist/store-CxqB-OrX.mjs.map +1 -0
  50. package/dist/{stream-DVuufwIj.mjs → stream-BguHx7vC.mjs} +4 -2
  51. package/dist/{stream-DVuufwIj.mjs.map → stream-BguHx7vC.mjs.map} +1 -1
  52. package/dist/testing/index.d.mts +81 -0
  53. package/dist/testing/index.d.mts.map +1 -0
  54. package/dist/testing/index.mjs +131 -0
  55. package/dist/testing/index.mjs.map +1 -0
  56. package/dist/{types-CRkoD-Mm.d.mts → types-CF6GuPJd.d.mts} +241 -261
  57. package/dist/types-CF6GuPJd.d.mts.map +1 -0
  58. package/dist/types-CbHJ-ZnH.d.mts +60 -0
  59. package/dist/types-CbHJ-ZnH.d.mts.map +1 -0
  60. package/package.json +44 -25
  61. package/dist/build-skills-BnqGyuCH.mjs.map +0 -1
  62. package/dist/dist-CUltriBW.mjs +0 -1628
  63. package/dist/dist-CUltriBW.mjs.map +0 -1
  64. package/dist/drive-Bu9zoFrO.mjs +0 -85
  65. package/dist/drive-Bu9zoFrO.mjs.map +0 -1
  66. package/dist/esm-C1DOsF1a.mjs +0 -13140
  67. package/dist/esm-C1DOsF1a.mjs.map +0 -1
  68. package/dist/events-BnwGFTjv.mjs +0 -237
  69. package/dist/events-BnwGFTjv.mjs.map +0 -1
  70. package/dist/folders-BYO1Wqqb.mjs +0 -256
  71. package/dist/folders-BYO1Wqqb.mjs.map +0 -1
  72. package/dist/local-signer-EFzJV3bn.mjs +0 -128
  73. package/dist/local-signer-EFzJV3bn.mjs.map +0 -1
  74. package/dist/markdown-D-sP2zw_.mjs +0 -275
  75. package/dist/markdown-D-sP2zw_.mjs.map +0 -1
  76. package/dist/proxy-BFR8GScT.mjs.map +0 -1
  77. package/dist/proxy-routes-DP3ztsnS.mjs +0 -215
  78. package/dist/proxy-routes-DP3ztsnS.mjs.map +0 -1
  79. package/dist/reactor-C9VIUX1H.mjs +0 -51
  80. package/dist/reactor-C9VIUX1H.mjs.map +0 -1
  81. package/dist/runners/clint-runner.d.mts +0 -398
  82. package/dist/runners/clint-runner.d.mts.map +0 -1
  83. package/dist/runners/clint-runner.mjs +0 -519
  84. package/dist/runners/clint-runner.mjs.map +0 -1
  85. package/dist/services-9E-r0nWl.mjs +0 -999
  86. package/dist/services-9E-r0nWl.mjs.map +0 -1
  87. package/dist/src-BebNN3xc.mjs.map +0 -1
  88. package/dist/start-b7Mn2cxB.mjs.map +0 -1
  89. package/dist/subscriptions-CfiflAsI.mjs +0 -38
  90. package/dist/subscriptions-CfiflAsI.mjs.map +0 -1
  91. package/dist/switchboard-CyvOavqL.mjs +0 -57
  92. package/dist/switchboard-CyvOavqL.mjs.map +0 -1
  93. package/dist/types-CRkoD-Mm.d.mts.map +0 -1
@@ -0,0 +1,1922 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
2
+ import { t as getSchemaFields } from "./schema-BEKAZGyT.mjs";
3
+ import "./remote-reactor-oBsHphPT.mjs";
4
+ import { createWriteStream, openAsBlob } from "node:fs";
5
+ import path, { extname } from "node:path";
6
+ import { z } from "zod";
7
+ import { randomUUID } from "node:crypto";
8
+ import { Readable } from "node:stream";
9
+ import { pipeline } from "node:stream/promises";
10
+ //#region src/core/command.ts
11
+ /**
12
+ * Define a command — the atomic unit of ph-clint.
13
+ * Compatible with Mastra createTool() shape.
14
+ */
15
+ function defineCommand(options) {
16
+ if (options.positional && options.positional.length > 0) {
17
+ const fields = getSchemaFields(options.inputSchema);
18
+ const fieldMap = new Map(fields.map((f) => [f.key, f]));
19
+ const seen = /* @__PURE__ */ new Set();
20
+ let sawOptional = false;
21
+ for (const key of options.positional) {
22
+ const field = fieldMap.get(key);
23
+ if (!field) throw new Error(`Command '${options.id}': positional field '${key}' is not in inputSchema`);
24
+ if (seen.has(key)) throw new Error(`Command '${options.id}': positional field '${key}' listed more than once`);
25
+ seen.add(key);
26
+ const isOptional = field.isOptional || field.hasDefault;
27
+ if (sawOptional && !isOptional) throw new Error(`Command '${options.id}': required positional '${key}' may not follow an optional positional`);
28
+ if (isOptional) sawOptional = true;
29
+ }
30
+ }
31
+ return options;
32
+ }
33
+ //#endregion
34
+ //#region src/integrations/powerhouse/change-trigger.ts
35
+ /**
36
+ * Build a Trigger that listens for document change events on the event bus,
37
+ * coalesces them, loads matching documents, narrows to the registered type,
38
+ * and hands them to the user's onChange handler.
39
+ *
40
+ * Runtime behavior:
41
+ * 1. `setup()` subscribes to `powerhouse:document:changed`. For each event,
42
+ * if any documentType matches (and, when `documentId` is a literal
43
+ * string, the id also matches), bump the pending counter.
44
+ * 2. If `initialReconcile !== false`, `setup()` bumps pending once on
45
+ * startup so the first poll reconciles without waiting for an event.
46
+ * 3. `poll()` returns null unless pending > 0. When pending > 0:
47
+ * - If `documentId` is set: load single doc, wrap in `[doc]`
48
+ * - If `documentId` is omitted: `find()` all docs of matching type(s)
49
+ * Applies `filter` per-doc, then calls `onChange(docs, ctx)`.
50
+ * 4. pending is reset to 0 at the start of each poll drain — multiple
51
+ * events within a tick coalesce to one `onChange` call.
52
+ */
53
+ function createDocumentChangeTrigger(options) {
54
+ const initialReconcile = options.initialReconcile !== false;
55
+ const types = Array.isArray(options.documentType) ? options.documentType : [options.documentType];
56
+ return {
57
+ id: options.id,
58
+ type: "condition",
59
+ state: options.state ?? (() => ({ pending: 0 })),
60
+ async setup(ctx) {
61
+ const log = ctx.context.log;
62
+ const on = ctx.context.on;
63
+ if (!on) {
64
+ log?.debug(`[${options.id}] no event bus on CoreContext — poll-only mode`);
65
+ if (initialReconcile) ctx.state.pending = 1;
66
+ return;
67
+ }
68
+ on("powerhouse:document:changed", (payload) => {
69
+ const documents = payload.documents ?? [];
70
+ if (!documents.some((d) => types.includes(d.header?.documentType))) return;
71
+ if (typeof options.documentId === "string") {
72
+ if (!documents.map((d) => d.header?.id).includes(options.documentId)) return;
73
+ }
74
+ ctx.state.pending += 1;
75
+ log?.debug(`[${options.id}] queued change (pending=${ctx.state.pending})`);
76
+ });
77
+ on("powerhouse:writes:ready", () => {
78
+ ctx.state.pending += 1;
79
+ });
80
+ if (initialReconcile) ctx.state.pending = 1;
81
+ },
82
+ async poll(ctx) {
83
+ if (!ctx.state.pending) return null;
84
+ ctx.state.pending = 0;
85
+ const reactor = await ctx.reactor();
86
+ if (!reactor) {
87
+ ctx.context.log?.debug(`[${options.id}] no reactor available, skipping`);
88
+ return null;
89
+ }
90
+ let docs;
91
+ if (options.documentId) {
92
+ const docId = typeof options.documentId === "function" ? await options.documentId(ctx) : options.documentId;
93
+ if (!docId) {
94
+ ctx.context.log?.debug(`[${options.id}] no target document id resolved, skipping`);
95
+ return null;
96
+ }
97
+ docs = [await reactor.client.get(docId)];
98
+ } else {
99
+ const allDocs = [];
100
+ for (const t of types) {
101
+ const found = (await reactor.client.find({ type: t }))?.results ?? [];
102
+ allDocs.push(...found);
103
+ }
104
+ docs = allDocs;
105
+ if (docs.length === 0 && !options.callOnEmpty) return null;
106
+ }
107
+ if (options.filter) {
108
+ const filtered = [];
109
+ for (const doc of docs) if (await options.filter(doc, ctx)) filtered.push(doc);
110
+ if (filtered.length === 0) return null;
111
+ docs = filtered;
112
+ }
113
+ return options.onChange(docs, ctx);
114
+ }
115
+ };
116
+ }
117
+ //#endregion
118
+ //#region src/integrations/powerhouse/registry.ts
119
+ /**
120
+ * Build a DocumentRegistry from a tuple of DocumentModelModules.
121
+ *
122
+ * ```ts
123
+ * const registry = defineRegistry([PhClintProject, DocumentDrive] as const);
124
+ * // typeof registry:
125
+ * // {
126
+ * // 'powerhouse/ph-clint-project': RegistryEntry<PhClintProjectPHState, PhClintProjectAction>;
127
+ * // 'powerhouse/document-drive': RegistryEntry<DocumentDrivePHState, DocumentDriveAction>;
128
+ * // }
129
+ * ```
130
+ *
131
+ * Runtime value is a plain object keyed by `documentModel.id`. Consumers can
132
+ * introspect it to list registered types; Phase 3's
133
+ * `createDocumentChangeTrigger` also uses it for runtime lookup.
134
+ */
135
+ function defineRegistry(modules) {
136
+ const out = {};
137
+ for (const mod of modules) out[mod.documentModel.global.id] = mod;
138
+ return out;
139
+ }
140
+ //#endregion
141
+ //#region src/integrations/powerhouse/subscriptions.ts
142
+ /**
143
+ * Bridge Reactor document subscriptions to the ph-clint event bus.
144
+ *
145
+ * @param client - The reactor client (in-process or remote)
146
+ * @param subscriptions - Filter configuration for which document changes to bridge
147
+ * @param emit - Event bus emit function from CommandContext
148
+ * @returns Unsubscribe function
149
+ */
150
+ function bridgeSubscriptions(client, subscriptions, emit) {
151
+ const search = {};
152
+ if (subscriptions.documentTypes) search.documentTypes = subscriptions.documentTypes;
153
+ return client.subscribe(search, (event) => {
154
+ try {
155
+ switch (event.type) {
156
+ case "created":
157
+ for (const doc of event.documents ?? []) emit("powerhouse:document:created", {
158
+ documentId: doc.header.id,
159
+ documentType: doc.header.documentType
160
+ });
161
+ break;
162
+ case "updated":
163
+ emit("powerhouse:document:changed", {
164
+ changeType: "updated",
165
+ documents: event.documents
166
+ });
167
+ break;
168
+ case "deleted": for (const doc of event.documents ?? []) emit("powerhouse:document:deleted", { documentId: doc.header.id });
169
+ }
170
+ } catch {}
171
+ });
172
+ }
173
+ //#endregion
174
+ //#region src/integrations/powerhouse/drive.ts
175
+ const DRIVE_DOCUMENT_TYPE = "powerhouse/document-drive";
176
+ /**
177
+ * Ensure a drive exists, matching by name. On first run, creates a new drive.
178
+ * On subsequent runs, finds the existing one by name.
179
+ *
180
+ * Works on a client alone, in-process or remote: drives are documents of type
181
+ * `powerhouse/document-drive`, listed with `client.find({ type })`, built
182
+ * with `client.newDocument()` and created, already named, with one
183
+ * `client.write.create()`. Those three are what both the in-process
184
+ * `IReactorClient` and `GraphQLReactorClient` (which has no
185
+ * `write.createEmpty` or `write.rename`) offer. A Cli passes its own
186
+ * `ReactorContext.client` as it is (see `EnsureDriveClient`).
187
+ *
188
+ * @param client - The reactor client the drive is looked up and created with
189
+ * @param driveConfig - Optional drive name/icon configuration and hooks
190
+ * @returns The drive ID and name; `deferred` (and id '') when `canCreate`
191
+ * held back a drive that does not exist yet
192
+ */
193
+ async function ensureDrive(client, driveConfig) {
194
+ const driveName = driveConfig?.name ?? "default";
195
+ const wantedId = driveConfig?.id;
196
+ const preferredEditor = driveConfig?.preferredEditor;
197
+ const resolved = await driveConfig?.resolveId?.(client);
198
+ if (resolved) return {
199
+ id: resolved,
200
+ name: driveName
201
+ };
202
+ const matchByName = driveConfig?.matchByName !== false;
203
+ const existing = wantedId || matchByName ? await findDrives(client) : [];
204
+ if (existing.length) {
205
+ if (wantedId) {
206
+ if (existing.find((doc) => doc.header.id === wantedId)) return {
207
+ id: wantedId,
208
+ name: driveName
209
+ };
210
+ }
211
+ for (const doc of matchByName ? existing : []) {
212
+ const named = doc;
213
+ if ((named.name ?? named.header?.name ?? named.state?.global?.name) === driveName) return {
214
+ id: doc.header.id,
215
+ name: driveName
216
+ };
217
+ }
218
+ if (matchByName && driveName === "default" && existing.length === 1) return {
219
+ id: existing[0].header.id,
220
+ name: driveName
221
+ };
222
+ }
223
+ if (driveConfig?.canCreate && !driveConfig.canCreate()) return {
224
+ id: "",
225
+ name: driveName,
226
+ deferred: true
227
+ };
228
+ const doc = await client.newDocument(DRIVE_DOCUMENT_TYPE, {
229
+ initialState: { global: { name: driveName } },
230
+ ...wantedId ? {
231
+ signaturePolicy: "legacy",
232
+ id: wantedId
233
+ } : {}
234
+ });
235
+ doc.header.name = driveName;
236
+ if (preferredEditor) doc.header.meta = {
237
+ ...doc.header.meta,
238
+ preferredEditor
239
+ };
240
+ const driveId = (await (await client.write.create(doc)).document()).header.id;
241
+ await driveConfig?.onCreated?.(driveId);
242
+ return {
243
+ id: driveId,
244
+ name: driveName
245
+ };
246
+ }
247
+ /** Every drive document the client serves, across result pages. */
248
+ async function findDrives(client) {
249
+ const drives = [];
250
+ let page = await client.find({ type: DRIVE_DOCUMENT_TYPE });
251
+ drives.push(...page.results);
252
+ while (page.next) {
253
+ page = await page.next();
254
+ drives.push(...page.results);
255
+ }
256
+ return drives;
257
+ }
258
+ //#endregion
259
+ //#region src/integrations/powerhouse/signing.ts
260
+ /** The agent cannot sign yet: its signer has no user. */
261
+ var SignerNotReadyError = class extends Error {
262
+ constructor(what = "this write") {
263
+ super(`The agent cannot sign ${what} yet: it has no signed-in identity.`);
264
+ this.name = "SignerNotReadyError";
265
+ }
266
+ };
267
+ /** True when the signer can sign as a user. */
268
+ function signerReady(signer) {
269
+ return Boolean(signer.user?.address);
270
+ }
271
+ /** The policy a header carries (same rule as document-model's `signaturePolicyOf`). */
272
+ function policyOfHeader(header) {
273
+ const version = header?.protocolVersions?.signature;
274
+ return typeof version === "number" && version >= 2 ? "v2-required" : "legacy";
275
+ }
276
+ /**
277
+ * The signer, refusing to sign while it has no user. Everything else is read
278
+ * through to the live signer.
279
+ */
280
+ function createGatedSigner(signer) {
281
+ return new Proxy(signer, { get(target, prop, receiver) {
282
+ if (prop === "signAction") return async (...args) => {
283
+ if (!signerReady(target)) throw new SignerNotReadyError();
284
+ return target.signAction(...args);
285
+ };
286
+ const value = Reflect.get(target, prop, receiver);
287
+ return typeof value === "function" ? value.bind(target) : value;
288
+ } });
289
+ }
290
+ /** Whether the agent may write `document` right now (no reactor call). */
291
+ function canWrite(rules, document) {
292
+ if (rules.accepts && !rules.accepts(document)) return false;
293
+ if (policyOfHeader(document.header) === "v2-required") return rules.ready();
294
+ return rules.legacyDocuments !== "refuse";
295
+ }
296
+ //#endregion
297
+ //#region src/integrations/powerhouse/writes.ts
298
+ /** See {@link ReactorWritesOptions} and {@link ReactorWritesHandle}. */
299
+ function createReactorWrites(options = {}) {
300
+ const source = options.signer;
301
+ const rules = {
302
+ ready: () => source ? signerReady(source) : true,
303
+ legacyDocuments: options.legacyDocuments ?? "sign-when-ready",
304
+ accepts: options.accepts
305
+ };
306
+ const writes = {
307
+ ready: rules.ready,
308
+ canWrite: (document) => canWrite(rules, document)
309
+ };
310
+ let signer;
311
+ if (source) {
312
+ const gated = createGatedSigner(source);
313
+ signer = () => {
314
+ if (!signerReady(source)) throw new SignerNotReadyError();
315
+ return gated;
316
+ };
317
+ }
318
+ let wasReady = rules.ready();
319
+ const unsubscribe = options.onSignerChange?.(() => {
320
+ const now = rules.ready();
321
+ if (now && !wasReady) options.emit?.("powerhouse:writes:ready", {});
322
+ wasReady = now;
323
+ });
324
+ return {
325
+ writes,
326
+ signer,
327
+ stop: () => unsubscribe?.()
328
+ };
329
+ }
330
+ //#endregion
331
+ //#region src/integrations/powerhouse/type-guard.ts
332
+ /**
333
+ * Type guard for discriminated narrowing in multi-type onChange handlers.
334
+ *
335
+ * Usage:
336
+ * onChange(docs, ctx) {
337
+ * for (const doc of docs) {
338
+ * if (isDocType(doc, 'powerhouse/ph-clint-project')) {
339
+ * // doc is narrowed to R['powerhouse/ph-clint-project']['document']
340
+ * }
341
+ * }
342
+ * }
343
+ */
344
+ function isDocType(doc, type) {
345
+ return doc.header?.documentType === type;
346
+ }
347
+ //#endregion
348
+ //#region src/integrations/powerhouse/folders.ts
349
+ /**
350
+ * FolderOperations — programmatic API for managing documents
351
+ * in the agent's personal drive using the drive's internal node tree.
352
+ *
353
+ * Folders and file references are stored as nodes in the drive document's
354
+ * `state.global.nodes` array, managed via ADD_FOLDER and ADD_FILE operations.
355
+ * This is distinct from the parent-child document graph (addRelationship/getOutgoingRelationships).
356
+ *
357
+ * Also exports `createFolderCommands()` to auto-generate CLI commands
358
+ * that wrap the folder operations.
359
+ */
360
+ var folders_exports = /* @__PURE__ */ __exportAll({
361
+ createFolderCommands: () => createFolderCommands,
362
+ createFolderOperations: () => createFolderOperations
363
+ });
364
+ const TAG = "[folders]";
365
+ function isFolder(node) {
366
+ return node.kind === "folder";
367
+ }
368
+ /**
369
+ * Read the drive document's internal nodes array.
370
+ */
371
+ async function getDriveNodes(client, driveId) {
372
+ return (await client.get(driveId))?.state?.global?.nodes ?? [];
373
+ }
374
+ /**
375
+ * Create a FolderOperations instance backed by the reactor client.
376
+ *
377
+ * Folders are nodes inside the drive document's `state.global.nodes` array,
378
+ * created via `ADD_FOLDER` and `ADD_FILE` drive operations executed on the
379
+ * personal drive. This is separate from the document relationship graph.
380
+ * Only calls the remote `GraphQLReactorClient` has too are made, so the same
381
+ * operations work on an in-process and on an attached reactor.
382
+ */
383
+ function createFolderOperations(client, personalDriveId, log) {
384
+ /**
385
+ * Lazy-load drive action creators from @powerhousedao/shared.
386
+ * Kept lazy so that importing folders.ts doesn't pull in the entire
387
+ * @powerhousedao/shared tree — which is an optional peer dependency
388
+ * and won't be installed in non-Powerhouse projects.
389
+ */
390
+ let _driveActions = null;
391
+ async function getDriveActions() {
392
+ if (!_driveActions) {
393
+ const mod = await import("@powerhousedao/shared/document-drive");
394
+ _driveActions = {
395
+ addFolder: mod.addFolder,
396
+ addFile: mod.addFile,
397
+ deleteNode: mod.deleteNode
398
+ };
399
+ }
400
+ return _driveActions;
401
+ }
402
+ function splitPath(folderPath) {
403
+ return folderPath.split("/").filter(Boolean);
404
+ }
405
+ /**
406
+ * Find a folder node by name under a given parent in the drive's nodes.
407
+ */
408
+ function findFolderInNodes(nodes, name, parentId) {
409
+ return nodes.find((n) => isFolder(n) && n.name === name && (n.parentFolder ?? null) === parentId);
410
+ }
411
+ async function ensureFolder(folderPath) {
412
+ const segments = splitPath(folderPath);
413
+ let parentFolderId = null;
414
+ for (const segment of segments) {
415
+ const existing = findFolderInNodes(await getDriveNodes(client, personalDriveId), segment, parentFolderId);
416
+ if (existing) {
417
+ log?.debug(`${TAG} ensureFolder segment "${segment}" → exists ${existing.id.slice(0, 8)}…`);
418
+ parentFolderId = existing.id;
419
+ continue;
420
+ }
421
+ const folderId = randomUUID();
422
+ log?.debug(`${TAG} ensureFolder creating folder "${segment}" (${folderId.slice(0, 8)}…) under ${parentFolderId?.slice(0, 8) ?? "root"}`);
423
+ const actions = await getDriveActions();
424
+ await (await client.write.execute(personalDriveId, "main", [actions.addFolder({
425
+ id: folderId,
426
+ name: segment,
427
+ parentFolder: parentFolderId
428
+ })])).document();
429
+ parentFolderId = folderId;
430
+ }
431
+ return parentFolderId;
432
+ }
433
+ async function addDocument(documentId, folderPath, name) {
434
+ log?.debug(`${TAG} addDocument ${documentId.slice(0, 8)}… to "${folderPath}" name=${name ?? "(none)"}`);
435
+ const folderId = await ensureFolder(folderPath);
436
+ const existingFile = (await getDriveNodes(client, personalDriveId)).find((n) => !isFolder(n) && n.id === documentId);
437
+ if (existingFile) {
438
+ log?.debug(`${TAG} addDocument ${documentId.slice(0, 8)}… already in drive as "${existingFile.name}"`);
439
+ return;
440
+ }
441
+ const doc = await client.get(documentId);
442
+ const documentType = doc?.header?.documentType ?? doc?.documentType ?? "unknown";
443
+ const displayName = name ?? doc?.header?.name ?? doc?.name ?? documentId;
444
+ const actions = await getDriveActions();
445
+ await (await client.write.execute(personalDriveId, "main", [actions.addFile({
446
+ id: documentId,
447
+ name: displayName,
448
+ documentType,
449
+ parentFolder: folderId
450
+ })])).document();
451
+ await (await client.write.addRelationship(personalDriveId, documentId, "child")).document();
452
+ if (name) await (await client.write.rename(documentId, name)).document();
453
+ log?.debug(`${TAG} addDocument ${documentId.slice(0, 8)}… added as "${displayName}" in folder ${folderId.slice(0, 8)}…`);
454
+ }
455
+ async function createDocument(documentType, folderPath, name) {
456
+ log?.debug(`${TAG} createDocument type=${documentType} folder="${folderPath}" name=${name ?? "(none)"}`);
457
+ const parentFolderId = await ensureFolder(folderPath);
458
+ const doc = await client.newDocument(documentType, {
459
+ parentIdentifier: personalDriveId,
460
+ name
461
+ });
462
+ const documentId = doc.header.id;
463
+ await (await client.write.create(doc)).readable;
464
+ const actions = await getDriveActions();
465
+ await (await client.write.execute(personalDriveId, "main", [actions.addFile({
466
+ id: documentId,
467
+ name: doc.header.name || documentId,
468
+ documentType: doc.header.documentType,
469
+ parentFolder: parentFolderId
470
+ })])).readable;
471
+ await (await client.write.addRelationship(personalDriveId, documentId, "child")).readable;
472
+ log?.debug(`${TAG} createDocument ${documentId.slice(0, 8)}… created in folder ${parentFolderId.slice(0, 8)}…`);
473
+ return { documentId };
474
+ }
475
+ async function removeDocument(documentId, _folderPath) {
476
+ const actions = await getDriveActions();
477
+ await (await client.write.execute(personalDriveId, "main", [actions.deleteNode({ id: documentId })])).document();
478
+ await (await client.write.removeRelationship(personalDriveId, documentId, "child")).document();
479
+ }
480
+ async function resolveFolder(folderPath) {
481
+ const segments = splitPath(folderPath);
482
+ const nodes = await getDriveNodes(client, personalDriveId);
483
+ let parentFolderId = null;
484
+ for (const segment of segments) {
485
+ const match = findFolderInNodes(nodes, segment, parentFolderId);
486
+ if (!match) return void 0;
487
+ parentFolderId = match.id;
488
+ }
489
+ return parentFolderId ?? void 0;
490
+ }
491
+ async function getDocument(documentId) {
492
+ return client.get(documentId);
493
+ }
494
+ async function listFolder(folderPath) {
495
+ let parentFolderId = null;
496
+ if (folderPath) {
497
+ const resolved = await resolveFolder(folderPath);
498
+ if (!resolved) return [];
499
+ parentFolderId = resolved;
500
+ }
501
+ const nodes = await getDriveNodes(client, personalDriveId);
502
+ const prefix = folderPath ? folderPath.replace(/\/+$/, "") : "";
503
+ return nodes.filter((n) => (n.parentFolder ?? null) === parentFolderId).map((n) => ({
504
+ id: n.id,
505
+ name: n.name,
506
+ type: isFolder(n) ? "folder" : "document",
507
+ documentType: isFolder(n) ? void 0 : n.documentType,
508
+ path: prefix ? `${prefix}/${n.name}` : n.name
509
+ }));
510
+ }
511
+ async function findByType(documentType) {
512
+ return (await getDriveNodes(client, personalDriveId)).filter((n) => !isFolder(n) && n.documentType === documentType).map((n) => ({
513
+ id: n.id,
514
+ name: n.name,
515
+ type: "document",
516
+ documentType: n.documentType,
517
+ path: n.name
518
+ }));
519
+ }
520
+ return {
521
+ addDocument,
522
+ createDocument,
523
+ removeDocument,
524
+ getDocument,
525
+ listFolder,
526
+ ensureFolder,
527
+ findByType
528
+ };
529
+ }
530
+ const addDocumentSchema = z.object({
531
+ documentId: z.string().describe("Document ID to add"),
532
+ folderPath: z.string().describe("Folder path (e.g. \"specs/my-project\")"),
533
+ name: z.string().optional().describe("Display name for the document")
534
+ });
535
+ const removeDocumentSchema = z.object({
536
+ documentId: z.string().describe("Document ID to remove"),
537
+ folderPath: z.string().optional().describe("Folder path to remove from")
538
+ });
539
+ const getDocumentSchema = z.object({ documentId: z.string().describe("Document ID to retrieve") });
540
+ const listFolderSchema = z.object({ folderPath: z.string().optional().describe("Folder path (root if omitted)") });
541
+ /**
542
+ * Auto-generate CLI commands that wrap FolderOperations.
543
+ */
544
+ function createFolderCommands(folderOps) {
545
+ return [
546
+ {
547
+ id: "folders-add-document",
548
+ description: "Add a document to the personal drive at a folder path",
549
+ inputSchema: addDocumentSchema,
550
+ outputSchema: z.object({ text: z.string() }),
551
+ execute: async (input) => {
552
+ await folderOps.addDocument(input.documentId, input.folderPath, input.name);
553
+ return { text: `Added document ${input.documentId} to ${input.folderPath}` };
554
+ }
555
+ },
556
+ {
557
+ id: "folders-remove-document",
558
+ description: "Remove a document from the personal drive",
559
+ inputSchema: removeDocumentSchema,
560
+ outputSchema: z.object({ text: z.string() }),
561
+ execute: async (input) => {
562
+ await folderOps.removeDocument(input.documentId, input.folderPath);
563
+ return { text: `Removed document ${input.documentId}` };
564
+ }
565
+ },
566
+ {
567
+ id: "folders-get-document",
568
+ description: "Get a document from the personal drive",
569
+ inputSchema: getDocumentSchema,
570
+ outputSchema: z.object({
571
+ text: z.string(),
572
+ data: z.unknown()
573
+ }),
574
+ execute: async (input) => {
575
+ const doc = await folderOps.getDocument(input.documentId);
576
+ return {
577
+ text: JSON.stringify(doc, null, 2),
578
+ data: doc
579
+ };
580
+ }
581
+ },
582
+ {
583
+ id: "folders-ls",
584
+ description: "List folder contents in the personal drive",
585
+ inputSchema: listFolderSchema,
586
+ outputSchema: z.object({
587
+ text: z.string(),
588
+ data: z.array(z.unknown())
589
+ }),
590
+ execute: async (input) => {
591
+ const entries = await folderOps.listFolder(input.folderPath);
592
+ if (entries.length === 0) return {
593
+ text: "Empty folder",
594
+ data: []
595
+ };
596
+ return {
597
+ text: entries.map((e) => {
598
+ const icon = e.type === "folder" ? "[dir]" : "[doc]";
599
+ const typeInfo = e.documentType ? ` (${e.documentType})` : "";
600
+ return ` ${icon} ${e.name}${typeInfo} ${e.id.slice(0, 8)}...`;
601
+ }).join("\n"),
602
+ data: entries
603
+ };
604
+ }
605
+ }
606
+ ];
607
+ }
608
+ //#endregion
609
+ //#region ../reactor-attachments/dist/switchboard-attachment-transport-BH3ZAmxE.js
610
+ /**
611
+ * Thrown when an attachment ref or hash is not known to the store.
612
+ */
613
+ var AttachmentNotFound = class extends Error {
614
+ constructor(identifier) {
615
+ super(`Attachment not found: ${identifier}`);
616
+ this.name = "AttachmentNotFound";
617
+ }
618
+ };
619
+ /**
620
+ * Thrown when a reservation ID is not found in the reservation store.
621
+ */
622
+ var ReservationNotFound = class extends Error {
623
+ constructor(reservationId) {
624
+ super(`Reservation not found: ${reservationId}`);
625
+ this.name = "ReservationNotFound";
626
+ }
627
+ };
628
+ /**
629
+ * Thrown when an attachment ref string does not match the expected format.
630
+ */
631
+ var InvalidAttachmentRef = class extends Error {
632
+ constructor(ref) {
633
+ super(`Invalid attachment ref: ${ref}`);
634
+ this.name = "InvalidAttachmentRef";
635
+ }
636
+ };
637
+ /**
638
+ * Thrown by reserve() when the claimed hash is already available in the store.
639
+ * The caller should use err.ref directly and upload nothing -- this is the
640
+ * dedup fast path: duplicate content never leaves the client.
641
+ */
642
+ var AttachmentAlreadyExists = class extends Error {
643
+ hash;
644
+ ref;
645
+ constructor(hash, ref) {
646
+ super(`Attachment already exists for hash: ${hash}`);
647
+ this.name = "AttachmentAlreadyExists";
648
+ this.hash = hash;
649
+ this.ref = ref;
650
+ }
651
+ };
652
+ /**
653
+ * Thrown by send() when the server-computed hash of the uploaded bytes
654
+ * does not match the hash claimed at reservation time. Nothing is committed;
655
+ * the reservation is retained so the client can retry with correct bytes.
656
+ */
657
+ var HashMismatch = class extends Error {
658
+ claimed;
659
+ actual;
660
+ constructor(claimed, actual) {
661
+ super(`Hash mismatch: claimed ${claimed} but computed ${actual}`);
662
+ this.name = "HashMismatch";
663
+ this.claimed = claimed;
664
+ this.actual = actual;
665
+ }
666
+ };
667
+ /**
668
+ * Thrown by send() when the uploaded byte count does not equal the
669
+ * sizeBytes declared at reservation time. The handle may reject
670
+ * mid-stream as soon as the count exceeds the declaration.
671
+ * Nothing is committed; the reservation is retained for retry.
672
+ *
673
+ * "actual" is the byte count received from the stream before aborting --
674
+ * it includes the chunk that crossed the declaration and can exceed bytes
675
+ * persisted. On mid-stream aborts the true total is unknown; at least
676
+ * "actual" bytes were sent.
677
+ */
678
+ var SizeMismatch = class extends Error {
679
+ declared;
680
+ actual;
681
+ constructor(declared, actual) {
682
+ super(`Size mismatch: declared ${declared} bytes but received ${actual}`);
683
+ this.name = "SizeMismatch";
684
+ this.declared = declared;
685
+ this.actual = actual;
686
+ }
687
+ };
688
+ /**
689
+ * Thrown when a remote transfer step fails. Identifies the stage only; it
690
+ * intentionally carries no URL, signature query, bucket key, or bearer
691
+ * material so it is always safe to log or surface.
692
+ */
693
+ var AttachmentTransferError = class extends Error {
694
+ stage;
695
+ status;
696
+ constructor(stage, status) {
697
+ super(status === void 0 ? `Attachment ${stage} request failed` : `Attachment ${stage} request failed with status ${status}`);
698
+ this.name = "AttachmentTransferError";
699
+ this.stage = stage;
700
+ this.status = status;
701
+ }
702
+ };
703
+ var AttachmentPending = class extends Error {
704
+ hash;
705
+ expiresAtUtc;
706
+ metadata;
707
+ constructor(hash, expiresAtUtc, meta) {
708
+ super(`Attachment pending upload for hash: ${hash}, expires: ${expiresAtUtc}`);
709
+ this.name = "AttachmentPending";
710
+ this.hash = hash;
711
+ this.expiresAtUtc = expiresAtUtc;
712
+ this.metadata = meta;
713
+ }
714
+ };
715
+ const REF_PATTERN = /^attachment:\/\/v(\d+):(.+)$/;
716
+ const DEFAULT_VERSION = 1;
717
+ function parseRef(ref) {
718
+ const match = REF_PATTERN.exec(ref);
719
+ if (!match) throw new InvalidAttachmentRef(ref);
720
+ return {
721
+ version: Number(match[1]),
722
+ hash: match[2]
723
+ };
724
+ }
725
+ function createRef(hash, version = DEFAULT_VERSION) {
726
+ return `attachment://v${version}:${hash}`;
727
+ }
728
+ async function buildAuthHeaders(url, jwtHandler) {
729
+ const headers = {};
730
+ if (jwtHandler) {
731
+ const token = await jwtHandler(url);
732
+ if (token) headers["Authorization"] = `Bearer ${token}`;
733
+ }
734
+ return headers;
735
+ }
736
+ //#endregion
737
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js
738
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
739
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
740
+ function isBytes(a) {
741
+ return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
742
+ }
743
+ /** Asserts something is Uint8Array. */
744
+ function abytes(b, ...lengths) {
745
+ if (!isBytes(b)) throw new Error("Uint8Array expected");
746
+ if (lengths.length > 0 && !lengths.includes(b.length)) throw new Error("Uint8Array expected of length " + lengths + ", got length=" + b.length);
747
+ }
748
+ /** Asserts a hash instance has not been destroyed / finished */
749
+ function aexists(instance, checkFinished = true) {
750
+ if (instance.destroyed) throw new Error("Hash instance has been destroyed");
751
+ if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
752
+ }
753
+ /** Asserts output is properly-sized byte array */
754
+ function aoutput(out, instance) {
755
+ abytes(out);
756
+ const min = instance.outputLen;
757
+ if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
758
+ }
759
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
760
+ function clean(...arrays) {
761
+ for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
762
+ }
763
+ /** Create DataView of an array for easy byte-level manipulation. */
764
+ function createView(arr) {
765
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
766
+ }
767
+ /** The rotate right (circular right shift) operation for uint32 */
768
+ function rotr(word, shift) {
769
+ return word << 32 - shift | word >>> shift;
770
+ }
771
+ const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
772
+ const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
773
+ /**
774
+ * Convert byte array to hex string. Uses built-in function, when available.
775
+ * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
776
+ */
777
+ function bytesToHex(bytes) {
778
+ abytes(bytes);
779
+ if (hasHexBuiltin) return bytes.toHex();
780
+ let hex = "";
781
+ for (let i = 0; i < bytes.length; i++) hex += hexes[bytes[i]];
782
+ return hex;
783
+ }
784
+ /**
785
+ * Converts string to bytes using UTF8 encoding.
786
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
787
+ */
788
+ function utf8ToBytes(str) {
789
+ if (typeof str !== "string") throw new Error("string expected");
790
+ return new Uint8Array(new TextEncoder().encode(str));
791
+ }
792
+ /**
793
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
794
+ * Warning: when Uint8Array is passed, it would NOT get copied.
795
+ * Keep in mind for future mutable operations.
796
+ */
797
+ function toBytes(data) {
798
+ if (typeof data === "string") data = utf8ToBytes(data);
799
+ abytes(data);
800
+ return data;
801
+ }
802
+ /** For runtime check if class implements interface */
803
+ var Hash = class {};
804
+ /** Wraps hash function, creating an interface on top of it */
805
+ function createHasher(hashCons) {
806
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
807
+ const tmp = hashCons();
808
+ hashC.outputLen = tmp.outputLen;
809
+ hashC.blockLen = tmp.blockLen;
810
+ hashC.create = () => hashCons();
811
+ return hashC;
812
+ }
813
+ //#endregion
814
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_md.js
815
+ /**
816
+ * Internal Merkle-Damgard hash utils.
817
+ * @module
818
+ */
819
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
820
+ function setBigUint64(view, byteOffset, value, isLE) {
821
+ if (typeof view.setBigUint64 === "function") return view.setBigUint64(byteOffset, value, isLE);
822
+ const _32n = BigInt(32);
823
+ const _u32_max = BigInt(4294967295);
824
+ const wh = Number(value >> _32n & _u32_max);
825
+ const wl = Number(value & _u32_max);
826
+ const h = isLE ? 4 : 0;
827
+ const l = isLE ? 0 : 4;
828
+ view.setUint32(byteOffset + h, wh, isLE);
829
+ view.setUint32(byteOffset + l, wl, isLE);
830
+ }
831
+ /** Choice: a ? b : c */
832
+ function Chi(a, b, c) {
833
+ return a & b ^ ~a & c;
834
+ }
835
+ /** Majority function, true if any two inputs is true. */
836
+ function Maj(a, b, c) {
837
+ return a & b ^ a & c ^ b & c;
838
+ }
839
+ /**
840
+ * Merkle-Damgard hash construction base class.
841
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
842
+ */
843
+ var HashMD = class extends Hash {
844
+ constructor(blockLen, outputLen, padOffset, isLE) {
845
+ super();
846
+ this.finished = false;
847
+ this.length = 0;
848
+ this.pos = 0;
849
+ this.destroyed = false;
850
+ this.blockLen = blockLen;
851
+ this.outputLen = outputLen;
852
+ this.padOffset = padOffset;
853
+ this.isLE = isLE;
854
+ this.buffer = new Uint8Array(blockLen);
855
+ this.view = createView(this.buffer);
856
+ }
857
+ update(data) {
858
+ aexists(this);
859
+ data = toBytes(data);
860
+ abytes(data);
861
+ const { view, buffer, blockLen } = this;
862
+ const len = data.length;
863
+ for (let pos = 0; pos < len;) {
864
+ const take = Math.min(blockLen - this.pos, len - pos);
865
+ if (take === blockLen) {
866
+ const dataView = createView(data);
867
+ for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
868
+ continue;
869
+ }
870
+ buffer.set(data.subarray(pos, pos + take), this.pos);
871
+ this.pos += take;
872
+ pos += take;
873
+ if (this.pos === blockLen) {
874
+ this.process(view, 0);
875
+ this.pos = 0;
876
+ }
877
+ }
878
+ this.length += data.length;
879
+ this.roundClean();
880
+ return this;
881
+ }
882
+ digestInto(out) {
883
+ aexists(this);
884
+ aoutput(out, this);
885
+ this.finished = true;
886
+ const { buffer, view, blockLen, isLE } = this;
887
+ let { pos } = this;
888
+ buffer[pos++] = 128;
889
+ clean(this.buffer.subarray(pos));
890
+ if (this.padOffset > blockLen - pos) {
891
+ this.process(view, 0);
892
+ pos = 0;
893
+ }
894
+ for (let i = pos; i < blockLen; i++) buffer[i] = 0;
895
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
896
+ this.process(view, 0);
897
+ const oview = createView(out);
898
+ const len = this.outputLen;
899
+ if (len % 4) throw new Error("_sha2: outputLen should be aligned to 32bit");
900
+ const outLen = len / 4;
901
+ const state = this.get();
902
+ if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
903
+ for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);
904
+ }
905
+ digest() {
906
+ const { buffer, outputLen } = this;
907
+ this.digestInto(buffer);
908
+ const res = buffer.slice(0, outputLen);
909
+ this.destroy();
910
+ return res;
911
+ }
912
+ _cloneInto(to) {
913
+ to || (to = new this.constructor());
914
+ to.set(...this.get());
915
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
916
+ to.destroyed = destroyed;
917
+ to.finished = finished;
918
+ to.length = length;
919
+ to.pos = pos;
920
+ if (length % blockLen) to.buffer.set(buffer);
921
+ return to;
922
+ }
923
+ clone() {
924
+ return this._cloneInto();
925
+ }
926
+ };
927
+ /**
928
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
929
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
930
+ */
931
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
932
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
933
+ 1779033703,
934
+ 3144134277,
935
+ 1013904242,
936
+ 2773480762,
937
+ 1359893119,
938
+ 2600822924,
939
+ 528734635,
940
+ 1541459225
941
+ ]);
942
+ //#endregion
943
+ //#region ../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha2.js
944
+ /**
945
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
946
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
947
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
948
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
949
+ * @module
950
+ */
951
+ /**
952
+ * Round constants:
953
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
954
+ */
955
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
956
+ 1116352408,
957
+ 1899447441,
958
+ 3049323471,
959
+ 3921009573,
960
+ 961987163,
961
+ 1508970993,
962
+ 2453635748,
963
+ 2870763221,
964
+ 3624381080,
965
+ 310598401,
966
+ 607225278,
967
+ 1426881987,
968
+ 1925078388,
969
+ 2162078206,
970
+ 2614888103,
971
+ 3248222580,
972
+ 3835390401,
973
+ 4022224774,
974
+ 264347078,
975
+ 604807628,
976
+ 770255983,
977
+ 1249150122,
978
+ 1555081692,
979
+ 1996064986,
980
+ 2554220882,
981
+ 2821834349,
982
+ 2952996808,
983
+ 3210313671,
984
+ 3336571891,
985
+ 3584528711,
986
+ 113926993,
987
+ 338241895,
988
+ 666307205,
989
+ 773529912,
990
+ 1294757372,
991
+ 1396182291,
992
+ 1695183700,
993
+ 1986661051,
994
+ 2177026350,
995
+ 2456956037,
996
+ 2730485921,
997
+ 2820302411,
998
+ 3259730800,
999
+ 3345764771,
1000
+ 3516065817,
1001
+ 3600352804,
1002
+ 4094571909,
1003
+ 275423344,
1004
+ 430227734,
1005
+ 506948616,
1006
+ 659060556,
1007
+ 883997877,
1008
+ 958139571,
1009
+ 1322822218,
1010
+ 1537002063,
1011
+ 1747873779,
1012
+ 1955562222,
1013
+ 2024104815,
1014
+ 2227730452,
1015
+ 2361852424,
1016
+ 2428436474,
1017
+ 2756734187,
1018
+ 3204031479,
1019
+ 3329325298
1020
+ ]);
1021
+ /** Reusable temporary buffer. "W" comes straight from spec. */
1022
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1023
+ var SHA256 = class extends HashMD {
1024
+ constructor(outputLen = 32) {
1025
+ super(64, outputLen, 8, false);
1026
+ this.A = SHA256_IV[0] | 0;
1027
+ this.B = SHA256_IV[1] | 0;
1028
+ this.C = SHA256_IV[2] | 0;
1029
+ this.D = SHA256_IV[3] | 0;
1030
+ this.E = SHA256_IV[4] | 0;
1031
+ this.F = SHA256_IV[5] | 0;
1032
+ this.G = SHA256_IV[6] | 0;
1033
+ this.H = SHA256_IV[7] | 0;
1034
+ }
1035
+ get() {
1036
+ const { A, B, C, D, E, F, G, H } = this;
1037
+ return [
1038
+ A,
1039
+ B,
1040
+ C,
1041
+ D,
1042
+ E,
1043
+ F,
1044
+ G,
1045
+ H
1046
+ ];
1047
+ }
1048
+ set(A, B, C, D, E, F, G, H) {
1049
+ this.A = A | 0;
1050
+ this.B = B | 0;
1051
+ this.C = C | 0;
1052
+ this.D = D | 0;
1053
+ this.E = E | 0;
1054
+ this.F = F | 0;
1055
+ this.G = G | 0;
1056
+ this.H = H | 0;
1057
+ }
1058
+ process(view, offset) {
1059
+ for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
1060
+ for (let i = 16; i < 64; i++) {
1061
+ const W15 = SHA256_W[i - 15];
1062
+ const W2 = SHA256_W[i - 2];
1063
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
1064
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10;
1065
+ SHA256_W[i] = s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
1066
+ }
1067
+ let { A, B, C, D, E, F, G, H } = this;
1068
+ for (let i = 0; i < 64; i++) {
1069
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1070
+ const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
1071
+ const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
1072
+ H = G;
1073
+ G = F;
1074
+ F = E;
1075
+ E = D + T1 | 0;
1076
+ D = C;
1077
+ C = B;
1078
+ B = A;
1079
+ A = T1 + T2 | 0;
1080
+ }
1081
+ A = A + this.A | 0;
1082
+ B = B + this.B | 0;
1083
+ C = C + this.C | 0;
1084
+ D = D + this.D | 0;
1085
+ E = E + this.E | 0;
1086
+ F = F + this.F | 0;
1087
+ G = G + this.G | 0;
1088
+ H = H + this.H | 0;
1089
+ this.set(A, B, C, D, E, F, G, H);
1090
+ }
1091
+ roundClean() {
1092
+ clean(SHA256_W);
1093
+ }
1094
+ destroy() {
1095
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
1096
+ clean(this.buffer);
1097
+ }
1098
+ };
1099
+ /**
1100
+ * SHA2-256 hash function from RFC 4634.
1101
+ *
1102
+ * It is the fastest JS hash, even faster than Blake3.
1103
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1104
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1105
+ */
1106
+ const sha256 = /* @__PURE__ */ createHasher(() => new SHA256());
1107
+ //#endregion
1108
+ //#region ../reactor-attachments/dist/hash-BobbR4r4.js
1109
+ const nodeCrypto = globalThis.process?.getBuiltinModule?.("node:crypto");
1110
+ /** Native SHA-256 from node:crypto, or undefined outside Node. */
1111
+ function nodeSha256() {
1112
+ if (!nodeCrypto) return void 0;
1113
+ const hash = nodeCrypto.createHash("sha256");
1114
+ return {
1115
+ update: (bytes) => void hash.update(bytes),
1116
+ hex: () => hash.digest("hex")
1117
+ };
1118
+ }
1119
+ /** SHA-256 in JavaScript, for browsers; about 10x slower than native. */
1120
+ function jsSha256() {
1121
+ const hash = sha256.create();
1122
+ return {
1123
+ update: (bytes) => void hash.update(bytes),
1124
+ hex: () => bytesToHex(hash.digest())
1125
+ };
1126
+ }
1127
+ /**
1128
+ * Lowercase SHA-256 hex of `bytes` -- the `attachment://v1:` hash format
1129
+ * (`packages/reactor/src/attachments/types.ts`).
1130
+ *
1131
+ * WebCrypto, so the same code runs in Node and in a browser realm. There is no
1132
+ * streaming digest in WebCrypto, which is why verification happens over
1133
+ * collected bytes.
1134
+ */
1135
+ async function sha256Hex(bytes) {
1136
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", digestable(bytes));
1137
+ return Array.from(new Uint8Array(digest)).map((byte) => byte.toString(16).padStart(2, "0")).join("");
1138
+ }
1139
+ /** WebCrypto refuses a SharedArrayBuffer-backed view, so only that one is copied. */
1140
+ function digestable(bytes) {
1141
+ if (typeof SharedArrayBuffer !== "undefined" && bytes.buffer instanceof SharedArrayBuffer) {
1142
+ const copy = new Uint8Array(bytes.byteLength);
1143
+ copy.set(bytes);
1144
+ return copy;
1145
+ }
1146
+ return bytes;
1147
+ }
1148
+ /** Same digest as `sha256Hex`, in bounded memory: natively in slices in Node, and in a
1149
+ * browser whole up to `oneShotMaxBytes`, then in JavaScript slices (no ~2 GB read). */
1150
+ async function sha256HexOfBlob(blob, options) {
1151
+ const chunkBytes = options?.chunkBytes ?? 8388608;
1152
+ if (!Number.isInteger(chunkBytes) || chunkBytes <= 0) throw new RangeError("chunkBytes must be a positive integer");
1153
+ options?.signal?.throwIfAborted();
1154
+ let hasher = (options?.native ?? nodeSha256)();
1155
+ if (!hasher) {
1156
+ if (blob.size <= (options?.oneShotMaxBytes ?? 268435456)) return sha256Hex(new Uint8Array(await blob.arrayBuffer()));
1157
+ hasher = jsSha256();
1158
+ }
1159
+ for (let offset = 0; offset < blob.size; offset += chunkBytes) {
1160
+ options?.signal?.throwIfAborted();
1161
+ const chunk = blob.slice(offset, offset + chunkBytes);
1162
+ hasher.update(new Uint8Array(await chunk.arrayBuffer()));
1163
+ }
1164
+ return hasher.hex();
1165
+ }
1166
+ //#endregion
1167
+ //#region ../reactor-attachments/dist/client.js
1168
+ /**
1169
+ * Runs `worker` over `items` with a hard upper bound on simultaneous
1170
+ * executions. Bounding starts (not just transfers) is what keeps memory flat:
1171
+ * an item's preprocessing (hashing/buffering) only begins when a slot frees.
1172
+ */
1173
+ async function runWithConcurrency(items, worker, options) {
1174
+ const { concurrency, signal, onSettled } = options;
1175
+ if (!Number.isInteger(concurrency) || concurrency < 1) throw new Error(`concurrency must be a positive integer, got: ${concurrency}`);
1176
+ const results = new Array(items.length);
1177
+ let nextIndex = 0;
1178
+ async function runLane() {
1179
+ for (;;) {
1180
+ const index = nextIndex++;
1181
+ if (index >= items.length) return;
1182
+ if (signal?.aborted) {
1183
+ results[index] = {
1184
+ index,
1185
+ status: "rejected",
1186
+ error: signalReason(signal)
1187
+ };
1188
+ onSettled?.(results[index]);
1189
+ continue;
1190
+ }
1191
+ try {
1192
+ const value = await worker(items[index], index);
1193
+ results[index] = {
1194
+ index,
1195
+ status: "fulfilled",
1196
+ value
1197
+ };
1198
+ } catch (error) {
1199
+ results[index] = {
1200
+ index,
1201
+ status: "rejected",
1202
+ error
1203
+ };
1204
+ }
1205
+ onSettled?.(results[index]);
1206
+ }
1207
+ }
1208
+ const lanes = Array.from({ length: Math.min(concurrency, items.length) }, () => runLane());
1209
+ await Promise.all(lanes);
1210
+ return results;
1211
+ }
1212
+ function signalReason(signal) {
1213
+ return signal.reason ?? new DOMException("The operation was aborted", "AbortError");
1214
+ }
1215
+ /**
1216
+ * Emits `AttachmentProgress` for one single-item operation, upholding:
1217
+ *
1218
+ * - **I1** exactly one terminal event (`done` or `error`) — never both, never twice.
1219
+ * - **I2** on `done`: `indeterminate === false`, `total` is a number, `loaded === total`.
1220
+ * - **I3** `loaded` is non-decreasing within a stage and resets to 0 on stage change.
1221
+ * - **I4** the terminal event bypasses the throttle unconditionally.
1222
+ * - **I5** `error` carries the last known `loaded`/`total`.
1223
+ *
1224
+ * Leading edge: the first `bytes()` after a `stage()` always emits, so a bar
1225
+ * leaves 0 immediately. There is deliberately no trailing-edge timer — it
1226
+ * would leak on throw, could fire after the terminal event and violate I1's
1227
+ * ordering, and is unnecessary because `finish()` always emits
1228
+ * `loaded === total`, making a dropped last intra-stage tick invisible.
1229
+ */
1230
+ var ProgressEmitter = class {
1231
+ listener;
1232
+ throttleMs;
1233
+ now;
1234
+ currentStage;
1235
+ loaded = 0;
1236
+ total;
1237
+ emittedBytesInStage = false;
1238
+ lastEmitAt = Number.NEGATIVE_INFINITY;
1239
+ settled = false;
1240
+ constructor(options) {
1241
+ this.listener = options?.onProgress;
1242
+ this.throttleMs = options?.throttleMs ?? 100;
1243
+ this.now = options?.now ?? (() => Date.now());
1244
+ }
1245
+ /** True when a listener is attached; lets callers skip instrumentation entirely. */
1246
+ get active() {
1247
+ return this.listener !== void 0;
1248
+ }
1249
+ /**
1250
+ * Enter a stage. Always emits and resets `loaded` to 0. Entry is always
1251
+ * indeterminate: no bytes have moved yet, and whether they can be observed
1252
+ * at all is only proven by a transport actually calling back.
1253
+ */
1254
+ stage(stage, options) {
1255
+ if (this.settled) return;
1256
+ this.currentStage = stage;
1257
+ this.loaded = 0;
1258
+ this.total = options?.total;
1259
+ this.emittedBytesInStage = false;
1260
+ this.emit({
1261
+ stage,
1262
+ loaded: 0,
1263
+ total: this.total,
1264
+ indeterminate: true
1265
+ });
1266
+ }
1267
+ /**
1268
+ * Report observed bytes within the current stage. Throttled by time, with
1269
+ * the first observation after a stage change always emitted.
1270
+ */
1271
+ bytes(loaded, total) {
1272
+ if (this.settled || this.currentStage === void 0) return;
1273
+ if (total !== void 0) this.total = total;
1274
+ if (loaded > this.loaded) this.loaded = loaded;
1275
+ if (!!this.emittedBytesInStage && this.now() - this.lastEmitAt < this.throttleMs) return;
1276
+ this.emittedBytesInStage = true;
1277
+ this.emit({
1278
+ stage: this.currentStage,
1279
+ loaded: this.loaded,
1280
+ total: this.total,
1281
+ indeterminate: false
1282
+ });
1283
+ }
1284
+ /**
1285
+ * Terminal success. `total` defaults to the bytes actually seen so a stage
1286
+ * with no known denominator still satisfies I2.
1287
+ */
1288
+ finish(override) {
1289
+ if (this.settled) return;
1290
+ this.settled = true;
1291
+ const total = override?.total ?? this.total ?? this.loaded;
1292
+ const loaded = override?.loaded ?? total;
1293
+ this.emit({
1294
+ stage: "done",
1295
+ loaded,
1296
+ total,
1297
+ indeterminate: false,
1298
+ ...override?.deduped ? { deduped: true } : {}
1299
+ });
1300
+ }
1301
+ /** Terminal success for a confirmed dedup: no bytes moved, and none needed to. */
1302
+ finishDeduped() {
1303
+ this.finish({
1304
+ loaded: 0,
1305
+ total: 0,
1306
+ deduped: true
1307
+ });
1308
+ }
1309
+ /** Terminal failure, carrying the last known byte counts. */
1310
+ fail() {
1311
+ if (this.settled) return;
1312
+ this.settled = true;
1313
+ this.emit({
1314
+ stage: "error",
1315
+ loaded: this.loaded,
1316
+ total: this.total,
1317
+ indeterminate: false
1318
+ });
1319
+ }
1320
+ emit(progress) {
1321
+ this.lastEmitAt = this.now();
1322
+ this.listener?.(progress);
1323
+ }
1324
+ };
1325
+ /**
1326
+ * Count bytes as a consumer reads them.
1327
+ *
1328
+ * Uses the manual-reader form rather than `pipeThrough`, whose internal queue
1329
+ * reads far ahead of the consumer and would make `loaded` overstate what was
1330
+ * actually received. `highWaterMark: 0` is load-bearing for the same reason:
1331
+ * at the default of 1 the wrapper pulls one chunk the instant it is
1332
+ * constructed, so a caller who never reads still sees bytes counted.
1333
+ *
1334
+ * `cancel` propagates to the source, which is what keeps reader refcounts
1335
+ * (e.g. `KyselyAttachmentStore`'s) correct. Cancelling is an abandonment, not
1336
+ * a completion, so it reports `onError` — never `onDone` — carrying the
1337
+ * cancel reason the way an `AbortSignal` carries its own, with the DOM's
1338
+ * default `AbortError` when the canceller gave none.
1339
+ *
1340
+ * Returns `source` unchanged when no hook is supplied, so a caller with no
1341
+ * listener pays nothing.
1342
+ */
1343
+ function withByteProgress(source, hooks) {
1344
+ if (!hooks.onBytes && !hooks.onDone && !hooks.onError) return source;
1345
+ let loaded = 0;
1346
+ let cancelled = false;
1347
+ const reader = source.getReader();
1348
+ return new ReadableStream({
1349
+ async pull(controller) {
1350
+ try {
1351
+ const { done, value } = await reader.read();
1352
+ if (cancelled) return;
1353
+ if (done) {
1354
+ hooks.onDone?.();
1355
+ controller.close();
1356
+ return;
1357
+ }
1358
+ loaded += value.byteLength;
1359
+ hooks.onBytes?.(loaded);
1360
+ controller.enqueue(value);
1361
+ } catch (err) {
1362
+ if (cancelled) return;
1363
+ hooks.onError?.(err);
1364
+ controller.error(err);
1365
+ }
1366
+ },
1367
+ cancel(reason) {
1368
+ cancelled = true;
1369
+ reader.cancel(reason).catch(() => {});
1370
+ hooks.onError?.(reason ?? abortError());
1371
+ }
1372
+ }, { highWaterMark: 0 });
1373
+ }
1374
+ /** What an `AbortSignal` carries when `abort()` is called with no reason. */
1375
+ function abortError() {
1376
+ return new DOMException("The operation was aborted", "AbortError");
1377
+ }
1378
+ /**
1379
+ * Duck-typed dedup detection: bundlers (notably Vite dev pre-bundling) can
1380
+ * load two copies of this package's error classes, one for the service and
1381
+ * one for the client wrapper, making a plain instanceof check miss the
1382
+ * cross-copy throw. Name plus payload shape identifies the error reliably.
1383
+ */
1384
+ function isAttachmentAlreadyExists$1(err) {
1385
+ if (err instanceof AttachmentAlreadyExists) return true;
1386
+ return err instanceof Error && err.name === "AttachmentAlreadyExists" && typeof err.hash === "string" && typeof err.ref === "string";
1387
+ }
1388
+ function dedupedHeader(hash, options) {
1389
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1390
+ return {
1391
+ hash,
1392
+ mimeType: options.mimeType,
1393
+ fileName: options.fileName,
1394
+ sizeBytes: options.sizeBytes,
1395
+ extension: options.extension ?? null,
1396
+ status: "available",
1397
+ source: "local",
1398
+ createdAtUtc: now,
1399
+ lastAccessedAtUtc: now,
1400
+ expiresAtUtc: null
1401
+ };
1402
+ }
1403
+ /** Stamps an item's index onto its progress events. */
1404
+ function itemProgress(options, index) {
1405
+ if (!options?.onProgress && options?.throttleMs === void 0) return;
1406
+ return {
1407
+ ...options.onProgress ? { onProgress: (progress) => options.onProgress?.({
1408
+ ...progress,
1409
+ index
1410
+ }) } : {},
1411
+ ...options.throttleMs !== void 0 ? { throttleMs: options.throttleMs } : {}
1412
+ };
1413
+ }
1414
+ function batchRunOptions(total, options) {
1415
+ const onItemSettled = options?.onItemSettled;
1416
+ let settled = 0;
1417
+ let completed = 0;
1418
+ let failed = 0;
1419
+ return {
1420
+ concurrency: options?.concurrency ?? 4,
1421
+ ...options?.signal ? { signal: options.signal } : {},
1422
+ ...onItemSettled ? { onSettled: (result) => {
1423
+ settled += 1;
1424
+ if (result.status === "fulfilled") completed += 1;
1425
+ else failed += 1;
1426
+ onItemSettled({
1427
+ settled,
1428
+ completed,
1429
+ failed,
1430
+ total
1431
+ });
1432
+ } } : {}
1433
+ };
1434
+ }
1435
+ var AttachmentClientImpl = class {
1436
+ service;
1437
+ constructor(service) {
1438
+ this.service = service;
1439
+ }
1440
+ preprocess(file, opts) {
1441
+ return this.hashFile(file, opts);
1442
+ }
1443
+ async hashFile(file, opts, signal) {
1444
+ const hash = await sha256HexOfBlob(file, signal ? { signal } : void 0);
1445
+ const ref = createRef(hash);
1446
+ const sizeBytes = file.size;
1447
+ return {
1448
+ ref,
1449
+ hash,
1450
+ sizeBytes,
1451
+ options: {
1452
+ mimeType: opts?.mimeType ?? file.type,
1453
+ fileName: opts?.fileName ?? (file instanceof File ? file.name : "attachment"),
1454
+ clientHash: hash,
1455
+ sizeBytes,
1456
+ ...opts?.documentId !== void 0 ? { documentId: opts.documentId } : {}
1457
+ },
1458
+ blob: file
1459
+ };
1460
+ }
1461
+ /**
1462
+ * Reserve, distinguishing a confirmed dedup from a live upload handle in the
1463
+ * type rather than with a flag: the two outcomes move a different number of
1464
+ * bytes, and every caller has to account for that.
1465
+ */
1466
+ async reserveOrDedup(options) {
1467
+ try {
1468
+ return {
1469
+ kind: "handle",
1470
+ handle: await this.service.reserve(options)
1471
+ };
1472
+ } catch (err) {
1473
+ if (!isAttachmentAlreadyExists$1(err)) throw err;
1474
+ return {
1475
+ kind: "deduped",
1476
+ result: {
1477
+ hash: err.hash,
1478
+ ref: err.ref,
1479
+ header: dedupedHeader(err.hash, options)
1480
+ }
1481
+ };
1482
+ }
1483
+ }
1484
+ async reserve(options, send) {
1485
+ const outcome = await this.reserveOrDedup(options);
1486
+ if (outcome.kind === "deduped") return outcome.result;
1487
+ return send(outcome.handle);
1488
+ }
1489
+ async upload(input, options) {
1490
+ const emitter = new ProgressEmitter(options);
1491
+ const signal = input.signal;
1492
+ try {
1493
+ signal?.throwIfAborted();
1494
+ let preprocessed;
1495
+ if ("preprocessed" in input) preprocessed = input.preprocessed;
1496
+ else {
1497
+ emitter.stage("hashing", { total: input.file.size });
1498
+ preprocessed = await this.hashFile(input.file, {
1499
+ ...input.fileName !== void 0 ? { fileName: input.fileName } : {},
1500
+ ...input.mimeType !== void 0 ? { mimeType: input.mimeType } : {},
1501
+ ...input.documentId !== void 0 ? { documentId: input.documentId } : {}
1502
+ }, signal);
1503
+ }
1504
+ const sizeBytes = preprocessed.sizeBytes;
1505
+ signal?.throwIfAborted();
1506
+ emitter.stage("reserving");
1507
+ const outcome = await this.reserveOrDedup(preprocessed.options);
1508
+ if (outcome.kind === "deduped") {
1509
+ emitter.finishDeduped();
1510
+ return outcome.result;
1511
+ }
1512
+ signal?.throwIfAborted();
1513
+ emitter.stage("uploading", { total: sizeBytes });
1514
+ const sendOptions = {
1515
+ ...emitter.active ? { onProgress: (loaded, total) => emitter.bytes(loaded, total ?? sizeBytes) } : {},
1516
+ ...signal ? { signal } : {}
1517
+ };
1518
+ const result = await outcome.handle.send(preprocessed.blob, sendOptions);
1519
+ emitter.finish();
1520
+ return result;
1521
+ } catch (err) {
1522
+ emitter.fail();
1523
+ throw err;
1524
+ }
1525
+ }
1526
+ /**
1527
+ * The single site where download bytes are instrumented.
1528
+ *
1529
+ * It sits here, above the service, rather than in any store or transport:
1530
+ * one logical get can be several byte streams underneath (an evicted
1531
+ * attachment is fetched from the transport, written to disk, then re-read),
1532
+ * so counting lower down would double-count that path and still miss
1533
+ * local-filesystem reads. Wrapping what `service.get` returns covers the
1534
+ * presigned, switchboard, legacy and local paths by construction, and
1535
+ * `downloadBlob`/`saveAttachment`/`downloadObjectUrl` inherit it.
1536
+ */
1537
+ async getWithProgress(input, emitter) {
1538
+ const { header, body } = await this.service.get(input.ref, {
1539
+ documentId: input.documentId,
1540
+ signal: input.signal
1541
+ });
1542
+ emitter.stage("downloading", { total: header.sizeBytes });
1543
+ if (!emitter.active) return {
1544
+ header,
1545
+ body
1546
+ };
1547
+ return {
1548
+ header,
1549
+ body: withByteProgress(body, {
1550
+ onBytes: (loaded) => emitter.bytes(loaded),
1551
+ onDone: () => emitter.finish(),
1552
+ onError: () => emitter.fail()
1553
+ })
1554
+ };
1555
+ }
1556
+ async download(input, options) {
1557
+ const emitter = new ProgressEmitter(options);
1558
+ try {
1559
+ input.signal?.throwIfAborted();
1560
+ emitter.stage("requesting-download-target");
1561
+ return await this.getWithProgress(input, emitter);
1562
+ } catch (err) {
1563
+ emitter.fail();
1564
+ throw err;
1565
+ }
1566
+ }
1567
+ async downloadBlob(input, options) {
1568
+ const emitter = new ProgressEmitter(options);
1569
+ try {
1570
+ input.signal?.throwIfAborted();
1571
+ emitter.stage("requesting-download-target");
1572
+ const { header, body } = await this.getWithProgress(input, emitter);
1573
+ const reader = body.getReader();
1574
+ const chunks = [];
1575
+ for (;;) {
1576
+ const { done, value } = await reader.read();
1577
+ if (done) break;
1578
+ chunks.push(value);
1579
+ }
1580
+ const blob = new Blob(chunks, { type: options?.mimeType ?? header.mimeType });
1581
+ emitter.finish();
1582
+ return {
1583
+ blob,
1584
+ header
1585
+ };
1586
+ } catch (err) {
1587
+ emitter.fail();
1588
+ throw err;
1589
+ }
1590
+ }
1591
+ async saveAttachment(input, options) {
1592
+ if (typeof document === "undefined") throw new Error("saveAttachment requires a browser environment; use downloadBlob elsewhere");
1593
+ const { blob, header } = await this.downloadBlob(input, options);
1594
+ const url = URL.createObjectURL(blob);
1595
+ try {
1596
+ const anchor = document.createElement("a");
1597
+ anchor.href = url;
1598
+ anchor.download = options?.fileName ?? header.fileName;
1599
+ anchor.click();
1600
+ } finally {
1601
+ URL.revokeObjectURL(url);
1602
+ }
1603
+ }
1604
+ async downloadObjectUrl(input, options) {
1605
+ const { blob, header } = await this.downloadBlob(input, options);
1606
+ const url = URL.createObjectURL(blob);
1607
+ let revoked = false;
1608
+ return {
1609
+ url,
1610
+ header,
1611
+ revoke: () => {
1612
+ if (revoked) return;
1613
+ revoked = true;
1614
+ URL.revokeObjectURL(url);
1615
+ }
1616
+ };
1617
+ }
1618
+ async getShareLink(input) {
1619
+ input.signal?.throwIfAborted();
1620
+ const target = await this.service.getDownloadTarget(input.ref, {
1621
+ documentId: input.documentId,
1622
+ ...input.expiresIn !== void 0 ? { expiresIn: input.expiresIn } : {},
1623
+ ...input.signal !== void 0 ? { signal: input.signal } : {}
1624
+ });
1625
+ if (target.kind !== "presigned-get") throw new Error("Public share links require a presigned-capable storage backend (S3); this server answered with an authenticated target");
1626
+ return {
1627
+ url: target.url,
1628
+ expiresAtUtc: target.expiresAtUtc
1629
+ };
1630
+ }
1631
+ uploadMany(inputs, options) {
1632
+ return runWithConcurrency(inputs, (input, index) => this.upload(input, itemProgress(options, index)), batchRunOptions(inputs.length, options));
1633
+ }
1634
+ /**
1635
+ * `concurrency` bounds download-target negotiation, not simultaneous byte
1636
+ * transfer: each item resolves when its stream is handed over, and the bytes
1637
+ * move only as the caller reads. Byte progress makes that pre-existing
1638
+ * behavior visible; it does not change it.
1639
+ */
1640
+ downloadMany(inputs, options) {
1641
+ return runWithConcurrency(inputs, (input, index) => this.download(input, itemProgress(options, index)), batchRunOptions(inputs.length, options));
1642
+ }
1643
+ };
1644
+ function createAttachmentClient(service) {
1645
+ return new AttachmentClientImpl(service);
1646
+ }
1647
+ //#endregion
1648
+ //#region src/integrations/powerhouse/attachment.ts
1649
+ /**
1650
+ * The attachment service of the run's reactor. Never builds the reactor for
1651
+ * it: only where the Cli serves (`folders` marks that) or where its reactor
1652
+ * is attached to a switchboard, which reaching builds nothing.
1653
+ */
1654
+ async function getAttachmentService(ctx) {
1655
+ if (!ctx.folders && !ctx.reactorAttached) return void 0;
1656
+ return (await ctx.reactor?.())?.attachments;
1657
+ }
1658
+ function attachmentsUnavailableMessage() {
1659
+ return "Attachments need a running reactor (daemon mode) on a switchboard the Cli attached to. None is available in this context.";
1660
+ }
1661
+ function asRef(ref) {
1662
+ return ref;
1663
+ }
1664
+ function isAttachmentAlreadyExists(err) {
1665
+ if (!(err instanceof Error)) return false;
1666
+ if (!("ref" in err) || !("hash" in err)) return false;
1667
+ return err.constructor.name === "AttachmentAlreadyExists" || /already exists/i.test(err.message);
1668
+ }
1669
+ const MIME_BY_EXT = {
1670
+ ".png": "image/png",
1671
+ ".jpg": "image/jpeg",
1672
+ ".jpeg": "image/jpeg",
1673
+ ".gif": "image/gif",
1674
+ ".webp": "image/webp",
1675
+ ".svg": "image/svg+xml",
1676
+ ".pdf": "application/pdf",
1677
+ ".json": "application/json",
1678
+ ".txt": "text/plain",
1679
+ ".md": "text/markdown",
1680
+ ".csv": "text/csv"
1681
+ };
1682
+ function inferMimeType(filePath, override) {
1683
+ if (override) return override;
1684
+ return MIME_BY_EXT[extname(filePath).toLowerCase()] ?? "application/octet-stream";
1685
+ }
1686
+ async function fileToBlob(filePath, mimeType) {
1687
+ return openAsBlob(filePath, { type: mimeType });
1688
+ }
1689
+ //#endregion
1690
+ //#region src/integrations/powerhouse/attachment-commands.ts
1691
+ const documentIdSchema = z.string().optional().describe("Document whose operations reference the attachment. A switchboard serves an attachment only through such a document, so a read there needs it.");
1692
+ function createAttachmentCommands() {
1693
+ return [
1694
+ defineCommand({
1695
+ id: "attachment-preprocess",
1696
+ description: "Compute an attachment's content-addressed ref (attachment://v1:<sha256>) from a local file WITHOUT uploading. Embed the returned ref in a document action now, then send the bytes with attachment-upload for the same file after / in parallel with submitting the action.",
1697
+ inputSchema: z.object({
1698
+ filePath: z.string().describe("Path to the local file to reference (absolute, or relative to the workdir)."),
1699
+ mimeType: z.string().optional().describe("MIME type; inferred from the file extension when omitted."),
1700
+ fileName: z.string().optional().describe("Stored file name; defaults to the file's basename.")
1701
+ }),
1702
+ execute: async (input, context) => {
1703
+ const service = await getAttachmentService(context);
1704
+ if (!service) return { text: attachmentsUnavailableMessage() };
1705
+ const filePath = path.resolve(context.workdir, input.filePath);
1706
+ const mimeType = inferMimeType(filePath, input.mimeType);
1707
+ const fileName = input.fileName ?? path.basename(filePath);
1708
+ const blob = await fileToBlob(filePath, mimeType);
1709
+ const pre = await createAttachmentClient(service).preprocess(blob, {
1710
+ fileName,
1711
+ mimeType
1712
+ });
1713
+ return { text: `ref: ${pre.ref}\nhash: ${pre.hash}\nsizeBytes: ${pre.sizeBytes}\nmimeType: ${mimeType}\nfileName: ${fileName}\nNot uploaded yet — embed this ref in the action, then run attachment-upload on the same file to send the bytes.` };
1714
+ }
1715
+ }),
1716
+ defineCommand({
1717
+ id: "attachment-upload",
1718
+ description: "Upload a local file to the attachment store and return its content-addressed ref (attachment://v1:<sha256>). The ref is deterministic from the bytes and identical content dedups. Embed the ref in a document action; the action may be submitted before or after this upload.",
1719
+ inputSchema: z.object({
1720
+ filePath: z.string().describe("Path to the local file to upload (absolute, or relative to the workdir)."),
1721
+ mimeType: z.string().optional().describe("MIME type; inferred from the file extension when omitted."),
1722
+ fileName: z.string().optional().describe("Stored file name; defaults to the file's basename.")
1723
+ }),
1724
+ execute: async (input, context) => {
1725
+ const service = await getAttachmentService(context);
1726
+ if (!service) return { text: attachmentsUnavailableMessage() };
1727
+ const filePath = path.resolve(context.workdir, input.filePath);
1728
+ const mimeType = inferMimeType(filePath, input.mimeType);
1729
+ const fileName = input.fileName ?? path.basename(filePath);
1730
+ const blob = await fileToBlob(filePath, mimeType);
1731
+ const client = createAttachmentClient(service);
1732
+ const pre = await client.preprocess(blob, {
1733
+ fileName,
1734
+ mimeType
1735
+ });
1736
+ let result;
1737
+ try {
1738
+ result = await client.reserve(pre.options, (handle) => handle.send(pre.blob));
1739
+ } catch (err) {
1740
+ if (!isAttachmentAlreadyExists(err)) throw err;
1741
+ const header = await service.stat(pre.ref);
1742
+ result = {
1743
+ ref: pre.ref,
1744
+ hash: pre.hash,
1745
+ header
1746
+ };
1747
+ }
1748
+ return { text: `ref: ${result.ref}\nhash: ${result.hash}\nstatus: ${result.header.status}\nsizeBytes: ${result.header.sizeBytes}\nmimeType: ${result.header.mimeType}\nfileName: ${result.header.fileName}` };
1749
+ }
1750
+ }),
1751
+ defineCommand({
1752
+ id: "attachment-stat",
1753
+ description: "Look up an attachment by ref (attachment://v1:<sha256>) and report its status + metadata. status='pending' = reserved but not yet uploaded; 'available' = stored; 'evicted' = metadata known, bytes reclaimed. On a switchboard, pass the documentId of a document whose operations reference the attachment.",
1754
+ inputSchema: z.object({
1755
+ ref: z.string().describe("Attachment ref, e.g. attachment://v1:<sha256hex>."),
1756
+ documentId: documentIdSchema
1757
+ }),
1758
+ execute: async (input, context) => {
1759
+ const service = await getAttachmentService(context);
1760
+ if (!service) return { text: attachmentsUnavailableMessage() };
1761
+ try {
1762
+ const h = await service.stat(asRef(input.ref), ...readOptions(input.documentId));
1763
+ return { text: `ref: ${input.ref}\nstatus: ${h.status}\nmimeType: ${h.mimeType}\nfileName: ${h.fileName}\nsizeBytes: ${h.sizeBytes}\ncreatedAtUtc: ${h.createdAtUtc}` };
1764
+ } catch (err) {
1765
+ return { text: `Not found or error for ${input.ref}: ${err.message}` + documentIdHint(input.documentId) };
1766
+ }
1767
+ }
1768
+ }),
1769
+ defineCommand({
1770
+ id: "attachment-get",
1771
+ description: "Download an attachment's bytes by ref (attachment://v1:<sha256>) to a local file. Errors if the attachment is still pending (bytes not yet uploaded). On a switchboard, pass the documentId of a document whose operations reference the attachment.",
1772
+ inputSchema: z.object({
1773
+ ref: z.string().describe("Attachment ref, e.g. attachment://v1:<sha256hex>."),
1774
+ outPath: z.string().describe("Path to write the bytes to (absolute, or relative to the workdir)."),
1775
+ documentId: documentIdSchema
1776
+ }),
1777
+ execute: async (input, context) => {
1778
+ const service = await getAttachmentService(context);
1779
+ if (!service) return { text: attachmentsUnavailableMessage() };
1780
+ const outPath = path.resolve(context.workdir, input.outPath);
1781
+ try {
1782
+ const res = await service.get(asRef(input.ref), ...readOptions(input.documentId));
1783
+ const body = res.body;
1784
+ await pipeline(Readable.fromWeb(body), createWriteStream(outPath));
1785
+ return { text: `Wrote ${res.header.sizeBytes} bytes to ${outPath}\nref: ${input.ref}\nmimeType: ${res.header.mimeType}\nfileName: ${res.header.fileName}` };
1786
+ } catch (err) {
1787
+ return { text: `Could not get ${input.ref}: ${err.message}` + documentIdHint(input.documentId) };
1788
+ }
1789
+ }
1790
+ })
1791
+ ];
1792
+ }
1793
+ /** The read options for `documentId`; none without one, as before. */
1794
+ function readOptions(documentId) {
1795
+ return documentId === void 0 ? [] : [{ documentId }];
1796
+ }
1797
+ /** Why a read without a document id fails on a switchboard. */
1798
+ function documentIdHint(documentId) {
1799
+ return documentId === void 0 ? "\nOn a switchboard an attachment is served only through a document that references it: pass documentId." : "";
1800
+ }
1801
+ //#endregion
1802
+ //#region src/integrations/powerhouse/index.ts
1803
+ /**
1804
+ * The `ReactorConfiguration.remote` a runner attaches with: the config as
1805
+ * given, or the function's answer for this setup context. None: `{}`.
1806
+ */
1807
+ async function resolveRemoteReactorConfig(source, setup) {
1808
+ if (typeof source === "function") return source(setup);
1809
+ return source ?? {};
1810
+ }
1811
+ /**
1812
+ * The attachment service of the switchboard at `endpoint`. Its
1813
+ * `/attachments/*` routes mount at the host root, so the origin is used.
1814
+ */
1815
+ async function remoteAttachmentService(endpoint, jwtHandler) {
1816
+ const { createRemoteAttachmentService } = await import("./dist-Bd6hUl0J.mjs");
1817
+ return createRemoteAttachmentService({
1818
+ remoteUrl: new URL(endpoint).origin,
1819
+ ...jwtHandler ? { jwtHandler } : {}
1820
+ });
1821
+ }
1822
+ /** The id of the drive a switchboard serves under `slug`. */
1823
+ async function driveOfAddress(client, slug, endpoint) {
1824
+ try {
1825
+ return (await client.get(slug)).header.id;
1826
+ } catch (cause) {
1827
+ throw new Error(`The switchboard at ${endpoint} serves no drive "${slug}": the drive address must name one of its drives.`, { cause });
1828
+ }
1829
+ }
1830
+ /**
1831
+ * Build a ReactorContext on a RUNNING switchboard, with the drives and
1832
+ * subscriptions the options ask for. The default drive is the first personal
1833
+ * drive the options ask for, else the first, else the one the address names.
1834
+ * The signer, its rules and its watch go to
1835
+ * `createReactorWrites`, which emits `powerhouse:writes:ready` on `ctx.emit`;
1836
+ * a signer change also reconnects the realtime socket with the current
1837
+ * bearer. Without `ctx.attachments` the context gets the switchboard's own
1838
+ * attachment service, authenticated by `ctx.attachmentJwtHandler`, else by
1839
+ * `tokenProvider`. `shutdown` releases only this process's side (the
1840
+ * bridged subscriptions, the signer watch, the client) and runs once.
1841
+ */
1842
+ async function attachDefaultReactor(ctx, options) {
1843
+ const { attachRemoteReactor } = await import("./remote-reactor-oBsHphPT.mjs").then((n) => n.n);
1844
+ const { switchboardOfDrive } = await import("@powerhousedao/shared/host-tokens");
1845
+ let credentialsChanged = () => void 0;
1846
+ const { onSignerChange } = options;
1847
+ const handle = createReactorWrites({
1848
+ signer: options.signer,
1849
+ legacyDocuments: options.legacyDocuments,
1850
+ accepts: options.accepts,
1851
+ ...onSignerChange ? { onSignerChange: (listener) => onSignerChange(() => {
1852
+ credentialsChanged();
1853
+ listener();
1854
+ }) } : {},
1855
+ ...ctx.emit ? { emit: ctx.emit } : {}
1856
+ });
1857
+ let attachment;
1858
+ try {
1859
+ attachment = await attachRemoteReactor({
1860
+ url: options.url,
1861
+ documentModels: options.documentModels ?? [],
1862
+ ...handle.signer ? { signer: handle.signer } : {},
1863
+ ...options.tokenProvider ? { tokenProvider: options.tokenProvider } : {}
1864
+ });
1865
+ } catch (error) {
1866
+ handle.stop();
1867
+ throw error;
1868
+ }
1869
+ const client = attachment.client;
1870
+ credentialsChanged = () => client.notifyCredentialsChanged?.();
1871
+ const driveConfigs = options.drives ?? (options.drive ? [{
1872
+ ...options.drive,
1873
+ role: "personal"
1874
+ }] : []);
1875
+ const drives = [];
1876
+ for (const cfg of driveConfigs) {
1877
+ const drive = await ensureDrive(client, cfg);
1878
+ if (drive.deferred) continue;
1879
+ drives.push({
1880
+ id: drive.id,
1881
+ name: drive.name,
1882
+ role: cfg.role
1883
+ });
1884
+ }
1885
+ const personal = drives.find((d) => d.role === "personal");
1886
+ const addressed = switchboardOfDrive(options.url);
1887
+ let driveId = personal?.id ?? drives[0]?.id ?? "";
1888
+ let driveUrl = addressed && driveId ? `${addressed.base}/d/${driveId}` : void 0;
1889
+ if (!driveId && addressed) {
1890
+ driveId = await driveOfAddress(client, addressed.slug, attachment.endpoint);
1891
+ driveUrl = options.url;
1892
+ }
1893
+ let unsubscribe;
1894
+ if (options.subscriptions && ctx.emit) unsubscribe = bridgeSubscriptions(client, options.subscriptions, ctx.emit);
1895
+ const { tokenProvider } = options;
1896
+ const attachments = ctx.attachments ?? await remoteAttachmentService(attachment.endpoint, ctx.attachmentJwtHandler ?? (tokenProvider && (() => tokenProvider())));
1897
+ let stopped = false;
1898
+ const result = {
1899
+ client,
1900
+ driveId,
1901
+ personalDriveId: personal?.id,
1902
+ drives,
1903
+ switchboardUrl: attachment.endpoint,
1904
+ ...driveUrl ? { driveUrl } : {},
1905
+ attachments,
1906
+ writes: handle.writes,
1907
+ shutdown() {
1908
+ if (stopped) return Promise.resolve();
1909
+ stopped = true;
1910
+ unsubscribe?.();
1911
+ handle.stop();
1912
+ client.dispose?.();
1913
+ return Promise.resolve();
1914
+ }
1915
+ };
1916
+ ctx.emit?.("powerhouse:ready", { driveId });
1917
+ return result;
1918
+ }
1919
+ //#endregion
1920
+ export { bridgeSubscriptions as A, isDocType as C, policyOfHeader as D, createGatedSigner as E, createDocumentChangeTrigger as M, defineCommand as N, signerReady as O, folders_exports as S, SignerNotReadyError as T, buildAuthHeaders as _, fileToBlob as a, createFolderCommands as b, isAttachmentAlreadyExists as c, AttachmentPending as d, AttachmentTransferError as f, SizeMismatch as g, ReservationNotFound as h, asRef as i, defineRegistry as j, ensureDrive as k, AttachmentAlreadyExists as l, InvalidAttachmentRef as m, resolveRemoteReactorConfig as n, getAttachmentService as o, HashMismatch as p, createAttachmentCommands as r, inferMimeType as s, attachDefaultReactor as t, AttachmentNotFound as u, createRef as v, createReactorWrites as w, createFolderOperations as x, parseRef as y };
1921
+
1922
+ //# sourceMappingURL=powerhouse-3XZmdY3_.mjs.map