@feltdb/feltkit 0.3.29 → 0.3.31

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 (185) hide show
  1. package/dist/app.d.ts +101 -11
  2. package/dist/app.js +131 -3
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +2 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/appboundry/guest-tenancy.d.ts +2 -2
  7. package/dist/appboundry/guest-tenancy.js.map +1 -1
  8. package/dist/appboundry/guest.js +27 -2
  9. package/dist/appboundry/guest.js.map +1 -1
  10. package/dist/appboundry/host.js +3 -0
  11. package/dist/appboundry/host.js.map +1 -1
  12. package/dist/authorize.d.ts +47 -4
  13. package/dist/authorize.js +37 -0
  14. package/dist/authorize.js.map +1 -1
  15. package/dist/cli/deploy-appboundry.d.ts +1 -1
  16. package/dist/cli/deploy-appboundry.js.map +1 -1
  17. package/dist/cli/deploy.js.map +1 -1
  18. package/dist/cli/main.js +27 -1
  19. package/dist/cli/main.js.map +1 -1
  20. package/dist/cli/skills.js.map +1 -1
  21. package/dist/client/index.js.map +1 -1
  22. package/dist/dashboard/assets/index-9rMS3yBm.js +15 -0
  23. package/dist/dashboard/assets/index-DkiYTUMR.css +1 -0
  24. package/dist/dashboard/index.html +2 -2
  25. package/dist/docs.d.ts +1 -1
  26. package/dist/docs.js +4 -0
  27. package/dist/docs.js.map +1 -1
  28. package/dist/errors.js.map +1 -1
  29. package/dist/event-stage.js.map +1 -1
  30. package/dist/execution.d.ts +186 -0
  31. package/dist/execution.js +105 -0
  32. package/dist/execution.js.map +1 -0
  33. package/dist/index.d.ts +10 -2
  34. package/dist/index.js +5 -0
  35. package/dist/index.js.map +1 -1
  36. package/dist/measure/index.js.map +1 -1
  37. package/dist/platform/approvals.js.map +1 -1
  38. package/dist/platform/artifacts.js.map +1 -1
  39. package/dist/platform/changes.d.ts +54 -54
  40. package/dist/platform/changes.js.map +1 -1
  41. package/dist/platform/deployments.d.ts +32 -32
  42. package/dist/platform/exec.js.map +1 -1
  43. package/dist/platform/platform.js.map +1 -1
  44. package/dist/platform/releases.js.map +1 -1
  45. package/dist/platform/server.js.map +1 -1
  46. package/dist/platform/workspaces.js.map +1 -1
  47. package/dist/policy.d.ts +172 -0
  48. package/dist/policy.js +311 -0
  49. package/dist/policy.js.map +1 -0
  50. package/dist/react/auth.d.ts +10 -10
  51. package/dist/react/auth.js +1 -1
  52. package/dist/react/auth.js.map +1 -1
  53. package/dist/react/context.d.ts +1 -1
  54. package/dist/react/index.js.map +1 -1
  55. package/dist/runtime/accounts.js.map +1 -1
  56. package/dist/runtime/activity.d.ts +17 -1
  57. package/dist/runtime/activity.js.map +1 -1
  58. package/dist/runtime/agent.d.ts +3 -3
  59. package/dist/runtime/agent.js +9 -3
  60. package/dist/runtime/agent.js.map +1 -1
  61. package/dist/runtime/application-authority.d.ts +33 -3
  62. package/dist/runtime/application-authority.js +74 -14
  63. package/dist/runtime/application-authority.js.map +1 -1
  64. package/dist/runtime/assemble.d.ts +13 -0
  65. package/dist/runtime/assemble.js +29 -1
  66. package/dist/runtime/assemble.js.map +1 -1
  67. package/dist/runtime/audit.js.map +1 -1
  68. package/dist/runtime/authboundry.d.ts +17 -0
  69. package/dist/runtime/authboundry.js +8 -1
  70. package/dist/runtime/authboundry.js.map +1 -1
  71. package/dist/runtime/authority.d.ts +10 -0
  72. package/dist/runtime/authority.js +17 -0
  73. package/dist/runtime/authority.js.map +1 -1
  74. package/dist/runtime/backup-environment.js.map +1 -1
  75. package/dist/runtime/backup.js.map +1 -1
  76. package/dist/runtime/changes.js.map +1 -1
  77. package/dist/runtime/claims.js.map +1 -1
  78. package/dist/runtime/collections.js.map +1 -1
  79. package/dist/runtime/content.d.ts +77 -2
  80. package/dist/runtime/content.js +153 -6
  81. package/dist/runtime/content.js.map +1 -1
  82. package/dist/runtime/context.d.ts +207 -3
  83. package/dist/runtime/contract.js +16 -3
  84. package/dist/runtime/contract.js.map +1 -1
  85. package/dist/runtime/credentials.d.ts +31 -2
  86. package/dist/runtime/credentials.js +55 -3
  87. package/dist/runtime/credentials.js.map +1 -1
  88. package/dist/runtime/crypto-token.js.map +1 -1
  89. package/dist/runtime/data.d.ts +25 -0
  90. package/dist/runtime/data.js +92 -8
  91. package/dist/runtime/data.js.map +1 -1
  92. package/dist/runtime/decisions.js.map +1 -1
  93. package/dist/runtime/deployment.js.map +1 -1
  94. package/dist/runtime/execution-host.d.ts +54 -0
  95. package/dist/runtime/execution-host.js +54 -0
  96. package/dist/runtime/execution-host.js.map +1 -0
  97. package/dist/runtime/generation.js.map +1 -1
  98. package/dist/runtime/image-variants.d.ts +48 -0
  99. package/dist/runtime/image-variants.js +295 -0
  100. package/dist/runtime/image-variants.js.map +1 -0
  101. package/dist/runtime/instance.js.map +1 -1
  102. package/dist/runtime/integrations.d.ts +8 -6
  103. package/dist/runtime/integrations.js +46 -5
  104. package/dist/runtime/integrations.js.map +1 -1
  105. package/dist/runtime/invocations.d.ts +313 -0
  106. package/dist/runtime/invocations.js +493 -0
  107. package/dist/runtime/invocations.js.map +1 -0
  108. package/dist/runtime/live.d.ts +10 -7
  109. package/dist/runtime/live.js +24 -12
  110. package/dist/runtime/live.js.map +1 -1
  111. package/dist/runtime/loader.js.map +1 -1
  112. package/dist/runtime/local-authority.d.ts +92 -0
  113. package/dist/runtime/local-authority.js +396 -0
  114. package/dist/runtime/local-authority.js.map +1 -0
  115. package/dist/runtime/oauth-credentials.d.ts +40 -3
  116. package/dist/runtime/oauth-credentials.js +133 -25
  117. package/dist/runtime/oauth-credentials.js.map +1 -1
  118. package/dist/runtime/outbox.js +3 -0
  119. package/dist/runtime/outbox.js.map +1 -1
  120. package/dist/runtime/policies.d.ts +89 -0
  121. package/dist/runtime/policies.js +152 -0
  122. package/dist/runtime/policies.js.map +1 -0
  123. package/dist/runtime/projects.d.ts +1 -1
  124. package/dist/runtime/readiness.js +11 -0
  125. package/dist/runtime/readiness.js.map +1 -1
  126. package/dist/runtime/runtime.d.ts +66 -5
  127. package/dist/runtime/runtime.js +328 -18
  128. package/dist/runtime/runtime.js.map +1 -1
  129. package/dist/runtime/services-rules.d.ts +9 -0
  130. package/dist/runtime/services-rules.js +47 -1
  131. package/dist/runtime/services-rules.js.map +1 -1
  132. package/dist/runtime/services.d.ts +154 -9
  133. package/dist/runtime/services.js +343 -14
  134. package/dist/runtime/services.js.map +1 -1
  135. package/dist/runtime/sessions.js.map +1 -1
  136. package/dist/runtime/state-contract.js.map +1 -1
  137. package/dist/runtime/storage-check.js.map +1 -1
  138. package/dist/runtime/targets.d.ts +1 -1
  139. package/dist/runtime/tenancy.js.map +1 -1
  140. package/dist/runtime/transactions.d.ts +15 -0
  141. package/dist/runtime/transactions.js +5 -0
  142. package/dist/runtime/transactions.js.map +1 -1
  143. package/dist/schema.js.map +1 -1
  144. package/dist/server/admin.d.ts +72 -51
  145. package/dist/server/admin.js +125 -0
  146. package/dist/server/admin.js.map +1 -1
  147. package/dist/server/components.js.map +1 -1
  148. package/dist/server/index.js +72 -6
  149. package/dist/server/index.js.map +1 -1
  150. package/dist/server/management.js.map +1 -1
  151. package/dist/server/mcp.d.ts +59 -37
  152. package/dist/server/mcp.js +24 -1
  153. package/dist/server/mcp.js.map +1 -1
  154. package/dist/server/operators.d.ts +1 -0
  155. package/dist/server/operators.js +1 -1
  156. package/dist/server/operators.js.map +1 -1
  157. package/dist/server/ports.d.ts +7 -0
  158. package/dist/server/ports.js +17 -0
  159. package/dist/server/ports.js.map +1 -1
  160. package/dist/server/production.js.map +1 -1
  161. package/dist/server/project.js.map +1 -1
  162. package/dist/server/session-http.js.map +1 -1
  163. package/dist/server/tenancy.js.map +1 -1
  164. package/dist/surfaces.d.ts +153 -0
  165. package/dist/surfaces.js +228 -0
  166. package/dist/surfaces.js.map +1 -0
  167. package/dist/testing/index.d.ts +11 -0
  168. package/dist/testing/index.js +7 -0
  169. package/dist/testing/index.js.map +1 -1
  170. package/docs/AGENT-OPERATIONS.md +1 -1
  171. package/docs/ARCHITECTURE.md +2 -1
  172. package/docs/CONNECTIONS.md +151 -0
  173. package/docs/EXECUTION.md +271 -0
  174. package/docs/GUARANTEES.md +134 -8
  175. package/docs/INVOCATIONS.md +170 -0
  176. package/docs/POLICIES.md +121 -0
  177. package/docs/README.md +6 -2
  178. package/docs/SECURITY.md +30 -0
  179. package/docs/TRANSACTIONS.md +4 -0
  180. package/package.json +27 -19
  181. package/skills/.claude-plugin/marketplace.json +1 -1
  182. package/skills/.claude-plugin/plugin.json +1 -1
  183. package/skills/feltkit-services/SKILL.md +1 -1
  184. package/dist/dashboard/assets/index-BehzsQOa.css +0 -1
  185. package/dist/dashboard/assets/index-UuZ63NA6.js +0 -15
@@ -30,17 +30,18 @@
30
30
  * File *bytes*: AppPort Files stores metadata and a `storageKey`; the bytes are in the
31
31
  * same instance (runtime/content.ts). Upload stores the bytes first (verified on every
32
32
  * read), then commits the metadata once, so a file record never points at bytes that
33
- * were not stored; deleting a file removes its bytes.
33
+ * were not stored; deleting a file removes its bytes and the image variants derived from them.
34
34
  */
35
35
  import { jobContextOperation } from "./job-context.js";
36
36
  import { createServices, isServiceAuthorityError, parseConfigurationExport, MAX_EVIDENCE_LOOKUP_LIMIT, VERSION, } from "@appport/services";
37
- import { randomUUID } from "node:crypto";
37
+ import { createHash, randomUUID } from "node:crypto";
38
38
  import { FeltKitError, isFeltKitError } from "../errors.js";
39
39
  import { grantsPermission } from "@appport/authorization";
40
- import { FileContent, FILE_CONTENT_COLLECTION } from "./content.js";
40
+ import { derivedLinkToken, FileContent, FILE_CONTENT_COLLECTION } from "./content.js";
41
+ import { OUTBOX_COLLECTION, outboxStore, performOutbox, settled } from "./transactions.js";
41
42
  import { readAll } from "./data.js";
42
- import { servicesDependencyProblem } from "./services-rules.js";
43
- import { EnvironmentCredentials, credentialId, isCustodyError, redactSecret } from "./credentials.js";
43
+ import { DEFAULT_MAX_VARIANT_PIXELS, servicesDependencyProblem, VARIANT_CODEC } from "./services-rules.js";
44
+ import { EnvironmentCredentials, credentialId, isConnectionId, isCustodyError, redactSecret } from "./credentials.js";
44
45
  import { systemPrincipal } from "./authority.js";
45
46
  export { FILE_CONTENT_COLLECTION };
46
47
  export const DEFAULT_MAX_FILE_BYTES = 1024 * 1024;
@@ -122,11 +123,18 @@ export class ServicesHost {
122
123
  db;
123
124
  #official;
124
125
  #content;
126
+ /** The application's outbox (`_feltkit_outbox`): a file removal records its byte release there first. */
127
+ #outbox;
125
128
  #authority;
126
129
  #environment;
127
130
  #tenantId;
128
131
  #applicationId;
129
132
  #maxBytes;
133
+ /** Declared image variants, with the digest of each spec (and the codec) that derived rows are keyed to. */
134
+ #variants;
135
+ #maxVariantPixels;
136
+ /** Variants being derived in this process, so concurrent first downloads derive once. */
137
+ #deriving = new Map();
130
138
  /** requestId → principal for invocations currently allowed to cause service effects */
131
139
  #bound = new Map();
132
140
  #lastError;
@@ -139,11 +147,17 @@ export class ServicesHost {
139
147
  this.#resolveDurable = options.resolveDurable ?? (async () => null);
140
148
  this.#withTenant = options.withTenant ?? (async (principal) => principal);
141
149
  this.#content = new FileContent(options.contentDb);
150
+ this.#outbox = options.outboxDb ?? null;
142
151
  this.#authority = options.authority;
143
152
  this.#environment = CONFIGURATION_ENVIRONMENT[options.environment] ?? "staging";
144
153
  this.credentials = options.credentials ?? new EnvironmentCredentials();
145
154
  const config = options.config;
146
155
  this.#maxBytes = typeof config.files === "object" ? config.files.maxBytes ?? DEFAULT_MAX_FILE_BYTES : DEFAULT_MAX_FILE_BYTES;
156
+ this.#maxVariantPixels = typeof config.files === "object" ? config.files.maxVariantPixels ?? DEFAULT_MAX_VARIANT_PIXELS : DEFAULT_MAX_VARIANT_PIXELS;
157
+ this.#variants = new Map(Object.entries(typeof config.files === "object" ? config.files.variants ?? {} : {}).map(([name, spec]) => {
158
+ const normal = { width: spec.width, height: spec.height ?? null, fit: spec.fit ?? "inside", format: spec.format ?? "auto", quality: spec.quality ?? 80 };
159
+ return [name, { spec, digest: createHash("sha256").update(JSON.stringify([VARIANT_CODEC, normal, this.#maxVariantPixels])).digest("hex") }];
160
+ }));
147
161
  this.apiKeyRoles = Object.freeze([...(typeof config.apiKeys === "object" ? config.apiKeys.roles ?? [] : [])]);
148
162
  this.jobHandlers = Object.freeze({ ...(typeof config.jobs === "object" ? config.jobs.handlers ?? {} : {}) });
149
163
  this.notificationTypes = Object.freeze([...(typeof config.notifications === "object" ? config.notifications.types ?? [] : [])]);
@@ -410,6 +424,9 @@ export class ServicesHost {
410
424
  throw new FeltKitError("INVALID_ARGUMENT", "Enter a value to store.");
411
425
  if (!credentialId(input.ref) || !input.ref.startsWith("credential-ref:"))
412
426
  throw new FeltKitError("INVALID_ARGUMENT", "A credential reference is credential-ref:<id>.");
427
+ // A person's own connection is theirs: no application credential (and no credential.store) reaches it.
428
+ if (isConnectionId(credentialId(input.ref)))
429
+ throw new FeltKitError("FORBIDDEN", "That is a person's own connection; only that person can store it, by connecting.");
413
430
  const value = input.value.trim();
414
431
  this.#requireCapability("credential.store");
415
432
  const result = await this.asPrincipal(principal, (verified) => this.#official
@@ -532,8 +549,85 @@ export class ServicesHost {
532
549
  if (!record)
533
550
  throw new FeltKitError("NOT_FOUND", "This file no longer exists.");
534
551
  const file = toInfo(record);
535
- const { bytes } = await this.#content.read(file.id, String(record.storageKey), file.checksum);
536
- return { file, bytes, disposition: grant.disposition };
552
+ // A link serves the content it was issued for, never other content behind the same id.
553
+ if (grant.checksum && file.checksum !== grant.checksum)
554
+ throw new FeltKitError("NOT_FOUND", "This file's content changed after the link was issued; ask for a new link.");
555
+ const storageKey = String(record.storageKey);
556
+ const maxAgeSeconds = grant.cache ? Math.max(0, Math.floor((grant.expiresAt - Date.now()) / 1000)) : null;
557
+ const served = (bytes, contentType, name, variant) => ({
558
+ file,
559
+ bytes,
560
+ disposition: grant.disposition,
561
+ ...(contentType ? { contentType } : {}),
562
+ filename: name,
563
+ etag: `"${createHash("sha256").update(bytes).digest("hex")}"`,
564
+ maxAgeSeconds,
565
+ ...(variant ? { variant } : {}),
566
+ });
567
+ const original = async (variant) => served((await this.#content.read(file.id, storageKey, file.checksum)).bytes, file.contentType, file.name, variant);
568
+ if (!grant.variant)
569
+ return original();
570
+ const declared = this.#variants.get(grant.variant);
571
+ if (!declared)
572
+ return original({ name: grant.variant, served: "original", reason: `The variant "${grant.variant}" is no longer declared (services.files.variants); the original is served.` });
573
+ const row = await this.#derivedVariant(file, storageKey, grant.variant, declared);
574
+ if (row.status !== "derived")
575
+ return original({ name: grant.variant, served: "original", reason: row.reason ?? "The variant could not be derived; the original is served." });
576
+ const extension = row.contentType === "image/png" ? ".png" : ".jpg";
577
+ return served(this.#content.readVariant(row), row.contentType, `${file.name.replace(/\.[^./]*$/, "")}-${grant.variant}${extension}`, { name: grant.variant, served: "variant" });
578
+ }
579
+ /** The declared variant `name`, or INVALID_ARGUMENT naming the declared ones. */
580
+ #variant(name) {
581
+ const declared = typeof name === "string" ? this.#variants.get(name) : undefined;
582
+ if (!declared) {
583
+ const names = [...this.#variants.keys()];
584
+ throw new FeltKitError("INVALID_ARGUMENT", `No file variant ${JSON.stringify(name)}. ${names.length ? `Declared: ${names.join(", ")}.` : "Declare variants in feltkit({ services: { files: { variants } } })."}`);
585
+ }
586
+ return { name: name, ...declared };
587
+ }
588
+ /** What a link to `name` of these bytes will serve, from what is stored (nothing is derived here). */
589
+ async #variantInfo(storageKey, name, digest) {
590
+ const row = await this.#content.variant(storageKey, name);
591
+ if (!row || row.spec !== digest)
592
+ return { name, status: "pending" };
593
+ if (row.status !== "derived")
594
+ return { name, status: "original", ...(row.reason ? { reason: row.reason } : {}) };
595
+ return { name, status: "ready", ...(row.width ? { width: row.width } : {}), ...(row.height ? { height: row.height } : {}), ...(row.contentType ? { contentType: row.contentType } : {}) };
596
+ }
597
+ /**
598
+ * The stored variant of a file's bytes, derived (once) when it is missing or was derived under
599
+ * another spec. An image it cannot be derived from is stored as `original` with the reason, so the
600
+ * work is not repeated on every download.
601
+ */
602
+ async #derivedVariant(file, storageKey, name, declared) {
603
+ const stored = await this.#content.variant(storageKey, name);
604
+ if (stored && stored.spec === declared.digest)
605
+ return stored;
606
+ const key = `${storageKey}\0${name}\0${declared.digest}`;
607
+ const running = this.#deriving.get(key);
608
+ if (running)
609
+ return running;
610
+ const work = (async () => {
611
+ const { bytes } = await this.#content.read(file.id, storageKey, file.checksum);
612
+ const { deriveVariant } = await import("./image-variants.js");
613
+ const derived = deriveVariant(bytes, declared.spec, { maxPixels: this.#maxVariantPixels });
614
+ const row = await this.#content.storeVariant(derived.status === "derived"
615
+ ? { source: storageKey, variant: name, spec: declared.digest, status: "derived", bytes: derived.bytes, width: derived.width, height: derived.height, contentType: derived.contentType }
616
+ : { source: storageKey, variant: name, spec: declared.digest, status: "original", reason: derived.reason });
617
+ // The bytes were released while this was derived (the file was removed): do not leave the variant behind.
618
+ if (!(await this.#content.has(storageKey))) {
619
+ await this.#content.releaseVariants(storageKey);
620
+ throw new FeltKitError("NOT_FOUND", "This file no longer exists.");
621
+ }
622
+ return row;
623
+ })();
624
+ this.#deriving.set(key, work);
625
+ try {
626
+ return await work;
627
+ }
628
+ finally {
629
+ this.#deriving.delete(key);
630
+ }
537
631
  }
538
632
  /**
539
633
  * `PUT /api/files/<token>`: create the file an upload link allows, as the principal who created
@@ -568,6 +662,172 @@ export class ServicesHost {
568
662
  release();
569
663
  }
570
664
  }
665
+ /** The durable intent to release a file's bytes (`files.remove`, step 1). Returns its outbox id. */
666
+ async #recordRelease(by, target) {
667
+ if (!this.#outbox)
668
+ throw new FeltKitError("CONFIGURATION", "files.remove needs the application's outbox; this services host was created without one.");
669
+ const now = Date.now();
670
+ const record = {
671
+ id: `outbox_${randomUUID()}`,
672
+ requestId: by.requestId,
673
+ function: by.function,
674
+ principalId: by.principalId,
675
+ ...(by.tenantId ? { tenantId: by.tenantId } : {}),
676
+ effect: { service: "files", method: "release", ...(target.fileId ? { fileId: target.fileId } : {}), storageKey: target.storageKey },
677
+ state: "pending",
678
+ createdAt: now,
679
+ updatedAt: now,
680
+ attempts: 0,
681
+ };
682
+ await this.#outbox.transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, requireAbsent: true, value: record }] });
683
+ return record.id;
684
+ }
685
+ /** A release that must not happen (its file was not deleted): settled failed, with the reason. */
686
+ async #settleRelease(id, error) {
687
+ const store = outboxStore(this.#outbox);
688
+ const record = await store.get(id).catch(() => null);
689
+ // Not settled (the write failed): the record stays pending, and the outbox's recovery finds the file
690
+ // still live and settles it the same way.
691
+ if (record && record.state === "pending")
692
+ await store.put(id, record.__version, settled(record, { ok: false, error }, Date.now())).catch(() => undefined);
693
+ }
694
+ /**
695
+ * Perform a recorded byte release (outbox effect `files.release`): claimed under the outbox's
696
+ * version check, so two performers never both hold it, and settled done or failed with evidence.
697
+ * Called by `files.remove`, by the outbox's recovery after a stop, and by an operator's retry.
698
+ *
699
+ * the file's record is still live failed: "not deleted"; the bytes are kept
700
+ * another live record uses the bytes done: { released: false, retained: true, referencedBy }
701
+ * otherwise the bytes are removed: done { released: true }, or
702
+ * { released: false } when they were already gone
703
+ * anything fails failed, with the error (an operator retries it)
704
+ *
705
+ * It reads as FeltKit's `file-release` principal (files.read only), never as the caller: the
706
+ * caller's files.delete was decided when the metadata was deleted, and nothing here can widen it.
707
+ */
708
+ async releaseFile(id, now = Date.now) {
709
+ if (!this.#outbox)
710
+ throw new FeltKitError("CONFIGURATION", "A file release needs the application's outbox.");
711
+ return performOutbox(outboxStore(this.#outbox), id, async (claim) => {
712
+ const effect = claim.effect;
713
+ if (effect.service !== "files")
714
+ throw new FeltKitError("INTERNAL", `Outbox record ${id} is not a file release.`);
715
+ return this.#releaseBytes(effect.fileId, effect.storageKey);
716
+ }, {
717
+ // A lookup that failed transiently is tried again by the outbox's recovery (backoff), bytes kept
718
+ // meanwhile. A refusal, an incomplete answer or a live file is final: an operator retries it.
719
+ retryAt: (claim, error) => (RELEASE_FINAL_CODES.has(error.code) || claim.attempts >= RELEASE_ATTEMPTS ? null : now() + RELEASE_BACKOFF_MS * 2 ** Math.max(0, claim.attempts - 1)),
720
+ now,
721
+ });
722
+ }
723
+ /**
724
+ * Which live files name `storageKey`, through AppPort Services' reference lookup
725
+ * (`FileService.references`): a bounded, indexed query, never a scan. Anything short of a complete
726
+ * answer throws, so no caller releases bytes on an unknown.
727
+ */
728
+ async #references(storageKey, verified) {
729
+ const files = this.#requireFiles();
730
+ if (typeof files.references !== "function") {
731
+ throw new FeltKitError("FAILED_PRECONDITION", `@appport/services ${VERSION} cannot look up a file's references (FileService.references), so its bytes were kept.`);
732
+ }
733
+ const answer = await this.#record(files.references(this.#tenantId, storageKey, verified, { limit: 100 }));
734
+ if (answer.live.length)
735
+ return [...answer.live].sort();
736
+ if (!answer.complete)
737
+ throw new FeltKitError("FAILED_PRECONDITION", `Whether any file still names ${storageKey} could not be established, so its bytes were kept.`);
738
+ return [];
739
+ }
740
+ async #releaseBytes(fileId, storageKey) {
741
+ const files = this.#requireFiles();
742
+ const requestId = `release_${randomUUID()}`;
743
+ const release = this.enter(requestId, FILE_RELEASE);
744
+ try {
745
+ const verified = this.#verified(FILE_RELEASE, requestId);
746
+ // Services answers NOT_FOUND for a deleted record (and checks no authority for it). An orphan reclaim
747
+ // names no file: only the reference check below applies.
748
+ const live = fileId === undefined ? false : await this.#record(files.get(this.#tenantId, fileId, verified)).then(() => true, (error) => {
749
+ if (isFeltKitError(error) && error.code === "NOT_FOUND")
750
+ return false;
751
+ throw error;
752
+ });
753
+ if (live)
754
+ throw new FeltKitError("FAILED_PRECONDITION", `File ${fileId} is not deleted, so its bytes were kept.`);
755
+ // 1. Is any live file (any workspace) naming these bytes? Unknown is a no.
756
+ const referencedBy = await this.#references(storageKey, verified);
757
+ if (referencedBy.length) {
758
+ // Kept. If they are already gone, a reference appeared after an earlier attempt removed them
759
+ // and that attempt stopped before it could put them back: say so.
760
+ return { released: false, retained: true, referencedBy, ...((await this.#content.has(storageKey)) ? {} : { bytesMissing: true }) };
761
+ }
762
+ // 2. Remove them, keeping what was removed.
763
+ const taken = await this.#content.take(storageKey);
764
+ // Variants derived from the bytes go with them (also when an earlier attempt removed the bytes).
765
+ const variants = async () => {
766
+ const removed = await this.#content.releaseVariants(storageKey);
767
+ return removed ? { variantsReleased: removed } : {};
768
+ };
769
+ if (!taken.removed)
770
+ return { released: false, ...(await variants()) };
771
+ // 3. Look again: a file may have been made to name these bytes (Services' management API takes any
772
+ // storageKey) between the lookup and the removal. Then, or if this cannot be established, put
773
+ // them back: nothing is left released on an unknown.
774
+ let after;
775
+ try {
776
+ after = await this.#references(storageKey, verified);
777
+ }
778
+ catch (error) {
779
+ await taken.restore();
780
+ throw error;
781
+ }
782
+ if (after.length) {
783
+ await taken.restore();
784
+ return { released: false, retained: true, referencedBy: after, raced: true };
785
+ }
786
+ return { released: true, ...(await variants()) };
787
+ }
788
+ finally {
789
+ release();
790
+ }
791
+ }
792
+ /**
793
+ * Stored bytes no live file record references: left by a removal before byte releases were
794
+ * recorded, by a delete through Services' management API (which removes metadata only), or by an
795
+ * upload that stopped between storing its bytes and recording its file. Bytes stored less than
796
+ * `graceMs` ago are excluded (an upload in flight has no record yet); rows from before `storedAt`
797
+ * was kept are treated as old.
798
+ */
799
+ async orphanedContent(graceMs = ORPHAN_GRACE_MS, now = Date.now()) {
800
+ this.#requireFiles();
801
+ const candidates = (await this.#content.stored()).filter((row) => row.storedAt === undefined || row.storedAt <= now - graceMs);
802
+ const requestId = `orphans_${randomUUID()}`;
803
+ const release = this.enter(requestId, FILE_RELEASE);
804
+ const orphans = [];
805
+ try {
806
+ const verified = this.#verified(FILE_RELEASE, requestId);
807
+ // One bounded lookup per stored row (FileService.references), never a list of every file.
808
+ for (const row of candidates)
809
+ if ((await this.#references(row.storageKey, verified)).length === 0)
810
+ orphans.push(row);
811
+ }
812
+ finally {
813
+ release();
814
+ }
815
+ return orphans.sort((a, b) => a.storageKey.localeCompare(b.storageKey));
816
+ }
817
+ /**
818
+ * An operator's reclaim of orphaned bytes: each is a recorded byte release (outbox effect
819
+ * `files.release`, no file), performed through the same checks as a removal's (nothing a live
820
+ * record references is released), and kept as evidence. Returns the outbox ids.
821
+ */
822
+ async reclaimOrphanedContent(by, graceMs = ORPHAN_GRACE_MS) {
823
+ const ids = [];
824
+ for (const orphan of await this.orphanedContent(graceMs)) {
825
+ const id = await this.#recordRelease({ principalId: by, requestId: `reclaim_${randomUUID()}`, function: "files.reclaim" }, { storageKey: orphan.storageKey });
826
+ await this.releaseFile(id);
827
+ ids.push(id);
828
+ }
829
+ return ids;
830
+ }
571
831
  /** Allow `principal` to cause service effects while request `requestId` runs. */
572
832
  enter(requestId, principal) {
573
833
  if (!principal)
@@ -653,11 +913,37 @@ export class ServicesHost {
653
913
  return { file, bytes, text: () => new TextDecoder().decode(bytes) };
654
914
  },
655
915
  link: async (id, options = {}) => {
656
- await reader.get(id); // the caller must be able to read it (files.read), and it must exist
657
- const ttl = linkSeconds(options.expiresInSeconds, 300);
658
- const expiresAt = Date.now() + ttl * 1000;
659
- const token = await this.#content.issueLink({ kind: "download", fileId: id, expiresAt, disposition: options.disposition === "inline" ? "inline" : "attachment" });
660
- return { url: `/api/files/${token}`, expiresAt: new Date(expiresAt).toISOString() };
916
+ // The caller must be able to read it (files.read, its workspace), and it must exist.
917
+ use();
918
+ this.#requireFiles();
919
+ reads.add("files");
920
+ const record = await owned(id);
921
+ const file = toInfo(record);
922
+ const storageKey = String(record.storageKey);
923
+ const disposition = options.disposition === "inline" ? "inline" : "attachment";
924
+ const variant = options.variant === undefined ? null : this.#variant(options.variant);
925
+ const variantInfo = variant ? { variant: await this.#variantInfo(storageKey, variant.name, variant.digest) } : {};
926
+ const grant = { kind: "download", fileId: id, disposition, ...(file.checksum ? { checksum: file.checksum } : {}), ...(variant ? { variant: variant.name } : {}) };
927
+ if (!options.cache) {
928
+ const ttl = linkSeconds(options.expiresInSeconds, 300);
929
+ const expiresAt = Date.now() + ttl * 1000;
930
+ const token = await this.#content.issueLink({ ...grant, expiresAt });
931
+ return { url: `/api/files/${token}`, expiresAt: new Date(expiresAt).toISOString(), ...variantInfo };
932
+ }
933
+ // Cacheable: time is cut into windows of half the lifetime. Within one window the same scope
934
+ // derives the same token; each URL lives until the end of the window after its own, so it is
935
+ // always issued with at least half its lifetime left, and never lives longer than asked.
936
+ const lifetime = linkSeconds(options.expiresInSeconds, 3600);
937
+ if (lifetime < 2)
938
+ throw new FeltKitError("INVALID_ARGUMENT", "A cacheable link needs expiresInSeconds of at least 2.");
939
+ const windowMs = Math.floor(lifetime / 2) * 1000;
940
+ const window = Math.floor(Date.now() / windowMs);
941
+ const expiresAt = (window + 2) * windowMs;
942
+ // The scope: this file's content (and variant spec) as it is now, and this caller in this
943
+ // workspace. Another principal never receives this URL; changed content gets a new one.
944
+ const token = derivedLinkToken([this.#applicationId, id, storageKey, file.checksum ?? null, variant?.name ?? null, variant?.digest ?? null, disposition, principal.type, principal.id, callerTenant, windowMs, window]);
945
+ await this.#content.issueDerivedLink(token, { ...grant, expiresAt, cache: true });
946
+ return { url: `/api/files/${token}`, expiresAt: new Date(expiresAt).toISOString(), stableUntil: new Date((window + 1) * windowMs).toISOString(), ...variantInfo };
661
947
  },
662
948
  };
663
949
  if (!writable)
@@ -700,8 +986,20 @@ export class ServicesHost {
700
986
  const service = this.#requireFiles();
701
987
  const verified = this.#verified(principal, requestId);
702
988
  const current = await owned(id, verified);
703
- await this.#record(service.delete(this.#tenantId, id, verified));
704
- await this.#content.release(String(current.storageKey));
989
+ // 1. The intent to release the bytes, committed before anything is deleted: a stop between the
990
+ // commits below leaves a pending record the outbox recovers, never stranded bytes.
991
+ const intent = await this.#recordRelease({ principalId: principal.id, ...(principal.tenant ? { tenantId: principal.tenant.id } : {}), requestId, function: "files.remove" }, { fileId: id, storageKey: String(current.storageKey) });
992
+ // 2. The metadata, as the caller (Services authorizes files.delete and audits it). Refused or
993
+ // failed: nothing was deleted, so nothing is released; the attempt stays as evidence.
994
+ try {
995
+ await this.#record(service.delete(this.#tenantId, id, verified));
996
+ }
997
+ catch (error) {
998
+ await this.#settleRelease(intent, { code: isFeltKitError(error) ? error.code : "INTERNAL", message: `The file was not deleted, so its bytes were kept: ${error.message}` });
999
+ throw error;
1000
+ }
1001
+ // 3. The bytes. The file is deleted whatever happens here: a failure is on the record, for a retry.
1002
+ await this.releaseFile(intent);
705
1003
  },
706
1004
  uploadLink: async (options = {}) => {
707
1005
  use();
@@ -779,6 +1077,18 @@ export class ServicesHost {
779
1077
  return page.items.map(toNotification);
780
1078
  },
781
1079
  get: async (id) => toNotification(await this.#record(service().get(this.#tenantId, id, me()))),
1080
+ page: async (options = {}) => {
1081
+ const s = paging(service());
1082
+ const verified = me();
1083
+ const page = await this.#record(s.inbox(this.#tenantId, { recipient: verified.principalId, ...(options.unread ? { unread: true } : {}), ...(options.type ? { type: options.type } : {}), ...(options.limit !== undefined ? { limit: options.limit } : {}), ...(options.cursor ? { cursor: options.cursor } : {}) }, verified));
1084
+ return { items: page.items.map(toNotification), ...(page.nextCursor ? { nextCursor: page.nextCursor } : {}) };
1085
+ },
1086
+ unreadCount: async (options = {}) => {
1087
+ const s = paging(service());
1088
+ const verified = me();
1089
+ const result = await this.#record(s.unreadCount(this.#tenantId, { recipient: verified.principalId, ...(options.type ? { type: options.type } : {}), ...(options.max !== undefined ? { max: options.max } : {}) }, verified));
1090
+ return { count: result.count, complete: result.complete };
1091
+ },
782
1092
  };
783
1093
  if (!writable)
784
1094
  return reader;
@@ -802,6 +1112,10 @@ export class ServicesHost {
802
1112
  },
803
1113
  markRead: async (id) => toNotification(await this.#record(service().markRead(this.#tenantId, id, me()))),
804
1114
  dismiss: async (id) => toNotification(await this.#record(service().dismiss(this.#tenantId, id, me()))),
1115
+ markAllRead: async (options = {}) => {
1116
+ const result = await this.#record(paging(service()).markAllRead(this.#tenantId, { ...(options.type ? { type: options.type } : {}) }, me()));
1117
+ return { marked: result.marked, complete: result.complete };
1118
+ },
805
1119
  };
806
1120
  }
807
1121
  #bindConfiguration(principal, requestId, reads, writable, used) {
@@ -1015,6 +1329,14 @@ function scrubError(error, secret) {
1015
1329
  /** FeltKit's host-only principals for `feltkit config export|import` (see Authority's system principals). */
1016
1330
  const ACCOUNT_MAIL = systemPrincipal("account-mail", "account-mail");
1017
1331
  const FILE_LINK = systemPrincipal("file-link", "file-link");
1332
+ const FILE_RELEASE = systemPrincipal("file-release", "file-release");
1333
+ /** A byte release whose lookup failed transiently is tried again, at most this many attempts in all, with backoff. */
1334
+ const RELEASE_ATTEMPTS = 5;
1335
+ const RELEASE_BACKOFF_MS = 30_000;
1336
+ /** Final at once: a refusal, an unestablished answer, a live file, a bad request. */
1337
+ const RELEASE_FINAL_CODES = new Set(["FAILED_PRECONDITION", "FORBIDDEN", "UNAUTHORIZED", "INVALID_ARGUMENT", "NOT_FOUND"]);
1338
+ /** Bytes younger than this are not orphans: an upload stores its bytes before it records its file. */
1339
+ export const ORPHAN_GRACE_MS = 60 * 60 * 1000;
1018
1340
  const TRANSFER_READ = systemPrincipal("configuration-transfer", "transfer-read");
1019
1341
  const TRANSFER_WRITE = systemPrincipal("configuration-transfer", "transfer-write");
1020
1342
  /** AppPort Services' service names → this host's fields. */
@@ -1046,6 +1368,13 @@ const UNCONFIGURED = {
1046
1368
  jobs: "Enabled; no job handlers declared (services.jobs.handlers).",
1047
1369
  schedules: "Enabled; no active schedules.",
1048
1370
  };
1371
+ function paging(service) {
1372
+ const s = service;
1373
+ if (typeof s.inbox !== "function" || typeof s.unreadCount !== "function" || typeof s.markAllRead !== "function") {
1374
+ throw new FeltKitError("FAILED_PRECONDITION", `Notification paging (page, unreadCount, markAllRead) needs @appport/services with NotificationService.inbox, unreadCount and markAllRead (after 0.19.0); this installation has ${VERSION}.`, { hint: "Update @appport/services. list() works on every release." });
1375
+ }
1376
+ return s;
1377
+ }
1049
1378
  function toNotification(item) {
1050
1379
  return {
1051
1380
  id: item.id,