@feltdb/feltkit 0.3.25 → 0.3.27

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 (95) hide show
  1. package/dist/app.d.ts +60 -3
  2. package/dist/app.js +23 -13
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.d.ts +5 -1
  5. package/dist/appboundry/build.js +16 -24
  6. package/dist/appboundry/build.js.map +1 -1
  7. package/dist/appboundry/guest-index.d.ts +1 -0
  8. package/dist/appboundry/guest-index.js +1 -0
  9. package/dist/appboundry/guest-index.js.map +1 -1
  10. package/dist/appboundry/guest-tenancy.d.ts +40 -0
  11. package/dist/appboundry/guest-tenancy.js +162 -0
  12. package/dist/appboundry/guest-tenancy.js.map +1 -0
  13. package/dist/appboundry/guest.js +22 -1
  14. package/dist/appboundry/guest.js.map +1 -1
  15. package/dist/appboundry/host.d.ts +24 -0
  16. package/dist/appboundry/host.js +157 -5
  17. package/dist/appboundry/host.js.map +1 -1
  18. package/dist/cli/main.js +17 -5
  19. package/dist/cli/main.js.map +1 -1
  20. package/dist/dashboard/assets/{index-BXTNQAg1.css → index-BehzsQOa.css} +1 -1
  21. package/dist/dashboard/assets/{index-BEjtLLYq.js → index-Clsfddp8.js} +9 -9
  22. package/dist/dashboard/index.html +2 -2
  23. package/dist/index.d.ts +3 -1
  24. package/dist/index.js +2 -0
  25. package/dist/index.js.map +1 -1
  26. package/dist/platform/deployments.d.ts +1 -1
  27. package/dist/platform/server.js +5 -3
  28. package/dist/platform/server.js.map +1 -1
  29. package/dist/react/auth.js +3 -2
  30. package/dist/react/auth.js.map +1 -1
  31. package/dist/runtime/agent.d.ts +14 -0
  32. package/dist/runtime/agent.js +59 -9
  33. package/dist/runtime/agent.js.map +1 -1
  34. package/dist/runtime/application-authority.d.ts +54 -0
  35. package/dist/runtime/application-authority.js +55 -0
  36. package/dist/runtime/application-authority.js.map +1 -0
  37. package/dist/runtime/authboundry.d.ts +25 -13
  38. package/dist/runtime/authboundry.js +15 -7
  39. package/dist/runtime/authboundry.js.map +1 -1
  40. package/dist/runtime/browser-inference.d.ts +2 -2
  41. package/dist/runtime/browser-inference.js +2 -2
  42. package/dist/runtime/content.d.ts +1 -0
  43. package/dist/runtime/context.d.ts +80 -0
  44. package/dist/runtime/data.d.ts +1 -24
  45. package/dist/runtime/data.js +4 -67
  46. package/dist/runtime/data.js.map +1 -1
  47. package/dist/runtime/job-context.d.ts +26 -0
  48. package/dist/runtime/job-context.js +24 -0
  49. package/dist/runtime/job-context.js.map +1 -0
  50. package/dist/runtime/paged-read.d.ts +35 -0
  51. package/dist/runtime/paged-read.js +69 -0
  52. package/dist/runtime/paged-read.js.map +1 -0
  53. package/dist/runtime/runtime.js +111 -13
  54. package/dist/runtime/runtime.js.map +1 -1
  55. package/dist/runtime/services.d.ts +39 -35
  56. package/dist/runtime/services.js +155 -8
  57. package/dist/runtime/services.js.map +1 -1
  58. package/dist/runtime/sha256.d.ts +1 -0
  59. package/dist/runtime/sha256.js +91 -0
  60. package/dist/runtime/sha256.js.map +1 -0
  61. package/dist/runtime/tenancy.d.ts +34 -1
  62. package/dist/runtime/tenancy.js +62 -11
  63. package/dist/runtime/tenancy.js.map +1 -1
  64. package/dist/runtime/transactions.d.ts +11 -2
  65. package/dist/runtime/transactions.js +6 -3
  66. package/dist/runtime/transactions.js.map +1 -1
  67. package/dist/server/admin.js +56 -3
  68. package/dist/server/admin.js.map +1 -1
  69. package/dist/server/index.d.ts +7 -0
  70. package/dist/server/index.js +38 -14
  71. package/dist/server/index.js.map +1 -1
  72. package/dist/server/ports.d.ts +43 -0
  73. package/dist/server/ports.js +96 -0
  74. package/dist/server/ports.js.map +1 -0
  75. package/dist/server/project.d.ts +8 -1
  76. package/dist/server/project.js +6 -9
  77. package/dist/server/project.js.map +1 -1
  78. package/dist/server/tenancy.js +2 -1
  79. package/dist/server/tenancy.js.map +1 -1
  80. package/dist/testing/index.d.ts +36 -2
  81. package/dist/testing/index.js +17 -4
  82. package/dist/testing/index.js.map +1 -1
  83. package/dist/words.d.ts +9 -0
  84. package/dist/words.js +15 -0
  85. package/dist/words.js.map +1 -0
  86. package/docs/APPBOUNDRY.md +15 -6
  87. package/docs/AUTH.md +16 -3
  88. package/docs/GUARANTEES.md +31 -0
  89. package/docs/PATH-TO-PRODUCTION.md +1 -1
  90. package/docs/README.md +2 -2
  91. package/docs/TRANSACTIONS.md +4 -0
  92. package/package.json +7 -7
  93. package/skills/.claude-plugin/marketplace.json +1 -1
  94. package/skills/.claude-plugin/plugin.json +1 -1
  95. package/skills/feltkit-services/SKILL.md +1 -1
@@ -0,0 +1,69 @@
1
+ import { FeltKitError } from "../errors.js";
2
+ /**
3
+ * The largest page FeltDB's `db.query` answers (it refuses a larger `limit`, on every runtime).
4
+ * Whole results are read as consecutive pages of this size, following FeltDB's cursor.
5
+ */
6
+ export const PAGE_LIMIT = 1_000;
7
+ /**
8
+ * Every record matching `request`, one FeltDB page at a time, following `nextCursor` to the end.
9
+ *
10
+ * This is the only way FeltKit reads more than one page. `collection.find()` is not used for
11
+ * whole results: FeltDB 0.18 answers it with a default page of 100 when given options (silently
12
+ * incomplete), and FeltDB 0.20 refuses it past 1,000 matches. A page that says more records remain
13
+ * without a cursor to them, or a cursor that does not move, is refused here rather than returned as
14
+ * a complete result.
15
+ */
16
+ export async function* queryPages(db, request, pageSize = PAGE_LIMIT) {
17
+ let cursor;
18
+ const seen = new Set();
19
+ for (;;) {
20
+ const page = await db.query({
21
+ collection: request.collection,
22
+ ...(request.where?.length ? { where: request.where } : {}),
23
+ ...(request.orderBy?.length ? { orderBy: request.orderBy } : {}),
24
+ limit: pageSize,
25
+ ...(cursor ? { cursor } : {}),
26
+ });
27
+ yield page.records.map(storedDocument);
28
+ if (!page.nextCursor) {
29
+ if (page.exhausted === false) {
30
+ throw new FeltKitError("INTERNAL", `FeltDB reported more "${request.collection}" records without a cursor to them; the read was stopped rather than returned incomplete.`, { details: { collection: request.collection } });
31
+ }
32
+ return;
33
+ }
34
+ if (seen.has(page.nextCursor)) {
35
+ throw new FeltKitError("INTERNAL", `FeltDB returned the same cursor twice while reading "${request.collection}"; the read was stopped rather than repeated.`, { details: { collection: request.collection } });
36
+ }
37
+ seen.add(page.nextCursor);
38
+ cursor = page.nextCursor;
39
+ }
40
+ }
41
+ /** Every matching record (or the first `limit`), read in pages. Holds the result, so use it for results the caller returns. */
42
+ export async function readAll(db, request, limit) {
43
+ const out = [];
44
+ for await (const page of queryPages(db, request, limit !== undefined ? Math.min(limit, PAGE_LIMIT) : PAGE_LIMIT)) {
45
+ for (const record of page) {
46
+ if (limit !== undefined && out.length >= limit)
47
+ return out;
48
+ out.push(record);
49
+ }
50
+ if (limit !== undefined && out.length >= limit)
51
+ return out;
52
+ }
53
+ return out;
54
+ }
55
+ /** How many records match, counted page by page; no page is kept. */
56
+ export async function countAll(db, request) {
57
+ let n = 0;
58
+ for await (const page of queryPages(db, request))
59
+ n += page.length;
60
+ return n;
61
+ }
62
+ /** As FeltDB's own `find()` does: a server reports a record's key as `recordId` beside its `id`. */
63
+ function storedDocument(record) {
64
+ if (!record || typeof record !== "object" || !("recordId" in record) || record.recordId !== record.id)
65
+ return record;
66
+ const { recordId: _key, ...document } = record;
67
+ return document;
68
+ }
69
+ //# sourceMappingURL=paged-read.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"paged-read.js","sourceRoot":"","sources":["../../src/runtime/paged-read.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAK5C;;;GAGG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,CAAC;AAQhC;;;;;;;;GAQG;AACH,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,UAAU,CAAC,EAAgB,EAAE,OAAkB,EAAE,QAAQ,GAAG,UAAU;IAC3F,IAAI,MAA0B,CAAC;IAC/B,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,SAAS,CAAC;QACR,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AAC;IAC1E,OAAO,QAAkB,CAAC;AAC5B,CAAC"}
@@ -7,6 +7,7 @@
7
7
  * application definition (functions, capabilities, policy) without reopening state.
8
8
  * close() is idempotent and releases the instance.
9
9
  */
10
+ import { JOB_CONTEXTS_COLLECTION, jobIdOfRun } from "./job-context.js";
10
11
  import { checkTokenBytes } from "./crypto-token.js";
11
12
  import { evaluateAuthorize } from "../authorize.js";
12
13
  import { eventDefinitions, observationAuthorizer, stageEvent } from "./events.js";
@@ -14,18 +15,19 @@ import { AppPortError, createApplication, defineCapability, createMcpBridge, err
14
15
  import { grantsPermission } from "@appport/authorization";
15
16
  import { AsyncLocalStorage } from "node:async_hooks";
16
17
  import { performance } from "node:perf_hooks";
17
- import { createHash, randomBytes, randomUUID } from "node:crypto";
18
+ import { createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
18
19
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
19
20
  import { dirname, join } from "node:path";
20
21
  import { AGENT_MAX_BACKOFF_MS } from "../app.js";
21
22
  import { IntegrationHost, integrationDescriptor } from "./integrations.js";
23
+ import { applicationAuthority } from "./application-authority.js";
22
24
  import { verifyStorage } from "./storage-check.js";
23
25
  import { assertNotPartiallyRestored, writeBackup } from "./backup.js";
24
26
  import { backupMeta, remoteBackupRefusal } from "./backup-environment.js";
25
27
  import { FeltKitError, isFeltKitError, statusFor } from "../errors.js";
26
28
  import { validate } from "../schema.js";
27
29
  import { ActivityLog, errorSummary } from "./activity.js";
28
- import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal } from "./authority.js";
30
+ import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal, toAppPortPrincipal } from "./authority.js";
29
31
  import { ChangeFeed } from "./changes.js";
30
32
  import { generationDigest } from "./generation.js";
31
33
  import { ModelHost } from "./decisions.js";
@@ -49,6 +51,12 @@ import { accountMail } from "./mail.js";
49
51
  import { ChallengeStore } from "./challenges.js";
50
52
  import { MEMBERSHIPS_COLLECTION, TenancyStore } from "./tenancy.js";
51
53
  import { hasTenantCollections, scopeToTenant } from "./tenant-scope.js";
54
+ /** Tenancy's randomness and HMAC in FeltKit's runtime (an artifact's guest supplies the host's crypto@1 instead). */
55
+ const NODE_TENANCY_CRYPTO = {
56
+ randomHex: (bytes) => randomBytes(bytes).toString("hex"),
57
+ randomBase64url: (bytes) => randomBytes(bytes).toString("base64url"),
58
+ hmacBase64url: (key, data) => createHmac("sha256", key).update(data).digest("base64url"),
59
+ };
52
60
  const consoleLogger = {
53
61
  info: (m, f) => console.log(`[feltkit] ${m}`, f ?? ""),
54
62
  warn: (m, f) => console.warn(`[feltkit] ${m}`, f ?? ""),
@@ -352,7 +360,7 @@ export class FeltKitRuntime {
352
360
  this.accounts = accounts ? new AccountStore(this.instance.handle("feltkit.accounts"), accounts) : null;
353
361
  this.challenges = accounts ? new ChallengeStore(this.instance.handle("feltkit.accounts"), () => this.authSecret()) : null;
354
362
  const tenant = app.options.auth?.tenant;
355
- this.tenancy = tenant ? new TenancyStore(this.instance.handle("feltkit.tenancy"), tenant, () => this.authSecret()) : null;
363
+ this.tenancy = tenant ? new TenancyStore(this.instance.handle("feltkit.tenancy"), tenant, () => this.authSecret(), NODE_TENANCY_CRYPTO) : null;
356
364
  this.mail = accounts?.email ? accountMail({ env: this.#env, development: !this.environment.production, from: accounts.email.from, identity: accounts.email.identity ?? "auth", logger: this.logger }) : null;
357
365
  const config = app.options.services ?? {};
358
366
  const store = this.accounts;
@@ -405,7 +413,8 @@ export class FeltKitRuntime {
405
413
  authority,
406
414
  config,
407
415
  environment: this.environment.name,
408
- resolveDurable: (subjectId) => this.#resolveDurable(subjectId),
416
+ resolveDurable: (subjectId, _kind, runId) => this.#resolveDurable(subjectId, runId),
417
+ withTenant: (principal, tenantId) => this.withTenant(principal, tenantId),
409
418
  runJob: async (fn, payload, principal, runId) => {
410
419
  // The job, not the attempt, is the unit of effect: a re-run (lease expired after the commit) replays the
411
420
  // first commit by its transaction id instead of committing again.
@@ -419,6 +428,13 @@ export class FeltKitRuntime {
419
428
  if (!result.ok)
420
429
  throw Object.assign(new Error(`${result.error.code}: ${result.error.message}`), { code: result.error.code });
421
430
  },
431
+ // An inbound webhook's handler: the declared mutation, as `integration:<provider>` (no tenant).
432
+ runInbound: async (fn, principal, event) => {
433
+ const result = await this.call(fn, { event }, { principal, via: "integration", requestId: `inbound_${String(event.integrationId)}_${String(event.eventId)}`.slice(0, 200) });
434
+ if (!result.ok)
435
+ throw Object.assign(new Error(`${result.error.code}: ${result.error.message}`), { code: result.error.code });
436
+ return result.value;
437
+ },
422
438
  credentials: this.credentials,
423
439
  ...(config.apiKeys ? { apiKeyVerifierKey: this.#verifierKey() } : {}),
424
440
  // Outside development, webhooks go only to public addresses unless the operator opts in
@@ -430,8 +446,10 @@ export class FeltKitRuntime {
430
446
  .filter(([, fn]) => fn.capability)
431
447
  .map(([name, fn]) => this.#capabilityFor(name, fn));
432
448
  for (const integration of app.integrations.values()) {
449
+ // An operation declared `expose: false` is for application code only: not an AppPort capability.
433
450
  for (const op of Object.values(integration.operations))
434
- capabilities.push(this.#integrationCapability(integration, op));
451
+ if ((op.expose ?? integration.expose ?? true) !== false)
452
+ capabilities.push(this.#integrationCapability(integration, op));
435
453
  }
436
454
  const appport = createApplication({
437
455
  application: { id: app.name, name: app.name, version: app.version, ...(app.options.description ? { description: app.options.description } : {}) },
@@ -461,6 +479,47 @@ export class FeltKitRuntime {
461
479
  this.#resolver = new CollectionResolver(app.collections);
462
480
  this.#generation += 1;
463
481
  }
482
+ /** `ctx.authority`: AuthBoundry through the shared adapter, as the application's executor; each decision recorded (never a credential). */
483
+ #applicationAuthority(principal, requestId) {
484
+ return applicationAuthority({
485
+ config: this.app.options.authority,
486
+ production: this.environment.production,
487
+ credentials: this.services.credentials,
488
+ tenantId: this.services.scope.tenantId,
489
+ record: ({ capability, executor, onBehalfOf, decision, durationMs }) => this.activity.record({
490
+ kind: "auth",
491
+ name: "authority.decide",
492
+ via: "runtime",
493
+ requestId,
494
+ principal: principal ? { id: principal.id, type: principal.type, roles: principal.roles } : null,
495
+ outcome: decision.allowed ? "success" : decision.outcome === "deny" ? "denied" : "error",
496
+ durationMs,
497
+ detail: { capability, executor, onBehalfOf, outcome: decision.outcome, decisionId: decision.decisionId, delegationId: decision.delegationId, reason: decision.reason },
498
+ }),
499
+ });
500
+ }
501
+ /** `ctx.integrations`: a declared integration operation, as the caller, under the operation's own permission. */
502
+ #integrationInvoker(principal) {
503
+ return {
504
+ invoke: async (capability, input, options = {}) => {
505
+ const found = this.integrations.operationFor(capability);
506
+ if (!found)
507
+ throw new FeltKitError("NOT_FOUND", `${capability} is not an integration operation.`);
508
+ if (!principal)
509
+ throw new FeltKitError("UNAUTHORIZED", `${capability} needs an authenticated caller.`);
510
+ if (!authContext(this.#authority, principal).has(found.op.access)) {
511
+ throw new FeltKitError("FORBIDDEN", `${capability} requires ${found.op.access}; ${principal.id} does not hold it.`);
512
+ }
513
+ // The operation's declared input is its contract on every path: AppPort validates it for a
514
+ // capability call, and here it is validated for application code, before anything is sent.
515
+ const parsed = validate(found.op.inputSchema, input);
516
+ if (!parsed.ok) {
517
+ throw new FeltKitError("INVALID_ARGUMENT", `Invalid input for ${capability}: ${parsed.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`, { details: { issues: parsed.issues } });
518
+ }
519
+ return this.integrations.invoke(capability, parsed.value, { principal, via: "function", ...(options.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}) });
520
+ },
521
+ };
522
+ }
464
523
  /** An integration operation as an AppPort capability: AppPort validates and authorizes; IntegrationHost calls and records. */
465
524
  #integrationCapability(integration, op) {
466
525
  return defineCapability({
@@ -636,8 +695,20 @@ export class FeltKitRuntime {
636
695
  * exists and is not revoked holds services.apiKeys.roles; anyone else holds the roles of
637
696
  * their most recent active session. No active session → null, and the work is refused.
638
697
  */
639
- async #resolveDurable(subjectId) {
640
- return this.resolvePrincipal(subjectId);
698
+ async #resolveDurable(subjectId, runId) {
699
+ const principal = await this.resolvePrincipal(subjectId);
700
+ if (!principal || !runId)
701
+ return principal;
702
+ // A job queued in a workspace runs in it, through the live membership only (job-context.ts).
703
+ const context = (await this.instance.handle("app").collection(JOB_CONTEXTS_COLLECTION).get(jobIdOfRun(runId))) ?? null;
704
+ if (!context)
705
+ return principal;
706
+ const inTenant = await this.withTenant(principal, context.tenantId);
707
+ if (inTenant.tenant?.id !== context.tenantId) {
708
+ this.logger.warn(`job ${context.jobId}: ${subjectId} is no longer a member of the workspace it was queued in; refused`, { tenantId: context.tenantId });
709
+ return null;
710
+ }
711
+ return inTenant;
641
712
  }
642
713
  /**
643
714
  * A principal as it is now, by id: a live API key, else the most recent active session.
@@ -722,10 +793,14 @@ export class FeltKitRuntime {
722
793
  performed += 1;
723
794
  continue;
724
795
  }
725
- const principal = await this.#resolveDurable(record.principalId);
796
+ // In the workspace the caller worked in, through the live membership only (no membership: not performed).
797
+ const account = await this.#resolveDurable(record.principalId);
798
+ const inTenant = account && record.tenantId ? await this.withTenant(account, record.tenantId) : account;
799
+ const principal = inTenant && record.tenantId && inTenant.tenant?.id !== record.tenantId ? null : inTenant;
726
800
  if (!principal) {
801
+ const why = account ? `${record.principalId} is no longer a member of the workspace the effect was staged in` : `${record.principalId} could not be resolved to a current principal (no active session or API key)`;
727
802
  await store
728
- .transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, ifVersion: record.__version, value: settled(record, { ok: false, error: { code: "UNAUTHORIZED", message: `${record.principalId} could not be resolved to a current principal (no active session or API key), so the effect was not performed.` } }, Date.now()) }] })
803
+ .transaction({ operations: [{ collection: OUTBOX_COLLECTION, id: record.id, ifVersion: record.__version, value: settled(record, { ok: false, error: { code: "UNAUTHORIZED", message: `${why}, so the effect was not performed.` } }, Date.now()) }] })
729
804
  .catch(() => undefined);
730
805
  continue;
731
806
  }
@@ -865,10 +940,16 @@ export class FeltKitRuntime {
865
940
  * its `on`). It records the tenant the caller worked in; whether the agent may work there is
866
941
  * decided when it runs, from the agent's own membership.
867
942
  */
868
- #agentEffect(name, input, principal, event) {
943
+ #agentEffect(name, input, principal, event, tenant) {
869
944
  if (!this.app.agents.has(name))
870
945
  throw new FeltKitError("INVALID_ARGUMENT", `No application agent named "${name}".`, { hint: `Declare it with app.agent("${name}", { principal, roles, handler }).` });
871
- return { service: "agent", method: "run", agent: name, input, ...(principal?.tenant ? { tenantId: principal.tenant.id } : {}), ...(event ? { event } : {}) };
946
+ // A caller in a tenant triggers the agent there; one in none (an inbound webhook) may name the
947
+ // tenant to ask for. Either way the agent works there only while it is a member itself.
948
+ if (tenant !== undefined && principal?.tenant && principal.tenant.id !== tenant) {
949
+ throw new FeltKitError("FORBIDDEN", `afterCommit.agent: a caller working in a tenant may not trigger "${name}" in another one.`);
950
+ }
951
+ const tenantId = principal?.tenant?.id ?? tenant;
952
+ return { service: "agent", method: "run", agent: name, input, ...(tenantId ? { tenantId } : {}), ...(event ? { event } : {}) };
872
953
  }
873
954
  /** Start an agent run now, without making the triggering call wait for it. */
874
955
  #dispatchAgent(id) {
@@ -1248,6 +1329,8 @@ export class FeltKitRuntime {
1248
1329
  requestId,
1249
1330
  log: this.logger,
1250
1331
  crypto: { token: async (bytes) => randomBytes(checkTokenBytes(bytes)).toString("base64url") },
1332
+ authority: this.#applicationAuthority(principal, requestId),
1333
+ integrations: this.#integrationInvoker(principal),
1251
1334
  };
1252
1335
  const starts = [];
1253
1336
  const agent = {
@@ -1270,7 +1353,7 @@ export class FeltKitRuntime {
1270
1353
  enabled: { notifications: Boolean(enabled.notifications), webhooks: Boolean(enabled.webhooks), jobs: Boolean(enabled.jobs) },
1271
1354
  stage: (record) => db.stageSystem(OUTBOX_COLLECTION, record),
1272
1355
  newId: newOutboxId,
1273
- agent: (agentName, input) => this.#agentEffect(agentName, input, principal, triggeringEvent),
1356
+ agent: (agentName, input, tenant) => this.#agentEffect(agentName, input, principal, triggeringEvent, tenant),
1274
1357
  work: (component, kind, input, opts) => {
1275
1358
  if (!this.app.options.components?.[component])
1276
1359
  throw new FeltKitError("INVALID_ARGUMENT", `afterCommit.work: "${component}" is not a component of this application.`, { hint: "Declare it in feltkit({ components })." });
@@ -1492,7 +1575,21 @@ export class FeltKitRuntime {
1492
1575
  return { ...result, receipt, memoryId, generationId: handle.generationId };
1493
1576
  },
1494
1577
  },
1578
+ authority: this.#applicationAuthority(principal, requestId),
1579
+ integrations: this.#integrationInvoker(principal),
1495
1580
  agent: {
1581
+ catalog: async () => (await agent.tools(signedIn())).map((t) => ({
1582
+ name: t.name,
1583
+ source: t.source,
1584
+ effect: t.effect,
1585
+ ...(t.description ? { description: t.description } : {}),
1586
+ allowed: t.allowed,
1587
+ ...(t.invoke ? { invoke: t.invoke } : {}),
1588
+ ...(t.approval ? { approval: t.approval } : {}),
1589
+ ...(t.inputSchema ? { inputSchema: t.inputSchema } : {}),
1590
+ ...(t.integration ? { integration: t.integration } : {}),
1591
+ ...(t.readiness ? { readiness: t.readiness } : {}),
1592
+ })),
1496
1593
  tools: async () => {
1497
1594
  const p = signedIn();
1498
1595
  return (await agent.tools(p))
@@ -1655,8 +1752,9 @@ function pick(principal) {
1655
1752
  function argKeys(value) {
1656
1753
  return value && typeof value === "object" ? Object.keys(value) : [];
1657
1754
  }
1755
+ /** As toAppPortPrincipal: the workspace travels with the principal (dropping it ran agent actions with no workspace, G-02). */
1658
1756
  function toAppPort(principal) {
1659
- return { id: principal.id, type: principal.type === "agent" ? "application" : principal.type, attributes: { roles: principal.roles, feltkitType: principal.type } };
1757
+ return toAppPortPrincipal(principal);
1660
1758
  }
1661
1759
  /**
1662
1760
  * HTTP status for the AppPort codes FeltKit itself returns that AppPort's HTTP binding does not