@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.
- package/dist/app.d.ts +106 -10
- package/dist/app.js +51 -0
- package/dist/app.js.map +1 -1
- package/dist/cli/deploy.js +9 -0
- package/dist/cli/deploy.js.map +1 -1
- package/dist/cli/main.js +339 -2
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/skills.d.ts +39 -0
- package/dist/cli/skills.js +125 -0
- package/dist/cli/skills.js.map +1 -0
- package/dist/dashboard/assets/{index-BLnBFDJs.css → index--1Tqbv_A.css} +1 -1
- package/dist/dashboard/assets/index-D9529PVz.js +15 -0
- package/dist/dashboard/index.html +2 -2
- package/dist/errors.d.ts +5 -1
- package/dist/errors.js +3 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/runtime/activity.d.ts +21 -8
- package/dist/runtime/activity.js +17 -3
- package/dist/runtime/activity.js.map +1 -1
- package/dist/runtime/agent.d.ts +353 -0
- package/dist/runtime/agent.js +1345 -0
- package/dist/runtime/agent.js.map +1 -0
- package/dist/runtime/authority.d.ts +24 -3
- package/dist/runtime/authority.js +72 -5
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/changes.d.ts +16 -8
- package/dist/runtime/changes.js.map +1 -1
- package/dist/runtime/content.d.ts +33 -0
- package/dist/runtime/content.js +46 -0
- package/dist/runtime/content.js.map +1 -0
- package/dist/runtime/context.d.ts +26 -1
- package/dist/runtime/credentials.d.ts +174 -0
- package/dist/runtime/credentials.js +407 -0
- package/dist/runtime/credentials.js.map +1 -0
- package/dist/runtime/data.d.ts +8 -2
- package/dist/runtime/data.js +74 -9
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/decisions.d.ts +141 -0
- package/dist/runtime/decisions.js +330 -0
- package/dist/runtime/decisions.js.map +1 -0
- package/dist/runtime/environment.js +11 -0
- package/dist/runtime/environment.js.map +1 -1
- package/dist/runtime/idempotency.d.ts +37 -0
- package/dist/runtime/idempotency.js +88 -0
- package/dist/runtime/idempotency.js.map +1 -0
- package/dist/runtime/instance.d.ts +8 -3
- package/dist/runtime/instance.js +27 -4
- package/dist/runtime/instance.js.map +1 -1
- package/dist/runtime/integrations.d.ts +125 -0
- package/dist/runtime/integrations.js +429 -0
- package/dist/runtime/integrations.js.map +1 -0
- package/dist/runtime/loader.d.ts +5 -1
- package/dist/runtime/loader.js +35 -13
- package/dist/runtime/loader.js.map +1 -1
- package/dist/runtime/projects.d.ts +1 -0
- package/dist/runtime/projects.js +6 -4
- package/dist/runtime/projects.js.map +1 -1
- package/dist/runtime/readiness.d.ts +29 -0
- package/dist/runtime/readiness.js +154 -0
- package/dist/runtime/readiness.js.map +1 -0
- package/dist/runtime/runtime.d.ts +53 -1
- package/dist/runtime/runtime.js +252 -9
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/services.d.ts +205 -36
- package/dist/runtime/services.js +479 -152
- package/dist/runtime/services.js.map +1 -1
- package/dist/runtime/sessions.d.ts +7 -18
- package/dist/runtime/sessions.js +7 -5
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/server/admin.d.ts +80 -0
- package/dist/server/admin.js +677 -8
- package/dist/server/admin.js.map +1 -1
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +13 -4
- package/dist/server/index.js.map +1 -1
- package/dist/server/management.d.ts +12 -0
- package/dist/server/management.js +177 -0
- package/dist/server/management.js.map +1 -0
- package/dist/server/mcp.d.ts +202 -0
- package/dist/server/mcp.js +62 -4
- package/dist/server/mcp.js.map +1 -1
- package/dist/server/operators.d.ts +77 -0
- package/dist/server/operators.js +162 -0
- package/dist/server/operators.js.map +1 -0
- package/dist/server/project.js +17 -4
- package/dist/server/project.js.map +1 -1
- package/dist/testing/index.js +3 -2
- package/dist/testing/index.js.map +1 -1
- package/package.json +18 -11
- package/skills/.claude-plugin/marketplace.json +16 -0
- package/skills/.claude-plugin/plugin.json +24 -0
- package/skills/README.md +44 -0
- package/skills/feltkit-agent/SKILL.md +84 -0
- package/skills/feltkit-build/SKILL.md +153 -0
- package/skills/feltkit-data/SKILL.md +79 -0
- package/skills/feltkit-operations/SKILL.md +72 -0
- package/skills/feltkit-services/SKILL.md +124 -0
- package/dist/dashboard/assets/index-CxJGCspE.js +0 -15
package/dist/server/admin.js
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
2
|
import { FeltKitError } from "../errors.js";
|
|
3
3
|
import { COLLECTION_MARKERS, CollectionResolver, Reader, Writer } from "../runtime/data.js";
|
|
4
|
-
import { ACTIVITY_COLLECTION
|
|
4
|
+
import { ACTIVITY_COLLECTION } from "../runtime/activity.js";
|
|
5
5
|
import { SESSIONS_COLLECTION } from "../runtime/sessions.js";
|
|
6
6
|
import { FILE_CONTENT_COLLECTION } from "../runtime/services.js";
|
|
7
7
|
import { describeEnvironments, listProjects } from "../runtime/projects.js";
|
|
8
8
|
import { readJSON, safeEqual, sendError, sendJSON, startSSE } from "./http.js";
|
|
9
|
+
import { INTELLIGENCE_CATALOG, getIntelligenceProvider } from "@appport/services";
|
|
10
|
+
import { systemPrincipal } from "../runtime/authority.js";
|
|
11
|
+
import { credentialId, looksLikeSecret } from "../runtime/credentials.js";
|
|
12
|
+
import { assessReadiness } from "../runtime/readiness.js";
|
|
13
|
+
import { INTEGRATION_CALLS } from "../runtime/integrations.js";
|
|
14
|
+
import { OPERATOR_PERMISSIONS, authenticateOperator, checkWrite, csrfFor, newRequestId, operatorKey, requireOperator, setSessionCookie, signIn } from "./operators.js";
|
|
9
15
|
const DASHBOARD = { id: "dashboard", type: "service", roles: [] };
|
|
10
16
|
/** Platform collections the data explorer may show, read-only, with what to redact. */
|
|
11
17
|
const PLATFORM_COLLECTIONS = {
|
|
@@ -20,14 +26,27 @@ const PLATFORM_COLLECTIONS = {
|
|
|
20
26
|
notification_deliveries: { owner: "AppPort Services", description: "Notification deliveries" },
|
|
21
27
|
ConfigurationVariables: { owner: "AppPort Services", description: "Configuration variables" },
|
|
22
28
|
file_audit_events: { owner: "AppPort Services", description: "File audit trail" },
|
|
23
|
-
|
|
29
|
+
service_effect_evidence: { owner: "AppPort Services", description: "Service effect evidence" },
|
|
30
|
+
ConfigurationSecrets: { owner: "AppPort Services", description: "Credential references (credential-ref:<id>; values are never stored)" },
|
|
31
|
+
jobs: { owner: "AppPort Services", description: "Jobs, with status, attempts, and last error" },
|
|
32
|
+
job_schedules: { owner: "AppPort Services", description: "Recurring job schedules" },
|
|
33
|
+
webhook_endpoints: { owner: "AppPort Services", description: "Webhook endpoints (signing credential by reference only)" },
|
|
34
|
+
webhook_deliveries: { owner: "AppPort Services", description: "Webhook deliveries, with attempts, status codes, and last error" },
|
|
35
|
+
_flow_agent_executions: { owner: "FeltDB", description: "Agent executions (FeltDB agent runtime)" },
|
|
36
|
+
"_feltdb.AgentTask": { owner: "FeltDB", description: "Agent tasks (FeltDB agent state)" },
|
|
37
|
+
"_feltdb.AgentCheckpoint": { owner: "FeltDB", description: "Agent checkpoints with verified evidence (FeltDB agent state)" },
|
|
38
|
+
"_feltdb.AgentHandoff": { owner: "FeltDB", description: "Agent handoffs (FeltDB agent state)" },
|
|
24
39
|
[COLLECTION_MARKERS]: { owner: "FeltKit", description: "Per-collection change markers used to fence whole-collection reads" },
|
|
25
40
|
[FILE_CONTENT_COLLECTION]: { owner: "FeltKit", description: "File bytes (base64)", redact: (r) => ({ ...r, data: `<${String(r.data ?? "").length} base64 chars>` }) },
|
|
41
|
+
[INTEGRATION_CALLS]: { owner: "FeltKit", description: "Integration calls: recorded before and after each request, with verification evidence (credentials are never stored)" },
|
|
26
42
|
};
|
|
27
43
|
export async function handleAdmin(ctx, request, response, path, url) {
|
|
28
44
|
const { runtime } = ctx;
|
|
29
45
|
const production = runtime.environment.production;
|
|
30
46
|
try {
|
|
47
|
+
// Production: verified operators only. The admin token, `as`, and dev identities carry no authority here.
|
|
48
|
+
if (production)
|
|
49
|
+
return await handleProduction(ctx, request, response, path, url);
|
|
31
50
|
const token = request.headers["x-feltkit-admin"];
|
|
32
51
|
if (typeof token !== "string" || !safeEqual(token, ctx.adminToken)) {
|
|
33
52
|
throw new FeltKitError("UNAUTHORIZED", "The admin API needs the environment's admin token.", {
|
|
@@ -195,9 +214,181 @@ export async function handleAdmin(ctx, request, response, path, url) {
|
|
|
195
214
|
await runtime.sessions.delete(session.id);
|
|
196
215
|
}
|
|
197
216
|
}
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
217
|
+
// Configuration transfer (`feltkit config export|import` against a running development
|
|
218
|
+
// server): AppPort Services' own export/import, as FeltKit's host-only transfer principal.
|
|
219
|
+
if (method === "GET" && segments[0] === "configuration" && segments[1] === "export") {
|
|
220
|
+
return sendJSON(response, 200, await runtime.services.exportConfiguration());
|
|
221
|
+
}
|
|
222
|
+
if (method === "POST" && segments[0] === "configuration" && segments[1] === "import") {
|
|
223
|
+
const body = await readJSON(request);
|
|
224
|
+
return sendJSON(response, 200, await runtime.services.importConfiguration(body.document, { dryRun: body.dryRun === true, overwrite: body.overwrite === true }));
|
|
225
|
+
}
|
|
226
|
+
if (method === "GET" && segments[0] === "services" && segments.length === 1) {
|
|
227
|
+
return sendJSON(response, 200, {
|
|
228
|
+
services: await runtime.services.status(runtime.state === "ready"),
|
|
229
|
+
console: ctx.console ? { url: ctx.console.url } : { url: null, reason: production ? "The services console is not served in production." : "The services console is not running." },
|
|
230
|
+
credentials: await credentialReport(runtime),
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
// A one-time sign-in link to the AppPort Services console, as a declared dev identity.
|
|
234
|
+
if (method === "POST" && segments[0] === "services" && segments[1] === "console") {
|
|
235
|
+
if (production || !ctx.console)
|
|
236
|
+
throw new FeltKitError("NOT_FOUND", "The services console is development-only.");
|
|
237
|
+
const body = await readJSON(request);
|
|
238
|
+
const principal = identityFor(runtime, body.as);
|
|
239
|
+
if (!principal)
|
|
240
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity to open the services console as; service operations are authorized as that identity.");
|
|
241
|
+
return sendJSON(response, 200, { url: await ctx.console.ticket(principal, typeof body.page === "string" ? body.page : "/services") });
|
|
242
|
+
}
|
|
243
|
+
// Execution and delivery history, from the services' own records.
|
|
244
|
+
if (method === "GET" && segments[0] === "services" && segments[1] === "jobs" && segments.length === 2) {
|
|
245
|
+
const jobs = runtime.services.jobs;
|
|
246
|
+
if (!jobs)
|
|
247
|
+
return sendJSON(response, 200, { items: [], enabled: false });
|
|
248
|
+
const items = (await jobs.listJobs(runtime.app.name)).map(jobView).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
249
|
+
return sendJSON(response, 200, { items, enabled: true, handlers: runtime.services.jobHandlers });
|
|
250
|
+
}
|
|
251
|
+
if (method === "GET" && segments[0] === "services" && segments[1] === "deliveries" && segments.length === 2) {
|
|
252
|
+
const hooks = runtime.services.webhooks;
|
|
253
|
+
if (!hooks)
|
|
254
|
+
return sendJSON(response, 200, { items: [], enabled: false });
|
|
255
|
+
const endpoints = new Map((await hooks.listWebhookEndpoints(runtime.app.name)).map((e) => [e.id, e]));
|
|
256
|
+
const items = (await hooks.listWebhookDeliveries(runtime.app.name, undefined, 200)).map((d) => deliveryView(d, endpoints.get(d.endpointId))).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
257
|
+
return sendJSON(response, 200, { items, enabled: true });
|
|
258
|
+
}
|
|
259
|
+
// Retry a job / replay a delivery as a declared dev identity, through the service.
|
|
260
|
+
if (method === "POST" && segments[0] === "services" && (segments[1] === "jobs" || segments[1] === "deliveries") && segments[3] && segments.length === 4) {
|
|
261
|
+
if (production)
|
|
262
|
+
throw new FeltKitError("FORBIDDEN", "Production is read-only from the dashboard.");
|
|
263
|
+
const body = await readJSON(request);
|
|
264
|
+
const principal = identityFor(runtime, body.as);
|
|
265
|
+
if (!principal)
|
|
266
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity; the retry is authorized as that identity.");
|
|
267
|
+
if (segments[1] === "jobs" && segments[3] === "retry")
|
|
268
|
+
await requireRetryable(runtime, segments[2]);
|
|
269
|
+
const result = await runtime.services.asPrincipal(principal, async (verified) => {
|
|
270
|
+
if (segments[1] === "jobs" && segments[3] === "retry") {
|
|
271
|
+
const job = await runtime.services.jobs?.retry(runtime.app.name, segments[2], verified);
|
|
272
|
+
return job ? jobView(job) : null;
|
|
273
|
+
}
|
|
274
|
+
if (segments[1] === "deliveries" && segments[3] === "replay") {
|
|
275
|
+
const delivery = await runtime.services.webhooks?.replayWebhookDelivery(runtime.app.name, segments[2], verified);
|
|
276
|
+
return delivery ? deliveryView(delivery, undefined) : null;
|
|
277
|
+
}
|
|
278
|
+
throw new FeltKitError("NOT_FOUND", `No action ${segments[3]}.`);
|
|
279
|
+
});
|
|
280
|
+
if (!result)
|
|
281
|
+
throw new FeltKitError("NOT_FOUND", "Nothing to retry: it does not exist, or it is not in a failed state.");
|
|
282
|
+
runtime.activity.record({ kind: "service", name: `${segments[1]}.${segments[3]}`, via: "dashboard", requestId: `req_${randomUUID()}`, principal: { id: principal.id, type: principal.type, roles: principal.roles }, outcome: "success", durationMs: 0, detail: { id: segments[2] } });
|
|
283
|
+
return sendJSON(response, 200, { item: result });
|
|
284
|
+
}
|
|
285
|
+
if (method === "POST" && segments[0] === "services" && segments[1] === "run" && segments.length === 2) {
|
|
286
|
+
if (production)
|
|
287
|
+
throw new FeltKitError("FORBIDDEN", "Production is read-only from the dashboard.");
|
|
288
|
+
return sendJSON(response, 200, await runtime.runServices());
|
|
289
|
+
}
|
|
290
|
+
// Models, integrations, readiness: the path from a local app to production.
|
|
291
|
+
if (method === "GET" && segments[0] === "readiness" && segments.length === 1) {
|
|
292
|
+
return sendJSON(response, 200, await assessReadiness(runtime, { projectDir: ctx.projectDir, dashboard: true }));
|
|
293
|
+
}
|
|
294
|
+
if (segments[0] === "models" && segments.length === 1 && method === "GET")
|
|
295
|
+
return sendJSON(response, 200, await modelsView(runtime));
|
|
296
|
+
if (segments[0] === "models" && segments.length === 1 && method === "POST") {
|
|
297
|
+
// Development: the local developer (holder of the admin token) selects the model for this
|
|
298
|
+
// environment. Studio sends `as` (a declared dev user): the key and the selection are then
|
|
299
|
+
// authorized as that identity (credential.store, intelligence.write).
|
|
300
|
+
requireDevelopment("Changing the model from Studio");
|
|
301
|
+
const body = await readJSON(request);
|
|
302
|
+
const principal = body.as !== undefined ? identityFor(runtime, body.as) : undefined;
|
|
303
|
+
if (body.as !== undefined && !principal)
|
|
304
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity; the model and its key are saved as that identity.");
|
|
305
|
+
const stored = await selectModel(runtime, body, { ...(principal ? { principal } : {}), via: "dashboard" });
|
|
306
|
+
return sendJSON(response, 200, { ...(await modelsView(runtime)), ...(stored ? { stored } : {}) });
|
|
307
|
+
}
|
|
308
|
+
if (method === "POST" && segments[0] === "models" && segments[1] === "test" && segments.length === 2)
|
|
309
|
+
return sendJSON(response, 200, await testModel(runtime));
|
|
310
|
+
if (method === "GET" && segments[0] === "integrations" && segments.length === 1)
|
|
311
|
+
return sendJSON(response, 200, await integrationsView(runtime));
|
|
312
|
+
if (method === "POST" && segments[0] === "integrations" && segments[2] === "check" && segments.length === 3)
|
|
313
|
+
return sendJSON(response, 200, await runtime.integrations.check(segments[1]));
|
|
314
|
+
// Credentials: references, where each value is kept, and a write path that never echoes it.
|
|
315
|
+
if (method === "GET" && segments[0] === "credentials" && segments.length === 1)
|
|
316
|
+
return sendJSON(response, 200, await credentialsView(runtime));
|
|
317
|
+
if (method === "POST" && segments[0] === "credentials" && segments.length === 1) {
|
|
318
|
+
const body = await readJSON(request);
|
|
319
|
+
// `as` (Studio): authorized as that dev identity. No `as` (the CLI on this host): FeltKit's host custody principal.
|
|
320
|
+
const principal = body.as !== undefined ? identityFor(runtime, body.as) : HOST_CUSTODY;
|
|
321
|
+
if (!principal)
|
|
322
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity; the key is stored as that identity.");
|
|
323
|
+
const stored = await storeCredential(runtime, { ref: body.ref, value: body.value, provider: body.provider }, principal, "dashboard");
|
|
324
|
+
return sendJSON(response, 200, { stored, ...(await credentialsView(runtime)) });
|
|
325
|
+
}
|
|
326
|
+
if (method === "DELETE" && segments[0] === "credentials" && segments[1] && segments.length === 2) {
|
|
327
|
+
const principal = identityFor(runtime, url.searchParams.get("as") ?? undefined) ?? HOST_CUSTODY;
|
|
328
|
+
await removeCredential(runtime, segments[1], principal, "dashboard");
|
|
329
|
+
return sendJSON(response, 200, await credentialsView(runtime));
|
|
330
|
+
}
|
|
331
|
+
if (method === "POST" && segments[0] === "integrations" && segments[1] === "calls" && segments[3] === "verify" && segments.length === 4) {
|
|
332
|
+
const body = await readJSON(request);
|
|
333
|
+
const principal = identityFor(runtime, body.as);
|
|
334
|
+
if (!principal)
|
|
335
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity; verification reads the API as that identity.");
|
|
336
|
+
return sendJSON(response, 200, { call: await runtime.integrations.verify(segments[2], principal) });
|
|
337
|
+
}
|
|
338
|
+
// The FeltKit agent. Reads with the admin token; every action as a declared dev identity.
|
|
339
|
+
if (segments[0] === "agent") {
|
|
340
|
+
const agent = runtime.agent;
|
|
341
|
+
if (method === "GET" && segments.length === 1) {
|
|
342
|
+
const as = url.searchParams.get("as");
|
|
343
|
+
const principal = as ? identityFor(runtime, as) : null;
|
|
344
|
+
return sendJSON(response, 200, {
|
|
345
|
+
tasks: await agent.list("admin"),
|
|
346
|
+
handoffs: await agent.openHandoffs("admin"),
|
|
347
|
+
tools: principal ? await agent.tools(principal) : [],
|
|
348
|
+
permissions: { read: "feltkit.agent.read", write: "feltkit.agent.write" },
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
if (method === "GET" && segments[1] === "tasks" && segments[2] && segments.length === 3) {
|
|
352
|
+
return sendJSON(response, 200, await agent.get(segments[2], "admin"));
|
|
353
|
+
}
|
|
354
|
+
if (method === "POST") {
|
|
355
|
+
if (production)
|
|
356
|
+
throw new FeltKitError("FORBIDDEN", "Production is read-only from the dashboard.");
|
|
357
|
+
const body = await readJSON(request);
|
|
358
|
+
const principal = identityFor(runtime, body.as);
|
|
359
|
+
if (segments[1] === "tasks" && segments.length === 2) {
|
|
360
|
+
return sendJSON(response, 200, await agent.createTask({
|
|
361
|
+
objective: String(body.objective ?? ""),
|
|
362
|
+
principal,
|
|
363
|
+
...(typeof body.playbook === "string" ? { playbook: body.playbook } : {}),
|
|
364
|
+
...(typeof body.target === "string" ? { target: body.target } : {}),
|
|
365
|
+
...(typeof body.capability === "string" ? { capability: body.capability } : {}),
|
|
366
|
+
...(body.args && typeof body.args === "object" ? { args: body.args } : {}),
|
|
367
|
+
}));
|
|
368
|
+
}
|
|
369
|
+
const taskId = segments[2];
|
|
370
|
+
if (segments[1] === "tasks" && taskId && segments.length === 4) {
|
|
371
|
+
switch (segments[3]) {
|
|
372
|
+
case "approve":
|
|
373
|
+
return sendJSON(response, 200, await agent.approve(taskId, String(body.actionId ?? ""), principal));
|
|
374
|
+
case "reject":
|
|
375
|
+
return sendJSON(response, 200, await agent.reject(taskId, String(body.actionId ?? ""), principal, typeof body.reason === "string" ? body.reason : undefined));
|
|
376
|
+
case "retry":
|
|
377
|
+
return sendJSON(response, 200, await agent.retry(taskId, String(body.actionId ?? ""), principal));
|
|
378
|
+
case "resolve":
|
|
379
|
+
return sendJSON(response, 200, await agent.resolve(taskId, String(body.actionId ?? ""), { outcome: body.outcome, ...(typeof body.note === "string" ? { note: body.note } : {}) }, principal));
|
|
380
|
+
case "propose":
|
|
381
|
+
return sendJSON(response, 200, await agent.propose(taskId, { capability: String(body.capability ?? ""), input: (body.input ?? {}), reason: String(body.reason ?? "") }, principal));
|
|
382
|
+
case "complete":
|
|
383
|
+
return sendJSON(response, 200, await agent.complete(taskId, String(body.summary ?? ""), principal));
|
|
384
|
+
case "cancel":
|
|
385
|
+
return sendJSON(response, 200, await agent.cancel(taskId, principal, typeof body.reason === "string" ? body.reason : undefined));
|
|
386
|
+
case "decide":
|
|
387
|
+
return sendJSON(response, 200, await agent.decide(taskId, principal));
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
throw new FeltKitError("NOT_FOUND", `No agent endpoint ${method} /${segments.join("/")}.`);
|
|
201
392
|
}
|
|
202
393
|
// Activity
|
|
203
394
|
if (method === "GET" && segments[0] === "activity" && segments.length === 1) {
|
|
@@ -214,7 +405,8 @@ export async function handleAdmin(ctx, request, response, path, url) {
|
|
|
214
405
|
const entry = await runtime.activity.get(segments[1]);
|
|
215
406
|
if (!entry)
|
|
216
407
|
throw new FeltKitError("NOT_FOUND", "No such activity entry.");
|
|
217
|
-
|
|
408
|
+
const lookup = await runtime.activity.serviceEvidenceLookup(entry.requestId);
|
|
409
|
+
return sendJSON(response, 200, { entry, serviceEvidence: lookup.records, serviceEvidenceState: lookup.state, serviceEvidenceTruncated: lookup.truncated });
|
|
218
410
|
}
|
|
219
411
|
// Sessions (agents, service accounts)
|
|
220
412
|
if (segments[0] === "sessions") {
|
|
@@ -260,7 +452,6 @@ export async function handleAdmin(ctx, request, response, path, url) {
|
|
|
260
452
|
}
|
|
261
453
|
/** Everything the Overview screen and `feltkit inspect` show. Never includes credentials. */
|
|
262
454
|
export async function overviewPayload(runtime) {
|
|
263
|
-
await runtime.services.check();
|
|
264
455
|
const counts = {};
|
|
265
456
|
const raw = runtime.instance.handle("feltkit.admin");
|
|
266
457
|
for (const name of runtime.app.collections.keys())
|
|
@@ -271,12 +462,14 @@ export async function overviewPayload(runtime) {
|
|
|
271
462
|
return {
|
|
272
463
|
...runtime.overview(),
|
|
273
464
|
counts,
|
|
274
|
-
services: runtime.services.status(runtime.state === "ready"),
|
|
465
|
+
services: await runtime.services.status(runtime.state === "ready"),
|
|
466
|
+
agent: await agentSummary(runtime),
|
|
275
467
|
capabilities: capabilitySummary(runtime, await runtime.activity.list({ kind: "capability", limit: 200 })),
|
|
276
468
|
recentActivity: recent,
|
|
277
469
|
recentErrors: errors,
|
|
278
470
|
recentDenials: denied,
|
|
279
471
|
devUsers: runtime.environment.development ? runtime.app.options.dev?.users ?? [] : [],
|
|
472
|
+
path: await pathToProduction(runtime),
|
|
280
473
|
};
|
|
281
474
|
}
|
|
282
475
|
function coerce(value) {
|
|
@@ -289,6 +482,482 @@ function coerce(value) {
|
|
|
289
482
|
return value;
|
|
290
483
|
}
|
|
291
484
|
/** Resolve the identity the dashboard should act as. Only declared dev users, or anonymous. */
|
|
485
|
+
async function agentSummary(runtime) {
|
|
486
|
+
if (!runtime.agent)
|
|
487
|
+
return { tasks: [], waiting: 0, handoffs: 0 };
|
|
488
|
+
const tasks = await runtime.agent.list("admin", 5);
|
|
489
|
+
return {
|
|
490
|
+
tasks: tasks.map((t) => ({ id: t.task.task_id, objective: t.task.objective, status: t.task.status, pending: t.pending })),
|
|
491
|
+
waiting: (await runtime.agent.list("admin", 200)).reduce((n, t) => n + t.pending, 0),
|
|
492
|
+
handoffs: (await runtime.agent.openHandoffs("admin")).length,
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
/** Every credential reference the services hold, and whether it resolves. Never a value. */
|
|
496
|
+
const credentialReport = (runtime) => credentialInventory(runtime);
|
|
497
|
+
/** FeltKit's host principal for storing a value from the CLI on this host (`feltkit credential set`). */
|
|
498
|
+
export const HOST_CUSTODY = systemPrincipal("credential-custody", "custody");
|
|
499
|
+
/**
|
|
500
|
+
* Every credential reference this environment knows of — service bindings and webhook
|
|
501
|
+
* signing, the model, integrations, and values already stored — with where its value is
|
|
502
|
+
* kept and its version. Never a value.
|
|
503
|
+
*/
|
|
504
|
+
export async function credentialInventory(runtime) {
|
|
505
|
+
const refs = new Map();
|
|
506
|
+
const add = (ref, usedBy) => {
|
|
507
|
+
if (!ref)
|
|
508
|
+
return;
|
|
509
|
+
const list = refs.get(ref) ?? [];
|
|
510
|
+
if (usedBy && !list.includes(usedBy))
|
|
511
|
+
list.push(usedBy);
|
|
512
|
+
refs.set(ref, list);
|
|
513
|
+
};
|
|
514
|
+
for (const r of await runtime.services.credentialReferences())
|
|
515
|
+
for (const u of r.usedBy)
|
|
516
|
+
add(r.ref, u);
|
|
517
|
+
const model = await runtime.models.status();
|
|
518
|
+
if (model.credential.ref)
|
|
519
|
+
add(model.credential.ref, `model ${model.provider}`);
|
|
520
|
+
for (const integration of runtime.integrations.definitions()) {
|
|
521
|
+
const s = runtime.integrations.status(integration);
|
|
522
|
+
if (s.credential?.ref)
|
|
523
|
+
add(s.credential.ref, `integration ${integration.name}`);
|
|
524
|
+
}
|
|
525
|
+
for (const ref of runtime.credentials.stored())
|
|
526
|
+
add(ref);
|
|
527
|
+
return [...refs].map(([ref, usedBy]) => ({ ...runtime.credentials.describe(ref), usedBy }));
|
|
528
|
+
}
|
|
529
|
+
async function credentialsView(runtime) {
|
|
530
|
+
return {
|
|
531
|
+
custody: {
|
|
532
|
+
writable: runtime.credentials.writable,
|
|
533
|
+
location: runtime.credentials.location,
|
|
534
|
+
environment: runtime.environment.name,
|
|
535
|
+
note: runtime.credentials.writable
|
|
536
|
+
? "Values are kept outside FeltDB, encrypted. An environment variable FELTKIT_CREDENTIAL_<ID> overrides a stored value."
|
|
537
|
+
: "Values come from the host's environment (FELTKIT_CREDENTIAL_<ID>). Storing them here needs the production vault opt-in (FELTKIT_CREDENTIAL_VAULT=1 with FELTKIT_CREDENTIAL_VAULT_KEY).",
|
|
538
|
+
},
|
|
539
|
+
credentials: await credentialInventory(runtime),
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Store a credential value through AppPort Services' credential.store, as `principal`.
|
|
544
|
+
* Recorded as activity with the reference and version only. Returns no value.
|
|
545
|
+
*/
|
|
546
|
+
export async function storeCredential(runtime, input, principal, via) {
|
|
547
|
+
const raw = typeof input.ref === "string" ? input.ref.trim() : "";
|
|
548
|
+
if (raw && looksLikeSecret(raw))
|
|
549
|
+
throw new FeltKitError("INVALID_ARGUMENT", "The reference field holds what looks like an API key; it was not stored or kept. Put the key in the value field and use a reference such as credential-ref:<provider>.");
|
|
550
|
+
const id = credentialId(raw);
|
|
551
|
+
if (!id)
|
|
552
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Name the credential: credential-ref:<id> (letters, digits, . _ : -).");
|
|
553
|
+
const ref = `credential-ref:${id}`;
|
|
554
|
+
if (typeof input.value !== "string" || !input.value.trim())
|
|
555
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Enter the value to store.");
|
|
556
|
+
const requestId = newRequestId();
|
|
557
|
+
const started = Date.now();
|
|
558
|
+
const who = { id: principal.id, type: principal.type, roles: principal.roles };
|
|
559
|
+
try {
|
|
560
|
+
const result = await runtime.services.storeCredential({ ref, value: input.value, ...(typeof input.provider === "string" && input.provider ? { provider: input.provider } : {}) }, principal, requestId);
|
|
561
|
+
const described = runtime.credentials.describe(ref);
|
|
562
|
+
runtime.activity.record({ kind: "service", name: "credential.store", via, requestId, principal: who, outcome: "success", durationMs: Date.now() - started, detail: { ref, version: result.version, location: described.location } });
|
|
563
|
+
void runtime.changes.check();
|
|
564
|
+
return { ref, version: result.version, storedAt: result.storedAt, location: described.location };
|
|
565
|
+
}
|
|
566
|
+
catch (error) {
|
|
567
|
+
const denied = isDenied(error);
|
|
568
|
+
runtime.activity.record({ kind: "service", name: "credential.store", via, requestId, principal: who, outcome: denied ? "denied" : "error", durationMs: Date.now() - started, error: { code: denied ? "FORBIDDEN" : (error.code ?? "INTERNAL"), message: error.message }, detail: { ref } });
|
|
569
|
+
if (denied)
|
|
570
|
+
throw new FeltKitError("FORBIDDEN", `${principal.id} may not store credentials (credential.store).`, { hint: "Store it as a dev user whose role grants credential.store (the starter's admin role), or with `feltkit credential set` on this host." });
|
|
571
|
+
throw error;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Remove a stored value. AppPort Services 0.8.0 defines custody removal (`SecretCustody.remove`)
|
|
576
|
+
* but no capability for it, so FeltKit authorizes it with the same permission as storing
|
|
577
|
+
* (credential.store, through the application's policy) and records it as activity.
|
|
578
|
+
*/
|
|
579
|
+
export async function removeCredential(runtime, refInput, principal, via) {
|
|
580
|
+
const id = credentialId(refInput);
|
|
581
|
+
if (!id)
|
|
582
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Name the credential: credential-ref:<id>.");
|
|
583
|
+
const ref = `credential-ref:${id}`;
|
|
584
|
+
const requestId = newRequestId();
|
|
585
|
+
const who = { id: principal.id, type: principal.type, roles: principal.roles };
|
|
586
|
+
if (principal !== HOST_CUSTODY) {
|
|
587
|
+
const decision = await runtime.authority.authorize({ access: "credential.store", principal, target: { name: "credential.remove" }, transport: via, requestId });
|
|
588
|
+
if (!decision.allowed) {
|
|
589
|
+
runtime.activity.record({ kind: "service", name: "credential.remove", via, requestId, principal: who, outcome: "denied", durationMs: 0, error: { code: "FORBIDDEN", message: decision.reason ?? "denied" }, detail: { ref } });
|
|
590
|
+
throw new FeltKitError("FORBIDDEN", `${principal.id} may not remove credentials (credential.store).`);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
try {
|
|
594
|
+
await runtime.credentials.remove({ reference: { secretId: id }, context: { principalId: principal.id, purpose: "credential.remove" } });
|
|
595
|
+
}
|
|
596
|
+
catch (error) {
|
|
597
|
+
const code = error.code;
|
|
598
|
+
if (code === "CUSTODY_READ_ONLY")
|
|
599
|
+
throw new FeltKitError("CUSTODY_READ_ONLY", error.message);
|
|
600
|
+
throw new FeltKitError("INVALID_ARGUMENT", error.message);
|
|
601
|
+
}
|
|
602
|
+
runtime.activity.record({ kind: "service", name: "credential.remove", via, requestId, principal: who, outcome: "success", durationMs: 0, detail: { ref } });
|
|
603
|
+
void runtime.changes.check();
|
|
604
|
+
}
|
|
605
|
+
/** Only a failed job whose handler is registered is retried: AppPort Services resets a job in any state. */
|
|
606
|
+
async function requireRetryable(runtime, jobId) {
|
|
607
|
+
const job = await runtime.services.jobs?.getJob(runtime.app.name, jobId);
|
|
608
|
+
if (!job)
|
|
609
|
+
throw new FeltKitError("NOT_FOUND", "No such job.");
|
|
610
|
+
if (job.status !== "failed")
|
|
611
|
+
throw new FeltKitError("CONFLICT", `The job is ${job.status}; only a failed job can be retried. Nothing was changed.`);
|
|
612
|
+
if (!runtime.services.jobHandlers[job.type])
|
|
613
|
+
throw new FeltKitError("CONFLICT", `No handler is registered for job type ${job.type}; a retry would fail the same way. Nothing was changed.`);
|
|
614
|
+
return job;
|
|
615
|
+
}
|
|
616
|
+
const retryable = (runtime, job) => job.status === "failed" && Boolean(runtime.services.jobHandlers[job.type]);
|
|
617
|
+
/** Refuse a client-chosen identity outright: production actions run as the signed-in operator. */
|
|
618
|
+
function refuseActAs(body) {
|
|
619
|
+
if (body.as !== undefined && body.as !== null && body.as !== "") {
|
|
620
|
+
throw new FeltKitError("FORBIDDEN", "Production actions run as the signed-in operator; acting as another identity (`as`) is not accepted.");
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
const REPLAY_DISABLED = "Webhook replay is disabled in production: AppPort Services makes the person replaying the delivery its new owner and accepts deliveries that already succeeded, so a replay would not preserve the original owner's authority.";
|
|
624
|
+
/**
|
|
625
|
+
* The production admin API. Every route authenticates the operator and authorizes the
|
|
626
|
+
* operation server-side; writes also pass checkWrite (JSON, same origin, CSRF, environment).
|
|
627
|
+
* Anything not listed here is not served in production.
|
|
628
|
+
*/
|
|
629
|
+
async function handleProduction(ctx, request, response, path, url) {
|
|
630
|
+
const { runtime } = ctx;
|
|
631
|
+
const method = request.method ?? "GET";
|
|
632
|
+
const segments = path.split("/").filter(Boolean).map(decodeURIComponent);
|
|
633
|
+
const route = `${method} /${segments.map((s, i) => (i >= 1 && /^(tasks|jobs|deliveries|activity)$/.test(segments[i - 1] ?? "") ? ":id" : s)).join("/")}`;
|
|
634
|
+
const environment = { name: runtime.environment.name, production: true, development: false };
|
|
635
|
+
// Signing in and out.
|
|
636
|
+
if (route === "GET /operator/session") {
|
|
637
|
+
let operator = null;
|
|
638
|
+
try {
|
|
639
|
+
operator = await authenticateOperator(runtime, request);
|
|
640
|
+
}
|
|
641
|
+
catch {
|
|
642
|
+
setSessionCookie(runtime, response, null);
|
|
643
|
+
}
|
|
644
|
+
return sendJSON(response, 200, {
|
|
645
|
+
application: runtime.app.name,
|
|
646
|
+
environment,
|
|
647
|
+
operator: operator ? operator.principal : null,
|
|
648
|
+
permissions: operator ? runtime.authority.permissionsFor(operator.principal) : [],
|
|
649
|
+
csrf: operator ? csrfFor(operator) : null,
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
if (route === "POST /operator/signin") {
|
|
653
|
+
checkWrite(runtime, request, null);
|
|
654
|
+
const body = await readJSON(request);
|
|
655
|
+
const issued = await signIn(runtime, String(body.grant ?? ""), operatorKey(runtime.environment.runtimeDir));
|
|
656
|
+
setSessionCookie(runtime, response, issued.token);
|
|
657
|
+
const operator = { principal: issued.principal, token: issued.token, via: "operator-session" };
|
|
658
|
+
return sendJSON(response, 200, { operator: issued.principal, permissions: runtime.authority.permissionsFor(issued.principal), csrf: csrfFor(operator), expiresAt: issued.expiresAt });
|
|
659
|
+
}
|
|
660
|
+
const operator = await authenticateOperator(runtime, request);
|
|
661
|
+
if (route === "POST /operator/signout") {
|
|
662
|
+
if (!operator)
|
|
663
|
+
throw new FeltKitError("UNAUTHORIZED", "Not signed in.");
|
|
664
|
+
checkWrite(runtime, request, operator);
|
|
665
|
+
if (operator.token)
|
|
666
|
+
await runtime.sessions.delete(operator.token);
|
|
667
|
+
setSessionCookie(runtime, response, null);
|
|
668
|
+
return sendJSON(response, 200, { ok: true });
|
|
669
|
+
}
|
|
670
|
+
const read = () => requireOperator(runtime, operator, OPERATOR_PERMISSIONS.read);
|
|
671
|
+
const write = async () => {
|
|
672
|
+
const p = await requireOperator(runtime, operator, OPERATOR_PERMISSIONS.write);
|
|
673
|
+
checkWrite(runtime, request, operator);
|
|
674
|
+
const body = await readJSON(request);
|
|
675
|
+
refuseActAs(body);
|
|
676
|
+
return { p, body };
|
|
677
|
+
};
|
|
678
|
+
switch (route) {
|
|
679
|
+
case "GET /overview": {
|
|
680
|
+
const p = await read();
|
|
681
|
+
return sendJSON(response, 200, { ...(await overviewPayload(runtime)), operator: { principal: p, permissions: runtime.authority.permissionsFor(p) } });
|
|
682
|
+
}
|
|
683
|
+
case "GET /capabilities": {
|
|
684
|
+
await read();
|
|
685
|
+
return sendJSON(response, 200, { manifest: runtime.appport.manifest(), capabilities: capabilitySummary(runtime, await runtime.activity.list({ kind: "capability", limit: 200 })), mcp: { endpoint: "/mcp", tools: runtime.mcpBridge(null).listTools().map((t) => t.name) } });
|
|
686
|
+
}
|
|
687
|
+
case "GET /services": {
|
|
688
|
+
await read();
|
|
689
|
+
return sendJSON(response, 200, {
|
|
690
|
+
services: await runtime.services.status(runtime.state === "ready"),
|
|
691
|
+
console: { url: null, reason: "The AppPort Services console is development-only: its pages need their own origin (see docs/SECURITY.md). Job runs and deliveries are shown here." },
|
|
692
|
+
credentials: await credentialReport(runtime),
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
case "GET /services/jobs": {
|
|
696
|
+
await read();
|
|
697
|
+
const jobs = runtime.services.jobs;
|
|
698
|
+
if (!jobs)
|
|
699
|
+
return sendJSON(response, 200, { items: [], enabled: false });
|
|
700
|
+
const items = (await jobs.listJobs(runtime.app.name)).map((j) => ({ ...jobView(j), retryable: retryable(runtime, j) })).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
701
|
+
return sendJSON(response, 200, { items, enabled: true, handlers: runtime.services.jobHandlers });
|
|
702
|
+
}
|
|
703
|
+
case "GET /services/deliveries": {
|
|
704
|
+
await read();
|
|
705
|
+
const hooks = runtime.services.webhooks;
|
|
706
|
+
if (!hooks)
|
|
707
|
+
return sendJSON(response, 200, { items: [], enabled: false });
|
|
708
|
+
const endpoints = new Map((await hooks.listWebhookEndpoints(runtime.app.name)).map((e) => [e.id, e]));
|
|
709
|
+
const items = (await hooks.listWebhookDeliveries(runtime.app.name, undefined, 200)).map((d) => ({ ...deliveryView(d, endpoints.get(d.endpointId)), replayable: false })).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
710
|
+
return sendJSON(response, 200, { items, enabled: true, replay: { enabled: false, reason: REPLAY_DISABLED } });
|
|
711
|
+
}
|
|
712
|
+
case "POST /services/jobs/:id/retry": {
|
|
713
|
+
const { p } = await write();
|
|
714
|
+
const requestId = newRequestId();
|
|
715
|
+
const job = await requireRetryable(runtime, segments[2]);
|
|
716
|
+
const started = Date.now();
|
|
717
|
+
try {
|
|
718
|
+
// Authorized as the operator (jobs.retry); the job keeps its owner and runs as them, re-authorized.
|
|
719
|
+
const retried = await runtime.services.asPrincipal(p, (verified) => runtime.services.jobs.retry(runtime.app.name, job.id, verified), requestId);
|
|
720
|
+
if (!retried)
|
|
721
|
+
throw new FeltKitError("CONFLICT", "The job changed while it was being retried (another retry won). Nothing more was changed.");
|
|
722
|
+
runtime.activity.record({ kind: "service", name: "jobs.retry", via: "dashboard", requestId, principal: { id: p.id, type: p.type, roles: p.roles }, outcome: "success", durationMs: Date.now() - started, detail: { id: job.id, owner: job.principal?.principalId ?? null } });
|
|
723
|
+
return sendJSON(response, 200, { item: jobView(retried) });
|
|
724
|
+
}
|
|
725
|
+
catch (error) {
|
|
726
|
+
const denied = isDenied(error);
|
|
727
|
+
runtime.activity.record({ kind: "service", name: "jobs.retry", via: "dashboard", requestId, principal: { id: p.id, type: p.type, roles: p.roles }, outcome: denied ? "denied" : "error", durationMs: Date.now() - started, error: { code: denied ? "FORBIDDEN" : (error.code ?? "INTERNAL"), message: error.message }, detail: { id: job.id } });
|
|
728
|
+
if (denied)
|
|
729
|
+
throw new FeltKitError("FORBIDDEN", `${p.id} may not retry this job.`);
|
|
730
|
+
throw error;
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
case "POST /services/deliveries/:id/replay": {
|
|
734
|
+
await requireOperator(runtime, operator, OPERATOR_PERMISSIONS.write);
|
|
735
|
+
throw new FeltKitError("FORBIDDEN", REPLAY_DISABLED);
|
|
736
|
+
}
|
|
737
|
+
case "GET /agent": {
|
|
738
|
+
const p = await read();
|
|
739
|
+
return sendJSON(response, 200, {
|
|
740
|
+
tasks: await runtime.agent.list("admin"),
|
|
741
|
+
handoffs: await runtime.agent.openHandoffs("admin"),
|
|
742
|
+
tools: await runtime.agent.tools(p),
|
|
743
|
+
permissions: { read: "feltkit.agent.read", write: "feltkit.agent.write" },
|
|
744
|
+
});
|
|
745
|
+
}
|
|
746
|
+
case "GET /agent/tasks/:id": {
|
|
747
|
+
await read();
|
|
748
|
+
return sendJSON(response, 200, await runtime.agent.get(segments[2], "admin"));
|
|
749
|
+
}
|
|
750
|
+
case "POST /agent/tasks/:id/approve":
|
|
751
|
+
case "POST /agent/tasks/:id/reject":
|
|
752
|
+
case "POST /agent/tasks/:id/retry":
|
|
753
|
+
case "POST /agent/tasks/:id/resolve": {
|
|
754
|
+
const { p, body } = await write();
|
|
755
|
+
const taskId = segments[2];
|
|
756
|
+
const actionId = String(body.actionId ?? "");
|
|
757
|
+
switch (segments[3]) {
|
|
758
|
+
case "approve":
|
|
759
|
+
return sendJSON(response, 200, await runtime.agent.approve(taskId, actionId, p));
|
|
760
|
+
case "reject":
|
|
761
|
+
return sendJSON(response, 200, await runtime.agent.reject(taskId, actionId, p, typeof body.reason === "string" ? body.reason : undefined));
|
|
762
|
+
case "retry":
|
|
763
|
+
return sendJSON(response, 200, await runtime.agent.retry(taskId, actionId, p));
|
|
764
|
+
default:
|
|
765
|
+
return sendJSON(response, 200, await runtime.agent.resolve(taskId, actionId, { outcome: body.outcome, ...(typeof body.note === "string" ? { note: body.note } : {}) }, p));
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
case "GET /activity": {
|
|
769
|
+
await read();
|
|
770
|
+
const kind = url.searchParams.get("kind") ?? undefined;
|
|
771
|
+
const outcome = url.searchParams.get("outcome") ?? undefined;
|
|
772
|
+
return sendJSON(response, 200, { entries: await runtime.activity.list({ ...(kind ? { kind: kind } : {}), ...(outcome ? { outcome: outcome } : {}), limit: Math.min(Number(url.searchParams.get("limit") ?? 100) || 100, 500) }) });
|
|
773
|
+
}
|
|
774
|
+
case "GET /activity/:id": {
|
|
775
|
+
await read();
|
|
776
|
+
const entry = await runtime.activity.get(segments[1]);
|
|
777
|
+
if (!entry)
|
|
778
|
+
throw new FeltKitError("NOT_FOUND", "No such activity entry.");
|
|
779
|
+
const lookup = await runtime.activity.serviceEvidenceLookup(entry.requestId);
|
|
780
|
+
return sendJSON(response, 200, { entry, serviceEvidence: lookup.records, serviceEvidenceState: lookup.state, serviceEvidenceTruncated: lookup.truncated });
|
|
781
|
+
}
|
|
782
|
+
case "GET /readiness": {
|
|
783
|
+
await read();
|
|
784
|
+
return sendJSON(response, 200, await assessReadiness(runtime, { dashboard: true }));
|
|
785
|
+
}
|
|
786
|
+
case "GET /models": {
|
|
787
|
+
await read();
|
|
788
|
+
return sendJSON(response, 200, await modelsView(runtime));
|
|
789
|
+
}
|
|
790
|
+
case "POST /models/test": {
|
|
791
|
+
await write();
|
|
792
|
+
return sendJSON(response, 200, await testModel(runtime));
|
|
793
|
+
}
|
|
794
|
+
case "GET /integrations": {
|
|
795
|
+
await read();
|
|
796
|
+
return sendJSON(response, 200, await integrationsView(runtime));
|
|
797
|
+
}
|
|
798
|
+
case "GET /credentials": {
|
|
799
|
+
await read();
|
|
800
|
+
return sendJSON(response, 200, await credentialsView(runtime));
|
|
801
|
+
}
|
|
802
|
+
case "POST /credentials": {
|
|
803
|
+
// Authorized twice: the operator holds feltkit.operations.write, and AppPort Services'
|
|
804
|
+
// gateway authorizes credential.store for them. Without the production vault opt-in the
|
|
805
|
+
// custody refuses with CUSTODY_READ_ONLY (values come from the host's environment).
|
|
806
|
+
const { p, body } = await write();
|
|
807
|
+
const stored = await storeCredential(runtime, { ref: body.ref, value: body.value, provider: body.provider }, p, "dashboard");
|
|
808
|
+
return sendJSON(response, 200, { stored, ...(await credentialsView(runtime)) });
|
|
809
|
+
}
|
|
810
|
+
case "POST /agent/tasks/:id/decide": {
|
|
811
|
+
const { p } = await write();
|
|
812
|
+
return sendJSON(response, 200, await runtime.agent.decide(segments[2], p));
|
|
813
|
+
}
|
|
814
|
+
case "GET /events": {
|
|
815
|
+
await read();
|
|
816
|
+
const stream = startSSE(response);
|
|
817
|
+
const offChanges = runtime.changes.subscribe((event) => stream.send("change", event));
|
|
818
|
+
const offActivity = runtime.activity.subscribe((entry) => stream.send("activity", entry));
|
|
819
|
+
request.on("close", () => {
|
|
820
|
+
offChanges();
|
|
821
|
+
offActivity();
|
|
822
|
+
stream.close();
|
|
823
|
+
});
|
|
824
|
+
return;
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
if (method === "POST" && segments[0] === "integrations" && segments[2] === "check" && segments.length === 3) {
|
|
828
|
+
await write();
|
|
829
|
+
return sendJSON(response, 200, await runtime.integrations.check(segments[1]));
|
|
830
|
+
}
|
|
831
|
+
if (method === "POST" && segments[0] === "integrations" && segments[1] === "calls" && segments[3] === "verify" && segments.length === 4) {
|
|
832
|
+
const { p } = await write();
|
|
833
|
+
return sendJSON(response, 200, { call: await runtime.integrations.verify(segments[2], p) });
|
|
834
|
+
}
|
|
835
|
+
// Model selection is changed on the host (`feltkit model set --env production`), not from Studio.
|
|
836
|
+
// Data browsing and editing, function runs, capability invocation, sessions, task creation,
|
|
837
|
+
// the services console, and "run due work" are development tools.
|
|
838
|
+
if (!operator)
|
|
839
|
+
throw new FeltKitError("UNAUTHORIZED", "Sign in as an operator to use Studio in production.");
|
|
840
|
+
throw new FeltKitError("NOT_FOUND", `${method} /${segments.join("/")} is not available in production.`);
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Create → configure → integrate → build a workflow → test → review readiness → deploy →
|
|
844
|
+
* operate, as this environment shows it. "done" only when the runtime can see it; steps it
|
|
845
|
+
* cannot see say so.
|
|
846
|
+
*/
|
|
847
|
+
async function pathToProduction(runtime) {
|
|
848
|
+
const model = await runtime.models.status();
|
|
849
|
+
const integrations = runtime.integrations.definitions().map((i) => runtime.integrations.status(i));
|
|
850
|
+
const configured = integrations.filter((i) => !i.problems.length).length;
|
|
851
|
+
const decisionTasks = (await runtime.agent.list("admin", 200)).filter((t) => t.task.constraints?.includes("playbook:decide")).length;
|
|
852
|
+
const capabilities = runtime.functions().filter((f) => f.capability).length + integrations.reduce((n, i) => n + i.operations.length, 0);
|
|
853
|
+
return [
|
|
854
|
+
{ step: "Create", state: "done", detail: `${runtime.app.name}: ${runtime.functions().length} function(s), ${capabilities} capabilit(ies).`, link: "capabilities" },
|
|
855
|
+
{ step: "Configure a model", state: model.ready ? "done" : "todo", detail: model.ready ? `${model.provider}${model.model ? ` / ${model.model}` : ""}` : model.problems[0]?.message ?? "No model.", link: "models" },
|
|
856
|
+
{ step: "Connect a tool", state: integrations.length && configured === integrations.length ? "done" : integrations.length ? "todo" : "todo", detail: integrations.length ? `${configured} of ${integrations.length} integration(s) configured` : "No integrations declared (app.integration).", link: "integrations" },
|
|
857
|
+
{ step: "Build a workflow", state: decisionTasks ? "done" : "todo", detail: decisionTasks ? `${decisionTasks} decision task(s) have run in ${runtime.environment.name}.` : "No decision task has run here yet (ctx.agent.start or playbook: decide).", link: "agent" },
|
|
858
|
+
{ step: "Test", state: "not-tracked", detail: "Run `npx feltkit test` (an isolated test environment); Studio does not see test results.", link: null },
|
|
859
|
+
{ step: "Review readiness", state: "info", detail: "Real checks of this environment, and what FeltKit cannot check.", link: "readiness" },
|
|
860
|
+
{ step: "Deploy", state: "not-tracked", detail: "`npx feltkit deploy` builds and verifies an artifact; hosting is yours (docs/PATH-TO-PRODUCTION.md).", link: null },
|
|
861
|
+
{ step: "Operate", state: runtime.environment.production ? "done" : "info", detail: runtime.environment.production ? "This is production Studio." : "Production Studio: operators sign in with `feltkit operator grant`.", link: null },
|
|
862
|
+
];
|
|
863
|
+
}
|
|
864
|
+
/** What decides in this environment, and the providers it could use. Never a secret. */
|
|
865
|
+
async function modelsView(runtime) {
|
|
866
|
+
return {
|
|
867
|
+
status: await runtime.models.status(),
|
|
868
|
+
intelligence: Boolean(runtime.services.intelligence),
|
|
869
|
+
catalog: INTELLIGENCE_CATALOG.map((p) => ({ id: p.id, displayName: p.displayName, protocol: p.protocol, credential: p.credential, models: p.models.map((m) => m.id), modelSelection: p.modelSelection, endpoints: p.endpoints.map((e) => e.url), customEndpoint: p.customEndpoint })),
|
|
870
|
+
};
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Select the environment's provider and model through the Intelligence service, storing
|
|
874
|
+
* the API key first when one is given (`apiKey`): credential.store, then intelligence.set
|
|
875
|
+
* with the reference. The reference defaults to credential-ref:<provider>. A reference
|
|
876
|
+
* field holding what looks like a key is refused before anything is stored, and never
|
|
877
|
+
* echoed. Returns the stored version (never the value).
|
|
878
|
+
*/
|
|
879
|
+
export async function selectModel(runtime, body, options = {}) {
|
|
880
|
+
const provider = String(body.provider ?? "");
|
|
881
|
+
const model = String(body.model ?? "");
|
|
882
|
+
if (!provider || !model)
|
|
883
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Choose a provider and a model.");
|
|
884
|
+
const entry = getIntelligenceProvider(provider);
|
|
885
|
+
if (!entry)
|
|
886
|
+
throw new FeltKitError("INVALID_ARGUMENT", `Unknown provider "${provider}".`);
|
|
887
|
+
let credentialRef = typeof body.credentialRef === "string" ? body.credentialRef.trim() : "";
|
|
888
|
+
if (credentialRef && !credentialRef.startsWith("credential-ref:")) {
|
|
889
|
+
// Defense in depth (Studio moves a pasted key out of this field before sending): never store or echo it.
|
|
890
|
+
throw new FeltKitError("INVALID_ARGUMENT", looksLikeSecret(credentialRef)
|
|
891
|
+
? "The credential reference field holds what looks like an API key. It was not saved anywhere. Enter the key in the API key field; it is stored in this environment's custody, never in configuration."
|
|
892
|
+
: "A credential reference must look like credential-ref:<id>; what was sent is not one and was not saved.");
|
|
893
|
+
}
|
|
894
|
+
const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
|
|
895
|
+
if (!credentialRef && (apiKey || entry.credential === "required"))
|
|
896
|
+
credentialRef = `credential-ref:${provider}`;
|
|
897
|
+
let stored = null;
|
|
898
|
+
if (apiKey)
|
|
899
|
+
stored = await storeCredential(runtime, { ref: credentialRef, value: apiKey, provider }, options.principal ?? HOST_CUSTODY, options.via ?? "dashboard");
|
|
900
|
+
await runtime.models.select({
|
|
901
|
+
provider,
|
|
902
|
+
model,
|
|
903
|
+
endpoint: typeof body.endpoint === "string" && body.endpoint ? body.endpoint : null,
|
|
904
|
+
...(credentialRef ? { credentialRef } : {}),
|
|
905
|
+
}, options.principal);
|
|
906
|
+
return stored;
|
|
907
|
+
}
|
|
908
|
+
/** One small binary decision through the configured model, to prove the configuration works. */
|
|
909
|
+
async function testModel(runtime) {
|
|
910
|
+
try {
|
|
911
|
+
const outcome = await runtime.models.decide({ kind: "binary", predicate: "Is the number in the context greater than 1?", context: { number: 2 } });
|
|
912
|
+
return { ok: true, result: outcome.result, runtime: outcome.metadata, capabilities: outcome.capabilities, provider: outcome.provider, durationMs: outcome.durationMs };
|
|
913
|
+
}
|
|
914
|
+
catch (error) {
|
|
915
|
+
const e = error;
|
|
916
|
+
return { ok: false, error: { code: e.code ?? "INTERNAL", message: e.message, hint: e.hint ?? null, problem: e.details?.problem ?? null } };
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
async function integrationsView(runtime) {
|
|
920
|
+
return {
|
|
921
|
+
integrations: runtime.integrations.definitions().map((i) => runtime.integrations.status(i)),
|
|
922
|
+
calls: (await runtime.integrations.calls({ limit: 100 })).map(({ input: _input, ...call }) => call),
|
|
923
|
+
};
|
|
924
|
+
}
|
|
925
|
+
function isDenied(error) {
|
|
926
|
+
const code = error?.code;
|
|
927
|
+
return code === "DENIED" || code === "FORBIDDEN" || error?.name === "ServiceAuthorityError";
|
|
928
|
+
}
|
|
929
|
+
function jobView(job) {
|
|
930
|
+
return {
|
|
931
|
+
id: job.id,
|
|
932
|
+
type: job.type,
|
|
933
|
+
status: job.status,
|
|
934
|
+
attemptCount: job.attemptCount,
|
|
935
|
+
maxAttempts: job.maxAttempts,
|
|
936
|
+
createdAt: job.createdAt,
|
|
937
|
+
runAt: job.runAt,
|
|
938
|
+
...(job.startedAt ? { startedAt: job.startedAt } : {}),
|
|
939
|
+
...(job.completedAt ? { completedAt: job.completedAt } : {}),
|
|
940
|
+
...(job.nextAttemptAt ? { nextAttemptAt: job.nextAttemptAt } : {}),
|
|
941
|
+
...(job.lastError ? { lastError: job.lastError } : {}),
|
|
942
|
+
principal: job.principal?.principalId ?? null,
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
function deliveryView(delivery, endpoint) {
|
|
946
|
+
return {
|
|
947
|
+
id: delivery.id,
|
|
948
|
+
endpointId: delivery.endpointId,
|
|
949
|
+
...(endpoint ? { destination: new URL(endpoint.url).origin } : {}),
|
|
950
|
+
eventType: delivery.eventType,
|
|
951
|
+
status: delivery.status,
|
|
952
|
+
attemptCount: delivery.attemptCount,
|
|
953
|
+
createdAt: delivery.createdAt,
|
|
954
|
+
...(delivery.deliveredAt ? { deliveredAt: delivery.deliveredAt } : {}),
|
|
955
|
+
...(delivery.nextAttemptAt ? { nextAttemptAt: delivery.nextAttemptAt } : {}),
|
|
956
|
+
...(delivery.lastStatusCode !== undefined ? { lastStatusCode: delivery.lastStatusCode } : {}),
|
|
957
|
+
...(delivery.lastError ? { lastError: delivery.lastError } : {}),
|
|
958
|
+
principal: delivery.principal?.principalId ?? null,
|
|
959
|
+
};
|
|
960
|
+
}
|
|
292
961
|
function identityFor(runtime, as) {
|
|
293
962
|
if (as === null || as === undefined || as === "anonymous")
|
|
294
963
|
return null;
|