@feltdb/feltkit 0.0.0-stage → 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 (129) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +22 -2
  3. package/bin/feltkit.js +3 -0
  4. package/dist/app.d.ts +247 -0
  5. package/dist/app.js +181 -0
  6. package/dist/app.js.map +1 -0
  7. package/dist/cli/deploy.d.ts +8 -0
  8. package/dist/cli/deploy.js +125 -0
  9. package/dist/cli/deploy.js.map +1 -0
  10. package/dist/cli/main.d.ts +9 -0
  11. package/dist/cli/main.js +581 -0
  12. package/dist/cli/main.js.map +1 -0
  13. package/dist/cli/output.d.ts +18 -0
  14. package/dist/cli/output.js +87 -0
  15. package/dist/cli/output.js.map +1 -0
  16. package/dist/cli/skills.d.ts +39 -0
  17. package/dist/cli/skills.js +125 -0
  18. package/dist/cli/skills.js.map +1 -0
  19. package/dist/client/index.d.ts +125 -0
  20. package/dist/client/index.js +306 -0
  21. package/dist/client/index.js.map +1 -0
  22. package/dist/dashboard/assets/index--1Tqbv_A.css +1 -0
  23. package/dist/dashboard/assets/index-Bm4qCYpv.js +15 -0
  24. package/dist/dashboard/index.html +16 -0
  25. package/dist/errors.d.ts +33 -0
  26. package/dist/errors.js +56 -0
  27. package/dist/errors.js.map +1 -0
  28. package/dist/index.d.ts +18 -0
  29. package/dist/index.js +12 -0
  30. package/dist/index.js.map +1 -0
  31. package/dist/react/index.d.ts +40 -0
  32. package/dist/react/index.js +85 -0
  33. package/dist/react/index.js.map +1 -0
  34. package/dist/runtime/activity.d.ts +110 -0
  35. package/dist/runtime/activity.js +113 -0
  36. package/dist/runtime/activity.js.map +1 -0
  37. package/dist/runtime/agent.d.ts +353 -0
  38. package/dist/runtime/agent.js +1345 -0
  39. package/dist/runtime/agent.js.map +1 -0
  40. package/dist/runtime/authority.d.ts +98 -0
  41. package/dist/runtime/authority.js +240 -0
  42. package/dist/runtime/authority.js.map +1 -0
  43. package/dist/runtime/changes.d.ts +42 -0
  44. package/dist/runtime/changes.js +85 -0
  45. package/dist/runtime/changes.js.map +1 -0
  46. package/dist/runtime/content.d.ts +33 -0
  47. package/dist/runtime/content.js +46 -0
  48. package/dist/runtime/content.js.map +1 -0
  49. package/dist/runtime/context.d.ts +76 -0
  50. package/dist/runtime/context.js +2 -0
  51. package/dist/runtime/context.js.map +1 -0
  52. package/dist/runtime/credentials.d.ts +42 -0
  53. package/dist/runtime/credentials.js +32 -0
  54. package/dist/runtime/credentials.js.map +1 -0
  55. package/dist/runtime/data.d.ts +145 -0
  56. package/dist/runtime/data.js +439 -0
  57. package/dist/runtime/data.js.map +1 -0
  58. package/dist/runtime/decisions.d.ts +131 -0
  59. package/dist/runtime/decisions.js +301 -0
  60. package/dist/runtime/decisions.js.map +1 -0
  61. package/dist/runtime/environment.d.ts +36 -0
  62. package/dist/runtime/environment.js +73 -0
  63. package/dist/runtime/environment.js.map +1 -0
  64. package/dist/runtime/idempotency.d.ts +37 -0
  65. package/dist/runtime/idempotency.js +88 -0
  66. package/dist/runtime/idempotency.js.map +1 -0
  67. package/dist/runtime/instance.d.ts +82 -0
  68. package/dist/runtime/instance.js +253 -0
  69. package/dist/runtime/instance.js.map +1 -0
  70. package/dist/runtime/integrations.d.ts +120 -0
  71. package/dist/runtime/integrations.js +412 -0
  72. package/dist/runtime/integrations.js.map +1 -0
  73. package/dist/runtime/loader.d.ts +15 -0
  74. package/dist/runtime/loader.js +121 -0
  75. package/dist/runtime/loader.js.map +1 -0
  76. package/dist/runtime/projects.d.ts +52 -0
  77. package/dist/runtime/projects.js +141 -0
  78. package/dist/runtime/projects.js.map +1 -0
  79. package/dist/runtime/readiness.d.ts +29 -0
  80. package/dist/runtime/readiness.js +154 -0
  81. package/dist/runtime/readiness.js.map +1 -0
  82. package/dist/runtime/runtime.d.ts +227 -0
  83. package/dist/runtime/runtime.js +664 -0
  84. package/dist/runtime/runtime.js.map +1 -0
  85. package/dist/runtime/services.d.ts +327 -0
  86. package/dist/runtime/services.js +686 -0
  87. package/dist/runtime/services.js.map +1 -0
  88. package/dist/runtime/sessions.d.ts +44 -0
  89. package/dist/runtime/sessions.js +109 -0
  90. package/dist/runtime/sessions.js.map +1 -0
  91. package/dist/schema.d.ts +56 -0
  92. package/dist/schema.js +44 -0
  93. package/dist/schema.js.map +1 -0
  94. package/dist/server/admin.d.ts +141 -0
  95. package/dist/server/admin.js +828 -0
  96. package/dist/server/admin.js.map +1 -0
  97. package/dist/server/http.d.ts +19 -0
  98. package/dist/server/http.js +99 -0
  99. package/dist/server/http.js.map +1 -0
  100. package/dist/server/index.d.ts +54 -0
  101. package/dist/server/index.js +305 -0
  102. package/dist/server/index.js.map +1 -0
  103. package/dist/server/management.d.ts +12 -0
  104. package/dist/server/management.js +177 -0
  105. package/dist/server/management.js.map +1 -0
  106. package/dist/server/mcp.d.ts +214 -0
  107. package/dist/server/mcp.js +135 -0
  108. package/dist/server/mcp.js.map +1 -0
  109. package/dist/server/operators.d.ts +77 -0
  110. package/dist/server/operators.js +162 -0
  111. package/dist/server/operators.js.map +1 -0
  112. package/dist/server/project.d.ts +60 -0
  113. package/dist/server/project.js +344 -0
  114. package/dist/server/project.js.map +1 -0
  115. package/dist/server/public.d.ts +14 -0
  116. package/dist/server/public.js +15 -0
  117. package/dist/server/public.js.map +1 -0
  118. package/dist/testing/index.d.ts +20 -0
  119. package/dist/testing/index.js +65 -0
  120. package/dist/testing/index.js.map +1 -0
  121. package/package.json +91 -4
  122. package/skills/.claude-plugin/marketplace.json +16 -0
  123. package/skills/.claude-plugin/plugin.json +24 -0
  124. package/skills/README.md +44 -0
  125. package/skills/feltkit-agent/SKILL.md +84 -0
  126. package/skills/feltkit-build/SKILL.md +143 -0
  127. package/skills/feltkit-data/SKILL.md +79 -0
  128. package/skills/feltkit-operations/SKILL.md +72 -0
  129. package/skills/feltkit-services/SKILL.md +102 -0
@@ -0,0 +1,828 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { FeltKitError } from "../errors.js";
3
+ import { COLLECTION_MARKERS, CollectionResolver, Reader, Writer } from "../runtime/data.js";
4
+ import { ACTIVITY_COLLECTION } from "../runtime/activity.js";
5
+ import { SESSIONS_COLLECTION } from "../runtime/sessions.js";
6
+ import { FILE_CONTENT_COLLECTION } from "../runtime/services.js";
7
+ import { describeEnvironments, listProjects } from "../runtime/projects.js";
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";
13
+ const DASHBOARD = { id: "dashboard", type: "service", roles: [] };
14
+ /** Platform collections the data explorer may show, read-only, with what to redact. */
15
+ const PLATFORM_COLLECTIONS = {
16
+ [ACTIVITY_COLLECTION]: { owner: "FeltKit", description: "Activity log" },
17
+ [SESSIONS_COLLECTION]: {
18
+ owner: "FeltKit",
19
+ description: "Sessions (ids are SHA-256 digests; tokens are never stored)",
20
+ redact: (r) => ({ ...r, id: `${String(r.id).slice(0, 12)}…` }),
21
+ },
22
+ files: { owner: "AppPort Services", description: "File records" },
23
+ notifications: { owner: "AppPort Services", description: "Notifications" },
24
+ notification_deliveries: { owner: "AppPort Services", description: "Notification deliveries" },
25
+ ConfigurationVariables: { owner: "AppPort Services", description: "Configuration variables" },
26
+ file_audit_events: { owner: "AppPort Services", description: "File audit trail" },
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)" },
37
+ [COLLECTION_MARKERS]: { owner: "FeltKit", description: "Per-collection change markers used to fence whole-collection reads" },
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)" },
40
+ };
41
+ export async function handleAdmin(ctx, request, response, path, url) {
42
+ const { runtime } = ctx;
43
+ const production = runtime.environment.production;
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);
48
+ const token = request.headers["x-feltkit-admin"];
49
+ if (typeof token !== "string" || !safeEqual(token, ctx.adminToken)) {
50
+ throw new FeltKitError("UNAUTHORIZED", "The admin API needs the environment's admin token.", {
51
+ hint: "Open the dashboard from the URL `feltkit dev` prints, or run `feltkit inspect`.",
52
+ });
53
+ }
54
+ const method = request.method ?? "GET";
55
+ const segments = path.split("/").filter(Boolean).map(decodeURIComponent);
56
+ const write = method !== "GET" && method !== "HEAD";
57
+ const requireDevelopment = (what) => {
58
+ if (!runtime.environment.development) {
59
+ throw new FeltKitError("FORBIDDEN", `${what} is available only in development; this is the ${runtime.environment.name} environment.`);
60
+ }
61
+ };
62
+ // GET /overview
63
+ if (method === "GET" && segments[0] === "overview") {
64
+ return sendJSON(response, 200, { ...(await overviewPayload(runtime)), url: ctx.url(), projectDir: ctx.projectDir });
65
+ }
66
+ if (method === "GET" && segments[0] === "environments")
67
+ return sendJSON(response, 200, describeEnvironments(ctx.projectDir, runtime));
68
+ if (method === "GET" && segments[0] === "projects")
69
+ return sendJSON(response, 200, { projects: listProjects(), current: ctx.projectDir });
70
+ // Data explorer
71
+ if (segments[0] === "collections") {
72
+ const raw = runtime.instance.handle("feltkit.admin");
73
+ if (method === "GET" && segments.length === 1) {
74
+ const app = await Promise.all([...runtime.app.collections.values()].map(async (c) => ({
75
+ name: c.name,
76
+ owner: "application",
77
+ editable: runtime.environment.development,
78
+ description: c.description ?? null,
79
+ count: (await raw.collection(c.name).find({})).length,
80
+ schema: c.schema.toJSONSchema(),
81
+ })));
82
+ const platform = await Promise.all(Object.entries(PLATFORM_COLLECTIONS).map(async ([name, info]) => ({
83
+ name,
84
+ owner: info.owner,
85
+ editable: false,
86
+ description: info.description,
87
+ count: (await raw.collection(name).find({})).length,
88
+ schema: null,
89
+ })));
90
+ return sendJSON(response, 200, { collections: [...app, ...platform] });
91
+ }
92
+ const name = segments[1];
93
+ const definition = runtime.app.collections.get(name);
94
+ const platform = PLATFORM_COLLECTIONS[name];
95
+ if (!definition && !platform)
96
+ throw new FeltKitError("NOT_FOUND", `Unknown collection "${name}".`);
97
+ const redact = platform?.redact ?? ((r) => r);
98
+ if (method === "GET" && segments.length === 2) {
99
+ const limit = Math.min(Number(url.searchParams.get("limit") ?? 50) || 50, 500);
100
+ const cursor = url.searchParams.get("cursor") ?? undefined;
101
+ const field = url.searchParams.get("field");
102
+ const eq = url.searchParams.get("eq");
103
+ const page = await raw.query({
104
+ collection: name,
105
+ ...(field && eq !== null ? { where: [{ field, eq: coerce(eq) }] } : {}),
106
+ orderBy: [{ field: "id", direction: "desc" }],
107
+ limit,
108
+ ...(cursor ? { cursor } : {}),
109
+ });
110
+ return sendJSON(response, 200, { records: page.records.map(redact), nextCursor: page.nextCursor ?? null, exhausted: page.exhausted });
111
+ }
112
+ if (method === "GET" && segments.length === 3) {
113
+ const record = await raw.collection(name).get(segments[2]);
114
+ if (!record)
115
+ throw new FeltKitError("NOT_FOUND", `${name}/${segments[2]} does not exist.`);
116
+ return sendJSON(response, 200, { record: redact(record) });
117
+ }
118
+ if (write) {
119
+ if (production)
120
+ throw new FeltKitError("FORBIDDEN", "Data edits from the dashboard are disabled in production.");
121
+ requireDevelopment("Editing records from the dashboard");
122
+ if (!definition)
123
+ throw new FeltKitError("FORBIDDEN", `"${name}" belongs to ${platform.owner} and is read-only here.`);
124
+ const started = Date.now();
125
+ const requestId = `req_${randomUUID()}`;
126
+ const writer = new Writer(runtime.instance.handle("feltkit.admin"), new CollectionResolver(runtime.app.collections));
127
+ let id = segments[2];
128
+ let op;
129
+ const body = method === "DELETE" ? {} : await readJSON(request);
130
+ try {
131
+ if (method === "POST" && segments.length === 2) {
132
+ id = await writer.insert(definition, (body.record ?? body));
133
+ op = "insert";
134
+ }
135
+ else if (method === "PATCH" && id) {
136
+ await writer.patch(definition, id, (body.record ?? body));
137
+ op = "update";
138
+ }
139
+ else if (method === "DELETE" && id) {
140
+ await writer.delete(definition, id);
141
+ op = "delete";
142
+ }
143
+ else {
144
+ throw new FeltKitError("INVALID_ARGUMENT", "Unsupported data operation.");
145
+ }
146
+ const commit = await writer.commit(requestId);
147
+ void runtime.changes.check();
148
+ runtime.activity.record({
149
+ kind: "admin",
150
+ name: `data.${op}`,
151
+ via: "dashboard",
152
+ requestId,
153
+ principal: DASHBOARD,
154
+ outcome: "success",
155
+ durationMs: Date.now() - started,
156
+ writes: commit.writes,
157
+ transactionId: commit.transactionId,
158
+ ...(commit.commitRevision !== undefined ? { commitRevision: commit.commitRevision } : {}),
159
+ detail: { note: "Development data edit: validated against the schema; function access rules do not apply." },
160
+ });
161
+ const record = op === "delete" ? null : await new Reader(runtime.instance.handle("feltkit.admin"), new CollectionResolver(runtime.app.collections)).get(definition, id);
162
+ return sendJSON(response, 200, { ok: true, id, record, transactionId: commit.transactionId });
163
+ }
164
+ catch (error) {
165
+ runtime.activity.record({
166
+ kind: "admin",
167
+ name: `data.${method.toLowerCase()}`,
168
+ via: "dashboard",
169
+ requestId,
170
+ principal: DASHBOARD,
171
+ outcome: "error",
172
+ error: { code: error.code ?? "INTERNAL", message: error.message },
173
+ durationMs: Date.now() - started,
174
+ });
175
+ throw error;
176
+ }
177
+ }
178
+ }
179
+ // Functions and capabilities
180
+ if (method === "GET" && segments[0] === "functions")
181
+ return sendJSON(response, 200, { functions: runtime.functions() });
182
+ if (method === "POST" && segments[0] === "functions" && segments[1] === "run") {
183
+ requireDevelopment("Running functions from the dashboard");
184
+ const body = await readJSON(request);
185
+ const principal = identityFor(runtime, body.as);
186
+ const result = await runtime.call(String(body.name ?? ""), body.args ?? {}, { principal, via: "dashboard" });
187
+ return sendJSON(response, 200, result);
188
+ }
189
+ if (method === "GET" && segments[0] === "capabilities") {
190
+ const manifest = runtime.appport.manifest();
191
+ const recent = await runtime.activity.list({ kind: "capability", limit: 200 });
192
+ return sendJSON(response, 200, { manifest, capabilities: capabilitySummary(runtime, recent), mcp: { endpoint: "/mcp", tools: runtime.mcpBridge(null).listTools().map((t) => t.name) } });
193
+ }
194
+ if (method === "POST" && segments[0] === "capabilities" && segments[1] === "invoke") {
195
+ requireDevelopment("Invoking capabilities from the dashboard");
196
+ const body = await readJSON(request);
197
+ const principal = identityFor(runtime, body.as);
198
+ // A short-lived session for the chosen identity: AppPort authorizes the call exactly as it would any other.
199
+ const session = principal ? await runtime.sessions.issue(runtime.app.name, principal, { kind: "dashboard-invoke", ttlMs: 60_000 }) : undefined;
200
+ try {
201
+ const reply = await runtime.appport.handleRequest({
202
+ protocol: "appport/1",
203
+ type: "request",
204
+ requestId: `req_${randomUUID()}`,
205
+ capability: { name: String(body.capability ?? ""), version: Number(body.version ?? 1) },
206
+ input: body.input ?? {},
207
+ }, { ...(session ? { session } : {}), transport: "dashboard" });
208
+ return sendJSON(response, 200, reply);
209
+ }
210
+ finally {
211
+ if (session)
212
+ await runtime.sessions.delete(session.id);
213
+ }
214
+ }
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("/")}.`);
368
+ }
369
+ // Activity
370
+ if (method === "GET" && segments[0] === "activity" && segments.length === 1) {
371
+ const kind = url.searchParams.get("kind") ?? undefined;
372
+ const outcome = url.searchParams.get("outcome") ?? undefined;
373
+ const entries = await runtime.activity.list({
374
+ ...(kind ? { kind: kind } : {}),
375
+ ...(outcome ? { outcome: outcome } : {}),
376
+ limit: Number(url.searchParams.get("limit") ?? 100) || 100,
377
+ });
378
+ return sendJSON(response, 200, { entries });
379
+ }
380
+ if (method === "GET" && segments[0] === "activity" && segments[1]) {
381
+ const entry = await runtime.activity.get(segments[1]);
382
+ if (!entry)
383
+ throw new FeltKitError("NOT_FOUND", "No such activity entry.");
384
+ const lookup = await runtime.activity.serviceEvidenceLookup(entry.requestId);
385
+ return sendJSON(response, 200, { entry, serviceEvidence: lookup.records, serviceEvidenceState: lookup.state, serviceEvidenceTruncated: lookup.truncated });
386
+ }
387
+ // Sessions (agents, service accounts)
388
+ if (segments[0] === "sessions") {
389
+ if (method === "GET")
390
+ return sendJSON(response, 200, { sessions: await runtime.sessions.list() });
391
+ if (method === "POST") {
392
+ requireDevelopment("Issuing sessions from the dashboard");
393
+ const body = await readJSON(request);
394
+ const issued = await runtime.issueSession(body.principal, {
395
+ kind: String(body.kind ?? "dashboard"),
396
+ ...(body.label ? { label: String(body.label) } : {}),
397
+ ...(body.ttlMs ? { ttlMs: Number(body.ttlMs) } : {}),
398
+ via: "dashboard",
399
+ actor: DASHBOARD,
400
+ });
401
+ return sendJSON(response, 200, issued);
402
+ }
403
+ if (method === "DELETE" && segments[1]) {
404
+ const revoked = await runtime.sessions.revoke(segments[1]);
405
+ runtime.activity.record({ kind: "auth", name: "session.revoked", via: "dashboard", requestId: `req_${randomUUID()}`, principal: DASHBOARD, outcome: revoked ? "success" : "error", durationMs: 0, detail: { ref: segments[1] } });
406
+ return sendJSON(response, revoked ? 200 : 404, { revoked });
407
+ }
408
+ }
409
+ // Live stream for the dashboard: every change (including platform collections) and every activity entry.
410
+ if (method === "GET" && segments[0] === "events") {
411
+ const stream = startSSE(response);
412
+ const offChanges = runtime.changes.subscribe((event) => stream.send("change", event));
413
+ const offActivity = runtime.activity.subscribe((entry) => stream.send("activity", entry));
414
+ const offReload = runtime.onReload(() => stream.send("reload", { generation: runtime.generation, at: new Date().toISOString() }));
415
+ request.on("close", () => {
416
+ offChanges();
417
+ offActivity();
418
+ offReload();
419
+ stream.close();
420
+ });
421
+ return;
422
+ }
423
+ throw new FeltKitError("NOT_FOUND", `No admin endpoint ${method} /${segments.join("/")}.`);
424
+ }
425
+ catch (error) {
426
+ sendError(response, error, production);
427
+ }
428
+ }
429
+ /** Everything the Overview screen and `feltkit inspect` show. Never includes credentials. */
430
+ export async function overviewPayload(runtime) {
431
+ const counts = {};
432
+ const raw = runtime.instance.handle("feltkit.admin");
433
+ for (const name of runtime.app.collections.keys())
434
+ counts[name] = (await raw.collection(name).find({})).length;
435
+ const recent = await runtime.activity.list({ limit: 15 });
436
+ const errors = await runtime.activity.list({ outcome: "error", limit: 10 });
437
+ const denied = await runtime.activity.list({ outcome: "denied", limit: 10 });
438
+ return {
439
+ ...runtime.overview(),
440
+ counts,
441
+ services: await runtime.services.status(runtime.state === "ready"),
442
+ agent: await agentSummary(runtime),
443
+ capabilities: capabilitySummary(runtime, await runtime.activity.list({ kind: "capability", limit: 200 })),
444
+ recentActivity: recent,
445
+ recentErrors: errors,
446
+ recentDenials: denied,
447
+ devUsers: runtime.environment.development ? runtime.app.options.dev?.users ?? [] : [],
448
+ path: await pathToProduction(runtime),
449
+ };
450
+ }
451
+ function coerce(value) {
452
+ if (value === "true")
453
+ return true;
454
+ if (value === "false")
455
+ return false;
456
+ if (value !== "" && !Number.isNaN(Number(value)))
457
+ return Number(value);
458
+ return value;
459
+ }
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
+ }
794
+ function identityFor(runtime, as) {
795
+ if (as === null || as === undefined || as === "anonymous")
796
+ return null;
797
+ const id = typeof as === "string" ? as : as.id;
798
+ const user = runtime.app.options.dev?.users?.find((u) => u.id === id);
799
+ if (!user)
800
+ throw new FeltKitError("INVALID_ARGUMENT", `"${String(id)}" is not a declared dev user. The dashboard can act only as identities declared in feltkit({ dev: { users } }).`);
801
+ return { id: user.id, type: user.type ?? "user", roles: user.roles, ...(user.name ? { displayName: user.name } : {}) };
802
+ }
803
+ function capabilitySummary(runtime, recent = []) {
804
+ const manifest = runtime.appport.manifest();
805
+ const functionsByCapability = new Map(runtime.functions().filter((f) => f.capability).map((f) => [f.capability.name, f]));
806
+ return (manifest.capabilities ?? [])
807
+ .filter((c) => !String(c.name).startsWith("appport."))
808
+ .map((c) => {
809
+ const fn = functionsByCapability.get(c.name);
810
+ const calls = recent.filter((e) => e.capability?.name === c.name);
811
+ return {
812
+ name: c.name,
813
+ version: c.latestVersion ?? c.versions?.at(-1) ?? 1,
814
+ versions: c.versions ?? [],
815
+ description: c.description ?? null,
816
+ effect: c.effect ?? null,
817
+ authorization: c.authorization ?? [],
818
+ idempotency: c.idempotency ?? null,
819
+ input: c.inputSchema ?? null,
820
+ output: c.outputSchema ?? null,
821
+ function: fn ? { name: fn.name, kind: fn.kind, access: fn.access } : null,
822
+ /** Observed, not declared: services these calls actually used. */
823
+ services: [...new Set(calls.flatMap((e) => e.services ?? []))],
824
+ recent: calls.slice(0, 10).map((e) => ({ id: e.id, at: e.at, outcome: e.outcome, via: e.via, principal: e.principal?.id ?? null, durationMs: e.durationMs, error: e.error ?? null })),
825
+ };
826
+ });
827
+ }
828
+ //# sourceMappingURL=admin.js.map