@feltdb/feltkit 0.1.1 → 0.3.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 (99) hide show
  1. package/dist/app.d.ts +106 -10
  2. package/dist/app.js +51 -0
  3. package/dist/app.js.map +1 -1
  4. package/dist/cli/deploy.js +9 -0
  5. package/dist/cli/deploy.js.map +1 -1
  6. package/dist/cli/main.js +339 -2
  7. package/dist/cli/main.js.map +1 -1
  8. package/dist/cli/skills.d.ts +39 -0
  9. package/dist/cli/skills.js +125 -0
  10. package/dist/cli/skills.js.map +1 -0
  11. package/dist/dashboard/assets/{index-BLnBFDJs.css → index--1Tqbv_A.css} +1 -1
  12. package/dist/dashboard/assets/index-D9529PVz.js +15 -0
  13. package/dist/dashboard/index.html +2 -2
  14. package/dist/errors.d.ts +5 -1
  15. package/dist/errors.js +3 -0
  16. package/dist/errors.js.map +1 -1
  17. package/dist/index.d.ts +1 -1
  18. package/dist/runtime/activity.d.ts +21 -8
  19. package/dist/runtime/activity.js +17 -3
  20. package/dist/runtime/activity.js.map +1 -1
  21. package/dist/runtime/agent.d.ts +353 -0
  22. package/dist/runtime/agent.js +1345 -0
  23. package/dist/runtime/agent.js.map +1 -0
  24. package/dist/runtime/authority.d.ts +24 -3
  25. package/dist/runtime/authority.js +72 -5
  26. package/dist/runtime/authority.js.map +1 -1
  27. package/dist/runtime/changes.d.ts +16 -8
  28. package/dist/runtime/changes.js.map +1 -1
  29. package/dist/runtime/content.d.ts +33 -0
  30. package/dist/runtime/content.js +46 -0
  31. package/dist/runtime/content.js.map +1 -0
  32. package/dist/runtime/context.d.ts +26 -1
  33. package/dist/runtime/credentials.d.ts +174 -0
  34. package/dist/runtime/credentials.js +407 -0
  35. package/dist/runtime/credentials.js.map +1 -0
  36. package/dist/runtime/data.d.ts +8 -2
  37. package/dist/runtime/data.js +74 -9
  38. package/dist/runtime/data.js.map +1 -1
  39. package/dist/runtime/decisions.d.ts +141 -0
  40. package/dist/runtime/decisions.js +330 -0
  41. package/dist/runtime/decisions.js.map +1 -0
  42. package/dist/runtime/environment.js +11 -0
  43. package/dist/runtime/environment.js.map +1 -1
  44. package/dist/runtime/idempotency.d.ts +37 -0
  45. package/dist/runtime/idempotency.js +88 -0
  46. package/dist/runtime/idempotency.js.map +1 -0
  47. package/dist/runtime/instance.d.ts +8 -3
  48. package/dist/runtime/instance.js +27 -4
  49. package/dist/runtime/instance.js.map +1 -1
  50. package/dist/runtime/integrations.d.ts +125 -0
  51. package/dist/runtime/integrations.js +429 -0
  52. package/dist/runtime/integrations.js.map +1 -0
  53. package/dist/runtime/loader.d.ts +5 -1
  54. package/dist/runtime/loader.js +35 -13
  55. package/dist/runtime/loader.js.map +1 -1
  56. package/dist/runtime/projects.d.ts +1 -0
  57. package/dist/runtime/projects.js +6 -4
  58. package/dist/runtime/projects.js.map +1 -1
  59. package/dist/runtime/readiness.d.ts +29 -0
  60. package/dist/runtime/readiness.js +154 -0
  61. package/dist/runtime/readiness.js.map +1 -0
  62. package/dist/runtime/runtime.d.ts +53 -1
  63. package/dist/runtime/runtime.js +252 -9
  64. package/dist/runtime/runtime.js.map +1 -1
  65. package/dist/runtime/services.d.ts +205 -36
  66. package/dist/runtime/services.js +479 -152
  67. package/dist/runtime/services.js.map +1 -1
  68. package/dist/runtime/sessions.d.ts +7 -18
  69. package/dist/runtime/sessions.js +7 -5
  70. package/dist/runtime/sessions.js.map +1 -1
  71. package/dist/server/admin.d.ts +80 -0
  72. package/dist/server/admin.js +677 -8
  73. package/dist/server/admin.js.map +1 -1
  74. package/dist/server/index.d.ts +2 -0
  75. package/dist/server/index.js +13 -4
  76. package/dist/server/index.js.map +1 -1
  77. package/dist/server/management.d.ts +12 -0
  78. package/dist/server/management.js +177 -0
  79. package/dist/server/management.js.map +1 -0
  80. package/dist/server/mcp.d.ts +202 -0
  81. package/dist/server/mcp.js +62 -4
  82. package/dist/server/mcp.js.map +1 -1
  83. package/dist/server/operators.d.ts +77 -0
  84. package/dist/server/operators.js +162 -0
  85. package/dist/server/operators.js.map +1 -0
  86. package/dist/server/project.js +17 -4
  87. package/dist/server/project.js.map +1 -1
  88. package/dist/testing/index.js +3 -2
  89. package/dist/testing/index.js.map +1 -1
  90. package/package.json +18 -11
  91. package/skills/.claude-plugin/marketplace.json +16 -0
  92. package/skills/.claude-plugin/plugin.json +24 -0
  93. package/skills/README.md +44 -0
  94. package/skills/feltkit-agent/SKILL.md +84 -0
  95. package/skills/feltkit-build/SKILL.md +153 -0
  96. package/skills/feltkit-data/SKILL.md +79 -0
  97. package/skills/feltkit-operations/SKILL.md +72 -0
  98. package/skills/feltkit-services/SKILL.md +124 -0
  99. package/dist/dashboard/assets/index-CxJGCspE.js +0 -15
@@ -0,0 +1,1345 @@
1
+ /**
2
+ * The FeltKit agent: FeltDB's agent runtime and agent state, operating this
3
+ * application through AppPort.
4
+ *
5
+ * What is FeltDB's, reused as is (all on the environment's single instance):
6
+ *
7
+ * db.defineAgent(...) the agent's identity, capabilities, approval policy
8
+ * db.createAgentExecution({ taskId }) / start / transition / resume / complete / fail / cancel
9
+ * the durable lifecycle record of each task; every change
10
+ * is committed by FeltDB, invalid transitions refuse, and
11
+ * db.findAgentExecution({ taskId }) finds it (indexed)
12
+ * openAgentState(db) tasks, checkpoints whose `record` evidence is verified
13
+ * inside the commit, task memory (pending proposals),
14
+ * leased handoffs to another participant, bounded
15
+ * context bundles (feltdb.agent-context@1), and bounded,
16
+ * cursor-paged listTasks / listHandoffs
17
+ *
18
+ * What FeltKit adds is the product layer FeltDB does not have:
19
+ *
20
+ * - Actions go only through AppPort: application capabilities via the application's
21
+ * own dispatch pipeline (validate → authorize → execute), service operations via
22
+ * AppPort Services' invoke() and gateway. The agent has no other access to state.
23
+ * - Every action runs as the task's owner. An "observation" runs at once; a
24
+ * "consequential" action (AppPort's and AppPort Services' own effect classes) waits
25
+ * for a human who is also authorized to perform it. Approval is recorded; it never
26
+ * widens the owner's authority.
27
+ * - Decisions: FeltDB has no planner, and FeltKit adds none. Built-in playbooks choose
28
+ * capabilities by code (as FeltDB's own worker does); open-ended work is handed off,
29
+ * through FeltDB's handoff, to an external coding agent that proposes actions over MCP.
30
+ *
31
+ * Every result is redacted before it is recorded: secrets returned by an operation
32
+ * (an API key's plaintext, a session token) never reach a checkpoint, memory, or reply.
33
+ */
34
+ import { FELTDB_AGENT_MEMORY_COLLECTION, openAgentState } from "@feltdb/core";
35
+ import { IDEMPOTENCY_OUTCOME_UNKNOWN, idempotencyErrorReason, isIdempotencyClaim } from "@appport/sdk";
36
+ import { createHash, randomUUID } from "node:crypto";
37
+ import { FeltKitError, isFeltKitError } from "../errors.js";
38
+ import { authContext } from "./authority.js";
39
+ export const AGENT_NAME = "feltkit";
40
+ export const AGENT_VERSION = 1;
41
+ /** Permissions for using the agent itself. Actions still need their own permissions. */
42
+ export const AGENT_PERMISSIONS = { read: "feltkit.agent.read", write: "feltkit.agent.write" };
43
+ /**
44
+ * FeltDB's execution collection, read only for executions created before FeltDB 0.14.0:
45
+ * those carry no `taskId`, so `findAgentExecution({ taskId })` cannot find them. See
46
+ * #legacyExecution.
47
+ */
48
+ const LEGACY_EXECUTIONS = "_flow_agent_executions";
49
+ const ACTIVITY = "_feltkit_activity";
50
+ const ACTION_TIMEOUT_MS = 30_000;
51
+ /** Always offered: hand the task to a person instead of acting. */
52
+ export const ESCALATE = "escalate";
53
+ const DECISION_REQUEST_KIND = "decision-request";
54
+ const DECISION_KIND = "decision";
55
+ /** States that still need something: approval, completion, or a person to settle them. */
56
+ export const OPEN_STATES = ["proposed", "approved", "executing", "interrupted"];
57
+ /** Valid transitions. `proposed → proposed` appends history only (a refused approval). */
58
+ const TRANSITIONS = {
59
+ proposed: ["proposed", "approved", "rejected", "cancelled"],
60
+ approved: ["executing", "proposed", "cancelled"],
61
+ executing: ["succeeded", "failed", "interrupted"],
62
+ interrupted: ["succeeded", "failed"],
63
+ failed: ["proposed"],
64
+ succeeded: [],
65
+ rejected: [],
66
+ cancelled: [],
67
+ };
68
+ const ACTION_KIND = "action";
69
+ /** Records written before the action lifecycle existed. Read as `proposed`. */
70
+ const LEGACY_PROPOSAL_KIND = "proposal";
71
+ const memoryEvidence = (memoryId, description) => ({ kind: "record", collection: FELTDB_AGENT_MEMORY_COLLECTION, id: memoryId, description: `action record (${description})` });
72
+ /** Stable per attempt: a duplicate of the same attempt is the same request; a retry is not. */
73
+ const idempotencyKeyFor = (taskId, action) => `feltkit-agent:${taskId}:${action.actionId}:${action.attempt}`;
74
+ export const PLAYBOOKS = ["diagnose-job", "diagnose-delivery", "inspect-app", "invoke", "decide", "handoff"];
75
+ const actorOf = (p) => `${p.type}:${p.id}`;
76
+ /** Remove credential material from anything recorded or returned. */
77
+ export function redact(value, depth = 0) {
78
+ if (depth > 12)
79
+ return "[truncated]";
80
+ if (typeof value === "string") {
81
+ return value
82
+ .replace(/\bapp_live_[0-9a-f]{6}_[A-Za-z0-9_-]+/g, "[redacted api key]")
83
+ .replace(/\bfk[sa]_[A-Za-z0-9_-]{20,}/g, "[redacted token]");
84
+ }
85
+ if (Array.isArray(value))
86
+ return value.slice(0, 200).map((v) => redact(v, depth + 1));
87
+ if (value && typeof value === "object") {
88
+ const out = {};
89
+ for (const [key, entry] of Object.entries(value)) {
90
+ if (/^(secret|plaintext|token|password|apiKey|key|secretHash|signingSecret|value)$/i.test(key) && typeof entry === "string" && entry.length >= 16) {
91
+ out[key] = "[redacted]";
92
+ }
93
+ else
94
+ out[key] = redact(entry, depth + 1);
95
+ }
96
+ return out;
97
+ }
98
+ return value;
99
+ }
100
+ function checkDecisionSpec(spec) {
101
+ if (!spec || typeof spec.question !== "string" || !spec.question.trim())
102
+ throw new FeltKitError("INVALID_ARGUMENT", "A decision needs a question.");
103
+ if (!Array.isArray(spec.options) || spec.options.length === 0 || spec.options.length > 12)
104
+ throw new FeltKitError("INVALID_ARGUMENT", "A decision needs 1–12 options.");
105
+ const ids = new Set();
106
+ for (const option of spec.options) {
107
+ if (!option || typeof option.id !== "string" || !/^[a-z0-9][a-z0-9-]{0,39}$/.test(option.id))
108
+ throw new FeltKitError("INVALID_ARGUMENT", `Decision option ids are 1–40 lowercase letters, digits, or dashes ("${String(option?.id)}").`);
109
+ if (ids.has(option.id))
110
+ throw new FeltKitError("INVALID_ARGUMENT", `Decision option "${option.id}" appears twice.`);
111
+ ids.add(option.id);
112
+ if (option.input !== undefined && (typeof option.input !== "object" || option.input === null || Array.isArray(option.input)))
113
+ throw new FeltKitError("INVALID_ARGUMENT", `Decision option "${option.id}": input must be an object.`);
114
+ }
115
+ return { question: spec.question.slice(0, 1000), options: spec.options.map((o) => ({ id: o.id, ...(o.label ? { label: String(o.label).slice(0, 200) } : {}), ...(o.capability ? { capability: o.capability } : {}), ...(o.input ? { input: redact(o.input) } : {}), ...(o.reason ? { reason: String(o.reason).slice(0, 1000) } : {}) })), ...(spec.context ? { context: redact(spec.context) } : {}) };
116
+ }
117
+ function summarize(value, max = 600) {
118
+ const text = JSON.stringify(value) ?? "null";
119
+ return text.length > max ? `${text.slice(0, max)}…` : text;
120
+ }
121
+ const SERVICE_KEYS = {
122
+ "api-keys": "apiKeys",
123
+ webhooks: "webhooks",
124
+ jobs: "jobs",
125
+ schedules: "schedules",
126
+ notifications: "notifications",
127
+ files: "files",
128
+ configuration: "configuration",
129
+ intelligence: "intelligence",
130
+ };
131
+ export class AgentHost {
132
+ #runtime;
133
+ #db;
134
+ #state;
135
+ #ref;
136
+ /** taskId → the FeltDB execution this process resumed (FeltDB's runtime mutates it on each change). */
137
+ #executions = new Map();
138
+ /** taskId → executionId of executions created before FeltDB 0.14.0; read once, on first need. */
139
+ #legacy = null;
140
+ /** taskId → controllers of actions running now, for cancellation. */
141
+ #running = new Map();
142
+ /** taskId → actionId → the approval running it in this process. */
143
+ #inflight = new Map();
144
+ /** Decision tasks started after a commit (ctx.agent.start), until their first decision is recorded. */
145
+ #background = new Set();
146
+ #hooks;
147
+ #timeoutMs;
148
+ /** Production: the person who proposed an action may not approve it. */
149
+ #separateApprover;
150
+ constructor(runtime, db, options = {}) {
151
+ this.#runtime = runtime;
152
+ this.#db = db;
153
+ this.#hooks = options.hooks ?? {};
154
+ this.#timeoutMs = options.actionTimeoutMs ?? ACTION_TIMEOUT_MS;
155
+ this.#separateApprover = options.separateApprover ?? false;
156
+ }
157
+ /** Open agent state and define the agent. The runtime reconciles open actions once it is ready (outcome hooks are function calls). */
158
+ async open() {
159
+ this.#state = await openAgentState(this.#db);
160
+ this.define();
161
+ }
162
+ /** (Re)define the agent with the application's current capabilities. Called on reload. */
163
+ define() {
164
+ const tools = this.#catalog();
165
+ this.#ref = this.#db.defineAgent({
166
+ name: AGENT_NAME,
167
+ version: AGENT_VERSION,
168
+ description: `Operates ${this.#runtime.app.name} through its AppPort capabilities and AppPort Services.`,
169
+ capabilities: tools.map((t) => t.name),
170
+ goals: ["Diagnose and correct application and service failures through authorized capabilities, with evidence"],
171
+ constraints: { maxIterations: 20 },
172
+ policies: { requireApproval: tools.filter((t) => t.effect === "consequential").map((t) => t.name) },
173
+ });
174
+ }
175
+ /** Whether the application capability the agent calls (version 1) declares AppPort idempotency. */
176
+ #idempotent(capability) {
177
+ const entry = this.#runtime.appport.manifest().capabilities.find((c) => c.name === capability);
178
+ return entry?.definitions.find((d) => d.version === 1)?.idempotency === "supported";
179
+ }
180
+ /** Every action the agent could take in this application, before authorization. */
181
+ #catalog() {
182
+ const manifest = this.#runtime.appport.manifest();
183
+ const functions = new Map(this.#runtime.functions().filter((f) => f.capability).map((f) => [f.capability.name, f]));
184
+ const application = (manifest.capabilities ?? [])
185
+ .filter((c) => !c.name.startsWith("appport."))
186
+ .map((c) => {
187
+ const fn = functions.get(c.name);
188
+ const integration = this.#runtime.integrations.operationFor(c.name);
189
+ return {
190
+ name: c.name,
191
+ source: "application",
192
+ effect: (c.effect === "observation" ? "observation" : "consequential"),
193
+ ...(c.description ? { description: c.description } : {}),
194
+ permission: integration ? [integration.op.access] : fn && fn.access !== "public" && fn.access !== "authenticated" ? [fn.access] : [],
195
+ };
196
+ });
197
+ const services = this.#runtime.services;
198
+ const official = services.capabilities();
199
+ const enabled = new Set(Object.keys(services.management()));
200
+ const serviceTools = official
201
+ .filter((c) => c.invocable && enabled.has(SERVICE_KEYS[c.service] ?? c.service))
202
+ .map((c) => ({ name: c.name, source: "services", effect: c.effect, description: `AppPort Services ${c.service}.${c.operation}`, permission: [c.name] }));
203
+ return [...application, ...serviceTools];
204
+ }
205
+ /** What `principal` could ask the agent to do, with an authorization decision for each. */
206
+ async tools(principal) {
207
+ const out = [];
208
+ for (const tool of this.#catalog()) {
209
+ const decision = await this.#runtime.authority.authorize({
210
+ access: tool.permission[0] ?? "authenticated",
211
+ principal,
212
+ target: { name: tool.name },
213
+ transport: "agent",
214
+ });
215
+ out.push({ name: tool.name, source: tool.source, effect: tool.effect, ...(tool.description ? { description: tool.description } : {}), allowed: decision.allowed });
216
+ }
217
+ return out;
218
+ }
219
+ /**
220
+ * The agent's own boundary: using the agent needs feltkit.agent.* (or a grant covering
221
+ * it). "admin" is the dashboard's admin token, which may read (never act).
222
+ */
223
+ authorizeRead(principal) {
224
+ this.#read(principal);
225
+ }
226
+ #read(principal) {
227
+ if (principal !== "admin")
228
+ this.#require(principal, AGENT_PERMISSIONS.read);
229
+ }
230
+ #require(principal, permission) {
231
+ if (!principal)
232
+ throw new FeltKitError("UNAUTHORIZED", "Authentication is required to use the agent.");
233
+ authContext(this.#runtime.authority, principal).require(permission);
234
+ return principal;
235
+ }
236
+ // ---- Tasks -------------------------------------------------------------------
237
+ async createTask(input) {
238
+ const principal = this.#require(input.principal, AGENT_PERMISSIONS.write);
239
+ const objective = String(input.objective ?? "").trim();
240
+ if (!objective)
241
+ throw new FeltKitError("INVALID_ARGUMENT", "A task needs an objective.");
242
+ const playbook = input.playbook ?? "handoff";
243
+ if (!PLAYBOOKS.includes(playbook)) {
244
+ throw new FeltKitError("INVALID_ARGUMENT", `Unknown playbook "${playbook}".`);
245
+ }
246
+ const actor = actorOf(principal);
247
+ if (input.taskId !== undefined && !/^task-[0-9a-f-]{36}$/.test(input.taskId))
248
+ throw new FeltKitError("INVALID_ARGUMENT", "A task id looks like task-<uuid>.");
249
+ const decision = playbook === "decide" ? checkDecisionSpec(input.decision) : null;
250
+ const taskId = input.taskId ?? `task-${randomUUID()}`;
251
+ const execution = await this.#db.createAgentExecution(this.#ref, objective, [`agent-task:${taskId}`], { taskId });
252
+ await this.#db.startAgentExecution(execution);
253
+ this.#executions.set(taskId, execution);
254
+ await this.#state.createTask({
255
+ taskId,
256
+ objective,
257
+ scope: { project: this.#runtime.app.name },
258
+ actor,
259
+ status: "running",
260
+ constraints: [`playbook:${playbook}`, ...(input.target ? [`target:${input.target}`] : []), ...(input.subject ? [`subject:${input.subject.collection}/${input.subject.id}`] : [])],
261
+ summary: `Started by ${actor} (${playbook}).`,
262
+ execution: { adapter: "feltkit", conversation_id: execution.executionId },
263
+ });
264
+ await this.#transition(taskId, "Observing");
265
+ this.#activity("task.created", principal, taskId, "success", { playbook, objective: objective.slice(0, 200) });
266
+ try {
267
+ if (playbook === "diagnose-job")
268
+ await this.#diagnoseJob(taskId, principal, String(input.target ?? ""));
269
+ else if (playbook === "diagnose-delivery")
270
+ await this.#diagnoseDelivery(taskId, principal, String(input.target ?? ""));
271
+ else if (playbook === "inspect-app")
272
+ await this.#inspect(taskId, principal);
273
+ else if (playbook === "decide") {
274
+ await this.#state.remember({ taskId, memoryId: `${taskId}.decision-request`, kind: DECISION_REQUEST_KIND, content: decision, source: { actor } });
275
+ await this.#decide(taskId, principal);
276
+ }
277
+ else if (playbook === "invoke") {
278
+ if (!input.capability)
279
+ throw new FeltKitError("INVALID_ARGUMENT", "The invoke playbook needs a capability.");
280
+ await this.propose(taskId, { capability: input.capability, input: input.args ?? {}, reason: objective }, principal);
281
+ }
282
+ else {
283
+ // Open-ended work: hand the task to an external coding agent through FeltDB's handoff.
284
+ await this.#state.checkpoint(taskId, { actor, summary: "Waiting for an agent to claim this task over MCP (feltkit_agent_claim).", status: "ready", pendingWork: ["claim the handoff", objective] });
285
+ await this.#state.createHandoff(taskId, { actor, note: objective });
286
+ await this.#transition(taskId, "Waiting");
287
+ }
288
+ }
289
+ catch (error) {
290
+ await this.#fail(taskId, actor, error);
291
+ }
292
+ return this.get(taskId, principal);
293
+ }
294
+ async list(principal, limit = 50) {
295
+ this.#read(principal);
296
+ const rows = await this.#tasks({ limit });
297
+ return Promise.all(rows.map(async (task) => ({ task, execution: await this.#executionRecord(task), pending: (await this.#heads(task.task_id)).filter((h) => h.record.state === "proposed").length })));
298
+ }
299
+ async get(taskId, principal) {
300
+ this.#read(principal);
301
+ const found = await this.#state.getTask(taskId);
302
+ if (!found || found.task.scope?.project !== this.#runtime.app.name)
303
+ throw new FeltKitError("NOT_FOUND", `No agent task ${taskId}.`);
304
+ const checkpoints = [];
305
+ for (let v = 1; v <= found.task.checkpoint_version; v += 1) {
306
+ const c = await this.#state.getCheckpoint(taskId, v);
307
+ if (c)
308
+ checkpoints.push(c);
309
+ }
310
+ const playbook = found.task.constraints.find((c) => c.startsWith("playbook:"))?.slice("playbook:".length);
311
+ const actions = (await this.#heads(taskId)).map((h) => h.record);
312
+ return { task: found.task, checkpoints, execution: await this.#executionRecord(found.task), pending: actions.filter((a) => a.state === "proposed"), actions, ...(playbook ? { playbook } : {}) };
313
+ }
314
+ /** The FeltDB context bundle for a task, plus this application's context. Redacted. */
315
+ async context(taskId, principal) {
316
+ const p = this.#require(principal, AGENT_PERMISSIONS.read);
317
+ const bundle = await this.#state.assembleContext(taskId, { maxBytes: 24_000 });
318
+ return redact({ task: bundle, application: await this.applicationContext(p) });
319
+ }
320
+ /**
321
+ * What an agent needs to know about this application, as `principal` sees it: the
322
+ * data model, capabilities it may use, services and their states, and recent failures.
323
+ */
324
+ async applicationContext(principal) {
325
+ const runtime = this.#runtime;
326
+ const errors = await runtime.activity.list({ outcome: "error", limit: 10 });
327
+ const denied = await runtime.activity.list({ outcome: "denied", limit: 10 });
328
+ return {
329
+ application: runtime.app.name,
330
+ environment: runtime.environment.name,
331
+ collections: [...runtime.app.collections.values()].map((c) => ({ name: c.name, ...(c.description ? { description: c.description } : {}), fields: Object.keys(c.schema.toJSONSchema().properties ?? {}) })),
332
+ tools: await this.tools(principal),
333
+ services: (await runtime.services.status(runtime.state === "ready")).map((s) => ({ id: s.id, state: s.state, detail: s.detail, ...(s.summary ? { summary: s.summary } : {}) })),
334
+ recentErrors: errors.map((e) => ({ at: e.at, name: e.name, via: e.via, code: e.error?.code, message: e.error?.message })),
335
+ recentDenials: denied.map((e) => ({ at: e.at, name: e.name, via: e.via, principal: e.principal?.id })),
336
+ };
337
+ }
338
+ // ---- Actions -----------------------------------------------------------------
339
+ //
340
+ // A consequential action is a chain of FeltDB agent-memory records in the task's
341
+ // scope: `<actionId>.1`, `.2`, … Each transition supersedes the head with
342
+ // `expectedRevision`, which FeltDB commits atomically or refuses (VERSION_CONFLICT), so
343
+ // a transition is a durable compare-and-swap. There is no other action store.
344
+ //
345
+ // proposed ──approve──▶ approved ──▶ executing ──▶ succeeded
346
+ // │ ▲ │ ├──▶ failed ──retry──▶ proposed (attempt + 1)
347
+ // │ └── restart ───────┘ └──▶ interrupted ──resolve──▶ succeeded | failed
348
+ // ├──reject──▶ rejected (timeout, cancel mid-run, crash: outcome unknown)
349
+ // └──cancel──▶ cancelled approved ──cancel──▶ cancelled
350
+ //
351
+ // A refused approval appends to the history and leaves the action proposed.
352
+ /**
353
+ * Propose an action. An observation runs now as the task owner; a consequential
354
+ * action waits for approval. Either way it goes only through AppPort.
355
+ */
356
+ async propose(taskId, proposal, principal) {
357
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
358
+ const { task } = await this.#owned(taskId, p);
359
+ const tool = this.#catalog().find((t) => t.name === proposal.capability);
360
+ if (!tool)
361
+ throw new FeltKitError("NOT_FOUND", `"${proposal.capability}" is not a capability of this application or an enabled service.`);
362
+ const input = proposal.input ?? {};
363
+ if (!input || typeof input !== "object" || Array.isArray(input))
364
+ throw new FeltKitError("INVALID_ARGUMENT", "Action input must be an object.");
365
+ const at = new Date().toISOString();
366
+ const action = {
367
+ actionId: `act-${randomUUID().replace(/-/g, "").slice(0, 20)}`,
368
+ capability: tool.name,
369
+ source: tool.source,
370
+ effect: tool.effect,
371
+ input: redact(input),
372
+ reason: String(proposal.reason ?? "").slice(0, 2000) || "(no reason given)",
373
+ proposedBy: actorOf(p),
374
+ proposedAt: at,
375
+ ...(proposal.decision ? { decision: proposal.decision } : {}),
376
+ };
377
+ if (tool.effect === "observation") {
378
+ const owner = await this.#ownerPrincipal(task);
379
+ const outcome = await this.#execute(taskId, { ...action, attempt: 1 }, owner, `agent_${randomUUID()}`);
380
+ await this.#record(taskId, task.owner, action, outcome, `Observed ${tool.name}${outcome.ok ? "" : ` (failed: ${outcome.error?.code})`}.`, []);
381
+ return this.get(taskId, p);
382
+ }
383
+ const record = { ...action, state: "proposed", seq: 1, attempt: 1, history: [{ state: "proposed", at, by: action.proposedBy }] };
384
+ const memory = await this.#state.remember({ taskId, memoryId: `${action.actionId}.1`, kind: ACTION_KIND, content: record, source: { actor: action.proposedBy } });
385
+ await this.#sync(taskId, task.owner, `Waiting for approval: ${tool.name}.`, { decisions: [`proposed ${action.actionId} (${tool.name}) by ${action.proposedBy} because: ${action.reason}`], evidence: [memoryEvidence(memory.memory_id, "proposal")] });
386
+ this.#activity("action.proposed", p, taskId, "success", { capability: tool.name, actionId: action.actionId });
387
+ return this.get(taskId, p);
388
+ }
389
+ /**
390
+ * Approve a proposed action, then run it as the task owner. Everything that can refuse
391
+ * is checked before the proposal is consumed: the approver is a person with
392
+ * feltkit.agent.write who may perform the action; the owner can still be resolved and
393
+ * may perform it. A refusal is recorded on the action, which stays proposed. A
394
+ * duplicate or concurrent approval of the same action never runs it twice.
395
+ */
396
+ async approve(taskId, actionId, approver) {
397
+ const p = this.#require(approver, AGENT_PERMISSIONS.write);
398
+ if (p.type !== "user")
399
+ throw new FeltKitError("FORBIDDEN", "Only a person can approve a consequential action; agents and services cannot.");
400
+ const { task } = await this.#loaded(taskId);
401
+ const head = await this.#head(taskId, actionId);
402
+ if (head.record.state !== "proposed")
403
+ 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;
418
+ if (refusal) {
419
+ const refused = await this.#move(head, "proposed", {}, actorOf(p), `approval refused: ${refusal}`);
420
+ 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")] });
421
+ this.#activity("action.approval_refused", p, taskId, "denied", { actionId, capability: head.record.capability, reason: refusal });
422
+ throw new FeltKitError("FORBIDDEN", `Approval refused: ${refusal}. The proposal is unchanged and can be approved once this is resolved.`);
423
+ }
424
+ let approved;
425
+ try {
426
+ approved = await this.#move(head, "approved", { decidedBy: actorOf(p), decidedAt: new Date().toISOString(), executedAs: task.owner }, actorOf(p), "approved");
427
+ }
428
+ catch (error) {
429
+ // Another approval (or a rejection) won the compare-and-swap: report the action as it is.
430
+ if (isFeltKitError(error) && error.code === "CONFLICT")
431
+ return this.#unchanged(taskId, p, (await this.#head(taskId, actionId)).record, "approve");
432
+ throw error;
433
+ }
434
+ return this.#run(taskId, task.owner, approved, owner, p);
435
+ }
436
+ /** Execute an approved action: durable intent first, then the call, then the outcome. */
437
+ async #run(taskId, ownerActor, approved, owner, approver) {
438
+ const work = (async () => {
439
+ const action = approved.record;
440
+ 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")] });
441
+ await this.#hooks.afterApproved?.({ taskId, actionId: action.actionId });
442
+ const requestId = `agent_${randomUUID()}`;
443
+ const executing = await this.#move(approved, "executing", {
444
+ requestId,
445
+ startedAt: new Date().toISOString(),
446
+ // Only to a capability that declares idempotency: AppPort refuses a key it would ignore (development).
447
+ ...(action.source === "application" && this.#idempotent(action.capability) ? { idempotencyKey: idempotencyKeyFor(taskId, action) } : {}),
448
+ }, ownerActor, `executing as ${ownerActor}`);
449
+ await this.#hooks.beforeInvoke?.({ taskId, actionId: action.actionId });
450
+ const outcome = await this.#execute(taskId, executing.record, owner, requestId, approver);
451
+ await this.#hooks.afterInvoke?.({ taskId, actionId: action.actionId });
452
+ await this.#finish(taskId, ownerActor, executing, outcome, approver);
453
+ })();
454
+ this.#track(taskId, approved.record.actionId, work);
455
+ await work;
456
+ return this.get(taskId, approver);
457
+ }
458
+ /** Record a dispatched outcome on the action, the task, the execution record, and the activity log. */
459
+ async #finish(taskId, ownerActor, executing, outcome, by) {
460
+ const action = executing.record;
461
+ // An external effect that may or may not have happened is not a failure: it is unknown until verified.
462
+ const unknown = !outcome.ok && outcome.error?.code === "OUTCOME_UNKNOWN";
463
+ const state = outcome.aborted || unknown ? "interrupted" : outcome.ok ? "succeeded" : "failed";
464
+ const done = await this.#move(executing, state, {
465
+ finishedAt: new Date().toISOString(),
466
+ outcome: { ok: outcome.ok, ...(outcome.ok ? { output: outcome.output } : { error: outcome.error }), ...(outcome.activityId ? { activityId: outcome.activityId } : {}), determinedBy: "dispatch" },
467
+ ...(outcome.aborted ? { interruption: outcome.aborted === "timeout" ? `timed out after ${this.#timeoutMs} ms; the action may still complete` : "cancelled while running; the action may still complete" } : {}),
468
+ ...(unknown ? { interruption: outcome.error.message } : {}),
469
+ }, ownerActor, state === "interrupted" ? `outcome unknown (${outcome.aborted ?? "no definite answer"})` : state);
470
+ await this.#runtime.activity.flush();
471
+ const summary = state === "succeeded"
472
+ ? `Ran ${action.capability}${action.decidedBy ? `, approved by ${action.decidedBy}` : ""}.`
473
+ : state === "failed"
474
+ ? `${action.capability} failed${action.decidedBy ? " after approval" : ""}: ${outcome.error?.message}`
475
+ : unknown
476
+ ? `${action.capability} was sent but no definite answer came back; its outcome is unknown and must be verified, not repeated.`
477
+ : `${action.capability} was ${outcome.aborted === "timeout" ? "timed out" : "cancelled"} while running; its outcome is unknown and must be reconciled.`;
478
+ await this.#sync(taskId, ownerActor, summary, {
479
+ completed: [`${action.capability} (attempt ${action.attempt}) → ${state === "succeeded" ? summarize(outcome.output) : state === "failed" ? `${outcome.error?.code}: ${outcome.error?.message}` : "outcome unknown"}`.slice(0, 4000)],
480
+ evidence: [...(outcome.activityId ? [{ kind: "record", collection: ACTIVITY, id: outcome.activityId, description: `${action.capability} ${state}` }] : []), memoryEvidence(done.memory.memory_id, state)],
481
+ });
482
+ if (by)
483
+ this.#activity(`action.${state}`, by, taskId, state === "succeeded" ? "success" : "error", { actionId: action.actionId, capability: action.capability, attempt: action.attempt });
484
+ }
485
+ /** Reject a proposed action. */
486
+ async reject(taskId, actionId, principal, reason = "rejected") {
487
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
488
+ const { task } = await this.#loaded(taskId);
489
+ const head = await this.#head(taskId, actionId);
490
+ if (head.record.state !== "proposed")
491
+ return this.#unchanged(taskId, p, head.record, "reject");
492
+ const why = String(reason).slice(0, 500);
493
+ const rejected = await this.#move(head, "rejected", { decidedBy: actorOf(p), decidedAt: new Date().toISOString(), decisionNote: why }, actorOf(p), `rejected: ${why}`);
494
+ 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")] });
495
+ this.#activity("action.rejected", p, taskId, "success", { actionId });
496
+ return this.get(taskId, p);
497
+ }
498
+ /**
499
+ * Retry an action that failed with a known outcome: a new attempt, with a new
500
+ * idempotency key, that needs approval again. The owner or a person may ask.
501
+ */
502
+ async retry(taskId, actionId, principal) {
503
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
504
+ const { task } = await this.#loaded(taskId);
505
+ if (p.type !== "user" && actorOf(p) !== task.owner)
506
+ throw new FeltKitError("FORBIDDEN", "Only the task owner or a person can retry an action.");
507
+ const head = await this.#head(taskId, actionId);
508
+ if (head.record.state !== "failed") {
509
+ throw new FeltKitError("CONFLICT", head.record.state === "interrupted" ? `${actionId}'s outcome is unknown; resolve it as succeeded or failed before retrying.` : `${actionId} is ${head.record.state}; only a failed action can be retried.`);
510
+ }
511
+ const next = await this.#move(head, "proposed", { attempt: head.record.attempt + 1, decidedBy: undefined, decidedAt: undefined, requestId: undefined, idempotencyKey: undefined, startedAt: undefined, finishedAt: undefined, outcome: undefined }, actorOf(p), `retry requested (attempt ${head.record.attempt + 1})`);
512
+ await this.#sync(taskId, task.owner, `Retry of ${head.record.capability} requested by ${p.id}; waiting for approval.`, { decisions: [`retry of ${actionId} (attempt ${head.record.attempt + 1}) requested by ${actorOf(p)}`], evidence: [memoryEvidence(next.memory.memory_id, "retry")] });
513
+ this.#activity("action.retry_requested", p, taskId, "success", { actionId, attempt: head.record.attempt + 1 });
514
+ return this.get(taskId, p);
515
+ }
516
+ /**
517
+ * Settle an interrupted action whose outcome FeltKit could not determine. Only a person
518
+ * who may perform the action can say what happened; FeltKit never guesses.
519
+ */
520
+ async resolve(taskId, actionId, input, principal) {
521
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
522
+ if (p.type !== "user")
523
+ throw new FeltKitError("FORBIDDEN", "Only a person can settle an action whose outcome is unknown.");
524
+ if (input?.outcome !== "succeeded" && input?.outcome !== "failed")
525
+ throw new FeltKitError("INVALID_ARGUMENT", 'outcome must be "succeeded" or "failed".');
526
+ const note = String(input.note ?? "").trim().slice(0, 500);
527
+ if (note.length < 3)
528
+ throw new FeltKitError("INVALID_ARGUMENT", "Say what you checked: settling an unknown outcome needs a note (the reason is recorded with your name).");
529
+ const { task } = await this.#loaded(taskId);
530
+ let head = await this.#head(taskId, actionId);
531
+ if (head.record.state !== "interrupted")
532
+ throw new FeltKitError("CONFLICT", `${actionId} is ${head.record.state}; only an interrupted action is resolved by hand.`);
533
+ const tool = this.#catalog().find((t) => t.name === head.record.capability);
534
+ const decision = await this.#runtime.authority.authorize({ access: tool?.permission[0] ?? "authenticated", principal: p, target: { name: head.record.capability }, transport: "agent" });
535
+ if (!decision.allowed)
536
+ throw new FeltKitError("FORBIDDEN", `${p.id} may not perform ${head.record.capability}, so cannot settle its outcome.`);
537
+ // Evidence first: a person's statement never overrides a recorded outcome.
538
+ const found = await this.#evidenceFor(head.record, p);
539
+ if (found) {
540
+ if (found.ok !== (input.outcome === "succeeded")) {
541
+ throw new FeltKitError("CONFLICT", `${actionId} has recorded evidence (${found.determinedBy}) that it ${found.ok ? "succeeded" : "failed"}; it cannot be settled as ${input.outcome}.`);
542
+ }
543
+ 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}`);
544
+ 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")] });
545
+ this.#activity("action.resolved", p, taskId, "success", { actionId, outcome: head.record.state, determinedBy: found.determinedBy });
546
+ return this.get(taskId, p);
547
+ }
548
+ // No evidence: an attributed decision, recorded as the person's statement, not as execution evidence.
549
+ 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}`);
550
+ 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")] });
551
+ this.#activity("action.resolved", p, taskId, "success", { actionId, outcome: input.outcome });
552
+ return this.get(taskId, p);
553
+ }
554
+ /**
555
+ * Bring every open action to a state that matches what is known, after a restart or on
556
+ * demand. Every open task (FeltDB's listTasks, paged), deterministic; it never runs an
557
+ * action:
558
+ *
559
+ * approved → proposed execution had not started; approval must be repeated
560
+ * executing → succeeded / failed from evidence (AppPort's idempotency record or the
561
+ * function's activity entry; AppPort Services' effect evidence), else
562
+ * → interrupted (outcome unknown)
563
+ * interrupted → succeeded / failed when such evidence has appeared since
564
+ */
565
+ async reconcile() {
566
+ const changes = [];
567
+ let examined = 0;
568
+ // Every open task, collected before any is changed (a checkpoint moves a task in the listing order).
569
+ const tasks = [];
570
+ for (const status of ["ready", "running", "blocked"])
571
+ tasks.push(...(await this.#tasks({ status })));
572
+ for (const task of tasks) {
573
+ const touched = [];
574
+ const evidence = [];
575
+ for (let head of await this.#heads(task.task_id)) {
576
+ const { state, actionId } = head.record;
577
+ if (!["approved", "executing", "interrupted"].includes(state))
578
+ continue;
579
+ if (this.#isRunning(task.task_id, actionId))
580
+ continue;
581
+ examined += 1;
582
+ if (state === "approved") {
583
+ head = await this.#move(head, "proposed", { decidedBy: undefined, decidedAt: undefined, executedAs: undefined }, "feltkit:recovery", "restart before execution started; the approval must be repeated");
584
+ changes.push({ taskId: task.task_id, actionId, from: state, to: "proposed", determinedBy: "not started" });
585
+ }
586
+ else {
587
+ const found = await this.#evidenceFor(head.record, await this.#resolveOwner(task));
588
+ if (found) {
589
+ head = await this.#move(head, found.ok ? "succeeded" : "failed", { finishedAt: new Date().toISOString(), outcome: { ...found } }, "feltkit:recovery", `outcome established from ${found.determinedBy}`);
590
+ changes.push({ taskId: task.task_id, actionId, from: state, to: found.ok ? "succeeded" : "failed", determinedBy: found.determinedBy });
591
+ }
592
+ else if (state === "executing") {
593
+ head = await this.#move(head, "interrupted", { interruption: "the process stopped while it was running; no evidence of its outcome" }, "feltkit:recovery", "outcome unknown after restart");
594
+ changes.push({ taskId: task.task_id, actionId, from: state, to: "interrupted", determinedBy: "no evidence" });
595
+ }
596
+ else
597
+ continue;
598
+ }
599
+ touched.push(`${actionId}: ${state} → ${head.record.state}`);
600
+ evidence.push(memoryEvidence(head.memory.memory_id, "recovery"));
601
+ }
602
+ if (touched.length) {
603
+ await this.#sync(task.task_id, task.owner, `Recovered ${touched.length} action(s) after restart.`, { decisions: touched.map((t) => `recovery: ${t}`), evidence });
604
+ }
605
+ }
606
+ return { examined, changes };
607
+ }
608
+ /** Finish a task. The summary is the owner's; evidence is what the checkpoints cite. */
609
+ async complete(taskId, summary, principal) {
610
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
611
+ const { task } = await this.#owned(taskId, p);
612
+ const open = (await this.#heads(taskId)).filter((h) => OPEN_STATES.includes(h.record.state));
613
+ if (open.length)
614
+ throw new FeltKitError("CONFLICT", `The task has open actions (${open.map((h) => `${h.record.actionId} ${h.record.state}`).join(", ")}); approve, reject, or settle them first.`);
615
+ await this.#state.checkpoint(taskId, { actor: task.owner, summary: String(summary || "Completed.").slice(0, 4000), status: "completed", pendingWork: [] });
616
+ await this.#ensureActing(taskId);
617
+ const execution = await this.#execution(taskId);
618
+ await this.#db.completeAgentExecution(execution, `agent-task:${taskId}`);
619
+ this.#activity("task.completed", p, taskId, "success", {});
620
+ return this.get(taskId, p);
621
+ }
622
+ /**
623
+ * Cancel a task. Actions not yet running are cancelled. A running action is aborted;
624
+ * since its effect may still complete, it becomes interrupted, and the task is not
625
+ * cancelled until every such action is settled (FeltDB takes no checkpoint after a
626
+ * terminal one, so settling must come first).
627
+ */
628
+ async cancel(taskId, principal, reason = "cancelled") {
629
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
630
+ const { task } = await this.#loaded(taskId);
631
+ if (p.type !== "user" && actorOf(p) !== task.owner)
632
+ throw new FeltKitError("FORBIDDEN", "Only the task owner or a person can cancel it.");
633
+ for (const controller of this.#running.get(taskId) ?? [])
634
+ controller.abort(new Error(`cancelled by ${p.id}`));
635
+ await Promise.allSettled([...(this.#inflight.get(taskId)?.values() ?? [])]);
636
+ const evidence = [];
637
+ for (const head of await this.#heads(taskId)) {
638
+ if (head.record.state === "proposed" || head.record.state === "approved") {
639
+ const cancelled = await this.#move(head, "cancelled", { decidedBy: actorOf(p), decidedAt: new Date().toISOString(), decisionNote: reason }, actorOf(p), `cancelled with the task: ${reason}`);
640
+ evidence.push(memoryEvidence(cancelled.memory.memory_id, "cancellation"));
641
+ }
642
+ }
643
+ const unknown = (await this.#heads(taskId)).filter((h) => h.record.state === "executing" || h.record.state === "interrupted");
644
+ if (unknown.length) {
645
+ await this.#sync(taskId, task.owner, `Cancellation requested by ${p.id}; ${unknown.length} action(s) have an unknown outcome and must be settled first.`, { decisions: [`cancel requested by ${actorOf(p)}: ${reason}`], evidence });
646
+ throw new FeltKitError("CONFLICT", `Settle ${unknown.map((h) => h.record.actionId).join(", ")} (outcome unknown) before cancelling the task.`);
647
+ }
648
+ await this.#state.checkpoint(taskId, { actor: task.owner, summary: `Cancelled by ${p.id}: ${reason}`.slice(0, 4000), status: "cancelled", pendingWork: [], ...(evidence.length ? { evidence } : {}) });
649
+ const execution = await this.#execution(taskId);
650
+ if (!TERMINAL_EXECUTION.includes(execution.status))
651
+ await this.#db.cancelAgentExecution(execution, `cancelled by ${actorOf(p)}: ${reason}`.slice(0, 1000));
652
+ this.#activity("task.cancelled", p, taskId, "success", { reason: reason.slice(0, 200) });
653
+ return this.get(taskId, p);
654
+ }
655
+ /** A request that does not apply to the action's current state changes nothing. */
656
+ async #unchanged(taskId, p, record, verb) {
657
+ if (verb === "approve" && ["approved", "executing", "succeeded", "failed", "interrupted"].includes(record.state)) {
658
+ // Already approved (a duplicate or a concurrent request): never run it again.
659
+ this.#activity("action.approve_ignored", p, taskId, "success", { actionId: record.actionId, state: record.state });
660
+ return this.get(taskId, p);
661
+ }
662
+ throw new FeltKitError("CONFLICT", `${record.actionId} is ${record.state}; it cannot be ${verb === "approve" ? "approved" : "rejected"}.`);
663
+ }
664
+ // ---- Handoffs to external agents ---------------------------------------------
665
+ async openHandoffs(principal) {
666
+ this.#read(principal);
667
+ const out = [];
668
+ let cursor;
669
+ do {
670
+ const page = await this.#state.listHandoffs({ open: true, limit: 200, ...(cursor ? { cursor } : {}) });
671
+ cursor = page.nextCursor;
672
+ for (const h of page.handoffs) {
673
+ const handoff = await this.#state.getHandoff(h.handoff_id);
674
+ if (handoff && handoff.status === "open" && handoff.scope?.project === this.#runtime.app.name)
675
+ out.push({ handoffId: handoff.handoff_id, taskId: handoff.task_id, objective: handoff.objective, from: handoff.from, note: handoff.note ?? null, createdAt: handoff.created_at });
676
+ }
677
+ } while (cursor);
678
+ return out;
679
+ }
680
+ /** Claim and accept a handoff: the claimant becomes the task's owner and gets its context. */
681
+ async claim(handoffId, principal) {
682
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
683
+ const actor = actorOf(p);
684
+ const claim = await this.#state.claimHandoff(handoffId, { claimant: actor });
685
+ const handoff = await this.#state.acceptHandoff(handoffId, { claimant: actor, leaseId: claim.leaseId });
686
+ await this.#state.checkpoint(handoff.task_id, { actor, summary: `Claimed by ${actor}.`, status: "running" });
687
+ await this.#transition(handoff.task_id, "Observing");
688
+ this.#activity("handoff.claimed", p, handoff.task_id, "success", { handoffId });
689
+ return { taskId: handoff.task_id, context: await this.context(handoff.task_id, p) };
690
+ }
691
+ /** A note from the owner: decisions and progress, recorded as a checkpoint. */
692
+ async note(taskId, input, principal) {
693
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
694
+ const { task } = await this.#owned(taskId, p);
695
+ await this.#state.checkpoint(taskId, {
696
+ actor: task.owner,
697
+ summary: String(input.summary ?? "").slice(0, 4000) || "Progress.",
698
+ ...(input.decisions ? { decisions: input.decisions.map((d) => String(redact(d)).slice(0, 4000)) } : {}),
699
+ ...(input.pendingWork ? { pendingWork: input.pendingWork.map((d) => String(d).slice(0, 4000)) } : {}),
700
+ });
701
+ return this.get(taskId, p);
702
+ }
703
+ // ---- Playbooks: capabilities chosen by code ----------------------------------
704
+ async #diagnoseJob(taskId, principal, jobId) {
705
+ if (!jobId)
706
+ throw new FeltKitError("INVALID_ARGUMENT", "diagnose-job needs a job id (target).");
707
+ await this.propose(taskId, { capability: "jobs.read", input: { id: jobId }, reason: `Read job ${jobId}` }, principal);
708
+ const job = await this.#lastOutput(taskId);
709
+ if (!job || typeof job !== "object")
710
+ return this.#conclude(taskId, principal, `Job ${jobId} could not be read (see the observation above).`);
711
+ const j = job;
712
+ const handler = this.#runtime.services.jobHandlers[j.type ?? ""];
713
+ const runs = (await this.#runtime.activity.list({ limit: 200 })).filter((e) => e.via === "job" && e.requestId.startsWith(`job_${jobId}:`));
714
+ const findings = [];
715
+ findings.push(`Job ${jobId} (${j.type}) is ${j.status} after ${j.attemptCount}/${j.maxAttempts} attempt(s).`);
716
+ if (!handler)
717
+ findings.push(`No handler is declared for "${j.type}": add it to services.jobs.handlers. Retrying will fail the same way.`);
718
+ else
719
+ findings.push(`Handler: ${handler}, run as ${j.principal?.principalId ?? "an unknown principal"}.`);
720
+ for (const run of runs.slice(0, 3))
721
+ findings.push(`Run ${run.requestId}: ${run.outcome}${run.error ? ` — ${run.error.code}: ${run.error.message}` : ""}.`);
722
+ if (j.lastError)
723
+ findings.push(`Last error: ${j.lastError}`);
724
+ const denied = /DENIED/.test(j.lastError ?? "");
725
+ if (denied)
726
+ findings.push(`The job was refused authorization: its enqueuer can no longer act (no active session or key). Retrying as is will be refused again.`);
727
+ await this.note(taskId, { summary: findings.join(" "), decisions: findings }, principal);
728
+ if (j.status === "failed" && handler && !denied) {
729
+ await this.propose(taskId, { capability: "jobs.retry", input: { id: jobId }, reason: `The failure (${(j.lastError ?? "unknown").slice(0, 200)}) may be transient; retry once the cause is fixed.` }, principal);
730
+ }
731
+ else {
732
+ await this.#conclude(taskId, principal, findings.join(" "));
733
+ }
734
+ }
735
+ async #diagnoseDelivery(taskId, principal, deliveryId) {
736
+ if (!deliveryId)
737
+ throw new FeltKitError("INVALID_ARGUMENT", "diagnose-delivery needs a delivery id (target).");
738
+ const services = this.#runtime.services;
739
+ if (!services.webhooks)
740
+ return this.#conclude(taskId, principal, "Webhooks are not enabled.");
741
+ // Each read is AppPort Services' own capability, invoked as the task owner.
742
+ const outcome = await this.#observeService(taskId, principal, "webhooks.deliveries.read", "webhook_delivery", { id: deliveryId });
743
+ const delivery = outcome.ok ? outcome.output : null;
744
+ if (!delivery)
745
+ return this.#conclude(taskId, principal, `Delivery ${deliveryId} could not be read${outcome.error ? `: ${outcome.error.message}` : ""}.`);
746
+ const endpoints = await this.#observeService(taskId, principal, "webhooks.read", "webhook_endpoint", { id: String(delivery.endpointId) });
747
+ const endpoint = endpoints.ok ? endpoints.output : null;
748
+ const findings = [`Delivery ${deliveryId} (${delivery.eventType}) is ${delivery.status} after ${delivery.attemptCount} attempt(s).`];
749
+ let fixable = false;
750
+ if (!endpoint)
751
+ findings.push("Its endpoint no longer exists.");
752
+ else {
753
+ findings.push(`Destination: ${new URL(endpoint.url).origin}${endpoint.disabledAt ? " (disabled)" : ""}.`);
754
+ const credential = services.credentials.describe(endpoint.signingCredentialRef ?? "");
755
+ if (!credential.present)
756
+ findings.push(`Its signing credential ${endpoint.signingCredentialRef} does not resolve: set ${credential.variable} in the environment, then replay.`);
757
+ if (delivery.lastStatusCode !== undefined)
758
+ findings.push(`Last HTTP status: ${delivery.lastStatusCode}${delivery.lastStatusCode >= 400 && delivery.lastStatusCode < 500 && delivery.lastStatusCode !== 408 && delivery.lastStatusCode !== 429 ? " (the receiver rejected it; not retried automatically)" : ""}.`);
759
+ fixable = !endpoint.disabledAt;
760
+ }
761
+ if (delivery.lastError)
762
+ findings.push(`Last error: ${delivery.lastError}`);
763
+ await this.note(taskId, { summary: findings.join(" "), decisions: findings }, principal);
764
+ if (delivery.status === "failed" && fixable) {
765
+ await this.propose(taskId, { capability: "webhooks.replay", input: { id: deliveryId }, reason: "Replay once the cause above is fixed; a replay is a new signed delivery of the same event." }, principal);
766
+ }
767
+ else
768
+ await this.#conclude(taskId, principal, findings.join(" "));
769
+ }
770
+ async #inspect(taskId, principal) {
771
+ const context = await this.applicationContext(principal);
772
+ const allowed = context.tools.filter((t) => t.allowed);
773
+ const unhealthy = context.services.filter((s) => s.state === "unhealthy");
774
+ const findings = [
775
+ `${context.application} (${context.environment}): ${context.collections.length} collection(s), ${allowed.length} of ${context.tools.length} capabilities available to ${principal.id}.`,
776
+ ...unhealthy.map((s) => `${s.id} is unhealthy: ${s.detail}`),
777
+ ...context.recentErrors.slice(0, 5).map((e) => `Recent error in ${e.name} via ${e.via}: ${e.code} ${e.message ?? ""}`.trim()),
778
+ ...(context.recentDenials.length ? [`${context.recentDenials.length} recent authorization denial(s); latest: ${context.recentDenials[0].name} for ${context.recentDenials[0].principal ?? "anonymous"}.`] : []),
779
+ ];
780
+ await this.note(taskId, { summary: findings[0], decisions: findings }, principal);
781
+ await this.#conclude(taskId, principal, findings.join(" "));
782
+ }
783
+ // ---- Decisions: the environment's model chooses among the application's candidates ----
784
+ /**
785
+ * Put the task's decision to the model again, e.g. after its configuration was fixed.
786
+ * The owner or a person may ask; the answer is a new proposal, never an execution.
787
+ */
788
+ async decide(taskId, principal) {
789
+ const p = this.#require(principal, AGENT_PERMISSIONS.write);
790
+ const { task } = await this.#loaded(taskId);
791
+ if (p.type !== "user" && actorOf(p) !== task.owner)
792
+ throw new FeltKitError("FORBIDDEN", "Only the task owner or a person can ask for a decision.");
793
+ if ((await this.#heads(taskId)).some((h) => OPEN_STATES.includes(h.record.state))) {
794
+ throw new FeltKitError("CONFLICT", "An action from this task is still open; settle it before asking for another decision.");
795
+ }
796
+ const owner = await this.#resolveOwner(task);
797
+ if (!owner)
798
+ throw new FeltKitError("FORBIDDEN", `The task owner ${task.owner} cannot be resolved (no active session or key), so nothing can be decided on their behalf.`);
799
+ await this.#decide(taskId, owner);
800
+ return this.get(taskId, p);
801
+ }
802
+ /** Start a decision task after the caller's transaction commits (ctx.agent.start). Tracked by idle(). */
803
+ startAfterCommit(input, principal) {
804
+ const work = this.createTask({ ...input, principal, playbook: "decide" })
805
+ .then(() => undefined)
806
+ .catch((error) => this.#runtime.logger.warn(`agent: could not start ${input.taskId}: ${error.message}`));
807
+ this.#background.add(work);
808
+ void work.finally(() => this.#background.delete(work));
809
+ }
810
+ /** Resolves when tasks started after commits have made their first decision. */
811
+ async idle() {
812
+ while (this.#background.size)
813
+ await Promise.all([...this.#background]);
814
+ }
815
+ async #decide(taskId, owner) {
816
+ const { task } = await this.#loaded(taskId);
817
+ const stored = (await this.#state.recallForTask(taskId, { limit: 100 })).find((m) => m.kind === DECISION_REQUEST_KIND);
818
+ if (!stored)
819
+ throw new FeltKitError("NOT_FOUND", `${taskId} has no decision to make.`);
820
+ const spec = stored.content;
821
+ const tools = await this.tools(owner);
822
+ const offered = [];
823
+ const excluded = [];
824
+ for (const option of spec.options) {
825
+ if (!option.capability) {
826
+ offered.push(option);
827
+ continue;
828
+ }
829
+ const tool = tools.find((t) => t.name === option.capability);
830
+ if (!tool)
831
+ excluded.push({ id: option.id, reason: `${option.capability} is not a capability of this application` });
832
+ else if (!tool.allowed)
833
+ excluded.push({ id: option.id, reason: `${task.owner} may not perform ${option.capability}` });
834
+ else
835
+ offered.push(option);
836
+ }
837
+ if (!offered.some((o) => o.id === ESCALATE))
838
+ offered.push({ id: ESCALATE, label: "Escalate to a person" });
839
+ const request = {
840
+ kind: "choice",
841
+ question: spec.question,
842
+ options: offered.map((o) => o.id),
843
+ context: redact({ objective: task.objective, ...(spec.context ?? {}), options: offered.map((o) => ({ id: o.id, label: o.label ?? o.id, ...(o.capability ? { capability: o.capability, effect: tools.find((t) => t.name === o.capability)?.effect } : {}) })) }),
844
+ };
845
+ const excludedNote = excluded.map((e) => `not offered: ${e.id} (${e.reason})`);
846
+ let outcome;
847
+ try {
848
+ outcome = await this.#runtime.models.decide(request);
849
+ }
850
+ catch (error) {
851
+ const problem = error?.details?.problem ?? "error";
852
+ const message = String(redact(error?.message ?? error)).slice(0, 500);
853
+ const hint = error?.hint ?? "";
854
+ await this.#state.checkpoint(taskId, {
855
+ actor: task.owner,
856
+ summary: `No decision: ${message}`,
857
+ status: "blocked",
858
+ pendingWork: [`decide by hand, or ask the model again once fixed${hint ? `: ${hint}` : ""}`],
859
+ decisions: [`model decision failed (${problem}): ${message}`, ...excludedNote],
860
+ });
861
+ await this.#settleExecution(taskId, "Waiting").catch(() => undefined);
862
+ this.#activity("decision.failed", owner, taskId, "error", { problem, message });
863
+ return;
864
+ }
865
+ const selected = offered.find((o) => o.id === outcome.result.selected);
866
+ const decided = await this.#state.remember({
867
+ taskId,
868
+ kind: DECISION_KIND,
869
+ content: {
870
+ question: spec.question,
871
+ offered: offered.map((o) => o.id),
872
+ excluded,
873
+ selected: selected.id,
874
+ result: outcome.result,
875
+ runtime: outcome.metadata,
876
+ capabilities: outcome.capabilities,
877
+ provider: outcome.provider,
878
+ source: outcome.source,
879
+ durationMs: outcome.durationMs,
880
+ decidedAt: new Date().toISOString(),
881
+ note: "A model's choice among the offered options: a proposal, not evidence that anything happened.",
882
+ },
883
+ source: { actor: task.owner },
884
+ });
885
+ const by = `${outcome.provider}${outcome.metadata.model ? `/${outcome.metadata.model}` : ""}`;
886
+ const evidence = [{ kind: "record", collection: FELTDB_AGENT_MEMORY_COLLECTION, id: decided.memory_id, description: "model decision" }];
887
+ this.#activity("decision.made", owner, taskId, "success", { selected: selected.id, provider: outcome.provider, model: outcome.metadata.model ?? null, offered: offered.length, excluded: excluded.length });
888
+ if (!selected.capability) {
889
+ await this.#state.checkpoint(taskId, {
890
+ actor: task.owner,
891
+ summary: `${by} chose "${selected.label ?? selected.id}": waiting for a person.`,
892
+ status: "blocked",
893
+ pendingWork: [`a person decides: ${selected.label ?? selected.id}`],
894
+ decisions: [`${by} chose ${selected.id}`, ...excludedNote],
895
+ evidence,
896
+ execution: { adapter: outcome.metadata.runtime, provider: outcome.provider, ...(outcome.metadata.model ? { model: outcome.metadata.model } : {}) },
897
+ });
898
+ await this.#settleExecution(taskId, "Waiting").catch(() => undefined);
899
+ return;
900
+ }
901
+ await this.#state.checkpoint(taskId, {
902
+ actor: task.owner,
903
+ summary: `${by} chose "${selected.label ?? selected.id}" (${selected.capability}).`,
904
+ decisions: [`${by} chose ${selected.id} → ${selected.capability}`, ...excludedNote],
905
+ evidence,
906
+ execution: { adapter: outcome.metadata.runtime, provider: outcome.provider, ...(outcome.metadata.model ? { model: outcome.metadata.model } : {}) },
907
+ });
908
+ await this.propose(taskId, {
909
+ capability: selected.capability,
910
+ input: selected.input ?? {},
911
+ reason: `${selected.reason ?? selected.label ?? selected.id} (chosen by ${by})`,
912
+ decision: { memoryId: decided.memory_id, runtime: outcome.metadata.runtime, provider: outcome.provider, ...(outcome.metadata.model ? { model: outcome.metadata.model } : {}) },
913
+ }, owner);
914
+ }
915
+ async #conclude(taskId, principal, summary) {
916
+ await this.complete(taskId, summary, principal);
917
+ }
918
+ // ---- Execution ---------------------------------------------------------------
919
+ /**
920
+ * Call one action as `owner`, once, through AppPort (application capabilities) or
921
+ * AppPort Services' invoke(). Consequential application calls carry the attempt's
922
+ * idempotency key, which AppPort honors for mutations: a repeat of the same attempt
923
+ * replays the stored response instead of running again.
924
+ */
925
+ async #execute(taskId, action, owner, requestId, approver) {
926
+ const started = Date.now();
927
+ const controller = new AbortController();
928
+ let aborted;
929
+ const timer = setTimeout(() => {
930
+ aborted = "timeout";
931
+ controller.abort(new Error(`timed out after ${this.#timeoutMs}ms`));
932
+ }, this.#timeoutMs);
933
+ controller.signal.addEventListener("abort", () => (aborted ??= "cancelled"), { once: true });
934
+ const running = this.#running.get(taskId) ?? new Set();
935
+ running.add(controller);
936
+ this.#running.set(taskId, running);
937
+ const attribution = { owner, ...(approver ? { approver } : {}) };
938
+ try {
939
+ let output;
940
+ const call = action.source === "application"
941
+ ? this.#runtime.appport.handleRequest({
942
+ protocol: "appport/1",
943
+ type: "request",
944
+ requestId,
945
+ capability: { name: action.capability, version: 1 },
946
+ input: action.input,
947
+ ...(action.idempotencyKey ? { idempotencyKey: action.idempotencyKey } : {}),
948
+ metadata: { transport: "agent" },
949
+ }, { principal: toAppPort(owner), transport: "agent", signal: controller.signal })
950
+ : this.#runtime.services.invoke(action.capability, action.input, owner, controller.signal, requestId);
951
+ // The call itself may not observe the signal; stop waiting for it either way.
952
+ const result = await Promise.race([call, new Promise((_, reject) => controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true }))]);
953
+ if (action.source === "application") {
954
+ const response = result;
955
+ // A claim left by an earlier run of this request: AppPort did not run it again, and its outcome is unknown.
956
+ if (!response.ok && idempotencyErrorReason(response.error) === IDEMPOTENCY_OUTCOME_UNKNOWN)
957
+ return this.#outcome(action, started, requestId, attribution, { code: "OUTCOME_UNKNOWN", message: response.error.message });
958
+ if (!response.ok)
959
+ return this.#outcome(action, started, requestId, attribution, { code: response.error.code, message: response.error.message });
960
+ output = response.output;
961
+ }
962
+ else
963
+ output = result;
964
+ return this.#outcome(action, started, requestId, attribution, undefined, output);
965
+ }
966
+ catch (error) {
967
+ const e = error;
968
+ const outcome = this.#outcome(action, started, requestId, attribution, { code: aborted ? (aborted === "timeout" ? "TIMEOUT" : "CANCELLED") : String(e.code ?? "INTERNAL"), message: String(e.message ?? error) });
969
+ return aborted ? { ...outcome, aborted } : outcome;
970
+ }
971
+ finally {
972
+ clearTimeout(timer);
973
+ running.delete(controller);
974
+ }
975
+ }
976
+ /** A service observation through AppPort Services' invoke(), authorized as the task owner by its gateway. */
977
+ async #observeService(taskId, principal, capability, type, input) {
978
+ const { task } = await this.#loaded(taskId);
979
+ const owner = await this.#ownerPrincipal(task);
980
+ const action = { actionId: `act-${randomUUID().slice(0, 16)}`, capability, source: "services", effect: "observation", input: { type, ...input }, reason: `Read ${type}`, proposedBy: actorOf(principal), proposedAt: new Date().toISOString() };
981
+ const started = Date.now();
982
+ const requestId = `agent_${randomUUID()}`;
983
+ let outcome;
984
+ try {
985
+ const output = await this.#runtime.services.invoke(capability, input, owner, undefined, requestId);
986
+ outcome = this.#outcome(action, started, requestId, { owner }, undefined, output);
987
+ }
988
+ catch (error) {
989
+ const e = error;
990
+ outcome = this.#outcome(action, started, requestId, { owner }, { code: String(e.code ?? "INTERNAL"), message: String(e.message ?? error) });
991
+ }
992
+ await this.#record(taskId, task.owner, action, outcome, `Observed ${type} under ${capability}${outcome.ok ? "" : ` (failed: ${outcome.error?.code})`}.`, []);
993
+ return outcome;
994
+ }
995
+ #outcome(action, started, requestId, by, error, output) {
996
+ const activity = this.#runtime.activity.record({
997
+ kind: "agent",
998
+ name: action.capability,
999
+ via: "agent",
1000
+ requestId,
1001
+ // The principal whose authority the action ran with; the approver is in detail.
1002
+ principal: { id: by.owner.id, type: by.owner.type, roles: by.owner.roles },
1003
+ outcome: error ? (error.code === "FORBIDDEN" || error.code === "UNAUTHORIZED" || error.code === "DENIED" ? "denied" : "error") : "success",
1004
+ durationMs: Date.now() - started,
1005
+ ...(error ? { error: { code: error.code, message: String(redact(error.message)) } } : {}),
1006
+ detail: { actionId: action.actionId, source: action.source, effect: action.effect, proposedBy: action.proposedBy, ...(by.approver ? { approvedBy: `${by.approver.type}:${by.approver.id}` } : {}) },
1007
+ });
1008
+ return {
1009
+ actionId: action.actionId,
1010
+ capability: action.capability,
1011
+ ok: !error,
1012
+ ...(error ? { error: { code: error.code, message: String(redact(error.message)) } } : { output: redact(output) }),
1013
+ ...(activity ? { activityId: activity.id } : {}),
1014
+ durationMs: Date.now() - started,
1015
+ };
1016
+ }
1017
+ /** Record an action's outcome as a checkpoint citing its activity entry (verified at commit). */
1018
+ async #record(taskId, owner, action, outcome, summary, decisions, status) {
1019
+ await this.#runtime.activity.flush();
1020
+ const evidence = outcome.activityId ? [{ kind: "record", collection: ACTIVITY, id: outcome.activityId, description: `${action.capability} ${outcome.ok ? "succeeded" : "failed"}` }] : [];
1021
+ await this.#state.checkpoint(taskId, {
1022
+ actor: owner,
1023
+ summary,
1024
+ ...(status ? { status } : {}),
1025
+ completed: [`${action.capability} → ${outcome.ok ? summarize(outcome.output) : `${outcome.error?.code}: ${outcome.error?.message}`}`.slice(0, 4000)],
1026
+ decisions,
1027
+ evidence,
1028
+ execution: { adapter: "feltkit" },
1029
+ });
1030
+ await this.#state.remember({ taskId, kind: "outcome", content: outcome, source: { actor: owner } });
1031
+ }
1032
+ async #lastOutput(taskId) {
1033
+ const memories = await this.#state.recallForTask(taskId, { limit: 50 });
1034
+ const outcome = memories.filter((m) => m.kind === "outcome").sort((a, b) => a.created_at.localeCompare(b.created_at)).at(-1);
1035
+ return outcome ? outcome.content.output ?? null : null;
1036
+ }
1037
+ async #fail(taskId, actor, error) {
1038
+ const message = String(redact(error?.message ?? error)).slice(0, 1000);
1039
+ try {
1040
+ await this.#state.checkpoint(taskId, { actor, summary: `Failed: ${message}`, status: "blocked", pendingWork: [] });
1041
+ }
1042
+ catch {
1043
+ /* the failure is still recorded on the execution below */
1044
+ }
1045
+ await this.#db.failAgentExecution(await this.#execution(taskId), message).catch(() => undefined);
1046
+ }
1047
+ // ---- FeltDB state helpers ----------------------------------------------------
1048
+ /** The current record of every consequential action on a task (one per action). */
1049
+ async #heads(taskId) {
1050
+ const memories = await this.#state.recallForTask(taskId, { limit: 100 });
1051
+ return memories
1052
+ .filter((m) => (m.kind === ACTION_KIND || m.kind === LEGACY_PROPOSAL_KIND) && m.scope.kind === "task" && m.status === "active")
1053
+ .map((m) => ({ memory: m, record: m.kind === ACTION_KIND ? m.content : legacy(m) }))
1054
+ .sort((a, b) => a.record.proposedAt.localeCompare(b.record.proposedAt));
1055
+ }
1056
+ async #head(taskId, actionId) {
1057
+ const head = (await this.#heads(taskId)).find((h) => h.record.actionId === actionId);
1058
+ if (!head)
1059
+ throw new FeltKitError("NOT_FOUND", `No action ${actionId} on ${taskId}.`);
1060
+ return head;
1061
+ }
1062
+ /**
1063
+ * One transition: supersede the head with `expectedRevision`, so a concurrent change
1064
+ * makes this fail (CONFLICT) instead of overwriting it. Invalid transitions refuse
1065
+ * before anything is written.
1066
+ */
1067
+ async #move(head, state, patch, by, note) {
1068
+ if (!TRANSITIONS[head.record.state].includes(state)) {
1069
+ throw new FeltKitError("CONFLICT", `${head.record.actionId} cannot go from ${head.record.state} to ${state}.`);
1070
+ }
1071
+ const at = new Date().toISOString();
1072
+ const seq = head.record.seq + 1;
1073
+ const record = {
1074
+ ...head.record,
1075
+ ...patch,
1076
+ state,
1077
+ seq,
1078
+ history: [...head.record.history, { state, at, by, ...(note ? { note: String(redact(note)).slice(0, 500) } : {}) }].slice(-50),
1079
+ };
1080
+ try {
1081
+ const { memory } = await this.#state.supersede(head.memory.memory_id, {
1082
+ memoryId: `${head.record.actionId}.${seq}`,
1083
+ kind: ACTION_KIND,
1084
+ content: redact(record),
1085
+ source: { actor: by },
1086
+ expectedRevision: head.memory.revision,
1087
+ });
1088
+ return { memory, record: memory.content };
1089
+ }
1090
+ catch (error) {
1091
+ const code = error.code;
1092
+ if (code === "VERSION_CONFLICT" || code === "INVALID_TRANSITION") {
1093
+ throw new FeltKitError("CONFLICT", `${head.record.actionId} changed concurrently; nothing was written.`, { cause: error });
1094
+ }
1095
+ throw error;
1096
+ }
1097
+ }
1098
+ /**
1099
+ * One checkpoint that makes the task agree with its actions: pending work is rebuilt
1100
+ * from the open actions (never carried forward), the status is blocked while a person
1101
+ * is needed, and the FeltDB execution waits or observes accordingly.
1102
+ */
1103
+ async #sync(taskId, ownerActor, summary, extra = {}) {
1104
+ const heads = await this.#heads(taskId);
1105
+ const pendingWork = heads
1106
+ .filter((h) => OPEN_STATES.includes(h.record.state))
1107
+ .map(({ record: r }) => r.state === "proposed"
1108
+ ? `approve ${r.actionId}: ${r.capability} ${summarize(r.input, 200)}`
1109
+ : r.state === "interrupted"
1110
+ ? `settle ${r.actionId}: ${r.capability} (outcome unknown: ${r.interruption ?? "interrupted"})`
1111
+ : `running ${r.actionId}: ${r.capability}`);
1112
+ const needsPerson = heads.some((h) => h.record.state === "proposed" || h.record.state === "interrupted");
1113
+ const running = heads.some((h) => h.record.state === "approved" || h.record.state === "executing");
1114
+ await this.#state.checkpoint(taskId, {
1115
+ actor: ownerActor,
1116
+ summary,
1117
+ status: needsPerson && !running ? "blocked" : "running",
1118
+ pendingWork,
1119
+ ...(extra.decisions?.length ? { decisions: extra.decisions.map((d) => String(redact(d)).slice(0, 4000)) } : {}),
1120
+ ...(extra.completed?.length ? { completed: extra.completed } : {}),
1121
+ ...(extra.evidence?.length ? { evidence: extra.evidence } : {}),
1122
+ execution: { adapter: "feltkit" },
1123
+ });
1124
+ await this.#settleExecution(taskId, running ? "Acting" : needsPerson ? "Waiting" : "Observing");
1125
+ }
1126
+ /** Move FeltDB's execution record along valid transitions to `target`. */
1127
+ async #settleExecution(taskId, target) {
1128
+ const execution = await this.#execution(taskId);
1129
+ if (TERMINAL_EXECUTION.includes(execution.status))
1130
+ return;
1131
+ const paths = {
1132
+ Observing: { Waiting: ["Waiting"], Acting: ["Deciding", "Acting"] },
1133
+ Waiting: { Observing: ["Observing"], Acting: ["Observing", "Deciding", "Acting"] },
1134
+ Deciding: { Observing: ["Acting", "Observing"], Waiting: ["Acting", "Waiting"], Acting: ["Acting"] },
1135
+ Acting: { Observing: ["Observing"], Waiting: ["Waiting"] },
1136
+ Planning: { Observing: ["Observing"], Waiting: ["Observing", "Waiting"], Acting: ["Observing", "Deciding", "Acting"] },
1137
+ Blocked: { Observing: ["Observing"], Waiting: ["Observing", "Waiting"], Acting: ["Observing", "Deciding", "Acting"] },
1138
+ };
1139
+ for (const step of paths[execution.status]?.[target] ?? [])
1140
+ await this.#db.transitionAgentExecution(execution, step);
1141
+ }
1142
+ #track(taskId, actionId, work) {
1143
+ const map = this.#inflight.get(taskId) ?? new Map();
1144
+ map.set(actionId, work);
1145
+ this.#inflight.set(taskId, map);
1146
+ void work.catch(() => undefined).finally(() => {
1147
+ if (map.get(actionId) === work)
1148
+ map.delete(actionId);
1149
+ });
1150
+ }
1151
+ #isRunning(taskId, actionId) {
1152
+ return this.#inflight.get(taskId)?.has(actionId) ?? false;
1153
+ }
1154
+ /**
1155
+ * What is known about an action that started: AppPort's idempotency record or the
1156
+ * function's activity entry (application capabilities), or AppPort Services' effect
1157
+ * evidence (service operations), all looked up by the request id recorded before the
1158
+ * call. Null when nothing shows how it ended.
1159
+ */
1160
+ async #evidenceFor(record, verifier = null) {
1161
+ if (!record.requestId)
1162
+ return null;
1163
+ if (record.source === "application") {
1164
+ // An integration call keeps its own evidence; an unknown one is verified through the
1165
+ // API's declared probe (never re-sent). Its activity entry is not evidence of failure.
1166
+ const call = await this.#runtime.integrations.call(record.requestId);
1167
+ if (call) {
1168
+ let current = call;
1169
+ if ((call.state === "unknown" || call.state === "started") && verifier) {
1170
+ current = await this.#runtime.integrations.verify(call.id, verifier).catch(() => call);
1171
+ }
1172
+ const determinedBy = current.determinedBy === "verification" ? "integration-verification" : "integration-call";
1173
+ if (current.state === "succeeded")
1174
+ return { ok: true, output: redact(current.output), determinedBy };
1175
+ if (current.state === "failed")
1176
+ return { ok: false, error: current.error ?? { code: "FAILED", message: "The integration call failed." }, determinedBy };
1177
+ return null;
1178
+ }
1179
+ // A claim without a response is AppPort saying the request started and its outcome is
1180
+ // unknown: not evidence either way.
1181
+ const stored = await this.#runtime.idempotency.findByRequestId(record.requestId);
1182
+ if (stored && !isIdempotencyClaim(stored)) {
1183
+ const r = stored.response;
1184
+ return { ok: r.ok, ...(r.ok ? { output: redact(r.output) } : { error: r.error }), determinedBy: "appport-idempotency-record" };
1185
+ }
1186
+ const entry = (await this.#runtime.activity.list({ requestId: record.requestId, limit: 10 })).find((e) => e.kind !== "agent");
1187
+ if (entry && entry.outcome === "success")
1188
+ return { ok: true, activityId: entry.id, determinedBy: "function-activity" };
1189
+ if (entry)
1190
+ return { ok: false, activityId: entry.id, error: { code: entry.error?.code ?? "ERROR", message: entry.error?.message ?? entry.outcome }, determinedBy: "function-activity" };
1191
+ return null;
1192
+ }
1193
+ const rows = (await this.#runtime.activity.serviceEvidence(record.requestId));
1194
+ if (!rows.length || rows.some((r) => r.outcome === "started"))
1195
+ return null;
1196
+ if (rows.every((r) => r.outcome === "succeeded"))
1197
+ return { ok: true, determinedBy: "service-evidence" };
1198
+ const failed = rows.find((r) => r.outcome !== "succeeded");
1199
+ return { ok: false, error: { code: failed.failureCode ?? String(failed.outcome).toUpperCase(), message: `AppPort Services recorded ${failed.outcome}` }, determinedBy: "service-evidence" };
1200
+ }
1201
+ /** The task owner as they are now, or null. Never a guess. */
1202
+ async #resolveOwner(task) {
1203
+ const [type, ...rest] = task.owner.split(":");
1204
+ const resolved = await this.#runtime.resolvePrincipal(rest.join(":"), { devUsers: true });
1205
+ return resolved && resolved.type === type ? resolved : null;
1206
+ }
1207
+ async #loaded(taskId) {
1208
+ const found = await this.#state.getTask(taskId);
1209
+ if (!found || found.task.scope?.project !== this.#runtime.app.name)
1210
+ throw new FeltKitError("NOT_FOUND", `No agent task ${taskId}.`);
1211
+ if (found.task.status === "completed" || found.task.status === "cancelled")
1212
+ throw new FeltKitError("CONFLICT", `Task ${taskId} is ${found.task.status}.`);
1213
+ return found;
1214
+ }
1215
+ /** The caller must own the task (FeltDB enforces the same on every checkpoint). */
1216
+ async #owned(taskId, principal) {
1217
+ const found = await this.#loaded(taskId);
1218
+ if (found.task.owner !== actorOf(principal))
1219
+ throw new FeltKitError("FORBIDDEN", `Task ${taskId} is owned by ${found.task.owner}.`);
1220
+ return found;
1221
+ }
1222
+ /** Actions run as the owner, with the owner's current roles. */
1223
+ async #ownerPrincipal(task) {
1224
+ const resolved = await this.#resolveOwner(task);
1225
+ if (!resolved)
1226
+ throw new FeltKitError("FORBIDDEN", `The task owner ${task.owner} can no longer be resolved (no active session or key); its actions cannot run.`);
1227
+ return resolved;
1228
+ }
1229
+ /**
1230
+ * This application's tasks, most recently updated first, through FeltDB's bounded,
1231
+ * cursor-paged listTasks. FeltKit filters by project itself rather than with
1232
+ * `listTasks({ project })`: a task last written before FeltDB 0.14.0 has no project
1233
+ * index key until its next write and would be missing from that listing. An
1234
+ * environment's instance holds one application, so the filter rarely discards anything.
1235
+ */
1236
+ async #tasks(query) {
1237
+ const out = [];
1238
+ const want = query.limit ?? Number.POSITIVE_INFINITY;
1239
+ let cursor;
1240
+ do {
1241
+ const page = await this.#state.listTasks({ ...(query.status ? { status: query.status } : {}), limit: Math.min(Math.max(want - out.length, 50), 1000), ...(cursor ? { cursor } : {}) });
1242
+ cursor = page.nextCursor;
1243
+ for (const task of page.tasks)
1244
+ if (task.scope?.project === this.#runtime.app.name && out.length < want)
1245
+ out.push(task);
1246
+ } while (cursor && out.length < want);
1247
+ return out;
1248
+ }
1249
+ /** The task's execution as recorded (for views); agentRef as its `flow://` reference. */
1250
+ async #executionRecord(task) {
1251
+ const execution = await this.#findExecution(task.task_id);
1252
+ return execution ? { ...execution, agentRef: String(execution.agentRef) } : null;
1253
+ }
1254
+ async #findExecution(taskId) {
1255
+ return (await this.#db.findAgentExecution({ taskId })) ?? (await this.#legacyExecution(taskId));
1256
+ }
1257
+ /**
1258
+ * Executions created before FeltDB 0.14.0 have no `taskId`; FeltKit linked them through
1259
+ * the input `agent-task:<taskId>`. No new execution is created that way, so the set is
1260
+ * closed: it is read from FeltDB's collection once per process, only when a task has no
1261
+ * linked execution. A legacy execution that changes again is linked (its `taskId` is set
1262
+ * before FeltDB commits the change), after which the indexed lookup finds it.
1263
+ */
1264
+ async #legacyExecution(taskId) {
1265
+ this.#legacy ??= (async () => {
1266
+ const byTask = new Map();
1267
+ for (const row of (await this.#db.collection(LEGACY_EXECUTIONS).find({}))) {
1268
+ if (row.taskId || !Array.isArray(row.inputs))
1269
+ continue;
1270
+ for (const input of row.inputs) {
1271
+ if (!String(input).startsWith("agent-task:"))
1272
+ continue;
1273
+ const task = String(input).slice("agent-task:".length);
1274
+ const createdMs = Number(row.createdMs ?? 0);
1275
+ if ((byTask.get(task)?.createdMs ?? -1) < createdMs)
1276
+ byTask.set(task, { id: String(row.id), createdMs });
1277
+ }
1278
+ }
1279
+ return new Map([...byTask].map(([task, { id }]) => [task, id]));
1280
+ })();
1281
+ const id = (await this.#legacy).get(taskId);
1282
+ const row = id ? await this.#db.collection(LEGACY_EXECUTIONS).get(id) : null;
1283
+ if (!row)
1284
+ return null;
1285
+ const { id: _id, __version: _v, ...rest } = row;
1286
+ return { ...rest, agentRef: this.#ref };
1287
+ }
1288
+ /** FeltDB's lifecycle object for a task, resumed by this process after a restart. */
1289
+ async #execution(taskId) {
1290
+ const cached = this.#executions.get(taskId);
1291
+ if (cached)
1292
+ return cached;
1293
+ const execution = await this.#findExecution(taskId);
1294
+ if (!execution)
1295
+ throw new FeltKitError("NOT_FOUND", `Task ${taskId} has no FeltDB execution record.`);
1296
+ // A legacy execution is linked to its task by the next change FeltDB commits.
1297
+ execution.taskId ??= taskId;
1298
+ // Ownership after a restart: FeltDB's resume claims it for this process and commits
1299
+ // Observing. A finished execution stays finished (FeltDB refuses to resume it).
1300
+ if (!TERMINAL_EXECUTION.includes(execution.status))
1301
+ await this.#db.resumeAgentExecution(execution, this.#db.instanceId());
1302
+ this.#executions.set(taskId, execution);
1303
+ return execution;
1304
+ }
1305
+ async #transition(taskId, status) {
1306
+ const execution = await this.#execution(taskId);
1307
+ if (execution.status === status || TERMINAL_EXECUTION.includes(execution.status))
1308
+ return;
1309
+ await this.#db.transitionAgentExecution(execution, status);
1310
+ }
1311
+ async #ensureActing(taskId) {
1312
+ const execution = await this.#execution(taskId);
1313
+ const path = {
1314
+ Waiting: ["Observing", "Deciding", "Acting"],
1315
+ Observing: ["Deciding", "Acting"],
1316
+ Deciding: ["Acting"],
1317
+ Planning: ["Observing", "Deciding", "Acting"],
1318
+ Blocked: ["Observing", "Deciding", "Acting"],
1319
+ };
1320
+ for (const step of path[execution.status] ?? [])
1321
+ await this.#db.transitionAgentExecution(execution, step);
1322
+ }
1323
+ #activity(name, principal, taskId, outcome, detail) {
1324
+ this.#runtime.activity.record({
1325
+ kind: "agent",
1326
+ name: `agent.${name}`,
1327
+ via: "agent",
1328
+ requestId: `agent_${randomUUID()}`,
1329
+ principal: { id: principal.id, type: principal.type, roles: principal.roles },
1330
+ outcome,
1331
+ durationMs: 0,
1332
+ detail: { taskId, ...detail },
1333
+ });
1334
+ }
1335
+ }
1336
+ const TERMINAL_EXECUTION = ["Completed", "Failed", "Cancelled"];
1337
+ /** A proposal recorded before the lifecycle existed, read as a proposed action. */
1338
+ function legacy(memory) {
1339
+ const content = memory.content;
1340
+ return { ...content, state: "proposed", seq: 1, attempt: 1, history: [{ state: "proposed", at: content.proposedAt, by: content.proposedBy }] };
1341
+ }
1342
+ function toAppPort(principal) {
1343
+ return { id: principal.id, type: principal.type === "agent" ? "application" : principal.type, attributes: { roles: principal.roles, feltkitType: principal.type } };
1344
+ }
1345
+ //# sourceMappingURL=agent.js.map