@feltdb/feltkit 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/dist/app.d.ts +106 -10
  2. package/dist/app.js +51 -0
  3. package/dist/app.js.map +1 -1
  4. package/dist/cli/main.js +218 -2
  5. package/dist/cli/main.js.map +1 -1
  6. package/dist/cli/skills.d.ts +39 -0
  7. package/dist/cli/skills.js +125 -0
  8. package/dist/cli/skills.js.map +1 -0
  9. package/dist/dashboard/assets/{index-BLnBFDJs.css → index--1Tqbv_A.css} +1 -1
  10. package/dist/dashboard/assets/index-Bm4qCYpv.js +15 -0
  11. package/dist/dashboard/index.html +2 -2
  12. package/dist/errors.d.ts +3 -1
  13. package/dist/errors.js +2 -0
  14. package/dist/errors.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/runtime/activity.d.ts +21 -8
  17. package/dist/runtime/activity.js +17 -3
  18. package/dist/runtime/activity.js.map +1 -1
  19. package/dist/runtime/agent.d.ts +353 -0
  20. package/dist/runtime/agent.js +1345 -0
  21. package/dist/runtime/agent.js.map +1 -0
  22. package/dist/runtime/authority.d.ts +23 -3
  23. package/dist/runtime/authority.js +69 -5
  24. package/dist/runtime/authority.js.map +1 -1
  25. package/dist/runtime/changes.d.ts +16 -8
  26. package/dist/runtime/changes.js.map +1 -1
  27. package/dist/runtime/content.d.ts +33 -0
  28. package/dist/runtime/content.js +46 -0
  29. package/dist/runtime/content.js.map +1 -0
  30. package/dist/runtime/context.d.ts +26 -1
  31. package/dist/runtime/credentials.d.ts +42 -0
  32. package/dist/runtime/credentials.js +32 -0
  33. package/dist/runtime/credentials.js.map +1 -0
  34. package/dist/runtime/data.d.ts +8 -2
  35. package/dist/runtime/data.js +74 -9
  36. package/dist/runtime/data.js.map +1 -1
  37. package/dist/runtime/decisions.d.ts +131 -0
  38. package/dist/runtime/decisions.js +301 -0
  39. package/dist/runtime/decisions.js.map +1 -0
  40. package/dist/runtime/environment.js +11 -0
  41. package/dist/runtime/environment.js.map +1 -1
  42. package/dist/runtime/idempotency.d.ts +37 -0
  43. package/dist/runtime/idempotency.js +88 -0
  44. package/dist/runtime/idempotency.js.map +1 -0
  45. package/dist/runtime/instance.d.ts +8 -3
  46. package/dist/runtime/instance.js +27 -4
  47. package/dist/runtime/instance.js.map +1 -1
  48. package/dist/runtime/integrations.d.ts +120 -0
  49. package/dist/runtime/integrations.js +412 -0
  50. package/dist/runtime/integrations.js.map +1 -0
  51. package/dist/runtime/loader.d.ts +5 -1
  52. package/dist/runtime/loader.js +35 -13
  53. package/dist/runtime/loader.js.map +1 -1
  54. package/dist/runtime/projects.d.ts +1 -0
  55. package/dist/runtime/projects.js +6 -4
  56. package/dist/runtime/projects.js.map +1 -1
  57. package/dist/runtime/readiness.d.ts +29 -0
  58. package/dist/runtime/readiness.js +154 -0
  59. package/dist/runtime/readiness.js.map +1 -0
  60. package/dist/runtime/runtime.d.ts +50 -1
  61. package/dist/runtime/runtime.js +225 -9
  62. package/dist/runtime/runtime.js.map +1 -1
  63. package/dist/runtime/services.d.ts +186 -36
  64. package/dist/runtime/services.js +420 -152
  65. package/dist/runtime/services.js.map +1 -1
  66. package/dist/runtime/sessions.d.ts +7 -18
  67. package/dist/runtime/sessions.js +7 -5
  68. package/dist/runtime/sessions.js.map +1 -1
  69. package/dist/server/admin.d.ts +26 -0
  70. package/dist/server/admin.js +510 -8
  71. package/dist/server/admin.js.map +1 -1
  72. package/dist/server/index.d.ts +2 -0
  73. package/dist/server/index.js +13 -4
  74. package/dist/server/index.js.map +1 -1
  75. package/dist/server/management.d.ts +12 -0
  76. package/dist/server/management.js +177 -0
  77. package/dist/server/management.js.map +1 -0
  78. package/dist/server/mcp.d.ts +202 -0
  79. package/dist/server/mcp.js +62 -4
  80. package/dist/server/mcp.js.map +1 -1
  81. package/dist/server/operators.d.ts +77 -0
  82. package/dist/server/operators.js +162 -0
  83. package/dist/server/operators.js.map +1 -0
  84. package/dist/server/project.js +17 -4
  85. package/dist/server/project.js.map +1 -1
  86. package/dist/testing/index.js +3 -2
  87. package/dist/testing/index.js.map +1 -1
  88. package/package.json +18 -11
  89. package/skills/.claude-plugin/marketplace.json +16 -0
  90. package/skills/.claude-plugin/plugin.json +24 -0
  91. package/skills/README.md +44 -0
  92. package/skills/feltkit-agent/SKILL.md +84 -0
  93. package/skills/feltkit-build/SKILL.md +143 -0
  94. package/skills/feltkit-data/SKILL.md +79 -0
  95. package/skills/feltkit-operations/SKILL.md +72 -0
  96. package/skills/feltkit-services/SKILL.md +102 -0
  97. package/dist/dashboard/assets/index-CxJGCspE.js +0 -15
@@ -1,11 +1,15 @@
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, SERVICE_EVIDENCE_COLLECTION } from "../runtime/activity.js";
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 } from "@appport/services";
10
+ import { assessReadiness } from "../runtime/readiness.js";
11
+ import { INTEGRATION_CALLS } from "../runtime/integrations.js";
12
+ import { OPERATOR_PERMISSIONS, authenticateOperator, checkWrite, csrfFor, newRequestId, operatorKey, requireOperator, setSessionCookie, signIn } from "./operators.js";
9
13
  const DASHBOARD = { id: "dashboard", type: "service", roles: [] };
10
14
  /** Platform collections the data explorer may show, read-only, with what to redact. */
11
15
  const PLATFORM_COLLECTIONS = {
@@ -20,14 +24,27 @@ const PLATFORM_COLLECTIONS = {
20
24
  notification_deliveries: { owner: "AppPort Services", description: "Notification deliveries" },
21
25
  ConfigurationVariables: { owner: "AppPort Services", description: "Configuration variables" },
22
26
  file_audit_events: { owner: "AppPort Services", description: "File audit trail" },
23
- [SERVICE_EVIDENCE_COLLECTION]: { owner: "AppPort Services", description: "Service effect evidence" },
27
+ service_effect_evidence: { owner: "AppPort Services", description: "Service effect evidence" },
28
+ ConfigurationSecrets: { owner: "AppPort Services", description: "Credential references (credential-ref:<id>; values are never stored)" },
29
+ jobs: { owner: "AppPort Services", description: "Jobs, with status, attempts, and last error" },
30
+ job_schedules: { owner: "AppPort Services", description: "Recurring job schedules" },
31
+ webhook_endpoints: { owner: "AppPort Services", description: "Webhook endpoints (signing credential by reference only)" },
32
+ webhook_deliveries: { owner: "AppPort Services", description: "Webhook deliveries, with attempts, status codes, and last error" },
33
+ _flow_agent_executions: { owner: "FeltDB", description: "Agent executions (FeltDB agent runtime)" },
34
+ "_feltdb.AgentTask": { owner: "FeltDB", description: "Agent tasks (FeltDB agent state)" },
35
+ "_feltdb.AgentCheckpoint": { owner: "FeltDB", description: "Agent checkpoints with verified evidence (FeltDB agent state)" },
36
+ "_feltdb.AgentHandoff": { owner: "FeltDB", description: "Agent handoffs (FeltDB agent state)" },
24
37
  [COLLECTION_MARKERS]: { owner: "FeltKit", description: "Per-collection change markers used to fence whole-collection reads" },
25
38
  [FILE_CONTENT_COLLECTION]: { owner: "FeltKit", description: "File bytes (base64)", redact: (r) => ({ ...r, data: `<${String(r.data ?? "").length} base64 chars>` }) },
39
+ [INTEGRATION_CALLS]: { owner: "FeltKit", description: "Integration calls: recorded before and after each request, with verification evidence (credentials are never stored)" },
26
40
  };
27
41
  export async function handleAdmin(ctx, request, response, path, url) {
28
42
  const { runtime } = ctx;
29
43
  const production = runtime.environment.production;
30
44
  try {
45
+ // Production: verified operators only. The admin token, `as`, and dev identities carry no authority here.
46
+ if (production)
47
+ return await handleProduction(ctx, request, response, path, url);
31
48
  const token = request.headers["x-feltkit-admin"];
32
49
  if (typeof token !== "string" || !safeEqual(token, ctx.adminToken)) {
33
50
  throw new FeltKitError("UNAUTHORIZED", "The admin API needs the environment's admin token.", {
@@ -195,9 +212,159 @@ export async function handleAdmin(ctx, request, response, path, url) {
195
212
  await runtime.sessions.delete(session.id);
196
213
  }
197
214
  }
198
- if (method === "GET" && segments[0] === "services") {
199
- await runtime.services.check();
200
- return sendJSON(response, 200, { services: runtime.services.status(runtime.state === "ready") });
215
+ // Configuration transfer (`feltkit config export|import` against a running development
216
+ // server): AppPort Services' own export/import, as FeltKit's host-only transfer principal.
217
+ if (method === "GET" && segments[0] === "configuration" && segments[1] === "export") {
218
+ return sendJSON(response, 200, await runtime.services.exportConfiguration());
219
+ }
220
+ if (method === "POST" && segments[0] === "configuration" && segments[1] === "import") {
221
+ const body = await readJSON(request);
222
+ return sendJSON(response, 200, await runtime.services.importConfiguration(body.document, { dryRun: body.dryRun === true, overwrite: body.overwrite === true }));
223
+ }
224
+ if (method === "GET" && segments[0] === "services" && segments.length === 1) {
225
+ return sendJSON(response, 200, {
226
+ services: await runtime.services.status(runtime.state === "ready"),
227
+ 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." },
228
+ credentials: await credentialReport(runtime),
229
+ });
230
+ }
231
+ // A one-time sign-in link to the AppPort Services console, as a declared dev identity.
232
+ if (method === "POST" && segments[0] === "services" && segments[1] === "console") {
233
+ if (production || !ctx.console)
234
+ throw new FeltKitError("NOT_FOUND", "The services console is development-only.");
235
+ const body = await readJSON(request);
236
+ const principal = identityFor(runtime, body.as);
237
+ if (!principal)
238
+ throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity to open the services console as; service operations are authorized as that identity.");
239
+ return sendJSON(response, 200, { url: await ctx.console.ticket(principal, typeof body.page === "string" ? body.page : "/services") });
240
+ }
241
+ // Execution and delivery history, from the services' own records.
242
+ if (method === "GET" && segments[0] === "services" && segments[1] === "jobs" && segments.length === 2) {
243
+ const jobs = runtime.services.jobs;
244
+ if (!jobs)
245
+ return sendJSON(response, 200, { items: [], enabled: false });
246
+ const items = (await jobs.listJobs(runtime.app.name)).map(jobView).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
247
+ return sendJSON(response, 200, { items, enabled: true, handlers: runtime.services.jobHandlers });
248
+ }
249
+ if (method === "GET" && segments[0] === "services" && segments[1] === "deliveries" && segments.length === 2) {
250
+ const hooks = runtime.services.webhooks;
251
+ if (!hooks)
252
+ return sendJSON(response, 200, { items: [], enabled: false });
253
+ const endpoints = new Map((await hooks.listWebhookEndpoints(runtime.app.name)).map((e) => [e.id, e]));
254
+ 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));
255
+ return sendJSON(response, 200, { items, enabled: true });
256
+ }
257
+ // Retry a job / replay a delivery as a declared dev identity, through the service.
258
+ if (method === "POST" && segments[0] === "services" && (segments[1] === "jobs" || segments[1] === "deliveries") && segments[3] && segments.length === 4) {
259
+ if (production)
260
+ throw new FeltKitError("FORBIDDEN", "Production is read-only from the dashboard.");
261
+ const body = await readJSON(request);
262
+ const principal = identityFor(runtime, body.as);
263
+ if (!principal)
264
+ throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity; the retry is authorized as that identity.");
265
+ if (segments[1] === "jobs" && segments[3] === "retry")
266
+ await requireRetryable(runtime, segments[2]);
267
+ const result = await runtime.services.asPrincipal(principal, async (verified) => {
268
+ if (segments[1] === "jobs" && segments[3] === "retry") {
269
+ const job = await runtime.services.jobs?.retry(runtime.app.name, segments[2], verified);
270
+ return job ? jobView(job) : null;
271
+ }
272
+ if (segments[1] === "deliveries" && segments[3] === "replay") {
273
+ const delivery = await runtime.services.webhooks?.replayWebhookDelivery(runtime.app.name, segments[2], verified);
274
+ return delivery ? deliveryView(delivery, undefined) : null;
275
+ }
276
+ throw new FeltKitError("NOT_FOUND", `No action ${segments[3]}.`);
277
+ });
278
+ if (!result)
279
+ throw new FeltKitError("NOT_FOUND", "Nothing to retry: it does not exist, or it is not in a failed state.");
280
+ 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] } });
281
+ return sendJSON(response, 200, { item: result });
282
+ }
283
+ if (method === "POST" && segments[0] === "services" && segments[1] === "run" && segments.length === 2) {
284
+ if (production)
285
+ throw new FeltKitError("FORBIDDEN", "Production is read-only from the dashboard.");
286
+ return sendJSON(response, 200, await runtime.runServices());
287
+ }
288
+ // Models, integrations, readiness: the path from a local app to production.
289
+ if (method === "GET" && segments[0] === "readiness" && segments.length === 1) {
290
+ return sendJSON(response, 200, await assessReadiness(runtime, { projectDir: ctx.projectDir, dashboard: true }));
291
+ }
292
+ if (segments[0] === "models" && segments.length === 1 && method === "GET")
293
+ return sendJSON(response, 200, await modelsView(runtime));
294
+ if (segments[0] === "models" && segments.length === 1 && method === "POST") {
295
+ // Development: the local developer (holder of the admin token) selects the model for this environment.
296
+ requireDevelopment("Changing the model from Studio");
297
+ const body = await readJSON(request);
298
+ await selectModel(runtime, body);
299
+ return sendJSON(response, 200, await modelsView(runtime));
300
+ }
301
+ if (method === "POST" && segments[0] === "models" && segments[1] === "test" && segments.length === 2)
302
+ return sendJSON(response, 200, await testModel(runtime));
303
+ if (method === "GET" && segments[0] === "integrations" && segments.length === 1)
304
+ return sendJSON(response, 200, await integrationsView(runtime));
305
+ if (method === "POST" && segments[0] === "integrations" && segments[2] === "check" && segments.length === 3)
306
+ return sendJSON(response, 200, await runtime.integrations.check(segments[1]));
307
+ if (method === "POST" && segments[0] === "integrations" && segments[1] === "calls" && segments[3] === "verify" && segments.length === 4) {
308
+ const body = await readJSON(request);
309
+ const principal = identityFor(runtime, body.as);
310
+ if (!principal)
311
+ throw new FeltKitError("INVALID_ARGUMENT", "Choose a dev identity; verification reads the API as that identity.");
312
+ return sendJSON(response, 200, { call: await runtime.integrations.verify(segments[2], principal) });
313
+ }
314
+ // The FeltKit agent. Reads with the admin token; every action as a declared dev identity.
315
+ if (segments[0] === "agent") {
316
+ const agent = runtime.agent;
317
+ if (method === "GET" && segments.length === 1) {
318
+ const as = url.searchParams.get("as");
319
+ const principal = as ? identityFor(runtime, as) : null;
320
+ return sendJSON(response, 200, {
321
+ tasks: await agent.list("admin"),
322
+ handoffs: await agent.openHandoffs("admin"),
323
+ tools: principal ? await agent.tools(principal) : [],
324
+ permissions: { read: "feltkit.agent.read", write: "feltkit.agent.write" },
325
+ });
326
+ }
327
+ if (method === "GET" && segments[1] === "tasks" && segments[2] && segments.length === 3) {
328
+ return sendJSON(response, 200, await agent.get(segments[2], "admin"));
329
+ }
330
+ if (method === "POST") {
331
+ if (production)
332
+ throw new FeltKitError("FORBIDDEN", "Production is read-only from the dashboard.");
333
+ const body = await readJSON(request);
334
+ const principal = identityFor(runtime, body.as);
335
+ if (segments[1] === "tasks" && segments.length === 2) {
336
+ return sendJSON(response, 200, await agent.createTask({
337
+ objective: String(body.objective ?? ""),
338
+ principal,
339
+ ...(typeof body.playbook === "string" ? { playbook: body.playbook } : {}),
340
+ ...(typeof body.target === "string" ? { target: body.target } : {}),
341
+ ...(typeof body.capability === "string" ? { capability: body.capability } : {}),
342
+ ...(body.args && typeof body.args === "object" ? { args: body.args } : {}),
343
+ }));
344
+ }
345
+ const taskId = segments[2];
346
+ if (segments[1] === "tasks" && taskId && segments.length === 4) {
347
+ switch (segments[3]) {
348
+ case "approve":
349
+ return sendJSON(response, 200, await agent.approve(taskId, String(body.actionId ?? ""), principal));
350
+ case "reject":
351
+ return sendJSON(response, 200, await agent.reject(taskId, String(body.actionId ?? ""), principal, typeof body.reason === "string" ? body.reason : undefined));
352
+ case "retry":
353
+ return sendJSON(response, 200, await agent.retry(taskId, String(body.actionId ?? ""), principal));
354
+ case "resolve":
355
+ return sendJSON(response, 200, await agent.resolve(taskId, String(body.actionId ?? ""), { outcome: body.outcome, ...(typeof body.note === "string" ? { note: body.note } : {}) }, principal));
356
+ case "propose":
357
+ return sendJSON(response, 200, await agent.propose(taskId, { capability: String(body.capability ?? ""), input: (body.input ?? {}), reason: String(body.reason ?? "") }, principal));
358
+ case "complete":
359
+ return sendJSON(response, 200, await agent.complete(taskId, String(body.summary ?? ""), principal));
360
+ case "cancel":
361
+ return sendJSON(response, 200, await agent.cancel(taskId, principal, typeof body.reason === "string" ? body.reason : undefined));
362
+ case "decide":
363
+ return sendJSON(response, 200, await agent.decide(taskId, principal));
364
+ }
365
+ }
366
+ }
367
+ throw new FeltKitError("NOT_FOUND", `No agent endpoint ${method} /${segments.join("/")}.`);
201
368
  }
202
369
  // Activity
203
370
  if (method === "GET" && segments[0] === "activity" && segments.length === 1) {
@@ -214,7 +381,8 @@ export async function handleAdmin(ctx, request, response, path, url) {
214
381
  const entry = await runtime.activity.get(segments[1]);
215
382
  if (!entry)
216
383
  throw new FeltKitError("NOT_FOUND", "No such activity entry.");
217
- return sendJSON(response, 200, { entry, serviceEvidence: await runtime.activity.serviceEvidence(entry.requestId) });
384
+ const lookup = await runtime.activity.serviceEvidenceLookup(entry.requestId);
385
+ return sendJSON(response, 200, { entry, serviceEvidence: lookup.records, serviceEvidenceState: lookup.state, serviceEvidenceTruncated: lookup.truncated });
218
386
  }
219
387
  // Sessions (agents, service accounts)
220
388
  if (segments[0] === "sessions") {
@@ -260,7 +428,6 @@ export async function handleAdmin(ctx, request, response, path, url) {
260
428
  }
261
429
  /** Everything the Overview screen and `feltkit inspect` show. Never includes credentials. */
262
430
  export async function overviewPayload(runtime) {
263
- await runtime.services.check();
264
431
  const counts = {};
265
432
  const raw = runtime.instance.handle("feltkit.admin");
266
433
  for (const name of runtime.app.collections.keys())
@@ -271,12 +438,14 @@ export async function overviewPayload(runtime) {
271
438
  return {
272
439
  ...runtime.overview(),
273
440
  counts,
274
- services: runtime.services.status(runtime.state === "ready"),
441
+ services: await runtime.services.status(runtime.state === "ready"),
442
+ agent: await agentSummary(runtime),
275
443
  capabilities: capabilitySummary(runtime, await runtime.activity.list({ kind: "capability", limit: 200 })),
276
444
  recentActivity: recent,
277
445
  recentErrors: errors,
278
446
  recentDenials: denied,
279
447
  devUsers: runtime.environment.development ? runtime.app.options.dev?.users ?? [] : [],
448
+ path: await pathToProduction(runtime),
280
449
  };
281
450
  }
282
451
  function coerce(value) {
@@ -289,6 +458,339 @@ function coerce(value) {
289
458
  return value;
290
459
  }
291
460
  /** Resolve the identity the dashboard should act as. Only declared dev users, or anonymous. */
461
+ async function agentSummary(runtime) {
462
+ if (!runtime.agent)
463
+ return { tasks: [], waiting: 0, handoffs: 0 };
464
+ const tasks = await runtime.agent.list("admin", 5);
465
+ return {
466
+ tasks: tasks.map((t) => ({ id: t.task.task_id, objective: t.task.objective, status: t.task.status, pending: t.pending })),
467
+ waiting: (await runtime.agent.list("admin", 200)).reduce((n, t) => n + t.pending, 0),
468
+ handoffs: (await runtime.agent.openHandoffs("admin")).length,
469
+ };
470
+ }
471
+ /** Every credential reference the services hold, and whether it resolves. Never a value. */
472
+ const credentialReport = (runtime) => runtime.services.credentialReferences();
473
+ /** Only a failed job whose handler is registered is retried: AppPort Services resets a job in any state. */
474
+ async function requireRetryable(runtime, jobId) {
475
+ const job = await runtime.services.jobs?.getJob(runtime.app.name, jobId);
476
+ if (!job)
477
+ throw new FeltKitError("NOT_FOUND", "No such job.");
478
+ if (job.status !== "failed")
479
+ throw new FeltKitError("CONFLICT", `The job is ${job.status}; only a failed job can be retried. Nothing was changed.`);
480
+ if (!runtime.services.jobHandlers[job.type])
481
+ throw new FeltKitError("CONFLICT", `No handler is registered for job type ${job.type}; a retry would fail the same way. Nothing was changed.`);
482
+ return job;
483
+ }
484
+ const retryable = (runtime, job) => job.status === "failed" && Boolean(runtime.services.jobHandlers[job.type]);
485
+ /** Refuse a client-chosen identity outright: production actions run as the signed-in operator. */
486
+ function refuseActAs(body) {
487
+ if (body.as !== undefined && body.as !== null && body.as !== "") {
488
+ throw new FeltKitError("FORBIDDEN", "Production actions run as the signed-in operator; acting as another identity (`as`) is not accepted.");
489
+ }
490
+ }
491
+ 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.";
492
+ /**
493
+ * The production admin API. Every route authenticates the operator and authorizes the
494
+ * operation server-side; writes also pass checkWrite (JSON, same origin, CSRF, environment).
495
+ * Anything not listed here is not served in production.
496
+ */
497
+ async function handleProduction(ctx, request, response, path, url) {
498
+ const { runtime } = ctx;
499
+ const method = request.method ?? "GET";
500
+ const segments = path.split("/").filter(Boolean).map(decodeURIComponent);
501
+ const route = `${method} /${segments.map((s, i) => (i >= 1 && /^(tasks|jobs|deliveries|activity)$/.test(segments[i - 1] ?? "") ? ":id" : s)).join("/")}`;
502
+ const environment = { name: runtime.environment.name, production: true, development: false };
503
+ // Signing in and out.
504
+ if (route === "GET /operator/session") {
505
+ let operator = null;
506
+ try {
507
+ operator = await authenticateOperator(runtime, request);
508
+ }
509
+ catch {
510
+ setSessionCookie(runtime, response, null);
511
+ }
512
+ return sendJSON(response, 200, {
513
+ application: runtime.app.name,
514
+ environment,
515
+ operator: operator ? operator.principal : null,
516
+ permissions: operator ? runtime.authority.permissionsFor(operator.principal) : [],
517
+ csrf: operator ? csrfFor(operator) : null,
518
+ });
519
+ }
520
+ if (route === "POST /operator/signin") {
521
+ checkWrite(runtime, request, null);
522
+ const body = await readJSON(request);
523
+ const issued = await signIn(runtime, String(body.grant ?? ""), operatorKey(runtime.environment.runtimeDir));
524
+ setSessionCookie(runtime, response, issued.token);
525
+ const operator = { principal: issued.principal, token: issued.token, via: "operator-session" };
526
+ return sendJSON(response, 200, { operator: issued.principal, permissions: runtime.authority.permissionsFor(issued.principal), csrf: csrfFor(operator), expiresAt: issued.expiresAt });
527
+ }
528
+ const operator = await authenticateOperator(runtime, request);
529
+ if (route === "POST /operator/signout") {
530
+ if (!operator)
531
+ throw new FeltKitError("UNAUTHORIZED", "Not signed in.");
532
+ checkWrite(runtime, request, operator);
533
+ if (operator.token)
534
+ await runtime.sessions.delete(operator.token);
535
+ setSessionCookie(runtime, response, null);
536
+ return sendJSON(response, 200, { ok: true });
537
+ }
538
+ const read = () => requireOperator(runtime, operator, OPERATOR_PERMISSIONS.read);
539
+ const write = async () => {
540
+ const p = await requireOperator(runtime, operator, OPERATOR_PERMISSIONS.write);
541
+ checkWrite(runtime, request, operator);
542
+ const body = await readJSON(request);
543
+ refuseActAs(body);
544
+ return { p, body };
545
+ };
546
+ switch (route) {
547
+ case "GET /overview": {
548
+ const p = await read();
549
+ return sendJSON(response, 200, { ...(await overviewPayload(runtime)), operator: { principal: p, permissions: runtime.authority.permissionsFor(p) } });
550
+ }
551
+ case "GET /capabilities": {
552
+ await read();
553
+ 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) } });
554
+ }
555
+ case "GET /services": {
556
+ await read();
557
+ return sendJSON(response, 200, {
558
+ services: await runtime.services.status(runtime.state === "ready"),
559
+ 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." },
560
+ credentials: await credentialReport(runtime),
561
+ });
562
+ }
563
+ case "GET /services/jobs": {
564
+ await read();
565
+ const jobs = runtime.services.jobs;
566
+ if (!jobs)
567
+ return sendJSON(response, 200, { items: [], enabled: false });
568
+ const items = (await jobs.listJobs(runtime.app.name)).map((j) => ({ ...jobView(j), retryable: retryable(runtime, j) })).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
569
+ return sendJSON(response, 200, { items, enabled: true, handlers: runtime.services.jobHandlers });
570
+ }
571
+ case "GET /services/deliveries": {
572
+ await read();
573
+ const hooks = runtime.services.webhooks;
574
+ if (!hooks)
575
+ return sendJSON(response, 200, { items: [], enabled: false });
576
+ const endpoints = new Map((await hooks.listWebhookEndpoints(runtime.app.name)).map((e) => [e.id, e]));
577
+ 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));
578
+ return sendJSON(response, 200, { items, enabled: true, replay: { enabled: false, reason: REPLAY_DISABLED } });
579
+ }
580
+ case "POST /services/jobs/:id/retry": {
581
+ const { p } = await write();
582
+ const requestId = newRequestId();
583
+ const job = await requireRetryable(runtime, segments[2]);
584
+ const started = Date.now();
585
+ try {
586
+ // Authorized as the operator (jobs.retry); the job keeps its owner and runs as them, re-authorized.
587
+ const retried = await runtime.services.asPrincipal(p, (verified) => runtime.services.jobs.retry(runtime.app.name, job.id, verified), requestId);
588
+ if (!retried)
589
+ throw new FeltKitError("CONFLICT", "The job changed while it was being retried (another retry won). Nothing more was changed.");
590
+ 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 } });
591
+ return sendJSON(response, 200, { item: jobView(retried) });
592
+ }
593
+ catch (error) {
594
+ const denied = isDenied(error);
595
+ 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 } });
596
+ if (denied)
597
+ throw new FeltKitError("FORBIDDEN", `${p.id} may not retry this job.`);
598
+ throw error;
599
+ }
600
+ }
601
+ case "POST /services/deliveries/:id/replay": {
602
+ await requireOperator(runtime, operator, OPERATOR_PERMISSIONS.write);
603
+ throw new FeltKitError("FORBIDDEN", REPLAY_DISABLED);
604
+ }
605
+ case "GET /agent": {
606
+ const p = await read();
607
+ return sendJSON(response, 200, {
608
+ tasks: await runtime.agent.list("admin"),
609
+ handoffs: await runtime.agent.openHandoffs("admin"),
610
+ tools: await runtime.agent.tools(p),
611
+ permissions: { read: "feltkit.agent.read", write: "feltkit.agent.write" },
612
+ });
613
+ }
614
+ case "GET /agent/tasks/:id": {
615
+ await read();
616
+ return sendJSON(response, 200, await runtime.agent.get(segments[2], "admin"));
617
+ }
618
+ case "POST /agent/tasks/:id/approve":
619
+ case "POST /agent/tasks/:id/reject":
620
+ case "POST /agent/tasks/:id/retry":
621
+ case "POST /agent/tasks/:id/resolve": {
622
+ const { p, body } = await write();
623
+ const taskId = segments[2];
624
+ const actionId = String(body.actionId ?? "");
625
+ switch (segments[3]) {
626
+ case "approve":
627
+ return sendJSON(response, 200, await runtime.agent.approve(taskId, actionId, p));
628
+ case "reject":
629
+ return sendJSON(response, 200, await runtime.agent.reject(taskId, actionId, p, typeof body.reason === "string" ? body.reason : undefined));
630
+ case "retry":
631
+ return sendJSON(response, 200, await runtime.agent.retry(taskId, actionId, p));
632
+ default:
633
+ return sendJSON(response, 200, await runtime.agent.resolve(taskId, actionId, { outcome: body.outcome, ...(typeof body.note === "string" ? { note: body.note } : {}) }, p));
634
+ }
635
+ }
636
+ case "GET /activity": {
637
+ await read();
638
+ const kind = url.searchParams.get("kind") ?? undefined;
639
+ const outcome = url.searchParams.get("outcome") ?? undefined;
640
+ 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) }) });
641
+ }
642
+ case "GET /activity/:id": {
643
+ await read();
644
+ const entry = await runtime.activity.get(segments[1]);
645
+ if (!entry)
646
+ throw new FeltKitError("NOT_FOUND", "No such activity entry.");
647
+ const lookup = await runtime.activity.serviceEvidenceLookup(entry.requestId);
648
+ return sendJSON(response, 200, { entry, serviceEvidence: lookup.records, serviceEvidenceState: lookup.state, serviceEvidenceTruncated: lookup.truncated });
649
+ }
650
+ case "GET /readiness": {
651
+ await read();
652
+ return sendJSON(response, 200, await assessReadiness(runtime, { dashboard: true }));
653
+ }
654
+ case "GET /models": {
655
+ await read();
656
+ return sendJSON(response, 200, await modelsView(runtime));
657
+ }
658
+ case "POST /models/test": {
659
+ await write();
660
+ return sendJSON(response, 200, await testModel(runtime));
661
+ }
662
+ case "GET /integrations": {
663
+ await read();
664
+ return sendJSON(response, 200, await integrationsView(runtime));
665
+ }
666
+ case "POST /agent/tasks/:id/decide": {
667
+ const { p } = await write();
668
+ return sendJSON(response, 200, await runtime.agent.decide(segments[2], p));
669
+ }
670
+ case "GET /events": {
671
+ await read();
672
+ const stream = startSSE(response);
673
+ const offChanges = runtime.changes.subscribe((event) => stream.send("change", event));
674
+ const offActivity = runtime.activity.subscribe((entry) => stream.send("activity", entry));
675
+ request.on("close", () => {
676
+ offChanges();
677
+ offActivity();
678
+ stream.close();
679
+ });
680
+ return;
681
+ }
682
+ }
683
+ if (method === "POST" && segments[0] === "integrations" && segments[2] === "check" && segments.length === 3) {
684
+ await write();
685
+ return sendJSON(response, 200, await runtime.integrations.check(segments[1]));
686
+ }
687
+ if (method === "POST" && segments[0] === "integrations" && segments[1] === "calls" && segments[3] === "verify" && segments.length === 4) {
688
+ const { p } = await write();
689
+ return sendJSON(response, 200, { call: await runtime.integrations.verify(segments[2], p) });
690
+ }
691
+ // Model selection is changed on the host (`feltkit model set --env production`), not from Studio.
692
+ // Data browsing and editing, function runs, capability invocation, sessions, task creation,
693
+ // the services console, and "run due work" are development tools.
694
+ if (!operator)
695
+ throw new FeltKitError("UNAUTHORIZED", "Sign in as an operator to use Studio in production.");
696
+ throw new FeltKitError("NOT_FOUND", `${method} /${segments.join("/")} is not available in production.`);
697
+ }
698
+ /**
699
+ * Create → configure → integrate → build a workflow → test → review readiness → deploy →
700
+ * operate, as this environment shows it. "done" only when the runtime can see it; steps it
701
+ * cannot see say so.
702
+ */
703
+ async function pathToProduction(runtime) {
704
+ const model = await runtime.models.status();
705
+ const integrations = runtime.integrations.definitions().map((i) => runtime.integrations.status(i));
706
+ const configured = integrations.filter((i) => !i.problems.length).length;
707
+ const decisionTasks = (await runtime.agent.list("admin", 200)).filter((t) => t.task.constraints?.includes("playbook:decide")).length;
708
+ const capabilities = runtime.functions().filter((f) => f.capability).length + integrations.reduce((n, i) => n + i.operations.length, 0);
709
+ return [
710
+ { step: "Create", state: "done", detail: `${runtime.app.name}: ${runtime.functions().length} function(s), ${capabilities} capabilit(ies).`, link: "capabilities" },
711
+ { 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" },
712
+ { 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" },
713
+ { 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" },
714
+ { step: "Test", state: "not-tracked", detail: "Run `npx feltkit test` (an isolated test environment); Studio does not see test results.", link: null },
715
+ { step: "Review readiness", state: "info", detail: "Real checks of this environment, and what FeltKit cannot check.", link: "readiness" },
716
+ { step: "Deploy", state: "not-tracked", detail: "`npx feltkit deploy` builds and verifies an artifact; hosting is yours (docs/PATH-TO-PRODUCTION.md).", link: null },
717
+ { 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 },
718
+ ];
719
+ }
720
+ /** What decides in this environment, and the providers it could use. Never a secret. */
721
+ async function modelsView(runtime) {
722
+ return {
723
+ status: await runtime.models.status(),
724
+ intelligence: Boolean(runtime.services.intelligence),
725
+ 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 })),
726
+ };
727
+ }
728
+ /** Select the environment's provider and model through the Intelligence service. */
729
+ export async function selectModel(runtime, body) {
730
+ const provider = String(body.provider ?? "");
731
+ const model = String(body.model ?? "");
732
+ if (!provider || !model)
733
+ throw new FeltKitError("INVALID_ARGUMENT", "Choose a provider and a model.");
734
+ await runtime.models.select({
735
+ provider,
736
+ model,
737
+ endpoint: typeof body.endpoint === "string" && body.endpoint ? body.endpoint : null,
738
+ ...(typeof body.credentialRef === "string" && body.credentialRef ? { credentialRef: body.credentialRef } : {}),
739
+ });
740
+ }
741
+ /** One small binary decision through the configured model, to prove the configuration works. */
742
+ async function testModel(runtime) {
743
+ try {
744
+ const outcome = await runtime.models.decide({ kind: "binary", predicate: "Is the number in the context greater than 1?", context: { number: 2 } });
745
+ return { ok: true, result: outcome.result, runtime: outcome.metadata, capabilities: outcome.capabilities, provider: outcome.provider, durationMs: outcome.durationMs };
746
+ }
747
+ catch (error) {
748
+ const e = error;
749
+ return { ok: false, error: { code: e.code ?? "INTERNAL", message: e.message, hint: e.hint ?? null, problem: e.details?.problem ?? null } };
750
+ }
751
+ }
752
+ async function integrationsView(runtime) {
753
+ return {
754
+ integrations: runtime.integrations.definitions().map((i) => runtime.integrations.status(i)),
755
+ calls: (await runtime.integrations.calls({ limit: 100 })).map(({ input: _input, ...call }) => call),
756
+ };
757
+ }
758
+ function isDenied(error) {
759
+ const code = error?.code;
760
+ return code === "DENIED" || code === "FORBIDDEN" || error?.name === "ServiceAuthorityError";
761
+ }
762
+ function jobView(job) {
763
+ return {
764
+ id: job.id,
765
+ type: job.type,
766
+ status: job.status,
767
+ attemptCount: job.attemptCount,
768
+ maxAttempts: job.maxAttempts,
769
+ createdAt: job.createdAt,
770
+ runAt: job.runAt,
771
+ ...(job.startedAt ? { startedAt: job.startedAt } : {}),
772
+ ...(job.completedAt ? { completedAt: job.completedAt } : {}),
773
+ ...(job.nextAttemptAt ? { nextAttemptAt: job.nextAttemptAt } : {}),
774
+ ...(job.lastError ? { lastError: job.lastError } : {}),
775
+ principal: job.principal?.principalId ?? null,
776
+ };
777
+ }
778
+ function deliveryView(delivery, endpoint) {
779
+ return {
780
+ id: delivery.id,
781
+ endpointId: delivery.endpointId,
782
+ ...(endpoint ? { destination: new URL(endpoint.url).origin } : {}),
783
+ eventType: delivery.eventType,
784
+ status: delivery.status,
785
+ attemptCount: delivery.attemptCount,
786
+ createdAt: delivery.createdAt,
787
+ ...(delivery.deliveredAt ? { deliveredAt: delivery.deliveredAt } : {}),
788
+ ...(delivery.nextAttemptAt ? { nextAttemptAt: delivery.nextAttemptAt } : {}),
789
+ ...(delivery.lastStatusCode !== undefined ? { lastStatusCode: delivery.lastStatusCode } : {}),
790
+ ...(delivery.lastError ? { lastError: delivery.lastError } : {}),
791
+ principal: delivery.principal?.principalId ?? null,
792
+ };
793
+ }
292
794
  function identityFor(runtime, as) {
293
795
  if (as === null || as === undefined || as === "anonymous")
294
796
  return null;