@feltdb/feltkit 0.3.22 → 0.3.24
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.
- package/dist/app.d.ts +17 -3
- package/dist/app.js +10 -0
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.js +4 -0
- package/dist/appboundry/build.js.map +1 -1
- package/dist/authorize.d.ts +1 -1
- package/dist/cli/deploy-appboundry.d.ts +26 -0
- package/dist/cli/deploy-appboundry.js +1 -1
- package/dist/cli/deploy-appboundry.js.map +1 -1
- package/dist/cli/main.js +17 -153
- package/dist/cli/main.js.map +1 -1
- package/dist/client/index.d.ts +83 -4
- package/dist/client/index.js +204 -10
- package/dist/client/index.js.map +1 -1
- package/dist/dashboard/assets/index-BEjtLLYq.js +15 -0
- package/dist/dashboard/index.html +1 -1
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +2 -0
- package/dist/docs.js.map +1 -1
- package/dist/index.d.ts +4 -2
- package/dist/index.js.map +1 -1
- package/dist/platform/approvals.d.ts +102 -0
- package/dist/platform/approvals.js +155 -0
- package/dist/platform/approvals.js.map +1 -0
- package/dist/platform/artifacts.d.ts +126 -0
- package/dist/platform/artifacts.js +251 -0
- package/dist/platform/artifacts.js.map +1 -0
- package/dist/platform/blobs.d.ts +25 -0
- package/dist/platform/blobs.js +78 -0
- package/dist/platform/blobs.js.map +1 -0
- package/dist/platform/diff.d.ts +23 -0
- package/dist/platform/diff.js +107 -0
- package/dist/platform/diff.js.map +1 -0
- package/dist/platform/exec.d.ts +182 -0
- package/dist/platform/exec.js +575 -0
- package/dist/platform/exec.js.map +1 -0
- package/dist/platform/managed.d.ts +43 -0
- package/dist/platform/managed.js +137 -0
- package/dist/platform/managed.js.map +1 -0
- package/dist/platform/operations.d.ts +30 -13
- package/dist/platform/operations.js +8 -17
- package/dist/platform/operations.js.map +1 -1
- package/dist/platform/permissions.d.ts +15 -0
- package/dist/platform/permissions.js +16 -0
- package/dist/platform/permissions.js.map +1 -0
- package/dist/platform/platform.d.ts +51 -0
- package/dist/platform/platform.js +105 -6
- package/dist/platform/platform.js.map +1 -1
- package/dist/platform/releases.d.ts +150 -0
- package/dist/platform/releases.js +467 -0
- package/dist/platform/releases.js.map +1 -0
- package/dist/platform/review.d.ts +10 -0
- package/dist/platform/review.js +109 -0
- package/dist/platform/review.js.map +1 -0
- package/dist/platform/server.js +7 -0
- package/dist/platform/server.js.map +1 -1
- package/dist/platform/source.d.ts +2 -0
- package/dist/platform/source.js +1 -1
- package/dist/platform/source.js.map +1 -1
- package/dist/platform/workspace-operations.d.ts +2 -0
- package/dist/platform/workspace-operations.js +605 -0
- package/dist/platform/workspace-operations.js.map +1 -0
- package/dist/platform/workspaces.d.ts +211 -0
- package/dist/platform/workspaces.js +435 -0
- package/dist/platform/workspaces.js.map +1 -0
- package/dist/react/index.d.ts +29 -1
- package/dist/react/index.js +50 -0
- package/dist/react/index.js.map +1 -1
- package/dist/runtime/activity.d.ts +1 -1
- package/dist/runtime/agent.d.ts +216 -2
- package/dist/runtime/agent.js +333 -7
- package/dist/runtime/agent.js.map +1 -1
- package/dist/runtime/approval-rules.d.ts +16 -0
- package/dist/runtime/approval-rules.js +37 -0
- package/dist/runtime/approval-rules.js.map +1 -0
- package/dist/runtime/authboundry.d.ts +53 -0
- package/dist/runtime/authboundry.js +82 -0
- package/dist/runtime/authboundry.js.map +1 -0
- package/dist/runtime/authority.d.ts +18 -1
- package/dist/runtime/authority.js +26 -1
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/browser-inference.d.ts +52 -0
- package/dist/runtime/browser-inference.js +53 -0
- package/dist/runtime/browser-inference.js.map +1 -0
- package/dist/runtime/context.d.ts +110 -0
- package/dist/runtime/decisions.d.ts +23 -0
- package/dist/runtime/decisions.js +54 -0
- package/dist/runtime/decisions.js.map +1 -1
- package/dist/runtime/generation.d.ts +94 -0
- package/dist/runtime/generation.js +295 -0
- package/dist/runtime/generation.js.map +1 -0
- package/dist/runtime/runtime.d.ts +10 -2
- package/dist/runtime/runtime.js +125 -1
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/server/admin.d.ts +9 -1
- package/dist/server/admin.js +84 -2
- package/dist/server/admin.js.map +1 -1
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.js +208 -11
- package/dist/server/index.js.map +1 -1
- package/dist/server/tenancy.js +1 -1
- package/dist/server/tenancy.js.map +1 -1
- package/dist/testing/index.d.ts +11 -0
- package/dist/testing/index.js +7 -3
- package/dist/testing/index.js.map +1 -1
- package/docs/AUTH.md +3 -2
- package/docs/EXTENSION-HOSTS.md +52 -0
- package/docs/GENERATION.md +136 -0
- package/docs/README.md +4 -2
- package/package.json +6 -8
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/dist/cli/compose.d.ts +0 -31
- package/dist/cli/compose.js +0 -274
- package/dist/cli/compose.js.map +0 -1
- package/dist/cli/create.d.ts +0 -219
- package/dist/cli/create.js +0 -1197
- package/dist/cli/create.js.map +0 -1
- package/dist/cli/domain.d.ts +0 -174
- package/dist/cli/domain.js +0 -1170
- package/dist/cli/domain.js.map +0 -1
- package/dist/cli/screens.d.ts +0 -25
- package/dist/cli/screens.js +0 -282
- package/dist/cli/screens.js.map +0 -1
- package/dist/cli/shell.d.ts +0 -7
- package/dist/cli/shell.js +0 -63
- package/dist/cli/shell.js.map +0 -1
- package/dist/composition/catalog.d.ts +0 -3
- package/dist/composition/catalog.js +0 -217
- package/dist/composition/catalog.js.map +0 -1
- package/dist/composition/contract.d.ts +0 -165
- package/dist/composition/contract.js +0 -12
- package/dist/composition/contract.js.map +0 -1
- package/dist/composition/execute.d.ts +0 -110
- package/dist/composition/execute.js +0 -350
- package/dist/composition/execute.js.map +0 -1
- package/dist/composition/generate.d.ts +0 -105
- package/dist/composition/generate.js +0 -274
- package/dist/composition/generate.js.map +0 -1
- package/dist/composition/plan.d.ts +0 -131
- package/dist/composition/plan.js +0 -558
- package/dist/composition/plan.js.map +0 -1
- package/dist/composition/profiles.d.ts +0 -20
- package/dist/composition/profiles.js +0 -81
- package/dist/composition/profiles.js.map +0 -1
- package/dist/composition/reconcile.d.ts +0 -153
- package/dist/composition/reconcile.js +0 -282
- package/dist/composition/reconcile.js.map +0 -1
- package/dist/composition/recover.d.ts +0 -89
- package/dist/composition/recover.js +0 -407
- package/dist/composition/recover.js.map +0 -1
- package/dist/composition/resolve.d.ts +0 -2
- package/dist/composition/resolve.js +0 -208
- package/dist/composition/resolve.js.map +0 -1
- package/dist/dashboard/assets/index-BrC1AtZ1.js +0 -15
package/dist/runtime/agent.js
CHANGED
|
@@ -50,6 +50,43 @@ export const AGENT_PERMISSIONS = { read: "feltkit.agent.read", write: "feltkit.a
|
|
|
50
50
|
const LEGACY_EXECUTIONS = "_flow_agent_executions";
|
|
51
51
|
const ACTIVITY = "_feltkit_activity";
|
|
52
52
|
const ACTION_TIMEOUT_MS = 30_000;
|
|
53
|
+
// One digest and canonical form for every approval (app actions and platform operations).
|
|
54
|
+
export { actionDigest, canonicalJson } from "./approval-rules.js";
|
|
55
|
+
import { actionDigest } from "./approval-rules.js";
|
|
56
|
+
/**
|
|
57
|
+
* Where a proposed input carries credential material (paths only, never values): a FeltKit or
|
|
58
|
+
* AppPort token, or a string under a key that names a secret. A proposal is stored and executed
|
|
59
|
+
* exactly as proposed, so such an input is refused rather than recorded or silently rewritten;
|
|
60
|
+
* pass a reference (a credential id or ref://) instead.
|
|
61
|
+
*/
|
|
62
|
+
export function credentialPaths(value, path = "input", depth = 0, out = []) {
|
|
63
|
+
if (depth > 12 || out.length >= 20)
|
|
64
|
+
return out;
|
|
65
|
+
if (typeof value === "string") {
|
|
66
|
+
if (/\bapp_live_[0-9a-f]{6}_[A-Za-z0-9_-]+/.test(value) || /\bfk[sa]_[A-Za-z0-9_-]{20,}/.test(value))
|
|
67
|
+
out.push(path);
|
|
68
|
+
}
|
|
69
|
+
else if (Array.isArray(value))
|
|
70
|
+
value.forEach((v, i) => credentialPaths(v, `${path}[${i}]`, depth + 1, out));
|
|
71
|
+
else if (value && typeof value === "object") {
|
|
72
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
73
|
+
if (/^(secret|plaintext|token|password|apiKey|secretHash|signingSecret|privateKey|accessToken|refreshToken|clientSecret)$/i.test(key) && typeof entry === "string" && entry.length > 0)
|
|
74
|
+
out.push(`${path}.${key}`);
|
|
75
|
+
else
|
|
76
|
+
credentialPaths(entry, `${path}.${key}`, depth + 1, out);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
const GENERATION_TRANSITIONS = {
|
|
82
|
+
requested: ["running", "failed", "cancelled", "interrupted"],
|
|
83
|
+
running: ["completed", "failed", "cancelled", "interrupted"],
|
|
84
|
+
completed: [],
|
|
85
|
+
failed: [],
|
|
86
|
+
cancelled: [],
|
|
87
|
+
interrupted: [],
|
|
88
|
+
};
|
|
89
|
+
const OPEN_GENERATION = ["requested", "running"];
|
|
53
90
|
/** Always offered: hand the task to a person instead of acting. */
|
|
54
91
|
export const ESCALATE = "escalate";
|
|
55
92
|
const DECISION_REQUEST_KIND = "decision-request";
|
|
@@ -73,7 +110,10 @@ const LEGACY_PROPOSAL_KIND = "proposal";
|
|
|
73
110
|
const memoryEvidence = (memoryId, description) => ({ kind: "record", collection: FELTDB_AGENT_MEMORY_COLLECTION, id: memoryId, description: `action record (${description})` });
|
|
74
111
|
/** Stable per attempt: a duplicate of the same attempt is the same request; a retry is not. */
|
|
75
112
|
const idempotencyKeyFor = (taskId, action) => `feltkit-agent:${taskId}:${action.actionId}:${action.attempt}`;
|
|
76
|
-
export const PLAYBOOKS = ["diagnose-job", "diagnose-delivery", "inspect-app", "invoke", "decide", "handoff"];
|
|
113
|
+
export const PLAYBOOKS = ["diagnose-job", "diagnose-delivery", "inspect-app", "invoke", "decide", "handoff", "assist"];
|
|
114
|
+
const GENERATION_KIND = "generation";
|
|
115
|
+
const GENERATION_TEXT_LIMIT = 32_000;
|
|
116
|
+
export const DEFAULT_PROPOSAL_TTL_MS = 24 * 3_600_000;
|
|
77
117
|
const actorOf = (p) => `${p.type}:${p.id}`;
|
|
78
118
|
/** Remove credential material from anything recorded or returned. */
|
|
79
119
|
export function redact(value, depth = 0) {
|
|
@@ -141,6 +181,12 @@ export class AgentHost {
|
|
|
141
181
|
#legacy = null;
|
|
142
182
|
/** taskId → controllers of actions running now, for cancellation. */
|
|
143
183
|
#running = new Map();
|
|
184
|
+
/** How long a consequential proposal can be approved (agent.proposalTtlMs; default 24 h). */
|
|
185
|
+
get #proposalTtlMs() {
|
|
186
|
+
return this.#runtime.app.options.agent?.proposalTtlMs ?? DEFAULT_PROPOSAL_TTL_MS;
|
|
187
|
+
}
|
|
188
|
+
/** Generations this process is running: recovery never marks these interrupted. */
|
|
189
|
+
#liveGenerations = new Set();
|
|
144
190
|
/** taskId → actionId → the approval running it in this process. */
|
|
145
191
|
#inflight = new Map();
|
|
146
192
|
/** Decision tasks started after a commit (ctx.agent.start), until their first decision is recorded. */
|
|
@@ -183,6 +229,7 @@ export class AgentHost {
|
|
|
183
229
|
#catalog() {
|
|
184
230
|
const manifest = this.#runtime.appport.manifest();
|
|
185
231
|
const functions = new Map(this.#runtime.functions().filter((f) => f.capability).map((f) => [f.capability.name, f]));
|
|
232
|
+
const schemas = new Map((this.#runtime.project?.functions ? [...this.#runtime.project.functions.values()] : []).filter((f) => f.capability).map((f) => [f.capability.name, f.argsSchema.toJSONSchema()]));
|
|
186
233
|
const application = (manifest.capabilities ?? [])
|
|
187
234
|
.filter((c) => !c.name.startsWith("appport."))
|
|
188
235
|
.map((c) => {
|
|
@@ -194,6 +241,7 @@ export class AgentHost {
|
|
|
194
241
|
effect: (c.effect === "observation" ? "observation" : "consequential"),
|
|
195
242
|
...(c.description ? { description: c.description } : {}),
|
|
196
243
|
...(fn?.approval ? { approval: fn.approval } : {}),
|
|
244
|
+
...(schemas.get(c.name) ? { inputSchema: schemas.get(c.name) } : {}),
|
|
197
245
|
permission: integration ? [integration.op.access] : fn && fn.access !== "public" && fn.access !== "authenticated" ? [fn.access] : [],
|
|
198
246
|
};
|
|
199
247
|
});
|
|
@@ -224,6 +272,7 @@ export class AgentHost {
|
|
|
224
272
|
allowed: decision.allowed,
|
|
225
273
|
...(decision.allowed ? { invoke: proposeOnly ? "propose" : "direct" } : {}),
|
|
226
274
|
...(tool.approval ? { approval: tool.approval } : {}),
|
|
275
|
+
...(tool.inputSchema ? { inputSchema: tool.inputSchema } : {}),
|
|
227
276
|
});
|
|
228
277
|
}
|
|
229
278
|
return out;
|
|
@@ -286,6 +335,11 @@ export class AgentHost {
|
|
|
286
335
|
await this.#state.remember({ taskId, memoryId: `${taskId}.decision-request`, kind: DECISION_REQUEST_KIND, content: decision, source: { actor } });
|
|
287
336
|
await this.#decide(taskId, principal);
|
|
288
337
|
}
|
|
338
|
+
else if (playbook === "assist") {
|
|
339
|
+
// A conversation turn: the application drives it (generations, proposals) from an action.
|
|
340
|
+
await this.#state.checkpoint(taskId, { actor, summary: `Assisting: ${objective.slice(0, 200)}`, status: "running", pendingWork: [] });
|
|
341
|
+
await this.#transition(taskId, "Waiting");
|
|
342
|
+
}
|
|
289
343
|
else if (playbook === "invoke") {
|
|
290
344
|
if (!input.capability)
|
|
291
345
|
throw new FeltKitError("INVALID_ARGUMENT", "The invoke playbook needs a capability.");
|
|
@@ -374,21 +428,49 @@ export class AgentHost {
|
|
|
374
428
|
const input = proposal.input ?? {};
|
|
375
429
|
if (!input || typeof input !== "object" || Array.isArray(input))
|
|
376
430
|
throw new FeltKitError("INVALID_ARGUMENT", "Action input must be an object.");
|
|
431
|
+
const secrets = credentialPaths(input);
|
|
432
|
+
if (secrets.length) {
|
|
433
|
+
this.#activity("action.refused", p, taskId, "denied", { capability: tool.name, reason: "credential material in the input", paths: secrets });
|
|
434
|
+
throw new FeltKitError("INVALID_ARGUMENT", `The proposed input to ${tool.name} carries credential material (${secrets.join(", ")}). A proposal is recorded and executed exactly as proposed, so it may not hold a secret; pass a reference instead.`, { details: { capability: tool.name, paths: secrets } });
|
|
435
|
+
}
|
|
436
|
+
// A model's tool call is limited to the tools it was offered (the owner's permitted capabilities):
|
|
437
|
+
// one outside them is refused now. Other proposers keep the recoverable contract: a proposal the
|
|
438
|
+
// owner may not perform is recorded and refused at approval until the owner is granted it.
|
|
439
|
+
const decision = proposal.model ? await this.#runtime.authority.authorize({ access: tool.permission[0] ?? "authenticated", principal: p, target: { name: tool.name }, transport: "agent" }) : { allowed: true };
|
|
440
|
+
if (!decision.allowed) {
|
|
441
|
+
this.#activity("action.refused", p, taskId, "denied", { capability: tool.name, reason: ("reason" in decision && decision.reason) || "not allowed" });
|
|
442
|
+
throw new FeltKitError("FORBIDDEN", `${actorOf(p)} may not perform ${tool.name}${proposal.model ? `, so the model's request for it was refused` : ""}.`, { details: { capability: tool.name } });
|
|
443
|
+
}
|
|
444
|
+
const actionId = proposal.idempotencyKey
|
|
445
|
+
? `act-${createHash("sha256").update(`${taskId}\u0000${proposal.idempotencyKey}`).digest("hex").slice(0, 20)}`
|
|
446
|
+
: `act-${randomUUID().replace(/-/g, "").slice(0, 20)}`;
|
|
447
|
+
if (proposal.idempotencyKey) {
|
|
448
|
+
// Already proposed (consequential) or already observed: the first one stands.
|
|
449
|
+
if ((await this.#heads(taskId)).some((h) => h.record.actionId === actionId))
|
|
450
|
+
return this.get(taskId, p);
|
|
451
|
+
if ((await this.#taskMemories(taskId)).some((m) => m.kind === "outcome" && m.content?.actionId === actionId))
|
|
452
|
+
return this.get(taskId, p);
|
|
453
|
+
}
|
|
377
454
|
const at = new Date().toISOString();
|
|
378
455
|
const action = {
|
|
379
|
-
actionId
|
|
456
|
+
actionId,
|
|
380
457
|
capability: tool.name,
|
|
381
458
|
source: tool.source,
|
|
382
459
|
effect: tool.effect,
|
|
383
|
-
input
|
|
460
|
+
input,
|
|
461
|
+
inputDigest: actionDigest(tool.name, input),
|
|
384
462
|
reason: String(proposal.reason ?? "").slice(0, 2000) || "(no reason given)",
|
|
385
|
-
proposedBy: actorOf(p),
|
|
463
|
+
proposedBy: proposal.model ? `model:${proposal.model.provider}/${proposal.model.model}` : actorOf(p),
|
|
386
464
|
proposedAt: at,
|
|
387
465
|
...(proposal.decision ? { decision: proposal.decision } : {}),
|
|
466
|
+
...(proposal.model ? { onBehalfOf: actorOf(p) } : {}),
|
|
467
|
+
...(proposal.model?.generation ? { generation: proposal.model.generation } : {}),
|
|
468
|
+
...(tool.effect === "consequential" ? { expiresAt: new Date(Date.parse(at) + this.#proposalTtlMs).toISOString() } : {}),
|
|
388
469
|
};
|
|
389
470
|
if (tool.effect === "observation") {
|
|
390
471
|
const owner = await this.#ownerPrincipal(task);
|
|
391
|
-
const
|
|
472
|
+
const executed = await this.#execute(taskId, { ...action, attempt: 1 }, owner, `agent_${randomUUID()}`);
|
|
473
|
+
const outcome = action.generation ? { ...executed, generation: action.generation } : executed;
|
|
392
474
|
await this.#record(taskId, task.owner, action, outcome, `Observed ${tool.name}${outcome.ok ? "" : ` (failed: ${outcome.error?.code})`}.`, []);
|
|
393
475
|
return this.get(taskId, p);
|
|
394
476
|
}
|
|
@@ -398,6 +480,216 @@ export class AgentHost {
|
|
|
398
480
|
this.#activity("action.proposed", p, taskId, "success", { capability: tool.name, actionId: action.actionId });
|
|
399
481
|
return this.get(taskId, p);
|
|
400
482
|
}
|
|
483
|
+
// ---- Conversation turns (application actions) -----------------------------------
|
|
484
|
+
/**
|
|
485
|
+
* The task for one conversation turn, owned by `principal`. Idempotent: the same key from the same
|
|
486
|
+
* owner is the same task, so a retried turn request does not open a second one.
|
|
487
|
+
*/
|
|
488
|
+
async openTask(input) {
|
|
489
|
+
const p = this.#require(input.principal, AGENT_PERMISSIONS.write);
|
|
490
|
+
const key = String(input.key ?? "");
|
|
491
|
+
if (!key || key.length > 500)
|
|
492
|
+
throw new FeltKitError("INVALID_ARGUMENT", "A turn needs a key (1-500 characters) that identifies it, e.g. the message id.");
|
|
493
|
+
const d = createHash("sha256").update(`${actorOf(p)}\u0000${key}`).digest("hex");
|
|
494
|
+
const taskId = `task-${d.slice(0, 8)}-${d.slice(8, 12)}-${d.slice(12, 16)}-${d.slice(16, 20)}-${d.slice(20, 32)}`;
|
|
495
|
+
const existing = async () => {
|
|
496
|
+
const found = await this.#state.getTask(taskId);
|
|
497
|
+
if (!found)
|
|
498
|
+
return null;
|
|
499
|
+
// Another owner's key cannot collide (the owner is in the digest); a match is this owner's own turn.
|
|
500
|
+
if (found.task.owner !== actorOf(p))
|
|
501
|
+
throw new FeltKitError("FORBIDDEN", `Task ${taskId} is owned by ${found.task.owner}.`);
|
|
502
|
+
return { taskId, created: false };
|
|
503
|
+
};
|
|
504
|
+
const before = await existing();
|
|
505
|
+
if (before)
|
|
506
|
+
return before;
|
|
507
|
+
try {
|
|
508
|
+
await this.createTask({ objective: input.objective || "Conversation turn", principal: p, playbook: "assist", taskId });
|
|
509
|
+
}
|
|
510
|
+
catch (error) {
|
|
511
|
+
// A concurrent request for the same turn created it first.
|
|
512
|
+
const after = await existing();
|
|
513
|
+
if (after)
|
|
514
|
+
return after;
|
|
515
|
+
throw error;
|
|
516
|
+
}
|
|
517
|
+
return { taskId, created: true };
|
|
518
|
+
}
|
|
519
|
+
// ---- Generations ---------------------------------------------------------------
|
|
520
|
+
//
|
|
521
|
+
// One FeltDB agent-memory chain per generation, `<taskId>.gen-<id>.<seq>`, superseded with
|
|
522
|
+
// `expectedRevision` like actions: requested → running → completed | failed | cancelled, and
|
|
523
|
+
// interrupted when the process stops while it is open (recovered at the next start).
|
|
524
|
+
/**
|
|
525
|
+
* Record that a generation is requested, before any provider is contacted, and return the handle
|
|
526
|
+
* the running process advances. Requires the task's owner.
|
|
527
|
+
*/
|
|
528
|
+
async beginGeneration(taskId, principal, input) {
|
|
529
|
+
const p = this.#require(principal, AGENT_PERMISSIONS.write);
|
|
530
|
+
const { task } = await this.#owned(taskId, p);
|
|
531
|
+
const generationId = `gen-${randomUUID().replace(/-/g, "").slice(0, 16)}`;
|
|
532
|
+
const at = new Date().toISOString();
|
|
533
|
+
const record = { generationId, taskId, state: "requested", seq: 1, requestedFor: actorOf(p), requestedAt: at, input, history: [{ state: "requested", at, by: actorOf(p) }] };
|
|
534
|
+
const memory = await this.#state.remember({ taskId, memoryId: `${taskId}.${generationId}.1`, kind: GENERATION_KIND, content: record, source: { actor: task.owner } });
|
|
535
|
+
let head = { memory, record };
|
|
536
|
+
this.#liveGenerations.add(generationId);
|
|
537
|
+
const started = Date.now();
|
|
538
|
+
const finish = async (state, patch, summary) => {
|
|
539
|
+
try {
|
|
540
|
+
head = await this.#moveGeneration(head, state, { ...patch, finishedAt: new Date().toISOString(), durationMs: Date.now() - started }, task.owner);
|
|
541
|
+
const model = head.record.model ? `${head.record.model.provider}/${head.record.model.model}${head.record.model.resolution ? ` (${head.record.model.resolution.ref} r${head.record.model.resolution.revision})` : ""}` : "no model";
|
|
542
|
+
await this.#state.checkpoint(taskId, {
|
|
543
|
+
actor: task.owner,
|
|
544
|
+
summary: `Generation ${generationId} ${state} (${model}): ${summary}`.slice(0, 1000),
|
|
545
|
+
decisions: (head.record.output?.toolCalls ?? []).map((c) => `${model} requested ${c.name}`),
|
|
546
|
+
evidence: [{ kind: "record", collection: FELTDB_AGENT_MEMORY_COLLECTION, id: head.memory.memory_id, description: `generation record (${state})` }],
|
|
547
|
+
execution: { adapter: "feltkit-generation", ...(head.record.model ? { provider: head.record.model.provider, model: head.record.model.model } : {}) },
|
|
548
|
+
});
|
|
549
|
+
this.#activity(`generation.${state}`, p, taskId, state === "completed" ? "success" : "error", { generationId, ...(head.record.model ? { provider: head.record.model.provider, model: head.record.model.model } : {}), ...(head.record.failure ? { problem: head.record.failure.problem } : {}) });
|
|
550
|
+
return head.memory.memory_id;
|
|
551
|
+
}
|
|
552
|
+
finally {
|
|
553
|
+
this.#liveGenerations.delete(generationId);
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
const output = (text, toolCalls = []) => ({ text: text.slice(0, GENERATION_TEXT_LIMIT), ...(text.length > GENERATION_TEXT_LIMIT ? { truncated: text.length } : {}), toolCalls: toolCalls.map((c) => ({ id: c.id, name: c.name, input: redact(c.input) })) });
|
|
557
|
+
return {
|
|
558
|
+
generationId,
|
|
559
|
+
taskId,
|
|
560
|
+
running: async (model) => {
|
|
561
|
+
head = await this.#moveGeneration(head, "running", { model, startedAt: new Date().toISOString() }, task.owner);
|
|
562
|
+
},
|
|
563
|
+
completed: (result) => finish("completed", { finish: result.finish, usage: result.usage, output: output(result.text, result.toolCalls) }, `${result.text.length} characters${result.toolCalls.length ? `, requested ${result.toolCalls.map((c) => c.name).join(", ")}` : ""}`),
|
|
564
|
+
cancelled: (reason, partial) => finish("cancelled", { finish: "cancelled", reason: reason.slice(0, 500), output: output(partial.text, partial.toolCalls), ...(partial.usage ? { usage: partial.usage } : {}) }, reason),
|
|
565
|
+
failed: (error, partialText) => {
|
|
566
|
+
const e = error;
|
|
567
|
+
const problem = e?.details?.problem ?? null;
|
|
568
|
+
const failure = {
|
|
569
|
+
code: e?.code ?? "INTERNAL",
|
|
570
|
+
problem,
|
|
571
|
+
message: String(redact(String(e?.message ?? error))).slice(0, 1000),
|
|
572
|
+
retryable: e?.retryable ?? (problem === "timeout" || problem === "unavailable" || problem === "resolver_unavailable"),
|
|
573
|
+
};
|
|
574
|
+
return finish("failed", { failure, ...(partialText ? { output: output(partialText) } : {}) }, `${failure.problem ?? failure.code}: ${failure.message}`);
|
|
575
|
+
},
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
async #moveGeneration(head, state, patch, by) {
|
|
579
|
+
if (!GENERATION_TRANSITIONS[head.record.state].includes(state))
|
|
580
|
+
throw new FeltKitError("CONFLICT", `${head.record.generationId} cannot go from ${head.record.state} to ${state}.`);
|
|
581
|
+
const seq = head.record.seq + 1;
|
|
582
|
+
const record = { ...head.record, ...patch, state, seq, history: [...head.record.history, { state, at: new Date().toISOString(), by }].slice(-20) };
|
|
583
|
+
try {
|
|
584
|
+
const { memory } = await this.#state.supersede(head.memory.memory_id, { memoryId: `${record.taskId}.${record.generationId}.${seq}`, kind: GENERATION_KIND, content: record, source: { actor: by }, expectedRevision: head.memory.revision });
|
|
585
|
+
return { memory, record: memory.content };
|
|
586
|
+
}
|
|
587
|
+
catch (error) {
|
|
588
|
+
const code = error.code;
|
|
589
|
+
if (code === "VERSION_CONFLICT" || code === "INVALID_TRANSITION")
|
|
590
|
+
throw new FeltKitError("CONFLICT", `${head.record.generationId} changed concurrently; nothing was written.`, { cause: error });
|
|
591
|
+
throw error;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
async #generationHeads(taskId) {
|
|
595
|
+
return (await this.#taskMemories(taskId))
|
|
596
|
+
.filter((m) => m.kind === GENERATION_KIND && m.status === "active" && m.content?.generationId)
|
|
597
|
+
.map((m) => ({ memory: m, record: m.content }))
|
|
598
|
+
.sort((a, b) => a.record.requestedAt.localeCompare(b.record.requestedAt));
|
|
599
|
+
}
|
|
600
|
+
/**
|
|
601
|
+
* The generations of a task, oldest first, each with its current record (the final one is the
|
|
602
|
+
* evidence a checkpoint cites) and the proposals and observations its tool calls led to.
|
|
603
|
+
*/
|
|
604
|
+
async generations(taskId, principal) {
|
|
605
|
+
if (principal === "admin")
|
|
606
|
+
this.#read("admin");
|
|
607
|
+
else
|
|
608
|
+
await this.#ownedOrNotFound(taskId, this.#require(principal, AGENT_PERMISSIONS.read));
|
|
609
|
+
const heads = await this.#generationHeads(taskId);
|
|
610
|
+
const actions = await this.#heads(taskId);
|
|
611
|
+
const observed = (await this.#taskMemories(taskId)).filter((m) => m.kind === "outcome").map((m) => m.content);
|
|
612
|
+
return heads.map(({ memory, record }) => ({
|
|
613
|
+
memoryId: memory.memory_id,
|
|
614
|
+
createdAt: record.requestedAt,
|
|
615
|
+
content: record,
|
|
616
|
+
actions: [
|
|
617
|
+
...actions.filter((a) => a.record.generation?.generationId === record.generationId).map((a) => ({ actionId: a.record.actionId, capability: a.record.capability, effect: a.record.effect, state: a.record.state, toolCallId: a.record.generation.toolCallId })),
|
|
618
|
+
...observed.filter((o) => o.generation?.generationId === record.generationId).map((o) => ({ actionId: o.actionId, capability: o.capability, effect: "observation", state: o.ok ? "succeeded" : "failed", toolCallId: o.generation.toolCallId })),
|
|
619
|
+
],
|
|
620
|
+
}));
|
|
621
|
+
}
|
|
622
|
+
/** A task the caller owns; another owner's task is reported as missing, so its existence is not disclosed. */
|
|
623
|
+
async #ownedOrNotFound(taskId, p) {
|
|
624
|
+
const found = await this.#state.getTask(taskId);
|
|
625
|
+
if (!found || found.task.scope?.project !== this.#runtime.app.name || found.task.owner !== actorOf(p))
|
|
626
|
+
throw new FeltKitError("NOT_FOUND", `No agent task ${taskId}.`);
|
|
627
|
+
return found;
|
|
628
|
+
}
|
|
629
|
+
/**
|
|
630
|
+
* The signed-in person's own actions: those on tasks they own, newest first. `state` filters
|
|
631
|
+
* (e.g. "proposed" for what waits for them). The app-facing view; Studio lists every task.
|
|
632
|
+
*/
|
|
633
|
+
async actionsOwnedBy(principal, filter = {}) {
|
|
634
|
+
const p = this.#require(principal, AGENT_PERMISSIONS.read);
|
|
635
|
+
const me = actorOf(p);
|
|
636
|
+
const out = [];
|
|
637
|
+
for (const task of await this.#tasks({ limit: 500 })) {
|
|
638
|
+
if (task.owner !== me)
|
|
639
|
+
continue;
|
|
640
|
+
for (const { record } of await this.#heads(task.task_id)) {
|
|
641
|
+
if (filter.state && record.state !== filter.state)
|
|
642
|
+
continue;
|
|
643
|
+
out.push({ taskId: task.task_id, objective: task.objective, action: record });
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
out.sort((a, b) => b.action.proposedAt.localeCompare(a.action.proposedAt));
|
|
647
|
+
return out.slice(0, filter.limit ?? 100);
|
|
648
|
+
}
|
|
649
|
+
/**
|
|
650
|
+
* Where a keyed proposal stands, for the application that made it: its state (proposed, or the
|
|
651
|
+
* outcome of an observation that ran) and, for an observation, its output.
|
|
652
|
+
*/
|
|
653
|
+
async proposalOutcome(taskId, idempotencyKey, principal) {
|
|
654
|
+
const p = this.#require(principal, AGENT_PERMISSIONS.read);
|
|
655
|
+
await this.#ownedOrNotFound(taskId, p);
|
|
656
|
+
const actionId = `act-${createHash("sha256").update(`${taskId}\u0000${idempotencyKey}`).digest("hex").slice(0, 20)}`;
|
|
657
|
+
const head = (await this.#heads(taskId)).find((h) => h.record.actionId === actionId);
|
|
658
|
+
if (head) {
|
|
659
|
+
const r = head.record;
|
|
660
|
+
return { taskId, actionId, capability: r.capability, effect: r.effect, state: r.state, ...(r.outcome?.ok && r.outcome.output !== undefined ? { output: r.outcome.output } : {}), ...(r.outcome && !r.outcome.ok && r.outcome.error ? { error: r.outcome.error } : {}) };
|
|
661
|
+
}
|
|
662
|
+
const observed = (await this.#taskMemories(taskId)).find((m) => m.kind === "outcome" && m.content?.actionId === actionId);
|
|
663
|
+
if (!observed)
|
|
664
|
+
throw new FeltKitError("NOT_FOUND", `No action ${actionId} on ${taskId}.`);
|
|
665
|
+
const o = observed.content;
|
|
666
|
+
return { taskId, actionId, capability: o.capability, effect: "observation", state: o.ok ? "succeeded" : "failed", ...(o.ok ? { output: o.output } : { error: o.error }) };
|
|
667
|
+
}
|
|
668
|
+
/** Every action of one of your turns: consequential ones (with their state) and observations that ran, oldest first. */
|
|
669
|
+
async turnActions(taskId, principal) {
|
|
670
|
+
const p = this.#require(principal, AGENT_PERMISSIONS.read);
|
|
671
|
+
await this.#ownedOrNotFound(taskId, p);
|
|
672
|
+
const consequential = (await this.#heads(taskId)).map(({ record: r }) => ({ taskId, actionId: r.actionId, capability: r.capability, effect: r.effect, state: r.state, ...(r.outcome?.ok && r.outcome.output !== undefined ? { output: r.outcome.output } : {}), ...(r.outcome && !r.outcome.ok && r.outcome.error ? { error: r.outcome.error } : {}), at: r.proposedAt }));
|
|
673
|
+
const observed = (await this.#taskMemories(taskId))
|
|
674
|
+
.filter((m) => m.kind === "outcome")
|
|
675
|
+
.map((m) => {
|
|
676
|
+
const o = m.content;
|
|
677
|
+
return { taskId, actionId: o.actionId, capability: o.capability, effect: "observation", state: o.ok ? "succeeded" : "failed", ...(o.ok ? { output: o.output } : { error: o.error }), at: m.created_at };
|
|
678
|
+
});
|
|
679
|
+
return [...consequential, ...observed].sort((a, b) => a.at.localeCompare(b.at));
|
|
680
|
+
}
|
|
681
|
+
/** Approve one of your own tasks' actions. The same server-side rules as approve(), plus ownership. */
|
|
682
|
+
async approveOwn(taskId, actionId, principal, reviewed) {
|
|
683
|
+
const p = this.#require(principal, AGENT_PERMISSIONS.write);
|
|
684
|
+
await this.#ownedOrNotFound(taskId, p);
|
|
685
|
+
return this.approve(taskId, actionId, p, reviewed);
|
|
686
|
+
}
|
|
687
|
+
/** Reject one of your own tasks' actions. */
|
|
688
|
+
async rejectOwn(taskId, actionId, principal, reason) {
|
|
689
|
+
const p = this.#require(principal, AGENT_PERMISSIONS.write);
|
|
690
|
+
await this.#ownedOrNotFound(taskId, p);
|
|
691
|
+
return this.reject(taskId, actionId, p, reason);
|
|
692
|
+
}
|
|
401
693
|
/**
|
|
402
694
|
* Approve a proposed action, then run it as the task owner. Everything that can refuse
|
|
403
695
|
* is checked before the proposal is consumed: the approver is a person with
|
|
@@ -405,14 +697,22 @@ export class AgentHost {
|
|
|
405
697
|
* may perform it. A refusal is recorded on the action, which stays proposed. A
|
|
406
698
|
* duplicate or concurrent approval of the same action never runs it twice.
|
|
407
699
|
*/
|
|
408
|
-
async approve(taskId, actionId, approver) {
|
|
700
|
+
async approve(taskId, actionId, approver, reviewed) {
|
|
409
701
|
const p = this.#require(approver, AGENT_PERMISSIONS.write);
|
|
410
702
|
if (p.type !== "user")
|
|
411
703
|
throw new FeltKitError("FORBIDDEN", "Only a person can approve a consequential action; agents and services cannot.");
|
|
412
704
|
const { task } = await this.#loaded(taskId);
|
|
413
705
|
const head = await this.#head(taskId, actionId);
|
|
706
|
+
// The approval is for what the person reviewed: a different operation or input is not approved.
|
|
707
|
+
if (reviewed?.inputDigest !== undefined && reviewed.inputDigest !== (head.record.inputDigest ?? actionDigest(head.record.capability, head.record.input))) {
|
|
708
|
+
throw new FeltKitError("FAILED_PRECONDITION", `The action you reviewed (${reviewed.inputDigest}) is not this proposal's operation and input; nothing was approved. Review it again.`, { details: { reviewed: reviewed.inputDigest, actual: head.record.inputDigest ?? null } });
|
|
709
|
+
}
|
|
414
710
|
if (head.record.state !== "proposed")
|
|
415
711
|
return this.#unchanged(taskId, p, head.record, "approve");
|
|
712
|
+
if (head.record.expiresAt && Date.now() > Date.parse(head.record.expiresAt)) {
|
|
713
|
+
await this.#expire(task, head).catch(() => undefined);
|
|
714
|
+
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 } });
|
|
715
|
+
}
|
|
416
716
|
const { refusal, owner } = await this.#approvalCheck(task, head.record, p);
|
|
417
717
|
if (refusal) {
|
|
418
718
|
const refused = await this.#move(head, "proposed", {}, actorOf(p), `approval refused: ${refusal}`);
|
|
@@ -432,6 +732,12 @@ export class AgentHost {
|
|
|
432
732
|
}
|
|
433
733
|
return this.#run(taskId, task.owner, approved, owner, p);
|
|
434
734
|
}
|
|
735
|
+
/** Cancel an expired proposal (it was never approved; nothing ran). Concurrent changes win. */
|
|
736
|
+
async #expire(task, head) {
|
|
737
|
+
const moved = await this.#move(head, "cancelled", { decidedBy: "feltkit:expiry", decidedAt: new Date().toISOString(), decisionNote: "expired" }, "feltkit:expiry", `expired at ${head.record.expiresAt}`);
|
|
738
|
+
await this.#sync(task.task_id, task.owner, `${head.record.capability} expired without approval.`, { decisions: [`${head.record.actionId} expired at ${head.record.expiresAt}`], evidence: [memoryEvidence(moved.memory.memory_id, "expiry")] });
|
|
739
|
+
this.#activity("action.expired", { id: "feltkit:expiry", type: "service", roles: [] }, task.task_id, "success", { actionId: head.record.actionId, capability: head.record.capability });
|
|
740
|
+
}
|
|
435
741
|
/** Why `p` may not approve `record` now (null: it may), and the resolved owner. The one rule approve() and Studio use. */
|
|
436
742
|
async #approvalCheck(task, record, p) {
|
|
437
743
|
const tool = this.#catalog().find((t) => t.name === record.capability);
|
|
@@ -603,6 +909,7 @@ export class AgentHost {
|
|
|
603
909
|
*/
|
|
604
910
|
async reconcile() {
|
|
605
911
|
const changes = [];
|
|
912
|
+
const generations = [];
|
|
606
913
|
let examined = 0;
|
|
607
914
|
// Every open task, collected before any is changed (a checkpoint moves a task in the listing order).
|
|
608
915
|
const tasks = [];
|
|
@@ -613,6 +920,11 @@ export class AgentHost {
|
|
|
613
920
|
const evidence = [];
|
|
614
921
|
for (let head of await this.#heads(task.task_id)) {
|
|
615
922
|
const { state, actionId } = head.record;
|
|
923
|
+
if (state === "proposed" && head.record.expiresAt && Date.now() > Date.parse(head.record.expiresAt)) {
|
|
924
|
+
await this.#expire(task, head).catch(() => undefined);
|
|
925
|
+
changes.push({ taskId: task.task_id, actionId, from: "proposed", to: "cancelled", determinedBy: "expired" });
|
|
926
|
+
continue;
|
|
927
|
+
}
|
|
616
928
|
if (!["approved", "executing", "interrupted"].includes(state))
|
|
617
929
|
continue;
|
|
618
930
|
if (this.#isRunning(task.task_id, actionId))
|
|
@@ -641,8 +953,17 @@ export class AgentHost {
|
|
|
641
953
|
if (touched.length) {
|
|
642
954
|
await this.#sync(task.task_id, task.owner, `Recovered ${touched.length} action(s) after restart.`, { decisions: touched.map((t) => `recovery: ${t}`), evidence });
|
|
643
955
|
}
|
|
956
|
+
// A generation open when the process stopped did not finish: it is interrupted, with what it had.
|
|
957
|
+
for (const head of await this.#generationHeads(task.task_id)) {
|
|
958
|
+
if (!OPEN_GENERATION.includes(head.record.state) || this.#liveGenerations.has(head.record.generationId))
|
|
959
|
+
continue;
|
|
960
|
+
examined += 1;
|
|
961
|
+
const moved = await this.#moveGeneration(head, "interrupted", { reason: `the process stopped while the generation was ${head.record.state}; it did not finish`, finishedAt: new Date().toISOString() }, "feltkit:recovery");
|
|
962
|
+
generations.push({ taskId: task.task_id, generationId: head.record.generationId, from: head.record.state });
|
|
963
|
+
await this.#state.checkpoint(task.task_id, { actor: task.owner, summary: `Generation ${head.record.generationId} interrupted (recovered after restart).`, evidence: [{ kind: "record", collection: FELTDB_AGENT_MEMORY_COLLECTION, id: moved.memory.memory_id, description: "generation record (interrupted)" }] });
|
|
964
|
+
}
|
|
644
965
|
}
|
|
645
|
-
return { examined, changes };
|
|
966
|
+
return { examined, changes, generations };
|
|
646
967
|
}
|
|
647
968
|
/** Finish a task. The summary is the owner's; evidence is what the checkpoints cite. */
|
|
648
969
|
async complete(taskId, summary, principal) {
|
|
@@ -982,6 +1303,11 @@ export class AgentHost {
|
|
|
982
1303
|
this.#running.set(taskId, running);
|
|
983
1304
|
const attribution = { owner, ...(approver ? { approver } : {}) };
|
|
984
1305
|
try {
|
|
1306
|
+
// What runs is what was proposed and approved: a stored input that no longer matches its
|
|
1307
|
+
// digest is refused before anything is dispatched.
|
|
1308
|
+
if (action.inputDigest && actionDigest(action.capability, action.input) !== action.inputDigest) {
|
|
1309
|
+
return this.#outcome(action, started, requestId, attribution, { code: "FAILED_PRECONDITION", message: `The input of ${action.actionId} no longer matches the digest it was proposed and approved with; it was not run.` });
|
|
1310
|
+
}
|
|
985
1311
|
let output;
|
|
986
1312
|
const dispatch = () => this.#runtime.appport.handleRequest({
|
|
987
1313
|
protocol: "appport/1",
|