@feltdb/feltkit 0.4.0 → 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 (126) 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 +153 -4
  5. package/dist/app.js +134 -25
  6. package/dist/app.js.map +1 -1
  7. package/dist/appboundry/build.d.ts +7 -0
  8. package/dist/appboundry/build.js +4 -1
  9. package/dist/appboundry/build.js.map +1 -1
  10. package/dist/appboundry/guest.js +4 -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 +265 -4
  32. package/dist/client/index.js +170 -3
  33. package/dist/client/index.js.map +1 -1
  34. package/dist/cron.d.ts +18 -0
  35. package/dist/cron.js +67 -0
  36. package/dist/cron.js.map +1 -0
  37. package/dist/dashboard/assets/index-iIj7SL77.js +15 -0
  38. package/dist/dashboard/index.html +1 -1
  39. package/dist/docs.d.ts +1 -1
  40. package/dist/docs.js +3 -0
  41. package/dist/docs.js.map +1 -1
  42. package/dist/eve/index.d.ts +77 -0
  43. package/dist/eve/index.js +128 -0
  44. package/dist/eve/index.js.map +1 -0
  45. package/dist/index.d.ts +7 -2
  46. package/dist/index.js +2 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/native/build.d.ts +112 -0
  49. package/dist/native/build.js +472 -0
  50. package/dist/native/build.js.map +1 -0
  51. package/dist/native/index.d.ts +67 -0
  52. package/dist/native/index.js +113 -0
  53. package/dist/native/index.js.map +1 -0
  54. package/dist/native/instance.d.ts +3 -0
  55. package/dist/native/instance.js +18 -0
  56. package/dist/native/instance.js.map +1 -0
  57. package/dist/react/agent-control.d.ts +2 -0
  58. package/dist/react/agent-control.js +1 -1
  59. package/dist/react/agent-control.js.map +1 -1
  60. package/dist/react/auth.d.ts +15 -1
  61. package/dist/react/auth.js +28 -5
  62. package/dist/react/auth.js.map +1 -1
  63. package/dist/react/hooks.d.ts +88 -0
  64. package/dist/react/hooks.js +188 -0
  65. package/dist/react/hooks.js.map +1 -0
  66. package/dist/react/index.d.ts +5 -88
  67. package/dist/react/index.js +3 -185
  68. package/dist/react/index.js.map +1 -1
  69. package/dist/runtime/agent-control.d.ts +10 -0
  70. package/dist/runtime/agent-control.js +9 -1
  71. package/dist/runtime/agent-control.js.map +1 -1
  72. package/dist/runtime/agent-run.d.ts +166 -0
  73. package/dist/runtime/agent-run.js +431 -0
  74. package/dist/runtime/agent-run.js.map +1 -0
  75. package/dist/runtime/agent.d.ts +158 -1
  76. package/dist/runtime/agent.js +329 -8
  77. package/dist/runtime/agent.js.map +1 -1
  78. package/dist/runtime/assemble.js +14 -1
  79. package/dist/runtime/assemble.js.map +1 -1
  80. package/dist/runtime/authority.d.ts +9 -0
  81. package/dist/runtime/authority.js.map +1 -1
  82. package/dist/runtime/context.d.ts +9 -0
  83. package/dist/runtime/required-capabilities.d.ts +73 -0
  84. package/dist/runtime/required-capabilities.js +69 -0
  85. package/dist/runtime/required-capabilities.js.map +1 -0
  86. package/dist/runtime/runtime.d.ts +70 -1
  87. package/dist/runtime/runtime.js +261 -9
  88. package/dist/runtime/runtime.js.map +1 -1
  89. package/dist/runtime/sessions.d.ts +1 -0
  90. package/dist/runtime/sessions.js +1 -1
  91. package/dist/runtime/sessions.js.map +1 -1
  92. package/dist/runtime/tenancy.d.ts +9 -1
  93. package/dist/runtime/tenancy.js +22 -0
  94. package/dist/runtime/tenancy.js.map +1 -1
  95. package/dist/runtime/transactions.d.ts +3 -1
  96. package/dist/runtime/transactions.js.map +1 -1
  97. package/dist/server/eve.d.ts +287 -0
  98. package/dist/server/eve.js +1071 -0
  99. package/dist/server/eve.js.map +1 -0
  100. package/dist/server/index.d.ts +2 -0
  101. package/dist/server/index.js +58 -1
  102. package/dist/server/index.js.map +1 -1
  103. package/dist/server/mcp.d.ts +7 -7
  104. package/dist/server/project.js +20 -3
  105. package/dist/server/project.js.map +1 -1
  106. package/dist/server/tenancy.d.ts +2 -0
  107. package/dist/server/tenancy.js +31 -1
  108. package/dist/server/tenancy.js.map +1 -1
  109. package/dist/testing/index.d.ts +1 -4
  110. package/dist/testing/index.js.map +1 -1
  111. package/docs/AGENT-CONTROL.md +36 -0
  112. package/docs/APPBOUNDRY.md +36 -0
  113. package/docs/AUTH.md +2 -0
  114. package/docs/EVE-COMPOSITION.md +75 -0
  115. package/docs/NATIVE-AGENTS.md +353 -0
  116. package/docs/NATIVE.md +137 -0
  117. package/docs/README.md +5 -2
  118. package/package.json +33 -7
  119. package/skills/.claude-plugin/marketplace.json +1 -1
  120. package/skills/.claude-plugin/plugin.json +1 -1
  121. package/skills/feltkit-agent/SKILL.md +1 -1
  122. package/skills/feltkit-build/SKILL.md +1 -1
  123. package/skills/feltkit-data/SKILL.md +1 -1
  124. package/skills/feltkit-operations/SKILL.md +1 -1
  125. package/skills/feltkit-services/SKILL.md +1 -1
  126. package/dist/dashboard/assets/index-BhxrvY37.js +0 -15
@@ -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
  }),
@@ -247,8 +259,33 @@ export class AgentHost {
247
259
  activity: (name, p, taskId, outcome, detail) => this.#activity(name, p, taskId, outcome, detail),
248
260
  changed: (taskId, changes, instructionId, state) => this.#runtime.agentChanged(taskId, changes, instructionId, state),
249
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
+ },
250
276
  });
251
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
+ }
252
289
  /** Work in flight ended while a person holds the task: its phase moved (pausing → paused). */
253
290
  async #inFlightEnded(taskId) {
254
291
  if ((await this.control.mode(taskId).catch(() => ({ mode: "running" }))).mode !== "running")
@@ -436,7 +473,12 @@ export class AgentHost {
436
473
  }
437
474
  const playbook = found.task.constraints.find((c) => c.startsWith("playbook:"))?.slice("playbook:".length);
438
475
  const actions = (await this.#heads(taskId)).map((h) => h.record);
439
- 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 } : {}) };
440
482
  }
441
483
  /** The FeltDB context bundle for a task, plus this application's context. Redacted. */
442
484
  async context(taskId, principal) {
@@ -587,6 +629,231 @@ export class AgentHost {
587
629
  }
588
630
  return { taskId, created: true };
589
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
+ }
590
857
  // ---- Generations ---------------------------------------------------------------
591
858
  //
592
859
  // One FeltDB agent-memory chain per generation, `<taskId>.gen-<id>.<seq>`, superseded with
@@ -801,6 +1068,7 @@ export class AgentHost {
801
1068
  return this.#unchanged(taskId, p, head.record, "approve");
802
1069
  if (head.record.expiresAt && Date.now() > Date.parse(head.record.expiresAt)) {
803
1070
  await this.#expire(task, head).catch(() => undefined);
1071
+ this.#onSettled(taskId, actionId);
804
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 } });
805
1073
  }
806
1074
  const { refusal, owner } = await this.#approvalCheck(task, head.record, p);
@@ -820,7 +1088,46 @@ export class AgentHost {
820
1088
  return this.#unchanged(taskId, p, (await this.#head(taskId, actionId)).record, "approve");
821
1089
  throw error;
822
1090
  }
823
- 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;
824
1131
  }
825
1132
  /** Cancel an expired proposal (it was never approved; nothing ran). Concurrent changes win. */
826
1133
  async #expire(task, head) {
@@ -873,7 +1180,8 @@ export class AgentHost {
873
1180
  async #run(taskId, ownerActor, approved, owner, approver) {
874
1181
  const work = (async () => {
875
1182
  const action = approved.record;
876
- 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")] });
877
1185
  await this.#hooks.afterApproved?.({ taskId, actionId: action.actionId });
878
1186
  const requestId = `agent_${randomUUID()}`;
879
1187
  const executing = await this.#move(approved, "executing", {
@@ -883,14 +1191,14 @@ export class AgentHost {
883
1191
  ...(action.source === "application" && this.#idempotent(action.capability) ? { idempotencyKey: idempotencyKeyFor(taskId, action) } : {}),
884
1192
  }, ownerActor, `executing as ${ownerActor}`);
885
1193
  await this.#hooks.beforeInvoke?.({ taskId, actionId: action.actionId });
886
- const outcome = await this.#execute(taskId, executing.record, owner, requestId, approver);
1194
+ const outcome = await this.#execute(taskId, executing.record, owner, requestId, approver ?? undefined);
887
1195
  await this.#hooks.afterInvoke?.({ taskId, actionId: action.actionId });
888
- await this.#finish(taskId, ownerActor, executing, outcome, approver);
1196
+ await this.#finish(taskId, ownerActor, executing, outcome, approver ?? owner);
889
1197
  await this.#inFlightEnded(taskId);
890
1198
  })();
891
1199
  this.#track(taskId, approved.record.actionId, work);
892
1200
  await work;
893
- return this.get(taskId, approver);
1201
+ return this.get(taskId, approver ?? owner);
894
1202
  }
895
1203
  /** Record a dispatched outcome on the action, the task, the execution record, and the activity log. */
896
1204
  async #finish(taskId, ownerActor, executing, outcome, by) {
@@ -931,6 +1239,7 @@ export class AgentHost {
931
1239
  const rejected = await this.#move(head, "rejected", { decidedBy: actorOf(p), decidedAt: new Date().toISOString(), decisionNote: why }, actorOf(p), `rejected: ${why}`);
932
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")] });
933
1241
  this.#activity("action.rejected", p, taskId, "success", { actionId });
1242
+ this.#onSettled(taskId, actionId);
934
1243
  return this.get(taskId, p);
935
1244
  }
936
1245
  /**
@@ -983,12 +1292,14 @@ export class AgentHost {
983
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}`);
984
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")] });
985
1294
  this.#activity("action.resolved", p, taskId, "success", { actionId, outcome: head.record.state, determinedBy: found.determinedBy });
1295
+ this.#onSettled(taskId, actionId);
986
1296
  return this.get(taskId, p);
987
1297
  }
988
1298
  // No evidence: an attributed decision, recorded as the person's statement, not as execution evidence.
989
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}`);
990
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")] });
991
1301
  this.#activity("action.resolved", p, taskId, "success", { actionId, outcome: input.outcome });
1302
+ this.#onSettled(taskId, actionId);
992
1303
  return this.get(taskId, p);
993
1304
  }
994
1305
  /**
@@ -1088,6 +1399,16 @@ export class AgentHost {
1088
1399
  const { task } = await this.#loaded(taskId);
1089
1400
  if (p.type !== "user" && actorOf(p) !== task.owner)
1090
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
+ }
1091
1412
  for (const controller of this.#running.get(taskId) ?? [])
1092
1413
  controller.abort(new Error(`cancelled by ${p.id}`));
1093
1414
  await Promise.allSettled([...(this.#inflight.get(taskId)?.values() ?? [])]);
@@ -1744,7 +2065,7 @@ export class AgentHost {
1744
2065
  if (!found || found.task.scope?.project !== this.#runtime.app.name)
1745
2066
  throw new FeltKitError("NOT_FOUND", `No agent task ${taskId}.`);
1746
2067
  if (found.task.status === "completed" || found.task.status === "cancelled")
1747
- 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 } });
1748
2069
  return found;
1749
2070
  }
1750
2071
  /** The caller must own the task (FeltDB enforces the same on every checkpoint). */