@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
@@ -0,0 +1,301 @@
1
+ import { getIntelligenceProvider } from "@appport/services";
2
+ import { FeltKitError } from "../errors.js";
3
+ import { systemPrincipal } from "./authority.js";
4
+ const CODE = {
5
+ not_configured: "CONFIGURATION",
6
+ intelligence_disabled: "CONFIGURATION",
7
+ unknown_protocol: "CONFIGURATION",
8
+ credential_missing: "CONFIGURATION",
9
+ credential_refused: "CONFIGURATION",
10
+ timeout: "UNAVAILABLE",
11
+ unavailable: "UNAVAILABLE",
12
+ provider_error: "UNAVAILABLE",
13
+ malformed: "UNAVAILABLE",
14
+ unsupported: "INVALID_ARGUMENT",
15
+ };
16
+ export function modelError(problem, message, hint, details = {}) {
17
+ return new FeltKitError(CODE[problem], message, { hint, details: { problem, ...details } });
18
+ }
19
+ export const DEFAULT_DECISION_TIMEOUT_MS = 20_000;
20
+ const PROMPT_REVISION = "feltkit-decision-v1";
21
+ /** Labels a decision may answer with. */
22
+ export function decisionLabels(request) {
23
+ return request.kind === "binary" ? ["YES", "NO"] : request.kind === "choice" ? [...request.options] : [...request.levels];
24
+ }
25
+ /** The same shape of prompt FeltDB's WebLLM runtime uses: the question, the labels, and only the authorized context. */
26
+ export function decisionPrompt(request) {
27
+ const question = request.kind === "binary" ? request.predicate : request.question;
28
+ return [
29
+ "Evaluate the question using only the authorized context below.",
30
+ "Return exactly one label from the allowed labels. Do not explain.",
31
+ `Allowed labels: ${decisionLabels(request).join(" | ")}`,
32
+ `Question: ${question}`,
33
+ `Authorized context: ${JSON.stringify(request.context ?? {})}`,
34
+ "Label:",
35
+ ].join("\n");
36
+ }
37
+ /** Build a FeltDB DecisionResult from one chosen label. Without a distribution, only the choice is reported. */
38
+ export function resultFor(request, selected, probabilities) {
39
+ const labels = decisionLabels(request);
40
+ const total = probabilities ? labels.reduce((sum, l) => sum + (probabilities[l] ?? 0), 0) : 0;
41
+ const distribution = labels.map((value) => ({ value, probability: total > 0 ? (probabilities[value] ?? 0) / total : value === selected ? 1 : 0 }));
42
+ const optionMass = distribution.find((d) => d.value === selected)?.probability ?? 0;
43
+ if (request.kind === "binary")
44
+ return { kind: "binary", decision: selected === "YES", option_mass: optionMass };
45
+ if (request.kind === "choice")
46
+ return { kind: "choice", selected, options: distribution, option_mass: optionMass };
47
+ return { kind: "score", selected, levels: distribution, option_mass: optionMass };
48
+ }
49
+ /** Match a model's answer to exactly one allowed label, or refuse it. */
50
+ export function matchLabel(answer, labels, provider) {
51
+ const text = typeof answer === "string" ? answer.trim().replace(/^["'`]+|["'`.]+$/g, "").trim() : "";
52
+ const exact = labels.find((l) => l === text) ?? labels.find((l) => l.toLowerCase() === text.toLowerCase());
53
+ if (!exact) {
54
+ throw modelError("malformed", `${provider} answered ${JSON.stringify(String(answer ?? "").slice(0, 80))}, which is not one of the allowed labels (${labels.join(", ")}).`, "Nothing was decided. Use a model that follows instructions, or check the endpoint serves the model you configured.", { provider });
55
+ }
56
+ return exact;
57
+ }
58
+ /** Remove a secret from text that may echo it (provider error bodies, URLs). */
59
+ const scrub = (text, secret) => (secret ? text.split(secret).join("[redacted]") : text).replace(/\b(sk|key)-[A-Za-z0-9_-]{12,}/g, "[redacted]");
60
+ async function post(connection, url, headers, body) {
61
+ const timeoutMs = connection.timeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
62
+ let response;
63
+ try {
64
+ response = await (connection.fetch ?? fetch)(url, { method: "POST", headers: { "content-type": "application/json", ...headers }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeoutMs) });
65
+ }
66
+ catch (error) {
67
+ const name = error?.name;
68
+ if (name === "TimeoutError" || name === "AbortError") {
69
+ throw modelError("timeout", `${connection.provider} did not answer within ${timeoutMs} ms.`, "Nothing was decided. Check the endpoint is reachable and not overloaded, or raise the timeout.", { provider: connection.provider, timeoutMs });
70
+ }
71
+ const cause = scrub(String(error?.cause?.code ?? error?.message ?? error), connection.credential);
72
+ throw modelError("unavailable", `${connection.provider} could not be reached at ${new URL(url).origin} (${cause}).`, "Nothing was decided. Start the model server, or correct the endpoint in the Intelligence configuration.", { provider: connection.provider });
73
+ }
74
+ const text = await response.text();
75
+ if (response.status === 401 || response.status === 403) {
76
+ throw modelError("credential_refused", `${connection.provider} refused the credential (HTTP ${response.status}).`, "Nothing was decided. Replace the value of the credential reference in the environment, or check the key's access to this model.", { provider: connection.provider, status: response.status });
77
+ }
78
+ if (!response.ok) {
79
+ throw modelError("provider_error", `${connection.provider} answered HTTP ${response.status}: ${scrub(text, connection.credential).slice(0, 200)}`, "Nothing was decided. Check the model name and the provider's status.", { provider: connection.provider, status: response.status });
80
+ }
81
+ try {
82
+ return JSON.parse(text);
83
+ }
84
+ catch {
85
+ throw modelError("malformed", `${connection.provider} answered with something that is not JSON.`, "Nothing was decided. Check the endpoint is the provider's API, not a web page or proxy.", { provider: connection.provider });
86
+ }
87
+ }
88
+ const join = (endpoint, path) => `${endpoint.replace(/\/+$/, "")}${path}`;
89
+ class HttpDecisionRuntime {
90
+ connection;
91
+ constructor(connection) {
92
+ this.connection = connection;
93
+ }
94
+ async executeBatch(batch) {
95
+ const out = [];
96
+ for (const decision of batch.decisions) {
97
+ const context = { ...(batch.context ?? {}), ...(decision.context ?? {}) };
98
+ const d = decision.definition;
99
+ const request = d.kind === "binary" ? { kind: "binary", predicate: d.predicate, context } : d.kind === "choice" ? { kind: "choice", question: d.question, options: d.options, context } : { kind: "score", question: d.question, levels: d.levels, context };
100
+ out.push({ id: decision.id, result: await this.execute(request) });
101
+ }
102
+ return out;
103
+ }
104
+ }
105
+ /** OpenAI chat completions: OpenAI itself and every OpenAI-compatible server. */
106
+ export class OpenAIChatDecisionRuntime extends HttpDecisionRuntime {
107
+ metadata() {
108
+ return { runtime: "feltkit-openai-chat", model: this.connection.model, prompt_revision: PROMPT_REVISION, execution_method: "generated", decision_schema_revision: "semantic-decision-v1" };
109
+ }
110
+ capabilities() {
111
+ // The answer is generated text matched to a label; no probability distribution is claimed.
112
+ return { binary: true, choice: true, score: true, batch: true, probability_distribution: false, execution_methods: ["generated"] };
113
+ }
114
+ async execute(request) {
115
+ const labels = decisionLabels(request);
116
+ const body = await post(this.connection, join(this.connection.endpoint, "/chat/completions"), this.connection.credential ? { authorization: `Bearer ${this.connection.credential}` } : {}, { model: this.connection.model, temperature: 0, max_tokens: 16, messages: [{ role: "user", content: decisionPrompt(request) }] });
117
+ const content = body?.choices?.[0]?.message?.content;
118
+ if (content === undefined)
119
+ throw modelError("malformed", `${this.connection.provider} returned no choices[0].message.content.`, "Nothing was decided. Check the endpoint implements OpenAI chat completions.", { provider: this.connection.provider });
120
+ return resultFor(request, matchLabel(content, labels, this.connection.provider));
121
+ }
122
+ }
123
+ /** Anthropic Messages, with the answer forced through a tool whose input is one of the labels. */
124
+ export class AnthropicDecisionRuntime extends HttpDecisionRuntime {
125
+ metadata() {
126
+ return { runtime: "feltkit-anthropic-messages", model: this.connection.model, prompt_revision: PROMPT_REVISION, execution_method: "structured", decision_schema_revision: "semantic-decision-v1" };
127
+ }
128
+ capabilities() {
129
+ return { binary: true, choice: true, score: true, batch: true, probability_distribution: false, execution_methods: ["structured"] };
130
+ }
131
+ async execute(request) {
132
+ const labels = decisionLabels(request);
133
+ const base = this.connection.endpoint.replace(/\/+$/, "");
134
+ const body = await post(this.connection, base.endsWith("/v1") ? `${base}/messages` : `${base}/v1/messages`, { "anthropic-version": "2023-06-01", ...(this.connection.credential ? { "x-api-key": this.connection.credential } : {}) }, {
135
+ model: this.connection.model,
136
+ max_tokens: 64,
137
+ tools: [{ name: "decide", description: "Record the decision as exactly one allowed label.", input_schema: { type: "object", properties: { label: { type: "string", enum: labels } }, required: ["label"] } }],
138
+ tool_choice: { type: "tool", name: "decide" },
139
+ messages: [{ role: "user", content: decisionPrompt(request) }],
140
+ });
141
+ const use = body?.content?.find((c) => c.type === "tool_use" && c.name === "decide");
142
+ if (!use)
143
+ throw modelError("malformed", `${this.connection.provider} did not answer with the decide tool.`, "Nothing was decided. Use a model that supports tool use.", { provider: this.connection.provider });
144
+ return resultFor(request, matchLabel(use.input?.label, labels, this.connection.provider));
145
+ }
146
+ }
147
+ /** Server-side runtimes by AppPort Services Intelligence protocol. */
148
+ export const PROTOCOL_RUNTIMES = {
149
+ openai: (c) => new OpenAIChatDecisionRuntime(c),
150
+ "openai-compatible": (c) => new OpenAIChatDecisionRuntime(c),
151
+ anthropic: (c) => new AnthropicDecisionRuntime(c),
152
+ };
153
+ /** One environment's model decisions. */
154
+ export class ModelHost {
155
+ #runtime;
156
+ #reader = systemPrincipal("model-configuration");
157
+ #writer = systemPrincipal("model-selection", "write");
158
+ #fetch;
159
+ constructor(runtime, options = {}) {
160
+ this.#runtime = runtime;
161
+ this.#fetch = options.fetch;
162
+ }
163
+ get #timeoutMs() {
164
+ return this.#runtime.app.options.agent?.decisionTimeoutMs ?? DEFAULT_DECISION_TIMEOUT_MS;
165
+ }
166
+ #applicationRuntime() {
167
+ const option = this.#runtime.app.options.agent?.decisions;
168
+ if (!option)
169
+ return null;
170
+ if (typeof option === "function")
171
+ return option({ name: this.#runtime.environment.name, production: this.#runtime.environment.production }) ?? null;
172
+ return option;
173
+ }
174
+ async #selection() {
175
+ const services = this.#runtime.services;
176
+ if (!services.intelligence)
177
+ return null;
178
+ return services.asPrincipal(this.#reader, (verified) => services.intelligence.resolveRuntime(services.scope, verified));
179
+ }
180
+ /**
181
+ * Select this environment's provider and model in AppPort Services Intelligence. Host
182
+ * code only (the CLI, tests, development Studio): production Studio does not expose it.
183
+ * The credential is a reference; its value lives in FELTKIT_CREDENTIAL_<ID>.
184
+ */
185
+ async select(input) {
186
+ const intelligence = this.#runtime.services.intelligence;
187
+ if (!intelligence)
188
+ throw new FeltKitError("CONFIGURATION", "The Intelligence service is not enabled.", { hint: "Add services: { intelligence: true } to feltkit({ ... })." });
189
+ if (!getIntelligenceProvider(input.provider))
190
+ throw new FeltKitError("INVALID_ARGUMENT", `Unknown provider "${input.provider}".`);
191
+ if (input.credentialRef && !/^credential-ref:[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/.test(input.credentialRef)) {
192
+ throw new FeltKitError("INVALID_ARGUMENT", "A credential is a reference such as credential-ref:openai, never a key. Its value goes in FELTKIT_CREDENTIAL_<ID>.");
193
+ }
194
+ try {
195
+ await this.#runtime.services.asPrincipal(this.#writer, (v) => intelligence.set({ ...this.#runtime.services.scope, provider: input.provider, model: input.model, endpoint: input.endpoint ?? null, ...(input.credentialRef ? { credentialRef: input.credentialRef } : {}) }, v));
196
+ }
197
+ catch (error) {
198
+ throw new FeltKitError("INVALID_ARGUMENT", error.message);
199
+ }
200
+ return this.status();
201
+ }
202
+ async status() {
203
+ const empty = { required: false, ref: null, variable: null, present: false };
204
+ const app = this.#applicationRuntime();
205
+ if (app) {
206
+ return { source: "application", ready: true, provider: app.metadata().runtime, protocol: null, model: app.metadata().model ?? null, endpoint: null, credential: empty, runtime: { metadata: app.metadata(), capabilities: app.capabilities() }, problems: [] };
207
+ }
208
+ const base = { source: "none", ready: false, provider: null, protocol: null, model: null, endpoint: null, credential: empty, runtime: null, problems: [] };
209
+ if (!this.#runtime.services.intelligence) {
210
+ base.problems.push({ problem: "intelligence_disabled", message: "No model is configured: the Intelligence service is not enabled and the application supplies no decision runtime.", fix: "Enable it with feltkit({ services: { intelligence: true } }) and choose a provider in Studio → Models, or pass agent.decisions." });
211
+ return base;
212
+ }
213
+ const selection = await this.#selection();
214
+ if (!selection) {
215
+ base.problems.push({ problem: "not_configured", message: `No model is selected for the ${this.#runtime.environment.name} environment.`, fix: this.#runtime.environment.production ? "Select a provider and model for production: `feltkit model set --env production --provider <id> --model <model>` on the host." : "Choose a provider and model in Studio → Models (or `feltkit model set`)." });
216
+ return base;
217
+ }
218
+ const provider = getIntelligenceProvider(selection.provider);
219
+ const required = provider?.credential === "required";
220
+ const described = selection.credentialRef ? this.#runtime.services.credentials.describe(selection.credentialRef) : null;
221
+ const status = {
222
+ source: "intelligence",
223
+ ready: true,
224
+ provider: selection.provider,
225
+ protocol: selection.protocol,
226
+ model: selection.model,
227
+ endpoint: selection.endpoint,
228
+ credential: { required, ref: selection.credentialRef ?? null, variable: described?.variable ?? null, present: described?.present ?? false },
229
+ runtime: null,
230
+ problems: [],
231
+ };
232
+ const factory = PROTOCOL_RUNTIMES[selection.protocol];
233
+ if (!factory) {
234
+ status.problems.push({ problem: "unknown_protocol", message: `FeltKit has no runtime for the "${selection.protocol}" protocol.`, fix: "Choose an OpenAI, OpenAI-compatible, or Anthropic provider, or pass agent.decisions." });
235
+ }
236
+ else {
237
+ const runtime = factory({ provider: selection.provider, model: selection.model, endpoint: selection.endpoint });
238
+ status.runtime = { metadata: runtime.metadata(), capabilities: runtime.capabilities() };
239
+ }
240
+ if (required && !selection.credentialRef) {
241
+ status.problems.push({ problem: "credential_missing", message: `${selection.provider} needs a credential and none is attached.`, fix: "Attach a credential reference (credential-ref:<id>) in Studio → Models or with `feltkit model set --credential`." });
242
+ }
243
+ else if (selection.credentialRef && !described?.present) {
244
+ status.problems.push({ problem: "credential_missing", message: `The credential ${selection.credentialRef} does not resolve.`, fix: `Set ${described?.variable ?? "its FELTKIT_CREDENTIAL_<ID> variable"} in this environment's process environment (never in code or FeltDB).` });
245
+ }
246
+ status.ready = status.problems.length === 0;
247
+ return status;
248
+ }
249
+ /**
250
+ * Ask the environment's model. Supported kinds only; the answer must be one of the
251
+ * request's labels. Errors carry the problem and the fix; nothing is retried.
252
+ */
253
+ async decide(request) {
254
+ const started = Date.now();
255
+ const app = this.#applicationRuntime();
256
+ const check = (runtime, provider) => {
257
+ if (!runtime.capabilities()[request.kind]) {
258
+ throw modelError("unsupported", `${provider} does not support ${request.kind} decisions.`, "Use a decision kind the runtime reports in capabilities(), or another runtime.", { provider });
259
+ }
260
+ };
261
+ if (app) {
262
+ check(app, app.metadata().runtime);
263
+ const result = await withTimeout(app.execute(request), this.#timeoutMs, app.metadata().runtime);
264
+ return { result: validated(request, result, app.metadata().runtime), metadata: app.metadata(), capabilities: app.capabilities(), provider: app.metadata().runtime, source: "application", durationMs: Date.now() - started };
265
+ }
266
+ const status = await this.status();
267
+ if (!status.ready || !status.provider || !status.protocol) {
268
+ const first = status.problems[0];
269
+ throw modelError(first.problem, first.message, first.fix);
270
+ }
271
+ const connect = (credential) => PROTOCOL_RUNTIMES[status.protocol]({ provider: status.provider, model: status.model, endpoint: status.endpoint, ...(credential ? { credential } : {}), timeoutMs: this.#timeoutMs, ...(this.#fetch ? { fetch: this.#fetch } : {}) });
272
+ const run = async (runtime) => {
273
+ check(runtime, status.provider);
274
+ return validated(request, await runtime.execute(request), status.provider);
275
+ };
276
+ const ref = status.credential.ref;
277
+ const result = ref
278
+ ? await this.#runtime.services.credentials.withSecret({ reference: { secretId: ref.slice("credential-ref:".length), tenantId: this.#runtime.services.scope.tenantId }, context: { purpose: "model decision" } }, (secret) => run(connect(secret.value)))
279
+ : await run(connect());
280
+ const runtime = connect();
281
+ return { result, metadata: runtime.metadata(), capabilities: runtime.capabilities(), provider: status.provider, source: "intelligence", durationMs: Date.now() - started };
282
+ }
283
+ }
284
+ function validated(request, result, provider) {
285
+ const labels = decisionLabels(request);
286
+ if (!result || result.kind !== request.kind)
287
+ throw modelError("malformed", `${provider} returned a ${String(result?.kind)} result for a ${request.kind} decision.`, "Nothing was decided.", { provider });
288
+ if (result.kind !== "binary" && !labels.includes(result.selected))
289
+ throw modelError("malformed", `${provider} selected "${result.selected}", which was not offered.`, "Nothing was decided.", { provider });
290
+ return result;
291
+ }
292
+ async function withTimeout(work, ms, provider) {
293
+ let timer;
294
+ try {
295
+ return await Promise.race([work, new Promise((_, reject) => (timer = setTimeout(() => reject(modelError("timeout", `${provider} did not decide within ${ms} ms.`, "Nothing was decided.", { provider })), ms)))]);
296
+ }
297
+ finally {
298
+ clearTimeout(timer);
299
+ }
300
+ }
301
+ //# sourceMappingURL=decisions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"decisions.js","sourceRoot":"","sources":["../../src/runtime/decisions.ts"],"names":[],"mappings":"AA0BA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAiBjD,MAAM,IAAI,GAA+E;IACvF,cAAc,EAAE,eAAe;IAC/B,qBAAqB,EAAE,eAAe;IACtC,gBAAgB,EAAE,eAAe;IACjC,kBAAkB,EAAE,eAAe;IACnC,kBAAkB,EAAE,eAAe;IACnC,OAAO,EAAE,aAAa;IACtB,WAAW,EAAE,aAAa;IAC1B,cAAc,EAAE,aAAa;IAC7B,SAAS,EAAE,aAAa;IACxB,WAAW,EAAE,kBAAkB;CAChC,CAAC;AAEF,MAAM,UAAU,UAAU,CAAC,OAAqB,EAAE,OAAe,EAAE,IAAY,EAAE,UAAmC,EAAE;IACpH,OAAO,IAAI,YAAY,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,OAAO,EAAE,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,OAAO,EAAE,GAAG,OAAO,EAAE,EAAE,CAAC,CAAC;AAC9F,CAAC;AAED,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAClD,MAAM,eAAe,GAAG,qBAAqB,CAAC;AAE9C,yCAAyC;AACzC,MAAM,UAAU,cAAc,CAAC,OAAwB;IACrD,OAAO,OAAO,CAAC,IAAI,KAAK,QA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M,IAAI,MAAM,CAAC,IAAI,KAAK,OAAO,CAAC,IAAI;QAAE,MAAM,UAAU,CAAC,WAAW,EAAE,GAAG,QAAQ,eAAe,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,iBAAiB,OAAO,CAAC,IAAI,YAAY,EAAE,sBAAsB,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC1M,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,QAAQ,CAAC;QAAE,MAAM,UAAU,CAAC,WAAW,EAAE,GAAG,QAAQ,cAAc,MAAM,CAAC,QAAQ,2BAA2B,EAAE,sBAAsB,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;IAC5M,OAAO,MAAM,CAAC;AAChB,CAAC;AAED,KAAK,UAAU,WAAW,CAAI,IAAgB,EAAE,EAAU,EAAE,QAAgB;IAC1E,IAAI,KAAiC,CAAC;IACtC,IAAI,CAAC;QACH,OAAO,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,IAAI,OAAO,CAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,UAAU,CAAC,SAAS,EAAE,GAAG,QAAQ,0BAA0B,EAAE,MAAM,EAAE,sBAAsB,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAC3N,CAAC;YAAS,CAAC;QACT,YAAY,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;AACH,CAAC"}
@@ -16,6 +16,12 @@ import { FeltKitError } from "../errors.js";
16
16
  const NAME = /^[a-z][a-z0-9-]{0,31}$/;
17
17
  export function resolveEnvironment(options) {
18
18
  const env = options.env ?? process.env;
19
+ // Fail closed when the environment is ambiguous: never guess which instance to act on.
20
+ if (options.name && env.FELTKIT_ENV && env.FELTKIT_ENV !== options.name) {
21
+ throw new FeltKitError("CONFIGURATION", `The ${options.name} environment was requested, but FELTKIT_ENV is "${env.FELTKIT_ENV}". Refusing to choose between them.`, {
22
+ hint: "Unset FELTKIT_ENV or make it match --env.",
23
+ });
24
+ }
19
25
  const name = options.name ?? env.FELTKIT_ENV ?? "development";
20
26
  if (!NAME.test(name)) {
21
27
  throw new FeltKitError("CONFIGURATION", `Environment name "${name}" is invalid; use lowercase letters, digits, and dashes.`);
@@ -26,6 +32,11 @@ export function resolveEnvironment(options) {
26
32
  const production = name === "production";
27
33
  let storage = options.storage;
28
34
  if (!storage) {
35
+ if (env.FELTDB_URL && env.FELTKIT_STATE_DIR && name !== "development" && name !== "test") {
36
+ throw new FeltKitError("CONFIGURATION", `Both FELTDB_URL and FELTKIT_STATE_DIR are set for ${name}; it is ambiguous which FeltDB instance to use.`, {
37
+ hint: "Set exactly one: FELTDB_URL (+ FELTDB_TOKEN) for a FeltDB server, or FELTKIT_STATE_DIR for local state.",
38
+ });
39
+ }
29
40
  if (env.FELTDB_URL && name !== "development" && name !== "test") {
30
41
  storage = {
31
42
  kind: "remote",
@@ -1 +1 @@
1
- {"version":3,"file":"environment.js","sourceRoot":"","sources":["../../src/runtime/environment.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AACtC,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AAC1C,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AA4B5C,MAAM,IAAI,GAAG,wBAAwB,CAAC;AAEtC,MAAM,UAAU,kBAAkB,CAAC,OAAkC;IACnE,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,OAAO,CAAC,GAAG,CAAC;IACvC,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAK,GAAG,CAAC,WA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G,CAAC;aAAM,CAAC;YACN,OAAO,GAAG,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,UAAU,EAAE,OAAO,CAAC,EAAE,CAAC;QAC/D,CAAC;IACH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,CAAC,OAAO,EAAE,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,UAAU,EAAE,CAAC;AAC5F,CAAC;AAED,mFAAmF;AACnF,MAAM,UAAU,eAAe,CAAC,OAA0B;IACxD,IAAI,OAAO,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC9F,IAAI,OAAO,CAAC,IAAI,KAAK,QAAQ;QAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,IAAI,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC/G,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAChE,CAAC"}
@@ -0,0 +1,37 @@
1
+ /**
2
+ * AppPort's idempotency store (specification §13.1), kept in the application's FeltDB
3
+ * instance instead of AppPort's in-memory default.
4
+ *
5
+ * It implements the whole published `IdempotencyStore` contract of @appport/core 1.4:
6
+ *
7
+ * claim an atomic create-if-absent of the in-progress claim AppPort writes
8
+ * before the handler runs. The guard is FeltDB's own: a transaction
9
+ * with `requireAbsent` (or, over an expired entry, `ifVersion`), checked
10
+ * by the authority inside the commit, so of any number of concurrent
11
+ * claimers — in any process sharing the instance — exactly one wins.
12
+ * set replaces the claim (or an older record) with the completed record.
13
+ * release removes the claim only while it is still the unresolved claim of that
14
+ * request id (version-guarded delete).
15
+ * get completed records only; never a claim.
16
+ * findByRequestId the claim or record a request wrote, for recovery and operators.
17
+ *
18
+ * Because the claim is durable, a process that dies while a handler runs leaves it
19
+ * behind: a replay with the same key is answered `CONFLICT` /
20
+ * `IDEMPOTENCY_OUTCOME_UNKNOWN` by AppPort instead of running the handler again. The
21
+ * claim lasts until it expires (24 h) or an operator resolves it.
22
+ */
23
+ import type { StateFirstDB } from "@feltdb/core";
24
+ import { type IdempotencyClaim, type IdempotencyClaimResult, type IdempotencyEntry, type IdempotencyRecord, type IdempotencyStore } from "@appport/sdk";
25
+ export declare const IDEMPOTENCY_COLLECTION = "_feltkit_idempotency";
26
+ export declare class FeltDbIdempotencyStore implements IdempotencyStore {
27
+ #private;
28
+ constructor(db: StateFirstDB);
29
+ get(key: string): Promise<IdempotencyRecord | undefined>;
30
+ set(record: IdempotencyRecord): Promise<void>;
31
+ claim(claim: IdempotencyClaim): Promise<IdempotencyClaimResult>;
32
+ release(target: {
33
+ key: string;
34
+ requestId: string;
35
+ }): Promise<void>;
36
+ findByRequestId(requestId: string): Promise<IdempotencyEntry | undefined>;
37
+ }
@@ -0,0 +1,88 @@
1
+ import { isIdempotencyClaim } from "@appport/sdk";
2
+ import { createHash } from "node:crypto";
3
+ export const IDEMPOTENCY_COLLECTION = "_feltkit_idempotency";
4
+ const idFor = (key) => createHash("sha256").update(key).digest("hex");
5
+ const live = (entry, now = Date.now()) => (entry && entry.expiresAt > now ? entry : undefined);
6
+ const isConflict = (error) => error?.code === "PRECONDITION_FAILED";
7
+ /** Bounded retries for a guarded write that lost a race; each retry re-reads. */
8
+ const ATTEMPTS = 8;
9
+ export class FeltDbIdempotencyStore {
10
+ #db;
11
+ constructor(db) {
12
+ this.#db = db;
13
+ }
14
+ async get(key) {
15
+ const found = live((await this.#read(key))?.entry);
16
+ return found && !isIdempotencyClaim(found) && found.key === key ? found : undefined;
17
+ }
18
+ async set(record) {
19
+ const id = idFor(record.key);
20
+ for (let attempt = 0;; attempt++) {
21
+ const current = await this.#read(record.key);
22
+ try {
23
+ await this.#db.transaction({ operations: [{ collection: IDEMPOTENCY_COLLECTION, id, ...guard(current), value: { ...record } }] });
24
+ return;
25
+ }
26
+ catch (error) {
27
+ if (!isConflict(error) || attempt + 1 >= ATTEMPTS)
28
+ throw error;
29
+ }
30
+ }
31
+ }
32
+ async claim(claim) {
33
+ const id = idFor(claim.key);
34
+ const value = { ...claim, status: "in-progress" };
35
+ for (let attempt = 0;; attempt++) {
36
+ const current = await this.#read(claim.key);
37
+ const existing = live(current?.entry);
38
+ if (existing)
39
+ return existing;
40
+ try {
41
+ // Absent → requireAbsent; expired → replace exactly the version that was read.
42
+ await this.#db.transaction({ operations: [{ collection: IDEMPOTENCY_COLLECTION, id, ...guard(current), value }] });
43
+ return "claimed";
44
+ }
45
+ catch (error) {
46
+ // Another claimer committed first: answer with what it wrote.
47
+ if (!isConflict(error) || attempt + 1 >= ATTEMPTS)
48
+ throw error;
49
+ }
50
+ }
51
+ }
52
+ async release(target) {
53
+ const current = await this.#read(target.key);
54
+ if (!current || !isIdempotencyClaim(current.entry) || current.entry.requestId !== target.requestId)
55
+ return;
56
+ try {
57
+ await this.#db.transaction({ operations: [{ collection: IDEMPOTENCY_COLLECTION, id: idFor(target.key), ifVersion: current.version }] });
58
+ }
59
+ catch (error) {
60
+ // The claim changed since it was read (completed, or replaced after expiry): not ours to remove.
61
+ if (!isConflict(error))
62
+ throw error;
63
+ }
64
+ }
65
+ async findByRequestId(requestId) {
66
+ const rows = (await this.#db.collection(IDEMPOTENCY_COLLECTION).find({ requestId }, { limit: 16 }));
67
+ const now = Date.now();
68
+ for (const row of rows) {
69
+ const entry = live(strip(row), now);
70
+ if (entry)
71
+ return entry;
72
+ }
73
+ return undefined;
74
+ }
75
+ async #read(key) {
76
+ const row = ((await this.#db.collection(IDEMPOTENCY_COLLECTION).get(idFor(key))) ?? null);
77
+ return row ? { entry: strip(row), version: row.__version } : undefined;
78
+ }
79
+ }
80
+ function guard(current) {
81
+ return current?.version !== undefined ? { ifVersion: current.version } : { requireAbsent: true };
82
+ }
83
+ /** The entry as AppPort wrote it, without FeltDB's record fields. */
84
+ function strip(row) {
85
+ const { id: _id, __version: _version, ...entry } = row;
86
+ return entry;
87
+ }
88
+ //# sourceMappingURL=idempotency.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"idempotency.js","sourceRoot":"","sources":["../../src/runtime/idempotency.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,kBAAkB,EAA4H,MAAM,cAAc,CAAC;AAC5K,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,CAAC,MAAM,sBAAsB,GAAG,sBAAsB,CAAC;AAI7D,MAAM,KAAK,GAAG,CAAC,GAAW,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;AAC9E,MAAM,IAAI,GAAG,CAAC,KAAmC,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,EAAE,EAAE,CAAC,CAAC,KAAK,IAAI,KAAK,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC;AAC7H,MAAM,UAAU,GAAG,CAAC,KAAc,EAAE,EAAE,CAAE,KAAmC,EAAE,IAAI,KAAK,qBAAqB,CAAC;AAC5G,iFAAiF;AACjF,MAAM,QAAQ,GAAG,CAAC,CAAC;AAEnB,MAAM,OAAO,sBAAsB;IACxB,GAAG,CAAe;IAE3B,YAAY,EAAgB;QAC1B,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;IAChB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,GAAW;QACnB,MAAM,KAAK,GAAG,IAAI,CAAC,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;QACnD,OAAO,KAAK,IAAI,CAAC,kBAAkB,CAAC,KAAK,CAAC,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C,IAAI,CAAC,EAAE,SAAS,EAAW,EAAE,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,CAAU,CAAC;QAC3H,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,KAAK,MAAM,GAAG,IAAI,IAAI,EAAE,CAAC;YACvB,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;YACpC,IAAI,KAAK;gBAAE,OAAO,KAAK,CAAC;QAC1B,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,KAAK,CAAC,KAAK,CAAC,GAAW;QACrB,MAAM,GAAG,GAAG,CAAC,CAAC,MAAM,IAAI,CAAC,GAAG,CAAC,UAAU,CAAM,sBAAsB,CAAC,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,IAAI,CAAe,CAAC;QAC7G,OAAO,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,GAAG,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IACzE,CAAC;CACF;AAED,SAAS,KAAK,CAAC,OAAoD;IACjE,OAAO,OAAO,EAAE,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC;AACnG,CAAC;AAED,qEAAqE;AACrE,SAAS,KAAK,CAAC,GAAQ;IACrB,MAAM,EAAE,EAAE,EAAE,GAAG,EAAE,SAAS,EAAE,QAAQ,EAAE,GAAG,KAAK,EAAE,GAAG,GAAG,CAAC;IACvD,OAAO,KAAyB,CAAC;AACnC,CAAC"}
@@ -7,9 +7,14 @@
7
7
  * Every layer (application functions, AppPort capabilities, AppPort Services, the
8
8
  * activity log, sessions) receives a handle through explicit dependency injection.
9
9
  *
10
- * FeltDB itself does not refuse a second instance over the same state in one
11
- * process, so the factory does: a second open for the same environment, or for
12
- * another environment pointing at the same state, throws DUPLICATE_INSTANCE.
10
+ * One owner per state directory:
11
+ *
12
+ * - across processes, FeltDB's own lock: `createFeltDB({ path })` takes `owner.lock`
13
+ * in the state directory and refuses any other process (STATE_LOCKED, mapped here
14
+ * to DUPLICATE_INSTANCE naming the owner, and its URL when it is a FeltKit server);
15
+ * - within a process, this factory: FeltDB lets handles in one process share the lock,
16
+ * so a second open for the same environment, or for another environment pointing
17
+ * at the same state, throws DUPLICATE_INSTANCE here.
13
18
  */
14
19
  import { type StateFirstDB } from "@feltdb/core";
15
20
  import type { EnvironmentDescriptor } from "./environment.js";
@@ -7,15 +7,21 @@
7
7
  * Every layer (application functions, AppPort capabilities, AppPort Services, the
8
8
  * activity log, sessions) receives a handle through explicit dependency injection.
9
9
  *
10
- * FeltDB itself does not refuse a second instance over the same state in one
11
- * process, so the factory does: a second open for the same environment, or for
12
- * another environment pointing at the same state, throws DUPLICATE_INSTANCE.
10
+ * One owner per state directory:
11
+ *
12
+ * - across processes, FeltDB's own lock: `createFeltDB({ path })` takes `owner.lock`
13
+ * in the state directory and refuses any other process (STATE_LOCKED, mapped here
14
+ * to DUPLICATE_INSTANCE naming the owner, and its URL when it is a FeltKit server);
15
+ * - within a process, this factory: FeltDB lets handles in one process share the lock,
16
+ * so a second open for the same environment, or for another environment pointing
17
+ * at the same state, throws DUPLICATE_INSTANCE here.
13
18
  */
14
- import { createFeltDB } from "@feltdb/core";
19
+ import { createFeltDB, FeltDBErrorCode, FeltDBServiceError, LocalStateLockedError } from "@feltdb/core";
15
20
  import { createRequire } from "node:module";
16
21
  import { mkdirSync } from "node:fs";
17
22
  import { resolve } from "node:path";
18
23
  import { FeltKitError } from "../errors.js";
24
+ import { readRuntimeRecord } from "./projects.js";
19
25
  const HANDLE = Symbol.for("feltkit.state-handle");
20
26
  export class StateInstance {
21
27
  identity;
@@ -162,6 +168,15 @@ export class InstanceFactory {
162
168
  db = createFeltDB(options);
163
169
  }
164
170
  catch (error) {
171
+ if (error instanceof LocalStateLockedError || (error instanceof FeltDBServiceError && error.code === FeltDBErrorCode.STATE_LOCKED)) {
172
+ const reason = lockedReason(environment, error);
173
+ this.#emit({ type: "refused", key, environment: environment.name, at: new Date().toISOString(), reason });
174
+ throw new FeltKitError("DUPLICATE_INSTANCE", reason, {
175
+ hint: "Use that server, or stop it first. Two processes on one environment would mean two FeltDB instances on the same state.",
176
+ details: { lockPath: error.lockPath ?? null, owner: error.owner ?? null },
177
+ cause: error,
178
+ });
179
+ }
165
180
  throw new FeltKitError("UNAVAILABLE", `FeltDB could not open ${identity.location}: ${error.message}`, { cause: error });
166
181
  }
167
182
  this.#open.set(key, environment.name);
@@ -217,6 +232,14 @@ export class InstanceFactory {
217
232
  };
218
233
  }
219
234
  }
235
+ /** Who holds the state: the FeltKit server's runtime record when there is one, else FeltDB's lock owner. */
236
+ function lockedReason(environment, error) {
237
+ const server = readRuntimeRecord(environment.runtimeDir);
238
+ if (server)
239
+ return `The ${environment.name} environment is already running (pid ${server.pid}) at ${server.url}.`;
240
+ const owner = error.owner ?? {};
241
+ return `The ${environment.name} environment's state is already open in another process${owner.pid ? ` (pid ${owner.pid}${owner.host ? ` on ${owner.host}` : ""})` : ""}; FeltDB holds ${error.lockPath ?? "its owner lock"}.`;
242
+ }
220
243
  function safeInstanceId(db) {
221
244
  try {
222
245
  return db.instanceId();