@feltdb/feltkit 0.3.11 → 0.3.13

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 (146) hide show
  1. package/README.md +4 -3
  2. package/dist/app.d.ts +98 -3
  3. package/dist/app.js +63 -0
  4. package/dist/app.js.map +1 -1
  5. package/dist/appboundry/build.d.ts +39 -1
  6. package/dist/appboundry/build.js +57 -6
  7. package/dist/appboundry/build.js.map +1 -1
  8. package/dist/appboundry/guest.js +46 -5
  9. package/dist/appboundry/guest.js.map +1 -1
  10. package/dist/appboundry/host.d.ts +24 -5
  11. package/dist/appboundry/host.js +234 -141
  12. package/dist/appboundry/host.js.map +1 -1
  13. package/dist/appboundry/runtime.d.ts +44 -0
  14. package/dist/appboundry/runtime.js +99 -0
  15. package/dist/appboundry/runtime.js.map +1 -0
  16. package/dist/cli/entry.d.ts +1 -0
  17. package/dist/cli/entry.js +4 -0
  18. package/dist/cli/entry.js.map +1 -0
  19. package/dist/cli/main.d.ts +5 -0
  20. package/dist/cli/main.js +550 -13
  21. package/dist/cli/main.js.map +1 -1
  22. package/dist/cli/test-reporter.d.ts +9 -0
  23. package/dist/cli/test-reporter.js +26 -0
  24. package/dist/cli/test-reporter.js.map +1 -0
  25. package/dist/client/index.d.ts +3 -0
  26. package/dist/client/index.js +3 -0
  27. package/dist/client/index.js.map +1 -1
  28. package/dist/dashboard/assets/index-BSnW2DC-.js +15 -0
  29. package/dist/dashboard/assets/{index-91I1zDK-.css → index-BXTNQAg1.css} +1 -1
  30. package/dist/dashboard/index.html +3 -3
  31. package/dist/docs.d.ts +12 -0
  32. package/dist/docs.js +42 -0
  33. package/dist/docs.js.map +1 -0
  34. package/dist/errors.d.ts +15 -0
  35. package/dist/errors.js +9 -0
  36. package/dist/errors.js.map +1 -1
  37. package/dist/index.d.ts +1 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/platform/changes.d.ts +340 -0
  40. package/dist/platform/changes.js +355 -0
  41. package/dist/platform/changes.js.map +1 -0
  42. package/dist/platform/deployments.d.ts +653 -0
  43. package/dist/platform/deployments.js +532 -0
  44. package/dist/platform/deployments.js.map +1 -0
  45. package/dist/platform/operations.d.ts +74 -0
  46. package/dist/platform/operations.js +198 -0
  47. package/dist/platform/operations.js.map +1 -0
  48. package/dist/platform/platform.d.ts +78 -0
  49. package/dist/platform/platform.js +264 -0
  50. package/dist/platform/platform.js.map +1 -0
  51. package/dist/platform/server.d.ts +25 -0
  52. package/dist/platform/server.js +165 -0
  53. package/dist/platform/server.js.map +1 -0
  54. package/dist/platform/source.d.ts +27 -0
  55. package/dist/platform/source.js +142 -0
  56. package/dist/platform/source.js.map +1 -0
  57. package/dist/runtime/activity.d.ts +25 -0
  58. package/dist/runtime/activity.js +38 -12
  59. package/dist/runtime/activity.js.map +1 -1
  60. package/dist/runtime/agent.d.ts +16 -0
  61. package/dist/runtime/agent.js +92 -28
  62. package/dist/runtime/agent.js.map +1 -1
  63. package/dist/runtime/backup-environment.d.ts +32 -0
  64. package/dist/runtime/backup-environment.js +92 -0
  65. package/dist/runtime/backup-environment.js.map +1 -0
  66. package/dist/runtime/backup.d.ts +129 -0
  67. package/dist/runtime/backup.js +344 -0
  68. package/dist/runtime/backup.js.map +1 -0
  69. package/dist/runtime/capabilities.js +4 -2
  70. package/dist/runtime/capabilities.js.map +1 -1
  71. package/dist/runtime/changes.js +2 -2
  72. package/dist/runtime/changes.js.map +1 -1
  73. package/dist/runtime/contract.js +4 -3
  74. package/dist/runtime/contract.js.map +1 -1
  75. package/dist/runtime/data.d.ts +36 -5
  76. package/dist/runtime/data.js +165 -55
  77. package/dist/runtime/data.js.map +1 -1
  78. package/dist/runtime/decisions.js +2 -1
  79. package/dist/runtime/decisions.js.map +1 -1
  80. package/dist/runtime/instance.js +17 -0
  81. package/dist/runtime/instance.js.map +1 -1
  82. package/dist/runtime/integrations.js +14 -6
  83. package/dist/runtime/integrations.js.map +1 -1
  84. package/dist/runtime/loader.js +28 -4
  85. package/dist/runtime/loader.js.map +1 -1
  86. package/dist/runtime/migration-context.d.ts +25 -0
  87. package/dist/runtime/migration-context.js +69 -0
  88. package/dist/runtime/migration-context.js.map +1 -0
  89. package/dist/runtime/outbox.d.ts +6 -82
  90. package/dist/runtime/outbox.js +14 -59
  91. package/dist/runtime/outbox.js.map +1 -1
  92. package/dist/runtime/readiness.js +18 -1
  93. package/dist/runtime/readiness.js.map +1 -1
  94. package/dist/runtime/runtime.d.ts +84 -8
  95. package/dist/runtime/runtime.js +372 -131
  96. package/dist/runtime/runtime.js.map +1 -1
  97. package/dist/runtime/services.d.ts +41 -5
  98. package/dist/runtime/services.js +49 -4
  99. package/dist/runtime/services.js.map +1 -1
  100. package/dist/runtime/sessions.js +4 -3
  101. package/dist/runtime/sessions.js.map +1 -1
  102. package/dist/runtime/state-contract.d.ts +167 -0
  103. package/dist/runtime/state-contract.js +438 -0
  104. package/dist/runtime/state-contract.js.map +1 -0
  105. package/dist/runtime/transactions.d.ts +199 -0
  106. package/dist/runtime/transactions.js +246 -0
  107. package/dist/runtime/transactions.js.map +1 -0
  108. package/dist/schema.d.ts +13 -1
  109. package/dist/schema.js +21 -2
  110. package/dist/schema.js.map +1 -1
  111. package/dist/server/admin.d.ts +3 -2
  112. package/dist/server/admin.js +62 -10
  113. package/dist/server/admin.js.map +1 -1
  114. package/dist/server/index.d.ts +6 -1
  115. package/dist/server/index.js +90 -9
  116. package/dist/server/index.js.map +1 -1
  117. package/dist/server/mcp.js +1 -1
  118. package/dist/server/mcp.js.map +1 -1
  119. package/dist/server/project.d.ts +5 -0
  120. package/dist/server/project.js +13 -2
  121. package/dist/server/project.js.map +1 -1
  122. package/dist/testing/index.d.ts +10 -3
  123. package/dist/testing/index.js +33 -7
  124. package/dist/testing/index.js.map +1 -1
  125. package/docs/AGENT-OPERATIONS.md +515 -0
  126. package/docs/APPBOUNDRY.md +240 -0
  127. package/docs/ARCHITECTURE.md +126 -0
  128. package/docs/BACKUP.md +115 -0
  129. package/docs/GUARANTEES.md +457 -0
  130. package/docs/PATH-TO-PRODUCTION.md +117 -0
  131. package/docs/README.md +15 -0
  132. package/docs/SECURITY.md +182 -0
  133. package/docs/TRANSACTIONS.md +216 -0
  134. package/docs/UPSTREAM-GAPS.md +270 -0
  135. package/docs/WHY-FELTKIT.md +64 -0
  136. package/docs/assets/feltkit-logo-dark.png +0 -0
  137. package/docs/assets/feltkit-logo.png +0 -0
  138. package/package.json +10 -8
  139. package/skills/.claude-plugin/marketplace.json +1 -1
  140. package/skills/.claude-plugin/plugin.json +3 -3
  141. package/skills/feltkit-agent/SKILL.md +9 -5
  142. package/skills/feltkit-build/SKILL.md +16 -4
  143. package/skills/feltkit-data/SKILL.md +20 -3
  144. package/skills/feltkit-services/SKILL.md +13 -7
  145. package/dist/dashboard/assets/index-BhFOquA7.js +0 -15
  146. package/dist/dashboard/theme.js +0 -11
@@ -0,0 +1,142 @@
1
+ /**
2
+ * A project's source as the platform sees it: a revision (the digest of its source tree, computed
3
+ * here, never taken from a caller), the paths a change set may write, writes that cannot leave the
4
+ * project, and isolated verification workspaces.
5
+ *
6
+ * The source tree is every regular file under the project except what FeltKit or a tool generates
7
+ * or keeps outside source: dot-entries (.feltkit state and builds, .git, .env files), node_modules,
8
+ * dist, and feltkit/_generated (rewritten by every build). Symbolic links are not followed.
9
+ */
10
+ import { createHash } from "node:crypto";
11
+ import { cpSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
12
+ import { dirname, isAbsolute, join, relative, sep } from "node:path";
13
+ export const LIMITS = { files: 200, fileBytes: 512 * 1024, totalBytes: 2 * 1024 * 1024 };
14
+ const EXCLUDED_DIRS = new Set(["node_modules", "dist"]);
15
+ const GENERATED = ["feltkit", "_generated"].join("/");
16
+ /** Whether a project-relative path (POSIX separators) is source. */
17
+ function isSource(path) {
18
+ const parts = path.split("/");
19
+ if (parts.some((part) => part.startsWith(".")))
20
+ return false;
21
+ if (EXCLUDED_DIRS.has(parts[0]))
22
+ return false;
23
+ return !(path === GENERATED || path.startsWith(`${GENERATED}/`));
24
+ }
25
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
26
+ /** Every source file's SHA-256, by project-relative path. */
27
+ export function sourceFiles(dir) {
28
+ const files = new Map();
29
+ const walk = (at) => {
30
+ for (const entry of readdirSync(at, { withFileTypes: true })) {
31
+ const path = join(at, entry.name);
32
+ const rel = relative(dir, path).split(sep).join("/");
33
+ if (!isSource(rel))
34
+ continue;
35
+ if (entry.isDirectory())
36
+ walk(path);
37
+ else if (entry.isFile())
38
+ files.set(rel, sha256(readFileSync(path)));
39
+ }
40
+ };
41
+ walk(dir);
42
+ return files;
43
+ }
44
+ /** The project's revision: `rev_` and the SHA-256 of its sorted (path, content digest) list. */
45
+ export function sourceRevision(dir) {
46
+ const files = [...sourceFiles(dir)].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
47
+ return `rev_${sha256(files.map(([path, digest]) => `${path}\0${digest}\n`).join(""))}`;
48
+ }
49
+ /** A change set's content digest: computed from its files, in path order. */
50
+ export function contentDigest(files) {
51
+ const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
52
+ return `sha256:${sha256(JSON.stringify(sorted.map((f) => [f.path, f.content])))}`;
53
+ }
54
+ /** Validate and normalize a change set's files; throws INVALID_INPUT naming the problem. */
55
+ export function checkFiles(files) {
56
+ const fail = (message) => Object.assign(new Error(message), { code: "INVALID_INPUT" });
57
+ if (!Array.isArray(files) || files.length === 0)
58
+ throw fail("files lists at least one { path, content } (content null deletes the file).");
59
+ if (files.length > LIMITS.files)
60
+ throw fail(`A change set holds at most ${LIMITS.files} files.`);
61
+ const seen = new Set();
62
+ let total = 0;
63
+ return files.map((file) => {
64
+ const path = typeof file?.path === "string" ? file.path.replace(/\\/g, "/") : "";
65
+ if (!path || isAbsolute(path) || /^[a-zA-Z]:/.test(path) || path.split("/").some((p) => p === ".." || p === "." || p === "") || path.includes("\0"))
66
+ throw fail(`${JSON.stringify(file?.path)} is not a project-relative path.`);
67
+ if (!isSource(path))
68
+ throw fail(`${path} is not source a change set may write (dot-entries, node_modules, dist and feltkit/_generated are not).`);
69
+ if (seen.has(path))
70
+ throw fail(`${path} appears twice.`);
71
+ seen.add(path);
72
+ if (file.content !== null && typeof file.content !== "string")
73
+ throw fail(`${path}: content is a string, or null to delete.`);
74
+ const bytes = file.content === null ? 0 : Buffer.byteLength(file.content);
75
+ if (bytes > LIMITS.fileBytes)
76
+ throw fail(`${path} is larger than ${LIMITS.fileBytes} bytes.`);
77
+ total += bytes;
78
+ if (total > LIMITS.totalBytes)
79
+ throw fail(`A change set's files total at most ${LIMITS.totalBytes} bytes.`);
80
+ return { path, content: file.content };
81
+ });
82
+ }
83
+ /**
84
+ * Where `path` would be written, refusing any route out of `dir`: a parent that is (or passes
85
+ * through) a symbolic link resolving outside it, or a target that is itself a symbolic link.
86
+ */
87
+ function target(dir, path) {
88
+ const real = realpathSync(dir);
89
+ const file = join(dir, ...path.split("/"));
90
+ let parent = dirname(file);
91
+ while (!existsSync(parent))
92
+ parent = dirname(parent);
93
+ const resolved = realpathSync(parent);
94
+ if (resolved !== real && !resolved.startsWith(real + sep))
95
+ throw Object.assign(new Error(`${path} resolves outside the project.`), { code: "FORBIDDEN" });
96
+ if (existsSync(file) && lstatSync(file).isSymbolicLink())
97
+ throw Object.assign(new Error(`${path} is a symbolic link; a change set writes regular files only.`), { code: "FORBIDDEN" });
98
+ return file;
99
+ }
100
+ /** The current content of each path (null when absent), for restoring after a failed apply. */
101
+ export function snapshot(dir, paths) {
102
+ return paths.map((path) => {
103
+ const file = target(dir, path);
104
+ return { path, content: existsSync(file) ? readFileSync(file, "utf8") : null };
105
+ });
106
+ }
107
+ /** Write (or delete) each file, each one atomically (a temporary file, then a rename). */
108
+ export function writeFiles(dir, files) {
109
+ for (const f of files)
110
+ target(dir, f.path);
111
+ for (const f of files) {
112
+ const file = target(dir, f.path);
113
+ if (f.content === null) {
114
+ if (existsSync(file))
115
+ unlinkSync(file);
116
+ continue;
117
+ }
118
+ mkdirSync(dirname(file), { recursive: true });
119
+ const temp = `${file}.${process.pid}.feltkit-tmp`;
120
+ writeFileSync(temp, f.content);
121
+ renameSync(temp, file);
122
+ }
123
+ }
124
+ /**
125
+ * A fresh workspace: a copy of the project's source and configuration (no state, builds, .env
126
+ * files or .git), its node_modules linked rather than copied, then the change set's files.
127
+ */
128
+ export function createWorkspace(projectDir, workspace, files) {
129
+ rmSync(workspace, { recursive: true, force: true });
130
+ mkdirSync(workspace, { recursive: true });
131
+ for (const entry of readdirSync(projectDir, { withFileTypes: true })) {
132
+ if (entry.name.startsWith(".") || EXCLUDED_DIRS.has(entry.name))
133
+ continue;
134
+ if (entry.isSymbolicLink())
135
+ continue;
136
+ cpSync(join(projectDir, entry.name), join(workspace, entry.name), { recursive: true, filter: (src) => !lstatSync(src).isSymbolicLink() && !relative(projectDir, src).split(sep).some((p) => p.startsWith(".")) });
137
+ }
138
+ if (existsSync(join(projectDir, "node_modules")))
139
+ symlinkSync(realpathSync(join(projectDir, "node_modules")), join(workspace, "node_modules"), "dir");
140
+ writeFiles(workspace, files);
141
+ }
142
+ //# sourceMappingURL=source.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"source.js","sourceRoot":"","sources":["../../src/platform/source.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,WAAW,EAAE,UAAU,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACxK,OAAO,EAAE,OAAO,EAAE,UAAU,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAQrE,MAAM,C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AC,IAAI,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC;YAAE,SAAS;QAC1E,IAAI,KAAK,CAAC,cAAc,EAAE;YAAE,SAAS;QACrC,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,IAAI,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,cAAc,EAAE,IAAI,CAAC,QAAQ,CAAC,UAAU,EAAE,GAAG,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;IACpN,CAAC;IACD,IAAI,UAAU,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC;QAAE,WAAW,CAAC,YAAY,CAAC,IAAI,CAAC,UAAU,EAAE,cAAc,CAAC,CAAC,EAAE,IAAI,CAAC,SAAS,EAAE,cAAc,CAAC,EAAE,KAAK,CAAC,CAAC;IACtJ,UAAU,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;AAC/B,CAAC"}
@@ -43,6 +43,12 @@ export interface ActivityEntry {
43
43
  reason?: string;
44
44
  /** AppPort's own authorization decision id, for calls dispatched by AppPort. */
45
45
  appportDecisionId?: string;
46
+ /** An `approval: "required"` mutation run as an approved agent action: which, and who approved it. */
47
+ approval?: {
48
+ taskId: string;
49
+ actionId: string;
50
+ approvedBy: string;
51
+ };
46
52
  };
47
53
  outcome: "success" | "error" | "denied";
48
54
  error?: {
@@ -76,6 +82,19 @@ export declare class ActivityLog {
76
82
  at: string;
77
83
  message: string;
78
84
  } | null;
85
+ /**
86
+ * Retention: when the log was last trimmed to `retain`, and the last failure to trim it. A failed
87
+ * prune is retried on the next recorded entry until one succeeds, and readiness reports it, so a
88
+ * failure cannot quietly leave the log growing.
89
+ */
90
+ readonly retention: {
91
+ retain: number;
92
+ lastPrunedAt: string | null;
93
+ pruneError: {
94
+ at: string;
95
+ message: string;
96
+ } | null;
97
+ };
79
98
  constructor(db: StateFirstDB, options: {
80
99
  mode: "all" | "writes" | "errors";
81
100
  retain?: number;
@@ -103,6 +122,12 @@ export declare class ActivityLog {
103
122
  * none: an incomplete set cannot prove an outcome, so the caller treats it as unknown.
104
123
  */
105
124
  serviceEvidence(requestId: string): Promise<EffectEvidenceRecord[]>;
125
+ /**
126
+ * Trim the log to the newest `retain` entries. Counted and read in FeltDB pages: entry ids start
127
+ * with their time, so FeltDB's id order is oldest first, and only the excess is read. Returns how
128
+ * many entries were removed. A failure is recorded in `retention` (and thrown), never ignored.
129
+ */
130
+ prune(): Promise<number>;
106
131
  }
107
132
  export declare function errorSummary(error: unknown): {
108
133
  code: string;
@@ -1,5 +1,7 @@
1
1
  import { isFeltKitError } from "../errors.js";
2
- import { newId } from "./data.js";
2
+ import { countAll, newId, readAll } from "./data.js";
3
+ /** Entries removed per transaction when the log is trimmed. */
4
+ const PRUNE_BATCH = 200;
3
5
  export const ACTIVITY_COLLECTION = "_feltkit_activity";
4
6
  export class ActivityLog {
5
7
  #db;
@@ -10,11 +12,18 @@ export class ActivityLog {
10
12
  #sincePrune = 0;
11
13
  #queue = Promise.resolve();
12
14
  lastError = null;
15
+ /**
16
+ * Retention: when the log was last trimmed to `retain`, and the last failure to trim it. A failed
17
+ * prune is retried on the next recorded entry until one succeeds, and readiness reports it, so a
18
+ * failure cannot quietly leave the log growing.
19
+ */
20
+ retention = { retain: 0, lastPrunedAt: null, pruneError: null };
13
21
  constructor(db, options) {
14
22
  this.#db = db;
15
23
  this.#evidence = options.evidence;
16
24
  this.#mode = options.mode;
17
25
  this.#retain = Math.max(100, options.retain ?? 2000);
26
+ this.retention.retain = this.#retain;
18
27
  }
19
28
  get mode() {
20
29
  return this.#mode;
@@ -48,10 +57,9 @@ export class ActivityLog {
48
57
  this.#queue = this.#queue
49
58
  .then(async () => {
50
59
  await this.#db.collection(ACTIVITY_COLLECTION).insert(full, full.id);
51
- if (++this.#sincePrune >= 100) {
52
- this.#sincePrune = 0;
53
- await this.#prune();
54
- }
60
+ // Every 100 entries, or on every entry while the last prune failed (until one succeeds).
61
+ if (++this.#sincePrune >= 100 || this.retention.pruneError)
62
+ await this.prune();
55
63
  })
56
64
  .catch((error) => {
57
65
  this.lastError = { at: new Date().toISOString(), message: error.message };
@@ -95,13 +103,31 @@ export class ActivityLog {
95
103
  const lookup = await this.#evidence(requestId);
96
104
  return lookup.truncated ? [] : [...lookup.records];
97
105
  }
98
- async #prune() {
99
- const all = await this.#db.collection(ACTIVITY_COLLECTION).find({});
100
- if (all.length <= this.#retain)
101
- return;
102
- const doomed = all.sort((a, b) => a.id.localeCompare(b.id)).slice(0, all.length - this.#retain);
103
- for (const entry of doomed)
104
- await this.#db.collection(ACTIVITY_COLLECTION).delete(entry.id);
106
+ /**
107
+ * Trim the log to the newest `retain` entries. Counted and read in FeltDB pages: entry ids start
108
+ * with their time, so FeltDB's id order is oldest first, and only the excess is read. Returns how
109
+ * many entries were removed. A failure is recorded in `retention` (and thrown), never ignored.
110
+ */
111
+ async prune() {
112
+ try {
113
+ const total = await countAll(this.#db, { collection: ACTIVITY_COLLECTION });
114
+ let removed = 0;
115
+ if (total > this.#retain) {
116
+ const doomed = await readAll(this.#db, { collection: ACTIVITY_COLLECTION }, total - this.#retain);
117
+ for (let i = 0; i < doomed.length; i += PRUNE_BATCH) {
118
+ await this.#db.transaction({ operations: doomed.slice(i, i + PRUNE_BATCH).map((entry) => ({ collection: ACTIVITY_COLLECTION, id: entry.id })) });
119
+ removed += Math.min(PRUNE_BATCH, doomed.length - i);
120
+ }
121
+ }
122
+ this.#sincePrune = 0;
123
+ this.retention.lastPrunedAt = new Date().toISOString();
124
+ this.retention.pruneError = null;
125
+ return removed;
126
+ }
127
+ catch (error) {
128
+ this.retention.pruneError = { at: new Date().toISOString(), message: error?.message ?? String(error) };
129
+ throw error;
130
+ }
105
131
  }
106
132
  }
107
133
  export function errorSummary(error) {
@@ -1 +1 @@
1
- {"version":3,"file":"activity.js","sourceRoot":"","sources":["../../src/runtime/activity.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAE9C,OAAO,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAGlC,MAAM,CAAC,MAAM,mBAAmB,GAAG,mBAAmB,CAAC;AAoDvD,MAAM,OAAO,WAAW;IACb,GAAG,CAAe;IAClB,KAAK,CAA8B;IACnC,OAAO,CAAS;IAChB,UAAU,GAAG,IAAI,GAAG,EAAoB,CAAC;IACzC,SAAS,CAAmD;IACrE,WAAW,GAAG,CAAC,CAAC;IAChB,MAAM,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAC1C,SAAS,GAA2C,IAAI,CAAC;IAEzD,YAAY,EAAgB,EAAE,OAA2H;QACvJ,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,SAAS,GAAG,OAAO,CAAC,QAAQ,CAAC;QAClC,IAAI,CAAC,KAAK,GAAG,OAAO,CAAC,IAAI,CAAC;QAC1B,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC,CAAC;IACvD,CAAC;IAED,IAAI,IAAI;QACN,OAAO,IAAI,CAAC,KAAK,CAAC;IACpB,CAAC;IAED,SAAS,CAAC,QAA0B;QAClC,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC9B,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAChD,CAAC;IAED,KAAK,CAAC,IAAkB,EAAE,OAAiC;QACzD,IAAI,IAAI,CAAC,KAAK,KAA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AE,KAAK,CAAC,EAAE,EAAE,CAAC,CAAC,EAAW,CAAC,CAAC;oBAC1J,OAAO,IAAI,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,MAAM,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;gBACtD,CAAC;YACH,CAAC;YACD,IAAI,CAAC,WAAW,GAAG,CAAC,CAAC;YACrB,IAAI,CAAC,SAAS,CAAC,YAAY,GAAG,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;YACvD,IAAI,CAAC,SAAS,CAAC,UAAU,GAAG,IAAI,CAAC;YACjC,OAAO,OAAO,CAAC;QACjB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,SAAS,CAAC,UAAU,GAAG,EAAE,EAAE,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE,EAAE,OAAO,EAAG,KAAe,EAAE,OAAO,IAAI,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;YAClH,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;CACF;AAED,MAAM,UAAU,YAAY,CAAC,KAAc;IACzC,IAAI,cAAc,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,CAAC,OAAO,EAAE,CAAC;IAC/E,MAAM,CAAC,GAAG,KAA8C,CAAC;IACzD,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC;AAC1I,CAAC"}
@@ -50,6 +50,14 @@ export interface AgentTool {
50
50
  description?: string;
51
51
  /** Whether the principal asking may perform it (a decision only; nothing runs). */
52
52
  allowed: boolean;
53
+ /**
54
+ * How this principal can use it: `"direct"` (call the tool), or `"propose"` (only through
55
+ * feltkit_agent_propose: an AppPort Services operation, which is not an MCP tool, or a
56
+ * capability that requires a person's approval). Absent when `allowed` is false.
57
+ */
58
+ invoke?: "direct" | "propose";
59
+ /** `"required"`: a consequential call by this principal runs only after a person approves it. */
60
+ approval?: "required";
53
61
  }
54
62
  export interface ProposedAction {
55
63
  actionId: string;
@@ -269,6 +277,14 @@ export declare class AgentHost {
269
277
  * duplicate or concurrent approval of the same action never runs it twice.
270
278
  */
271
279
  approve(taskId: string, actionId: string, approver: Principal | null): Promise<TaskView>;
280
+ /**
281
+ * For each proposed action of a task: whether `principal` may approve it now, and if not, why
282
+ * (the same checks approve() makes; nothing changes). Studio shows Approve only when it may.
283
+ */
284
+ approvability(taskId: string, principal: Principal): Promise<Record<string, {
285
+ allowed: boolean;
286
+ reason?: string;
287
+ }>>;
272
288
  /** Reject a proposed action. */
273
289
  reject(taskId: string, actionId: string, principal: Principal | null, reason?: string): Promise<TaskView>;
274
290
  /**
@@ -33,9 +33,11 @@
33
33
  */
34
34
  import { FELTDB_AGENT_MEMORY_COLLECTION, openAgentState } from "@feltdb/core";
35
35
  import { IDEMPOTENCY_OUTCOME_UNKNOWN, idempotencyErrorReason, isIdempotencyClaim } from "@appport/sdk";
36
+ import { grantsPermission } from "@appport/authorization";
36
37
  import { createHash, randomUUID } from "node:crypto";
37
38
  import { FeltKitError, isFeltKitError } from "../errors.js";
38
39
  import { authContext } from "./authority.js";
40
+ import { readAll } from "./data.js";
39
41
  export const AGENT_NAME = "feltkit";
40
42
  export const AGENT_VERSION = 1;
41
43
  /** Permissions for using the agent itself. Actions still need their own permissions. */
@@ -191,6 +193,7 @@ export class AgentHost {
191
193
  source: "application",
192
194
  effect: (c.effect === "observation" ? "observation" : "consequential"),
193
195
  ...(c.description ? { description: c.description } : {}),
196
+ ...(fn?.approval ? { approval: fn.approval } : {}),
194
197
  permission: integration ? [integration.op.access] : fn && fn.access !== "public" && fn.access !== "authenticated" ? [fn.access] : [],
195
198
  };
196
199
  });
@@ -212,7 +215,16 @@ export class AgentHost {
212
215
  target: { name: tool.name },
213
216
  transport: "agent",
214
217
  });
215
- out.push({ name: tool.name, source: tool.source, effect: tool.effect, ...(tool.description ? { description: tool.description } : {}), allowed: decision.allowed });
218
+ const proposeOnly = tool.source === "services" || (tool.approval === "required" && principal.type !== "user");
219
+ out.push({
220
+ name: tool.name,
221
+ source: tool.source,
222
+ effect: tool.effect,
223
+ ...(tool.description ? { description: tool.description } : {}),
224
+ allowed: decision.allowed,
225
+ ...(decision.allowed ? { invoke: proposeOnly ? "propose" : "direct" } : {}),
226
+ ...(tool.approval ? { approval: tool.approval } : {}),
227
+ });
216
228
  }
217
229
  return out;
218
230
  }
@@ -401,20 +413,7 @@ export class AgentHost {
401
413
  const head = await this.#head(taskId, actionId);
402
414
  if (head.record.state !== "proposed")
403
415
  return this.#unchanged(taskId, p, head.record, "approve");
404
- const tool = this.#catalog().find((t) => t.name === head.record.capability);
405
- const owner = await this.#resolveOwner(task);
406
- const allowed = async (who) => (await this.#runtime.authority.authorize({ access: tool?.permission[0] ?? "authenticated", principal: who, target: { name: head.record.capability }, transport: "agent" })).allowed;
407
- const refusal = !tool
408
- ? `${head.record.capability} is no longer a capability of this application`
409
- : this.#separateApprover && head.record.proposedBy === actorOf(p)
410
- ? `${actorOf(p)} proposed this action and may not also approve it`
411
- : !owner
412
- ? `the task owner ${task.owner} cannot be resolved (no active session or key)`
413
- : !(await allowed(p))
414
- ? `${actorOf(p)} may not perform ${head.record.capability}`
415
- : !(await allowed(owner))
416
- ? `the task owner ${task.owner} may not perform ${head.record.capability}`
417
- : null;
416
+ const { refusal, owner } = await this.#approvalCheck(task, head.record, p);
418
417
  if (refusal) {
419
418
  const refused = await this.#move(head, "proposed", {}, actorOf(p), `approval refused: ${refusal}`);
420
419
  await this.#sync(taskId, task.owner, `Approval of ${head.record.capability} refused: ${refusal}.`, { decisions: [`approval of ${actionId} by ${actorOf(p)} refused: ${refusal}`], evidence: [memoryEvidence(refused.memory.memory_id, "refused approval")] });
@@ -433,6 +432,46 @@ export class AgentHost {
433
432
  }
434
433
  return this.#run(taskId, task.owner, approved, owner, p);
435
434
  }
435
+ /** Why `p` may not approve `record` now (null: it may), and the resolved owner. The one rule approve() and Studio use. */
436
+ async #approvalCheck(task, record, p) {
437
+ const tool = this.#catalog().find((t) => t.name === record.capability);
438
+ const owner = await this.#resolveOwner(task);
439
+ const allowed = async (who) => (await this.#runtime.authority.authorize({ access: tool?.permission[0] ?? "authenticated", principal: who, target: { name: record.capability }, transport: "agent" })).allowed;
440
+ const refusal = !tool
441
+ ? `${record.capability} is no longer a capability of this application`
442
+ : this.#separateApprover && record.proposedBy === actorOf(p)
443
+ ? `${actorOf(p)} proposed this action and may not also approve it`
444
+ : !owner
445
+ ? `the task owner ${task.owner} cannot be resolved (no active session or key)`
446
+ : !(await allowed(p))
447
+ ? `${actorOf(p)} may not perform ${record.capability}`
448
+ : !(await allowed(owner))
449
+ ? `the task owner ${task.owner} may not perform ${record.capability}`
450
+ : null;
451
+ return { refusal, owner };
452
+ }
453
+ /**
454
+ * For each proposed action of a task: whether `principal` may approve it now, and if not, why
455
+ * (the same checks approve() makes; nothing changes). Studio shows Approve only when it may.
456
+ */
457
+ async approvability(taskId, principal) {
458
+ const { task } = await this.#loaded(taskId);
459
+ const out = {};
460
+ const writer = grantsPermission(this.#runtime.authority.permissionsFor(principal), AGENT_PERMISSIONS.write);
461
+ for (const { record } of await this.#heads(taskId)) {
462
+ if (record.state !== "proposed")
463
+ continue;
464
+ if (principal.type !== "user")
465
+ out[record.actionId] = { allowed: false, reason: "only a person can approve a consequential action" };
466
+ else if (!writer)
467
+ out[record.actionId] = { allowed: false, reason: `${actorOf(principal)} lacks ${AGENT_PERMISSIONS.write}` };
468
+ else {
469
+ const { refusal } = await this.#approvalCheck(task, record, principal);
470
+ out[record.actionId] = refusal ? { allowed: false, reason: refusal } : { allowed: true };
471
+ }
472
+ }
473
+ return out;
474
+ }
436
475
  /** Execute an approved action: durable intent first, then the call, then the outcome. */
437
476
  async #run(taskId, ownerActor, approved, owner, approver) {
438
477
  const work = (async () => {
@@ -818,7 +857,7 @@ export class AgentHost {
818
857
  }
819
858
  async #decide(taskId, owner) {
820
859
  const { task } = await this.#loaded(taskId);
821
- const stored = (await this.#state.recallForTask(taskId, { limit: 100 })).find((m) => m.kind === DECISION_REQUEST_KIND);
860
+ const stored = (await this.#taskMemories(taskId)).find((m) => m.kind === DECISION_REQUEST_KIND);
822
861
  if (!stored)
823
862
  throw new FeltKitError("NOT_FOUND", `${taskId} has no decision to make.`);
824
863
  const spec = stored.content;
@@ -941,16 +980,21 @@ export class AgentHost {
941
980
  const attribution = { owner, ...(approver ? { approver } : {}) };
942
981
  try {
943
982
  let output;
983
+ const dispatch = () => this.#runtime.appport.handleRequest({
984
+ protocol: "appport/1",
985
+ type: "request",
986
+ requestId,
987
+ capability: { name: action.capability, version: 1 },
988
+ input: action.input,
989
+ ...(action.idempotencyKey ? { idempotencyKey: action.idempotencyKey } : {}),
990
+ metadata: { transport: "agent" },
991
+ }, { principal: toAppPort(owner), transport: "agent", signal: controller.signal });
992
+ // An approved action runs inside the approval it carries: the only way a non-person
993
+ // principal runs an `approval: "required"` mutation (runtime.#approvalRefusal).
944
994
  const call = action.source === "application"
945
- ? this.#runtime.appport.handleRequest({
946
- protocol: "appport/1",
947
- type: "request",
948
- requestId,
949
- capability: { name: action.capability, version: 1 },
950
- input: action.input,
951
- ...(action.idempotencyKey ? { idempotencyKey: action.idempotencyKey } : {}),
952
- metadata: { transport: "agent" },
953
- }, { principal: toAppPort(owner), transport: "agent", signal: controller.signal })
995
+ ? approver
996
+ ? this.#runtime.runApproved({ capability: action.capability, taskId, actionId: action.actionId, approvedBy: actorOf(approver) }, dispatch)
997
+ : dispatch()
954
998
  : this.#runtime.services.invoke(action.capability, action.input, owner, controller.signal, requestId);
955
999
  // The call itself may not observe the signal; stop waiting for it either way.
956
1000
  const result = await Promise.race([call, new Promise((_, reject) => controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true }))]);
@@ -1034,7 +1078,7 @@ export class AgentHost {
1034
1078
  await this.#state.remember({ taskId, kind: "outcome", content: outcome, source: { actor: owner } });
1035
1079
  }
1036
1080
  async #lastOutput(taskId) {
1037
- const memories = await this.#state.recallForTask(taskId, { limit: 50 });
1081
+ const memories = await this.#taskMemories(taskId);
1038
1082
  const outcome = memories.filter((m) => m.kind === "outcome").sort((a, b) => a.created_at.localeCompare(b.created_at)).at(-1);
1039
1083
  return outcome ? outcome.content.output ?? null : null;
1040
1084
  }
@@ -1049,9 +1093,29 @@ export class AgentHost {
1049
1093
  await this.#db.failAgentExecution(await this.#execution(taskId), message).catch(() => undefined);
1050
1094
  }
1051
1095
  // ---- FeltDB state helpers ----------------------------------------------------
1096
+ /**
1097
+ * Every active memory scoped to the task, paged with FeltDB's cursor. Not `recallForTask`: it
1098
+ * returns at most the 100 newest per scope, with no cursor, so a task with more active memories
1099
+ * would lose its oldest actions and its decision request (FeltKit's records are all task-scoped).
1100
+ */
1101
+ async #taskMemories(taskId) {
1102
+ const out = [];
1103
+ let cursor;
1104
+ const seen = new Set();
1105
+ do {
1106
+ const page = await this.#state.recall({ scope: { kind: "task", taskId }, limit: 1000, ...(cursor ? { cursor } : {}) });
1107
+ out.push(...page.memories);
1108
+ cursor = page.nextCursor;
1109
+ if (cursor && seen.has(cursor))
1110
+ throw new FeltKitError("INTERNAL", `FeltDB returned the same cursor twice while reading ${taskId}'s memories.`);
1111
+ if (cursor)
1112
+ seen.add(cursor);
1113
+ } while (cursor);
1114
+ return out;
1115
+ }
1052
1116
  /** The current record of every consequential action on a task (one per action). */
1053
1117
  async #heads(taskId) {
1054
- const memories = await this.#state.recallForTask(taskId, { limit: 100 });
1118
+ const memories = await this.#taskMemories(taskId);
1055
1119
  return memories
1056
1120
  .filter((m) => (m.kind === ACTION_KIND || m.kind === LEGACY_PROPOSAL_KIND) && m.scope.kind === "task" && m.status === "active")
1057
1121
  .map((m) => ({ memory: m, record: m.kind === ACTION_KIND ? m.content : legacy(m) }))
@@ -1268,7 +1332,7 @@ export class AgentHost {
1268
1332
  async #legacyExecution(taskId) {
1269
1333
  this.#legacy ??= (async () => {
1270
1334
  const byTask = new Map();
1271
- for (const row of (await this.#db.collection(LEGACY_EXECUTIONS).find({}))) {
1335
+ for (const row of (await readAll(this.#db, { collection: LEGACY_EXECUTIONS }))) {
1272
1336
  if (row.taskId || !Array.isArray(row.inputs))
1273
1337
  continue;
1274
1338
  for (const input of row.inputs) {