@feltdb/feltkit 0.3.37 → 0.5.0

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 (184) hide show
  1. package/dist/agent-engine.d.ts +93 -0
  2. package/dist/agent-engine.js +40 -0
  3. package/dist/agent-engine.js.map +1 -0
  4. package/dist/app.d.ts +306 -7
  5. package/dist/app.js +289 -28
  6. package/dist/app.js.map +1 -1
  7. package/dist/appboundry/build.d.ts +7 -0
  8. package/dist/appboundry/build.js +25 -1
  9. package/dist/appboundry/build.js.map +1 -1
  10. package/dist/appboundry/guest.js +8 -0
  11. package/dist/appboundry/guest.js.map +1 -1
  12. package/dist/appboundry/host.d.ts +21 -0
  13. package/dist/appboundry/host.js +25 -0
  14. package/dist/appboundry/host.js.map +1 -1
  15. package/dist/appboundry/runtime.js +1 -0
  16. package/dist/appboundry/runtime.js.map +1 -1
  17. package/dist/boards/index.d.ts +1258 -0
  18. package/dist/boards/index.js +1410 -0
  19. package/dist/boards/index.js.map +1 -0
  20. package/dist/boards/model.d.ts +177 -0
  21. package/dist/boards/model.js +177 -0
  22. package/dist/boards/model.js.map +1 -0
  23. package/dist/boards/react.d.ts +18 -0
  24. package/dist/boards/react.js +339 -0
  25. package/dist/boards/react.js.map +1 -0
  26. package/dist/cli/deploy-appboundry-self-hosted.js +2 -2
  27. package/dist/cli/deploy.js +19 -6
  28. package/dist/cli/deploy.js.map +1 -1
  29. package/dist/cli/main.js +70 -5
  30. package/dist/cli/main.js.map +1 -1
  31. package/dist/client/index.d.ts +454 -4
  32. package/dist/client/index.js +371 -3
  33. package/dist/client/index.js.map +1 -1
  34. package/dist/clock.d.ts +24 -0
  35. package/dist/clock.js +49 -0
  36. package/dist/clock.js.map +1 -0
  37. package/dist/cron.d.ts +18 -0
  38. package/dist/cron.js +67 -0
  39. package/dist/cron.js.map +1 -0
  40. package/dist/dashboard/assets/index-iIj7SL77.js +15 -0
  41. package/dist/dashboard/index.html +1 -1
  42. package/dist/docs.d.ts +1 -1
  43. package/dist/docs.js +4 -0
  44. package/dist/docs.js.map +1 -1
  45. package/dist/eve/index.d.ts +77 -0
  46. package/dist/eve/index.js +128 -0
  47. package/dist/eve/index.js.map +1 -0
  48. package/dist/event-stage.js +2 -0
  49. package/dist/event-stage.js.map +1 -1
  50. package/dist/index.d.ts +17 -2
  51. package/dist/index.js +3 -1
  52. package/dist/index.js.map +1 -1
  53. package/dist/native/build.d.ts +112 -0
  54. package/dist/native/build.js +472 -0
  55. package/dist/native/build.js.map +1 -0
  56. package/dist/native/index.d.ts +67 -0
  57. package/dist/native/index.js +113 -0
  58. package/dist/native/index.js.map +1 -0
  59. package/dist/native/instance.d.ts +3 -0
  60. package/dist/native/instance.js +18 -0
  61. package/dist/native/instance.js.map +1 -0
  62. package/dist/policy.d.ts +9 -1
  63. package/dist/policy.js +16 -3
  64. package/dist/policy.js.map +1 -1
  65. package/dist/presence.d.ts +85 -0
  66. package/dist/presence.js +37 -0
  67. package/dist/presence.js.map +1 -0
  68. package/dist/quota.d.ts +72 -0
  69. package/dist/quota.js +143 -0
  70. package/dist/quota.js.map +1 -0
  71. package/dist/react/agent-control.d.ts +191 -0
  72. package/dist/react/agent-control.js +366 -0
  73. package/dist/react/agent-control.js.map +1 -0
  74. package/dist/react/auth.d.ts +15 -1
  75. package/dist/react/auth.js +28 -5
  76. package/dist/react/auth.js.map +1 -1
  77. package/dist/react/hooks.d.ts +88 -0
  78. package/dist/react/hooks.js +188 -0
  79. package/dist/react/hooks.js.map +1 -0
  80. package/dist/react/index.d.ts +5 -75
  81. package/dist/react/index.js +4 -145
  82. package/dist/react/index.js.map +1 -1
  83. package/dist/runtime/activity.d.ts +8 -0
  84. package/dist/runtime/activity.js.map +1 -1
  85. package/dist/runtime/agent-control.d.ts +28 -0
  86. package/dist/runtime/agent-control.js +43 -2
  87. package/dist/runtime/agent-control.js.map +1 -1
  88. package/dist/runtime/agent-run.d.ts +166 -0
  89. package/dist/runtime/agent-run.js +431 -0
  90. package/dist/runtime/agent-run.js.map +1 -0
  91. package/dist/runtime/agent.d.ts +158 -1
  92. package/dist/runtime/agent.js +345 -12
  93. package/dist/runtime/agent.js.map +1 -1
  94. package/dist/runtime/assemble.js +15 -2
  95. package/dist/runtime/assemble.js.map +1 -1
  96. package/dist/runtime/authority.d.ts +47 -0
  97. package/dist/runtime/authority.js +13 -2
  98. package/dist/runtime/authority.js.map +1 -1
  99. package/dist/runtime/capabilities.js +2 -1
  100. package/dist/runtime/capabilities.js.map +1 -1
  101. package/dist/runtime/changes.d.ts +17 -0
  102. package/dist/runtime/changes.js +65 -2
  103. package/dist/runtime/changes.js.map +1 -1
  104. package/dist/runtime/context.d.ts +123 -0
  105. package/dist/runtime/contract.js +9 -3
  106. package/dist/runtime/contract.js.map +1 -1
  107. package/dist/runtime/events.js +17 -1
  108. package/dist/runtime/events.js.map +1 -1
  109. package/dist/runtime/integrations.js +7 -7
  110. package/dist/runtime/integrations.js.map +1 -1
  111. package/dist/runtime/invocations.d.ts +19 -2
  112. package/dist/runtime/invocations.js +16 -3
  113. package/dist/runtime/invocations.js.map +1 -1
  114. package/dist/runtime/policies.d.ts +5 -2
  115. package/dist/runtime/policies.js.map +1 -1
  116. package/dist/runtime/presence-host.d.ts +84 -0
  117. package/dist/runtime/presence-host.js +303 -0
  118. package/dist/runtime/presence-host.js.map +1 -0
  119. package/dist/runtime/providers.d.ts +5 -1
  120. package/dist/runtime/providers.js +11 -5
  121. package/dist/runtime/providers.js.map +1 -1
  122. package/dist/runtime/required-capabilities.d.ts +73 -0
  123. package/dist/runtime/required-capabilities.js +69 -0
  124. package/dist/runtime/required-capabilities.js.map +1 -0
  125. package/dist/runtime/resource-access.d.ts +137 -0
  126. package/dist/runtime/resource-access.js +177 -0
  127. package/dist/runtime/resource-access.js.map +1 -0
  128. package/dist/runtime/runtime.d.ts +143 -1
  129. package/dist/runtime/runtime.js +853 -44
  130. package/dist/runtime/runtime.js.map +1 -1
  131. package/dist/runtime/sessions.d.ts +12 -0
  132. package/dist/runtime/sessions.js +16 -1
  133. package/dist/runtime/sessions.js.map +1 -1
  134. package/dist/runtime/tenancy.d.ts +68 -1
  135. package/dist/runtime/tenancy.js +150 -0
  136. package/dist/runtime/tenancy.js.map +1 -1
  137. package/dist/runtime/transactions.d.ts +3 -1
  138. package/dist/runtime/transactions.js.map +1 -1
  139. package/dist/runtime/workers.d.ts +123 -0
  140. package/dist/runtime/workers.js +291 -0
  141. package/dist/runtime/workers.js.map +1 -0
  142. package/dist/server/eve.d.ts +287 -0
  143. package/dist/server/eve.js +1071 -0
  144. package/dist/server/eve.js.map +1 -0
  145. package/dist/server/index.d.ts +2 -19
  146. package/dist/server/index.js +102 -5
  147. package/dist/server/index.js.map +1 -1
  148. package/dist/server/mcp.d.ts +15 -22
  149. package/dist/server/mcp.js +40 -3
  150. package/dist/server/mcp.js.map +1 -1
  151. package/dist/server/project.js +26 -8
  152. package/dist/server/project.js.map +1 -1
  153. package/dist/server/tenancy.d.ts +9 -0
  154. package/dist/server/tenancy.js +62 -1
  155. package/dist/server/tenancy.js.map +1 -1
  156. package/dist/server/watch.d.ts +10 -0
  157. package/dist/server/watch.js +88 -0
  158. package/dist/server/watch.js.map +1 -0
  159. package/dist/testing/index.d.ts +4 -5
  160. package/dist/testing/index.js +3 -2
  161. package/dist/testing/index.js.map +1 -1
  162. package/docs/AGENT-CONTROL.md +166 -4
  163. package/docs/APPBOUNDRY.md +73 -0
  164. package/docs/ARCHITECTURE.md +6 -2
  165. package/docs/AUTH.md +37 -0
  166. package/docs/COMPONENTS.md +71 -0
  167. package/docs/EVE-COMPOSITION.md +75 -0
  168. package/docs/GUARANTEES.md +4 -4
  169. package/docs/NATIVE-AGENTS.md +353 -0
  170. package/docs/NATIVE.md +137 -0
  171. package/docs/PRESENCE-AND-SIGNALING-PROPOSAL.md +152 -0
  172. package/docs/README.md +6 -2
  173. package/docs/SECURITY.md +71 -3
  174. package/docs/TRANSACTIONS.md +48 -0
  175. package/docs/UPSTREAM-GAPS.md +16 -2
  176. package/package.json +42 -16
  177. package/skills/.claude-plugin/marketplace.json +1 -1
  178. package/skills/.claude-plugin/plugin.json +1 -1
  179. package/skills/feltkit-agent/SKILL.md +1 -1
  180. package/skills/feltkit-build/SKILL.md +11 -1
  181. package/skills/feltkit-data/SKILL.md +1 -1
  182. package/skills/feltkit-operations/SKILL.md +1 -1
  183. package/skills/feltkit-services/SKILL.md +1 -1
  184. package/dist/dashboard/assets/index-BhxrvY37.js +0 -15
@@ -32,7 +32,7 @@
32
32
  * (an API key's plaintext, a session token) never reach a checkpoint, memory, or reply.
33
33
  */
34
34
  import { FELTDB_AGENT_MEMORY_COLLECTION, openAgentState } from "@feltdb/core";
35
- import { IDEMPOTENCY_OUTCOME_UNKNOWN, idempotencyErrorReason, isIdempotencyClaim } from "@appport/sdk";
35
+ import { isIdempotencyClaim, isOutcomeUnknown } from "@appport/sdk";
36
36
  import { grantsPermission } from "@appport/authorization";
37
37
  import { createHash, randomUUID } from "node:crypto";
38
38
  import { FeltKitError, isFeltKitError } from "../errors.js";
@@ -113,6 +113,10 @@ const LEGACY_PROPOSAL_KIND = "proposal";
113
113
  const memoryEvidence = (memoryId, description) => ({ kind: "record", collection: FELTDB_AGENT_MEMORY_COLLECTION, id: memoryId, description: `action record (${description})` });
114
114
  /** Stable per attempt: a duplicate of the same attempt is the same request; a retry is not. */
115
115
  const idempotencyKeyFor = (taskId, action) => `feltkit-agent:${taskId}:${action.actionId}:${action.attempt}`;
116
+ /** Task memory kinds of a reasoning agent's run (runtime/agent-run.ts). */
117
+ export const RUN_MEMORY_KIND = "agent-run";
118
+ export const LEASE_MEMORY_KIND = "agent-lease";
119
+ export const MESSAGE_MEMORY_KIND = "agent-message";
116
120
  export const PLAYBOOKS = ["diagnose-job", "diagnose-delivery", "inspect-app", "invoke", "decide", "handoff", "assist"];
117
121
  const GENERATION_KIND = "generation";
118
122
  const GENERATION_TEXT_LIMIT = 32_000;
@@ -204,8 +208,16 @@ export class AgentHost {
204
208
  #timeoutMs;
205
209
  /** Production: the person who proposed an action may not approve it. */
206
210
  #separateApprover;
211
+ /** Called after a person settles one of a task's actions (approve and run, reject, resolve): resumes a reasoning agent run waiting on it. */
212
+ #onSettled;
207
213
  constructor(runtime, db, options = {}) {
208
214
  this.#runtime = runtime;
215
+ const notify = options.onSettled ?? (() => { });
216
+ const hooks = options.hooks ?? {};
217
+ this.#onSettled = (taskId, actionId) => {
218
+ hooks.afterSettled?.({ taskId, actionId });
219
+ notify(taskId, actionId);
220
+ };
209
221
  this.#db = db;
210
222
  this.#hooks = options.hooks ?? {};
211
223
  this.#timeoutMs = options.actionTimeoutMs ?? ACTION_TIMEOUT_MS;
@@ -229,7 +241,7 @@ export class AgentHost {
229
241
  return null;
230
242
  return found;
231
243
  },
232
- inFlight: async (taskId) => ({
244
+ inFlight: async (taskId) => (await this.#reasonerOf(taskId))?.inFlight() ?? ({
233
245
  generations: (await this.#generationHeads(taskId)).filter((h) => OPEN_GENERATION.includes(h.record.state)).map((h) => h.record.generationId),
234
246
  actions: [...new Set([...(await this.#heads(taskId)).filter((h) => h.record.state === "approved" || h.record.state === "executing").map((h) => h.record.actionId), ...(this.#dispatched.get(taskId) ?? [])])],
235
247
  }),
@@ -245,8 +257,40 @@ export class AgentHost {
245
257
  return n;
246
258
  },
247
259
  activity: (name, p, taskId, outcome, detail) => this.#activity(name, p, taskId, outcome, detail),
260
+ changed: (taskId, changes, instructionId, state) => this.#runtime.agentChanged(taskId, changes, instructionId, state),
261
+ sequence: (taskId) => this.#runtime.agentChangeSequence(taskId),
262
+ external: async (taskId, op, p, reason) => {
263
+ const reasoner = await this.#reasonerOf(taskId);
264
+ if (!reasoner)
265
+ return false;
266
+ if (op === "pause")
267
+ reasoner.observe();
268
+ else
269
+ await (op === "interrupt" ? reasoner.interrupt(p, reason) : reasoner.resume(p, reason));
270
+ return true;
271
+ },
272
+ ended: async (taskId) => {
273
+ const reasoner = await this.#reasonerOf(taskId);
274
+ return reasoner?.ended ? reasoner.ended() : false;
275
+ },
248
276
  });
249
277
  }
278
+ #reasoners = null;
279
+ /**
280
+ * Tasks whose reasoner runs outside this process (an agent on the agent runtime): `resolve` finds a task's reasoner
281
+ * (null when it has none). Control then reads in-flight work from it and carries interrupt, resume and stop to it.
282
+ */
283
+ useExternalReasoners(resolve) {
284
+ this.#reasoners = resolve;
285
+ }
286
+ #reasonerOf(taskId) {
287
+ return this.#reasoners ? this.#reasoners(taskId) : Promise.resolve(null);
288
+ }
289
+ /** Work in flight ended while a person holds the task: its phase moved (pausing → paused). */
290
+ async #inFlightEnded(taskId) {
291
+ if ((await this.control.mode(taskId).catch(() => ({ mode: "running" }))).mode !== "running")
292
+ await this.control.inFlightChanged(taskId);
293
+ }
250
294
  /** Open agent state and define the agent. The runtime reconciles open actions once it is ready (outcome hooks are function calls). */
251
295
  async open() {
252
296
  this.#state = await openAgentState(this.#db);
@@ -274,9 +318,11 @@ export class AgentHost {
274
318
  #catalog() {
275
319
  const manifest = this.#runtime.appport.manifest();
276
320
  const functions = new Map(this.#runtime.functions().filter((f) => f.capability).map((f) => [f.capability.name, f]));
321
+ // Worker and service functions are not the agent's: it acts as a person's agent, never as a worker or a service.
322
+ const restricted = new Set((this.#runtime.project?.functions ? [...this.#runtime.project.functions.values()] : []).filter((f) => f.capability && f.visibility).map((f) => f.capability.name));
277
323
  const schemas = new Map((this.#runtime.project?.functions ? [...this.#runtime.project.functions.values()] : []).filter((f) => f.capability).map((f) => [f.capability.name, f.argsSchema.toJSONSchema()]));
278
324
  const application = (manifest.capabilities ?? [])
279
- .filter((c) => !c.name.startsWith("appport."))
325
+ .filter((c) => !c.name.startsWith("appport.") && !restricted.has(c.name))
280
326
  .map((c) => {
281
327
  const fn = functions.get(c.name);
282
328
  const integration = this.#runtime.integrations.operationFor(c.name);
@@ -427,7 +473,12 @@ export class AgentHost {
427
473
  }
428
474
  const playbook = found.task.constraints.find((c) => c.startsWith("playbook:"))?.slice("playbook:".length);
429
475
  const actions = (await this.#heads(taskId)).map((h) => h.record);
430
- return { task: found.task, checkpoints, execution: await this.#executionRecord(found.task), pending: actions.filter((a) => a.state === "proposed"), actions, ...(playbook ? { playbook } : {}) };
476
+ const transcript = (await this.#taskMemories(taskId))
477
+ .filter((m) => m.kind === MESSAGE_MEMORY_KIND)
478
+ .map((m) => m.content)
479
+ .sort((a, b) => a.seq - b.seq)
480
+ .map(({ seq, role, content, toolCalls, toolCallId, engine, model }) => ({ seq, role, content, ...(toolCalls?.length ? { toolCalls: toolCalls.map((c) => ({ id: c.id, name: c.name })) } : {}), ...(toolCallId ? { toolCallId } : {}), ...(engine ? { engine } : {}), ...(model ? { model } : {}) }));
481
+ return { task: found.task, checkpoints, execution: await this.#executionRecord(found.task), pending: actions.filter((a) => a.state === "proposed"), actions, ...(playbook ? { playbook } : {}), ...(transcript.length ? { transcript } : {}) };
431
482
  }
432
483
  /** The FeltDB context bundle for a task, plus this application's context. Redacted. */
433
484
  async context(taskId, principal) {
@@ -578,6 +629,231 @@ export class AgentHost {
578
629
  }
579
630
  return { taskId, created: true };
580
631
  }
632
+ // ---- Run records (app.agent reasoning runs) --------------------------------------
633
+ //
634
+ // A reasoning run's own durable state on its task: the run record (which agent, input, definition
635
+ // version) and its transcript, one memory per message at a fixed id, so a message is written once
636
+ // and a resumed run reads exactly what was committed. Only the task owner writes or reads them.
637
+ /** Write `content` at `<taskId>.<key>` once; a second write of the same key returns the first. */
638
+ async rememberOnce(taskId, principal, key, kind, content) {
639
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
640
+ await this.#inScope(taskId, p);
641
+ const { task } = await this.#owned(taskId, p);
642
+ const memoryId = `${taskId}.${key}`;
643
+ const existing = async () => (await this.#taskMemories(taskId)).find((m) => m.memory_id === memoryId) ?? null;
644
+ const before = await existing();
645
+ if (before)
646
+ return { memoryId, content: before.content, created: false };
647
+ try {
648
+ await this.#state.remember({ taskId, memoryId, kind, content, source: { actor: task.owner } });
649
+ return { memoryId, content, created: true };
650
+ }
651
+ catch (error) {
652
+ const after = await existing();
653
+ if (after)
654
+ return { memoryId, content: after.content, created: false };
655
+ throw error;
656
+ }
657
+ }
658
+ /** A task's memories of one kind, in id order. The owner, or "admin" (the runtime resuming a run). */
659
+ async memoriesOf(taskId, principal, kind) {
660
+ if (principal !== "admin")
661
+ await this.#ownedOrNotFound(taskId, this.#require(principal, AGENT_PERMISSIONS.read));
662
+ return (await this.#taskMemories(taskId)).filter((m) => m.kind === kind).map((m) => ({ memoryId: m.memory_id, content: m.content })).sort((a, b) => a.memoryId.localeCompare(b.memoryId));
663
+ }
664
+ /**
665
+ * Replace the active memory `<taskId>.<fromKey>` with `<taskId>.<toKey>`, only if `fromKey` is still active at
666
+ * `expectedRevision` (FeltDB's supersede: one transaction, compare-and-set). The run lease is a chain of these.
667
+ * Returns false when another writer superseded it first (or `toKey` exists): the caller lost the race.
668
+ */
669
+ async supersedeIfCurrent(taskId, principal, fromKey, toKey, kind, content, expectedRevision) {
670
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
671
+ // Also on an ended task: an attempt releases the run's lease after completing it.
672
+ const { task } = await this.#ownedOrNotFound(taskId, p);
673
+ try {
674
+ await this.#state.supersede(`${taskId}.${fromKey}`, { memoryId: `${taskId}.${toKey}`, kind, content, expectedRevision, source: { actor: task.owner } });
675
+ return true;
676
+ }
677
+ catch (error) {
678
+ const code = error.code;
679
+ if (code === "VERSION_CONFLICT" || code === "INVALID_TRANSITION" || code === "NOT_FOUND" || code === "ALREADY_EXISTS" || /exists|conflict/i.test(String(error.message)))
680
+ return false;
681
+ throw error;
682
+ }
683
+ }
684
+ /** The active memories of one kind on a task, with their revision. The owner, or "admin" (the runtime's reconciliation). */
685
+ async activeMemories(taskId, principal, kind) {
686
+ if (principal !== "admin")
687
+ await this.#ownedOrNotFound(taskId, this.#require(principal, AGENT_PERMISSIONS.read));
688
+ return (await this.#taskMemories(taskId))
689
+ .filter((m) => m.kind === kind && m.status === "active")
690
+ .map((m) => ({ key: m.memory_id.slice(taskId.length + 1), content: m.content, revision: m.revision ?? 1 }));
691
+ }
692
+ /** Every action of a task with its current state (reconciliation reads these; nothing changes). */
693
+ async actionStates(taskId) {
694
+ return new Map((await this.#heads(taskId)).map((h) => [h.record.actionId, { state: h.record.state, capability: h.record.capability, ...(h.record.expiresAt ? { expiresAt: h.record.expiresAt } : {}) }]));
695
+ }
696
+ /**
697
+ * Cancel the task's proposals whose approval window has passed (the same expiry approve() applies when someone
698
+ * tries too late), so a run waiting on them resumes. Returns the expired action ids. Idempotent: an action a
699
+ * person decided first keeps that decision (the move is compare-and-set).
700
+ */
701
+ async expireDue(taskId, now = Date.now()) {
702
+ const found = await this.#state.getTask(taskId);
703
+ if (!found || found.task.status === "completed" || found.task.status === "cancelled")
704
+ return [];
705
+ const expired = [];
706
+ for (const head of await this.#heads(taskId)) {
707
+ if (head.record.state !== "proposed" || !head.record.expiresAt || now <= Date.parse(head.record.expiresAt))
708
+ continue;
709
+ try {
710
+ await this.#expire(found.task, head);
711
+ expired.push(head.record.actionId);
712
+ }
713
+ catch (error) {
714
+ if (!(isFeltKitError(error) && error.code === "CONFLICT"))
715
+ throw error;
716
+ }
717
+ }
718
+ for (const actionId of expired)
719
+ this.#onSettled(taskId, actionId);
720
+ return expired;
721
+ }
722
+ // ---- Agent approvals: proposals by the application's agents, for the people who may decide them ----------------
723
+ //
724
+ // The app-facing inbox. A proposal is listed to a person only when it is on a task owned by one of this
725
+ // application's declared agents, in the person's own workspace, and the person may perform its capability (so
726
+ // may approve it). Everything else does not exist here: other people's own tasks, other workspaces, capabilities
727
+ // the person lacks. Decisions go through approve()/reject(): the same rules Studio applies.
728
+ #agentOwned(task) {
729
+ const [type, ...rest] = task.owner.split(":");
730
+ if (type !== "agent")
731
+ return null;
732
+ const id = rest.join(":");
733
+ for (const a of this.#runtime.app.agents.values())
734
+ if (a.principal.id === id)
735
+ return { name: a.name, ...(a.principal.displayName ? { displayName: a.principal.displayName } : {}) };
736
+ return null;
737
+ }
738
+ async #mayPerform(principal, capability) {
739
+ const tool = this.#catalog().find((t) => t.name === capability);
740
+ if (!tool)
741
+ return false;
742
+ return (await this.#runtime.authority.authorize({ access: tool.permission[0] ?? "authenticated", principal, target: { name: capability }, transport: "agent" })).allowed;
743
+ }
744
+ /** Proposals by this application's agents that `principal` may decide (default: those waiting, `proposed`). */
745
+ async agentApprovals(principal, filter = {}) {
746
+ const p = this.#require(principal, AGENT_PERMISSIONS.read);
747
+ if (p.type !== "user")
748
+ throw new FeltKitError("FORBIDDEN", "Agent approvals are for people: an agent or service cannot list or decide them.");
749
+ const state = filter.state ?? "proposed";
750
+ const limit = Math.min(Math.max(filter.limit ?? 100, 1), 500);
751
+ const out = [];
752
+ for (const task of await this.#tasks({ limit: 500 })) {
753
+ const agent = this.#agentOwned(task);
754
+ if (!agent || !this.#visible(task, p))
755
+ continue;
756
+ for (const { record } of await this.#heads(task.task_id)) {
757
+ if (state !== "all" && record.state !== state)
758
+ continue;
759
+ if (!(await this.#mayPerform(p, record.capability)))
760
+ continue;
761
+ out.push({ task, agent, action: record, approvable: record.state === "proposed" ? await this.#approvable(task, record, p) : { allowed: false, reason: `it is ${record.state}` } });
762
+ }
763
+ }
764
+ out.sort((a, b) => b.action.proposedAt.localeCompare(a.action.proposedAt));
765
+ return out.slice(0, limit);
766
+ }
767
+ async #approvable(task, record, p) {
768
+ if (!grantsPermission(this.#runtime.authority.permissionsFor(p), AGENT_PERMISSIONS.write))
769
+ return { allowed: false, reason: `${actorOf(p)} lacks ${AGENT_PERMISSIONS.write}` };
770
+ if (record.expiresAt && Date.now() > Date.parse(record.expiresAt))
771
+ return { allowed: false, reason: `it expired at ${record.expiresAt}` };
772
+ const { refusal } = await this.#approvalCheck(task, record, p);
773
+ return refusal ? { allowed: false, reason: refusal } : { allowed: true };
774
+ }
775
+ /** One agent proposal, with what a person needs to decide it. NOT_FOUND unless agentApprovals would list it to them in some state. */
776
+ async agentApproval(taskId, actionId, principal) {
777
+ const p = this.#require(principal, AGENT_PERMISSIONS.read);
778
+ const missing = () => new FeltKitError("NOT_FOUND", `No agent proposal ${actionId} on ${taskId} for you.`);
779
+ if (p.type !== "user")
780
+ throw new FeltKitError("FORBIDDEN", "Agent approvals are for people: an agent or service cannot list or decide them.");
781
+ const found = await this.#state.getTask(taskId);
782
+ if (!found || found.task.scope?.project !== this.#runtime.app.name || !this.#visible(found.task, p))
783
+ throw missing();
784
+ const agent = this.#agentOwned(found.task);
785
+ if (!agent)
786
+ throw missing();
787
+ const head = (await this.#heads(taskId)).find((h) => h.record.actionId === actionId);
788
+ if (!head || !(await this.#mayPerform(p, head.record.capability)))
789
+ throw missing();
790
+ const memories = await this.#taskMemories(taskId);
791
+ // The agent's own words for this call: the turn whose tool call it is (keyed <message>:<call id>).
792
+ let explanation = null;
793
+ for (const m of memories) {
794
+ if (m.kind !== MESSAGE_MEMORY_KIND)
795
+ continue;
796
+ const msg = m.content;
797
+ if (msg.role !== "assistant" || !msg.toolCalls)
798
+ continue;
799
+ for (const call of msg.toolCalls) {
800
+ const key = `msg-${String(msg.seq).padStart(4, "0")}:${call.id}`;
801
+ if (`act-${createHash("sha256").update(`${taskId}\u0000${key}`).digest("hex").slice(0, 20)}` === actionId)
802
+ explanation = msg.content;
803
+ }
804
+ }
805
+ const run = memories.find((m) => m.kind === RUN_MEMORY_KIND)?.content;
806
+ const approvable = head.record.state === "proposed" ? await this.#approvable(found.task, head.record, p) : { allowed: false, reason: `it is ${head.record.state}` };
807
+ return { task: found.task, agent, action: head.record, approvable, explanation, runInput: run?.input ?? null };
808
+ }
809
+ /**
810
+ * Decide an agent's proposal as `principal`, bound to the version they reviewed: the attempt and the input digest
811
+ * they were shown. A different attempt (a retry since) or input is refused, nothing changes. Deciding what is
812
+ * already decided returns its current state (idempotent); the rules are approve()'s and reject()'s.
813
+ */
814
+ async decideAgentProposal(taskId, actionId, principal, decision) {
815
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
816
+ const view = await this.agentApproval(taskId, actionId, p);
817
+ const record = view.action;
818
+ if (!Number.isInteger(decision.attempt))
819
+ throw new FeltKitError("INVALID_ARGUMENT", "Send the proposal's attempt you reviewed (approval.action.attempt).");
820
+ if (decision.attempt !== record.attempt)
821
+ throw new FeltKitError("FAILED_PRECONDITION", `You reviewed attempt ${decision.attempt} of ${actionId}; it is now attempt ${record.attempt}. Nothing was decided: review it again.`, { details: { reason: "STALE_PROPOSAL", reviewed: decision.attempt, current: record.attempt } });
822
+ if (decision.approve && typeof decision.inputDigest !== "string")
823
+ throw new FeltKitError("INVALID_ARGUMENT", "Send the proposal's inputDigest you reviewed: an approval binds to the exact operation and input.");
824
+ // Already decided (by this person, someone else, or an expiry): the decision stands and is answered as it is.
825
+ if (record.state !== "proposed")
826
+ return record;
827
+ try {
828
+ if (decision.approve)
829
+ await this.approve(taskId, actionId, p, { inputDigest: decision.inputDigest });
830
+ else
831
+ await this.reject(taskId, actionId, p, decision.reason ?? "rejected");
832
+ }
833
+ catch (error) {
834
+ // Decided concurrently, and the run may already have ended its task: answer what was decided.
835
+ const now = (await this.#head(taskId, actionId)).record;
836
+ if (now.state !== "proposed" && isFeltKitError(error) && error.code === "CONFLICT")
837
+ return now;
838
+ throw error;
839
+ }
840
+ return (await this.#head(taskId, actionId)).record;
841
+ }
842
+ /** Open tasks (ready, running, blocked) owned by any of `owners` ("agent:<id>"), through FeltDB's indexed, paged listing; at most `limit`. */
843
+ async openTasksOwnedBy(owners, limit = 1000) {
844
+ const out = [];
845
+ for (const status of ["ready", "running", "blocked"]) {
846
+ for (const task of await this.#tasks({ status, limit }))
847
+ if (owners.has(task.owner) && out.length < limit)
848
+ out.push(task);
849
+ }
850
+ return out;
851
+ }
852
+ /** The task's status and owner, for the runtime deciding whether to resume a run. */
853
+ async taskStatus(taskId) {
854
+ const found = await this.#state.getTask(taskId);
855
+ return found && found.task.scope?.project === this.#runtime.app.name ? { status: found.task.status, owner: found.task.owner } : null;
856
+ }
581
857
  // ---- Generations ---------------------------------------------------------------
582
858
  //
583
859
  // One FeltDB agent-memory chain per generation, `<taskId>.gen-<id>.<seq>`, superseded with
@@ -623,6 +899,7 @@ export class AgentHost {
623
899
  aborts.delete(generationId);
624
900
  if (!aborts.size && this.#generationAborts.get(taskId) === aborts)
625
901
  this.#generationAborts.delete(taskId);
902
+ await this.#inFlightEnded(taskId);
626
903
  }
627
904
  };
628
905
  const output = (text, toolCalls = []) => ({ text: text.slice(0, GENERATION_TEXT_LIMIT), ...(text.length > GENERATION_TEXT_LIMIT ? { truncated: text.length } : {}), toolCalls: toolCalls.map((c) => ({ id: c.id, name: c.name, input: redact(c.input) })) });
@@ -791,6 +1068,7 @@ export class AgentHost {
791
1068
  return this.#unchanged(taskId, p, head.record, "approve");
792
1069
  if (head.record.expiresAt && Date.now() > Date.parse(head.record.expiresAt)) {
793
1070
  await this.#expire(task, head).catch(() => undefined);
1071
+ this.#onSettled(taskId, actionId);
794
1072
  throw new FeltKitError("FAILED_PRECONDITION", `This proposal expired at ${head.record.expiresAt} and can no longer be approved; nothing ran.`, { details: { expiredAt: head.record.expiresAt } });
795
1073
  }
796
1074
  const { refusal, owner } = await this.#approvalCheck(task, head.record, p);
@@ -810,7 +1088,46 @@ export class AgentHost {
810
1088
  return this.#unchanged(taskId, p, (await this.#head(taskId, actionId)).record, "approve");
811
1089
  throw error;
812
1090
  }
813
- return this.#run(taskId, task.owner, approved, owner, p);
1091
+ try {
1092
+ return await this.#run(taskId, task.owner, approved, owner, p);
1093
+ }
1094
+ finally {
1095
+ this.#onSettled(taskId, actionId);
1096
+ }
1097
+ }
1098
+ /**
1099
+ * Approve a proposed action under the application's own declared policy (an `app.agent` that lists the
1100
+ * capability in `autonomous`), then run it as the task owner. Only the task owner may ask, only for an action
1101
+ * the owner may perform; an `approval: "required"` capability is left waiting for a person (and would run
1102
+ * without an approval context, which the execution boundary refuses).
1103
+ */
1104
+ async approveByPolicy(taskId, actionId, owner, policy) {
1105
+ const p = this.#require(owner, AGENT_PERMISSIONS.write);
1106
+ await this.#inScope(taskId, p);
1107
+ const { task } = await this.#owned(taskId, p);
1108
+ const head = await this.#head(taskId, actionId);
1109
+ if (head.record.state !== "proposed")
1110
+ return head.record;
1111
+ const tool = this.#catalog().find((t) => t.name === head.record.capability);
1112
+ if (!tool)
1113
+ throw new FeltKitError("NOT_FOUND", `${head.record.capability} is no longer a capability of this application.`);
1114
+ if (tool.approval === "required")
1115
+ return head.record;
1116
+ const allowed = (await this.#runtime.authority.authorize({ access: tool.permission[0] ?? "authenticated", principal: p, target: { name: tool.name }, transport: "agent" })).allowed;
1117
+ if (!allowed)
1118
+ throw new FeltKitError("FORBIDDEN", `${actorOf(p)} may not perform ${tool.name}.`);
1119
+ const by = `policy:${policy}`;
1120
+ let approved;
1121
+ try {
1122
+ approved = await this.#move(head, "approved", { decidedBy: by, decidedAt: new Date().toISOString(), decisionNote: `autonomous under ${policy}`, executedAs: task.owner }, by, `approved by the application's declared policy ${policy}`);
1123
+ }
1124
+ catch (error) {
1125
+ if (isFeltKitError(error) && error.code === "CONFLICT")
1126
+ return (await this.#head(taskId, actionId)).record;
1127
+ throw error;
1128
+ }
1129
+ await this.#run(taskId, task.owner, approved, p, null);
1130
+ return (await this.#head(taskId, actionId)).record;
814
1131
  }
815
1132
  /** Cancel an expired proposal (it was never approved; nothing ran). Concurrent changes win. */
816
1133
  async #expire(task, head) {
@@ -863,7 +1180,8 @@ export class AgentHost {
863
1180
  async #run(taskId, ownerActor, approved, owner, approver) {
864
1181
  const work = (async () => {
865
1182
  const action = approved.record;
866
- await this.#sync(taskId, ownerActor, `Approved by ${approver.id}: running ${action.capability}.`, { decisions: [`approved ${action.actionId} (${action.capability}) by ${actorOf(approver)}; runs as ${ownerActor}`], evidence: [memoryEvidence(approved.memory.memory_id, "approval")] });
1183
+ const approvedBy = approver ? actorOf(approver) : (action.decidedBy ?? "policy");
1184
+ await this.#sync(taskId, ownerActor, `Approved by ${approvedBy}: running ${action.capability}.`, { decisions: [`approved ${action.actionId} (${action.capability}) by ${approvedBy}; runs as ${ownerActor}`], evidence: [memoryEvidence(approved.memory.memory_id, "approval")] });
867
1185
  await this.#hooks.afterApproved?.({ taskId, actionId: action.actionId });
868
1186
  const requestId = `agent_${randomUUID()}`;
869
1187
  const executing = await this.#move(approved, "executing", {
@@ -873,13 +1191,14 @@ export class AgentHost {
873
1191
  ...(action.source === "application" && this.#idempotent(action.capability) ? { idempotencyKey: idempotencyKeyFor(taskId, action) } : {}),
874
1192
  }, ownerActor, `executing as ${ownerActor}`);
875
1193
  await this.#hooks.beforeInvoke?.({ taskId, actionId: action.actionId });
876
- const outcome = await this.#execute(taskId, executing.record, owner, requestId, approver);
1194
+ const outcome = await this.#execute(taskId, executing.record, owner, requestId, approver ?? undefined);
877
1195
  await this.#hooks.afterInvoke?.({ taskId, actionId: action.actionId });
878
- await this.#finish(taskId, ownerActor, executing, outcome, approver);
1196
+ await this.#finish(taskId, ownerActor, executing, outcome, approver ?? owner);
1197
+ await this.#inFlightEnded(taskId);
879
1198
  })();
880
1199
  this.#track(taskId, approved.record.actionId, work);
881
1200
  await work;
882
- return this.get(taskId, approver);
1201
+ return this.get(taskId, approver ?? owner);
883
1202
  }
884
1203
  /** Record a dispatched outcome on the action, the task, the execution record, and the activity log. */
885
1204
  async #finish(taskId, ownerActor, executing, outcome, by) {
@@ -920,6 +1239,7 @@ export class AgentHost {
920
1239
  const rejected = await this.#move(head, "rejected", { decidedBy: actorOf(p), decidedAt: new Date().toISOString(), decisionNote: why }, actorOf(p), `rejected: ${why}`);
921
1240
  await this.#sync(taskId, task.owner, `${head.record.capability} was rejected by ${p.id}.`, { decisions: [`rejected ${actionId} by ${actorOf(p)}: ${why}`], evidence: [memoryEvidence(rejected.memory.memory_id, "rejection")] });
922
1241
  this.#activity("action.rejected", p, taskId, "success", { actionId });
1242
+ this.#onSettled(taskId, actionId);
923
1243
  return this.get(taskId, p);
924
1244
  }
925
1245
  /**
@@ -972,12 +1292,14 @@ export class AgentHost {
972
1292
  head = await this.#move(head, found.ok ? "succeeded" : "failed", { finishedAt: new Date().toISOString(), outcome: { ...found, resolvedBy: actorOf(p) } }, actorOf(p), `outcome established from ${found.determinedBy}; confirmed by ${actorOf(p)}: ${note}`);
973
1293
  await this.#sync(taskId, task.owner, `${head.record.capability} ${head.record.state}, from ${found.determinedBy}.`, { decisions: [`settled ${actionId} from ${found.determinedBy}, confirmed by ${actorOf(p)}: ${note}`], evidence: [memoryEvidence(head.memory.memory_id, "resolution")] });
974
1294
  this.#activity("action.resolved", p, taskId, "success", { actionId, outcome: head.record.state, determinedBy: found.determinedBy });
1295
+ this.#onSettled(taskId, actionId);
975
1296
  return this.get(taskId, p);
976
1297
  }
977
1298
  // No evidence: an attributed decision, recorded as the person's statement, not as execution evidence.
978
1299
  const settled = await this.#move(head, input.outcome, { finishedAt: new Date().toISOString(), outcome: { ok: input.outcome === "succeeded", ...(input.outcome === "failed" ? { error: { code: "RESOLVED_FAILED", message: note } } : {}), determinedBy: "person", resolvedBy: actorOf(p) } }, actorOf(p), `settled as ${input.outcome} by ${actorOf(p)} without execution evidence: ${note}`);
979
1300
  await this.#sync(taskId, task.owner, `${head.record.capability} settled as ${input.outcome} by ${p.id} (their decision; no execution evidence).`, { decisions: [`settled ${actionId} as ${input.outcome} by ${actorOf(p)}, without execution evidence: ${note}`], evidence: [memoryEvidence(settled.memory.memory_id, "resolution decision")] });
980
1301
  this.#activity("action.resolved", p, taskId, "success", { actionId, outcome: input.outcome });
1302
+ this.#onSettled(taskId, actionId);
981
1303
  return this.get(taskId, p);
982
1304
  }
983
1305
  /**
@@ -1077,6 +1399,16 @@ export class AgentHost {
1077
1399
  const { task } = await this.#loaded(taskId);
1078
1400
  if (p.type !== "user" && actorOf(p) !== task.owner)
1079
1401
  throw new FeltKitError("FORBIDDEN", "Only the task owner or a person can cancel it.");
1402
+ // An external reasoner is ended first: the task is never recorded stopped while it can still act.
1403
+ const reasoner = await this.#reasonerOf(taskId);
1404
+ if (reasoner) {
1405
+ try {
1406
+ await reasoner.stop(p, reason);
1407
+ }
1408
+ catch (error) {
1409
+ throw new FeltKitError("UNAVAILABLE", `The agent could not be stopped (${error instanceof Error ? error.message : String(error)}); the task is not stopped. Try again.`);
1410
+ }
1411
+ }
1080
1412
  for (const controller of this.#running.get(taskId) ?? [])
1081
1413
  controller.abort(new Error(`cancelled by ${p.id}`));
1082
1414
  await Promise.allSettled([...(this.#inflight.get(taskId)?.values() ?? [])]);
@@ -1429,8 +1761,9 @@ export class AgentHost {
1429
1761
  const result = await Promise.race([call, new Promise((_, reject) => controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true }))]);
1430
1762
  if (action.source === "application") {
1431
1763
  const response = result;
1432
- // A claim left by an earlier run of this request: AppPort did not run it again, and its outcome is unknown.
1433
- if (!response.ok && idempotencyErrorReason(response.error) === IDEMPOTENCY_OUTCOME_UNKNOWN)
1764
+ // An unknown outcome (AppPort's classification): a claim left by an earlier run of this request, or an effect
1765
+ // that started and gave no definite answer. Never a failure: it may have happened.
1766
+ if (!response.ok && isOutcomeUnknown(response.error))
1434
1767
  return this.#outcome(action, started, requestId, attribution, { code: "OUTCOME_UNKNOWN", message: response.error.message });
1435
1768
  if (!response.ok)
1436
1769
  return this.#outcome(action, started, requestId, attribution, { code: response.error.code, message: response.error.message });
@@ -1732,7 +2065,7 @@ export class AgentHost {
1732
2065
  if (!found || found.task.scope?.project !== this.#runtime.app.name)
1733
2066
  throw new FeltKitError("NOT_FOUND", `No agent task ${taskId}.`);
1734
2067
  if (found.task.status === "completed" || found.task.status === "cancelled")
1735
- throw new FeltKitError("CONFLICT", `Task ${taskId} is ${found.task.status}.`);
2068
+ throw new FeltKitError("CONFLICT", `Task ${taskId} is ${found.task.status} (${found.task.status === "cancelled" ? "AGENT_STOPPED" : "AGENT_COMPLETED"}).`, { details: { reason: found.task.status === "cancelled" ? "AGENT_STOPPED" : "AGENT_COMPLETED", taskId } });
1736
2069
  return found;
1737
2070
  }
1738
2071
  /** The caller must own the task (FeltDB enforces the same on every checkpoint). */