@feltdb/feltkit 0.3.21 → 0.3.23

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 (140) hide show
  1. package/dist/app.d.ts +17 -3
  2. package/dist/app.js +10 -0
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.js +4 -0
  5. package/dist/appboundry/build.js.map +1 -1
  6. package/dist/authorize.d.ts +1 -1
  7. package/dist/cli/main.js +8 -152
  8. package/dist/cli/main.js.map +1 -1
  9. package/dist/client/index.d.ts +83 -4
  10. package/dist/client/index.js +154 -2
  11. package/dist/client/index.js.map +1 -1
  12. package/dist/dashboard/assets/index-BEjtLLYq.js +15 -0
  13. package/dist/dashboard/index.html +1 -1
  14. package/dist/docs.d.ts +1 -1
  15. package/dist/docs.js +1 -0
  16. package/dist/docs.js.map +1 -1
  17. package/dist/index.d.ts +4 -2
  18. package/dist/index.js.map +1 -1
  19. package/dist/platform/approvals.d.ts +102 -0
  20. package/dist/platform/approvals.js +155 -0
  21. package/dist/platform/approvals.js.map +1 -0
  22. package/dist/platform/artifacts.d.ts +126 -0
  23. package/dist/platform/artifacts.js +251 -0
  24. package/dist/platform/artifacts.js.map +1 -0
  25. package/dist/platform/blobs.d.ts +25 -0
  26. package/dist/platform/blobs.js +78 -0
  27. package/dist/platform/blobs.js.map +1 -0
  28. package/dist/platform/diff.d.ts +23 -0
  29. package/dist/platform/diff.js +107 -0
  30. package/dist/platform/diff.js.map +1 -0
  31. package/dist/platform/exec.d.ts +182 -0
  32. package/dist/platform/exec.js +575 -0
  33. package/dist/platform/exec.js.map +1 -0
  34. package/dist/platform/operations.d.ts +30 -13
  35. package/dist/platform/operations.js +8 -17
  36. package/dist/platform/operations.js.map +1 -1
  37. package/dist/platform/permissions.d.ts +15 -0
  38. package/dist/platform/permissions.js +16 -0
  39. package/dist/platform/permissions.js.map +1 -0
  40. package/dist/platform/platform.d.ts +28 -0
  41. package/dist/platform/platform.js +84 -5
  42. package/dist/platform/platform.js.map +1 -1
  43. package/dist/platform/releases.d.ts +110 -0
  44. package/dist/platform/releases.js +344 -0
  45. package/dist/platform/releases.js.map +1 -0
  46. package/dist/platform/review.d.ts +10 -0
  47. package/dist/platform/review.js +109 -0
  48. package/dist/platform/review.js.map +1 -0
  49. package/dist/platform/server.js +7 -0
  50. package/dist/platform/server.js.map +1 -1
  51. package/dist/platform/source.d.ts +2 -0
  52. package/dist/platform/source.js +1 -1
  53. package/dist/platform/source.js.map +1 -1
  54. package/dist/platform/workspace-operations.d.ts +2 -0
  55. package/dist/platform/workspace-operations.js +590 -0
  56. package/dist/platform/workspace-operations.js.map +1 -0
  57. package/dist/platform/workspaces.d.ts +211 -0
  58. package/dist/platform/workspaces.js +435 -0
  59. package/dist/platform/workspaces.js.map +1 -0
  60. package/dist/react/index.d.ts +29 -1
  61. package/dist/react/index.js +50 -0
  62. package/dist/react/index.js.map +1 -1
  63. package/dist/runtime/activity.d.ts +1 -1
  64. package/dist/runtime/agent.d.ts +216 -2
  65. package/dist/runtime/agent.js +333 -7
  66. package/dist/runtime/agent.js.map +1 -1
  67. package/dist/runtime/approval-rules.d.ts +16 -0
  68. package/dist/runtime/approval-rules.js +37 -0
  69. package/dist/runtime/approval-rules.js.map +1 -0
  70. package/dist/runtime/authority.d.ts +18 -1
  71. package/dist/runtime/authority.js +26 -1
  72. package/dist/runtime/authority.js.map +1 -1
  73. package/dist/runtime/browser-inference.d.ts +52 -0
  74. package/dist/runtime/browser-inference.js +53 -0
  75. package/dist/runtime/browser-inference.js.map +1 -0
  76. package/dist/runtime/context.d.ts +110 -0
  77. package/dist/runtime/decisions.d.ts +23 -0
  78. package/dist/runtime/decisions.js +54 -0
  79. package/dist/runtime/decisions.js.map +1 -1
  80. package/dist/runtime/generation.d.ts +94 -0
  81. package/dist/runtime/generation.js +295 -0
  82. package/dist/runtime/generation.js.map +1 -0
  83. package/dist/runtime/runtime.d.ts +10 -2
  84. package/dist/runtime/runtime.js +125 -1
  85. package/dist/runtime/runtime.js.map +1 -1
  86. package/dist/server/admin.d.ts +9 -1
  87. package/dist/server/admin.js +84 -2
  88. package/dist/server/admin.js.map +1 -1
  89. package/dist/server/index.d.ts +1 -1
  90. package/dist/server/index.js +159 -8
  91. package/dist/server/index.js.map +1 -1
  92. package/dist/testing/index.d.ts +11 -0
  93. package/dist/testing/index.js +7 -3
  94. package/dist/testing/index.js.map +1 -1
  95. package/docs/AUTH.md +2 -2
  96. package/docs/GENERATION.md +136 -0
  97. package/docs/README.md +3 -2
  98. package/package.json +2 -4
  99. package/skills/.claude-plugin/marketplace.json +1 -1
  100. package/skills/.claude-plugin/plugin.json +1 -1
  101. package/dist/cli/compose.d.ts +0 -31
  102. package/dist/cli/compose.js +0 -274
  103. package/dist/cli/compose.js.map +0 -1
  104. package/dist/cli/create.d.ts +0 -219
  105. package/dist/cli/create.js +0 -1193
  106. package/dist/cli/create.js.map +0 -1
  107. package/dist/cli/domain.d.ts +0 -174
  108. package/dist/cli/domain.js +0 -1119
  109. package/dist/cli/domain.js.map +0 -1
  110. package/dist/cli/shell.d.ts +0 -7
  111. package/dist/cli/shell.js +0 -59
  112. package/dist/cli/shell.js.map +0 -1
  113. package/dist/composition/catalog.d.ts +0 -3
  114. package/dist/composition/catalog.js +0 -217
  115. package/dist/composition/catalog.js.map +0 -1
  116. package/dist/composition/contract.d.ts +0 -165
  117. package/dist/composition/contract.js +0 -12
  118. package/dist/composition/contract.js.map +0 -1
  119. package/dist/composition/execute.d.ts +0 -110
  120. package/dist/composition/execute.js +0 -350
  121. package/dist/composition/execute.js.map +0 -1
  122. package/dist/composition/generate.d.ts +0 -105
  123. package/dist/composition/generate.js +0 -274
  124. package/dist/composition/generate.js.map +0 -1
  125. package/dist/composition/plan.d.ts +0 -131
  126. package/dist/composition/plan.js +0 -558
  127. package/dist/composition/plan.js.map +0 -1
  128. package/dist/composition/profiles.d.ts +0 -20
  129. package/dist/composition/profiles.js +0 -81
  130. package/dist/composition/profiles.js.map +0 -1
  131. package/dist/composition/reconcile.d.ts +0 -153
  132. package/dist/composition/reconcile.js +0 -282
  133. package/dist/composition/reconcile.js.map +0 -1
  134. package/dist/composition/recover.d.ts +0 -89
  135. package/dist/composition/recover.js +0 -407
  136. package/dist/composition/recover.js.map +0 -1
  137. package/dist/composition/resolve.d.ts +0 -2
  138. package/dist/composition/resolve.js +0 -208
  139. package/dist/composition/resolve.js.map +0 -1
  140. package/dist/dashboard/assets/index-BrC1AtZ1.js +0 -15
@@ -0,0 +1,94 @@
1
+ import { type ModelConnection, type ModelResolution } from "./decisions.js";
2
+ export type GenerationRole = "system" | "user" | "assistant" | "tool";
3
+ export interface ToolCall {
4
+ /** The provider's id for this call, used to send its result back. */
5
+ id: string;
6
+ /** The capability name ("tasks.create"), not the provider-safe tool name. */
7
+ name: string;
8
+ input: Record<string, unknown>;
9
+ }
10
+ export interface GenerationMessage {
11
+ role: GenerationRole;
12
+ content: string;
13
+ /** role "assistant": the tool calls the model made in this turn. */
14
+ toolCalls?: ToolCall[];
15
+ /** role "tool": which call this is the result of. */
16
+ toolCallId?: string;
17
+ }
18
+ export interface ToolDefinition {
19
+ /** An AppPort capability name, e.g. "tasks.create". */
20
+ name: string;
21
+ description?: string;
22
+ /** JSON Schema of the capability's input (an object schema). */
23
+ inputSchema: Record<string, unknown>;
24
+ }
25
+ export interface GenerationRequest {
26
+ messages: GenerationMessage[];
27
+ tools?: ToolDefinition[];
28
+ maxTokens?: number;
29
+ temperature?: number;
30
+ signal?: AbortSignal;
31
+ /** Called with each piece of text as it arrives. */
32
+ onDelta?: (text: string) => void;
33
+ }
34
+ export type FinishReason = "stop" | "tool_calls" | "length" | "cancelled" | "refusal";
35
+ export interface GenerationResult {
36
+ text: string;
37
+ toolCalls: ToolCall[];
38
+ finish: FinishReason;
39
+ /** Token counts, and the cost when the provider reports one (e.g. a gateway's usage.cost, in its currency). */
40
+ usage: {
41
+ inputTokens: number | null;
42
+ outputTokens: number | null;
43
+ cost?: number | null;
44
+ };
45
+ }
46
+ /** The digest of a generation's input (messages and tool names): identifies it without storing it twice. */
47
+ export declare function generationDigest(request: {
48
+ messages: GenerationMessage[];
49
+ tools?: ToolDefinition[];
50
+ }): string;
51
+ /** An error that ended a stream, with the text that arrived before it (not sent to callers; recorded as evidence). */
52
+ export type GenerationError = Error & {
53
+ partialText?: string;
54
+ };
55
+ /** What a generation ran on and how it ended. Recorded as evidence; never holds a secret or the prompt text. */
56
+ export interface GenerationReceipt {
57
+ provider: string;
58
+ model: string;
59
+ protocol: string;
60
+ endpoint: string;
61
+ source: "resolver" | "intelligence";
62
+ resolution?: ModelResolution;
63
+ credential: string | null;
64
+ finish: FinishReason;
65
+ usage: GenerationResult["usage"];
66
+ toolCalls: Array<{
67
+ id: string;
68
+ name: string;
69
+ }>;
70
+ startedAt: string;
71
+ durationMs: number;
72
+ /** sha256 of the request messages and tool names: proves which input produced the output without storing it twice. */
73
+ inputDigest: string;
74
+ }
75
+ export declare const DEFAULT_GENERATION_TIMEOUT_MS = 120000;
76
+ export declare const DEFAULT_MAX_TOKENS = 1024;
77
+ /**
78
+ * Provider tool names allow [A-Za-z0-9_-] only. AppPort capability names are dotted lowercase words
79
+ * and never contain "_" (appport names.ts), so "." ↔ "_" is exact and reversible: the same
80
+ * mapping as @appport/mcp's toToolName, without its 64-character truncation (refused instead).
81
+ */
82
+ export declare function toolName(capability: string): string;
83
+ export declare const capabilityName: (tool: string) => string;
84
+ /** Split a fetch body into SSE events ({ event, data }). Tolerates \r\n and multi-line data. */
85
+ export declare function sseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<{
86
+ event: string | null;
87
+ data: string;
88
+ }>;
89
+ export declare function supportsGeneration(protocol: string): boolean;
90
+ /**
91
+ * Stream one generation over a resolved connection. Cancellation by the caller's signal returns
92
+ * what was received with finish "cancelled"; the timeout is a `timeout` model error.
93
+ */
94
+ export declare function streamGeneration(protocol: string, connection: ModelConnection, request: GenerationRequest): Promise<GenerationResult>;
@@ -0,0 +1,295 @@
1
+ /**
2
+ * Model generation: open-ended text, streamed, with tool calls.
3
+ *
4
+ * The sibling of decisions.ts. The same ModelHost resolves the model, the provider protocol, the
5
+ * endpoint and the credential (AppPort Services Intelligence + FeltKit custody, or a Resolver
6
+ * reference), so generation inherits the same custody, receipts and error taxonomy. This module
7
+ * only speaks the two provider protocols FeltKit supports:
8
+ *
9
+ * - OpenAI chat completions with `stream: true` (OpenAI and every OpenAI-compatible server)
10
+ * - Anthropic Messages with `stream: true`
11
+ *
12
+ * A model's tool call is *data*: a name and an input. Nothing here runs it. The caller turns it
13
+ * into a proposal (runtime/agent.ts), which runs only through AppPort, as the task owner, and
14
+ * only after approval when it is consequential.
15
+ *
16
+ * Cancellation: the caller's AbortSignal aborts the provider request. A cancelled generation is
17
+ * a result (finish: "cancelled", with the text received so far), not an error, so its receipt is
18
+ * still recorded.
19
+ */
20
+ import { createHash } from "node:crypto";
21
+ import { modelError } from "./decisions.js";
22
+ /** The digest of a generation's input (messages and tool names): identifies it without storing it twice. */
23
+ export function generationDigest(request) {
24
+ return `sha256:${createHash("sha256").update(JSON.stringify({ messages: request.messages, tools: (request.tools ?? []).map((t) => t.name) })).digest("hex")}`;
25
+ }
26
+ export const DEFAULT_GENERATION_TIMEOUT_MS = 120_000;
27
+ export const DEFAULT_MAX_TOKENS = 1024;
28
+ /**
29
+ * Provider tool names allow [A-Za-z0-9_-] only. AppPort capability names are dotted lowercase words
30
+ * and never contain "_" (appport names.ts), so "." ↔ "_" is exact and reversible: the same
31
+ * mapping as @appport/mcp's toToolName, without its 64-character truncation (refused instead).
32
+ */
33
+ export function toolName(capability) {
34
+ const name = capability.replace(/\./g, "_");
35
+ if (!/^[a-z][a-z0-9_]{0,63}$/.test(name))
36
+ throw modelError("unsupported", `Capability "${capability}" cannot be offered to a model as a tool (its name must map to [a-z0-9_], at most 64 characters).`, "Shorten the capability name.");
37
+ return name;
38
+ }
39
+ export const capabilityName = (tool) => tool.replace(/_/g, ".");
40
+ // ---- Server-sent events -------------------------------------------------------------------
41
+ /** Split a fetch body into SSE events ({ event, data }). Tolerates \r\n and multi-line data. */
42
+ export async function* sseEvents(body) {
43
+ const reader = body.getReader();
44
+ const decoder = new TextDecoder();
45
+ let buffer = "";
46
+ try {
47
+ for (;;) {
48
+ const { value, done } = await reader.read();
49
+ if (done)
50
+ break;
51
+ buffer += decoder.decode(value, { stream: true });
52
+ let index;
53
+ while ((index = buffer.search(/\r?\n\r?\n/)) >= 0) {
54
+ const raw = buffer.slice(0, index);
55
+ buffer = buffer.slice(index).replace(/^\r?\n\r?\n/, "");
56
+ let event = null;
57
+ const data = [];
58
+ for (const line of raw.split(/\r?\n/)) {
59
+ if (line.startsWith(":"))
60
+ continue;
61
+ const colon = line.indexOf(":");
62
+ const field = colon < 0 ? line : line.slice(0, colon);
63
+ const val = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
64
+ if (field === "event")
65
+ event = val;
66
+ else if (field === "data")
67
+ data.push(val);
68
+ }
69
+ if (data.length)
70
+ yield { event, data: data.join("\n") };
71
+ }
72
+ }
73
+ }
74
+ finally {
75
+ reader.releaseLock();
76
+ }
77
+ }
78
+ const scrub = (text, secret) => (secret ? text.split(secret).join("[redacted]") : text).replace(/\b(sk|key)-[A-Za-z0-9_-]{12,}/g, "[redacted]");
79
+ /** POST and return the streaming body, mapping transport and HTTP failures to model problems. */
80
+ async function open(connection, url, headers, body, signal) {
81
+ let response;
82
+ try {
83
+ response = await (connection.fetch ?? fetch)(url, { method: "POST", headers: { "content-type": "application/json", accept: "text/event-stream", ...headers }, body: JSON.stringify(body), signal });
84
+ }
85
+ catch (error) {
86
+ if (signal.aborted)
87
+ throw error; // the caller decides: cancelled or timed out
88
+ const cause = scrub(String(error?.cause?.code ?? error?.message ?? error), connection.credential);
89
+ throw modelError("unavailable", `${connection.provider} could not be reached at ${new URL(url).origin} (${cause}).`, "Nothing was generated. Check the endpoint is reachable.", { provider: connection.provider });
90
+ }
91
+ if (!response.ok || !response.body) {
92
+ const text = scrub(await response.text().catch(() => ""), connection.credential);
93
+ if (response.status === 401 || response.status === 403) {
94
+ throw modelError("credential_refused", `${connection.provider} refused the credential (HTTP ${response.status}).`, "Nothing was generated. Replace the API key (Studio → Models, `feltkit credential set`, or Resolver).", { provider: connection.provider, status: response.status });
95
+ }
96
+ throw modelError("provider_error", `${connection.provider} answered HTTP ${response.status}: ${text.slice(0, 300)}`, "Nothing was generated. Check the model name and the provider's status.", { provider: connection.provider, status: response.status });
97
+ }
98
+ return response.body;
99
+ }
100
+ function parse(data, provider) {
101
+ try {
102
+ return JSON.parse(data);
103
+ }
104
+ catch {
105
+ throw modelError("malformed", `${provider} streamed an event that is not JSON.`, "Check the endpoint is the provider's API.", { provider });
106
+ }
107
+ }
108
+ function parseInput(raw, provider, name) {
109
+ if (!raw.trim())
110
+ return {};
111
+ try {
112
+ const value = JSON.parse(raw);
113
+ if (value && typeof value === "object" && !Array.isArray(value))
114
+ return value;
115
+ }
116
+ catch {
117
+ // fall through
118
+ }
119
+ throw modelError("malformed", `${provider} called tool ${name} with input that is not a JSON object.`, "The tool call was not used.", { provider });
120
+ }
121
+ const join = (endpoint, path) => `${endpoint.replace(/\/+$/, "")}${path}`;
122
+ // ---- OpenAI chat completions --------------------------------------------------------------
123
+ async function openaiStream(connection, request, signal) {
124
+ const messages = request.messages.map((m) => {
125
+ if (m.role === "tool")
126
+ return { role: "tool", tool_call_id: m.toolCallId, content: m.content };
127
+ if (m.role === "assistant" && m.toolCalls?.length) {
128
+ return { role: "assistant", content: m.content || null, tool_calls: m.toolCalls.map((c) => ({ id: c.id, type: "function", function: { name: toolName(c.name), arguments: JSON.stringify(c.input) } })) };
129
+ }
130
+ return { role: m.role, content: m.content };
131
+ });
132
+ const body = {
133
+ model: connection.model,
134
+ messages,
135
+ stream: true,
136
+ stream_options: { include_usage: true },
137
+ max_tokens: request.maxTokens ?? DEFAULT_MAX_TOKENS,
138
+ ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),
139
+ ...(request.tools?.length ? { tools: request.tools.map((t) => ({ type: "function", function: { name: toolName(t.name), ...(t.description ? { description: t.description } : {}), parameters: t.inputSchema } })) } : {}),
140
+ };
141
+ const stream = await open(connection, join(connection.endpoint, "/chat/completions"), connection.credential ? { authorization: `Bearer ${connection.credential}` } : {}, body, signal);
142
+ let text = "";
143
+ let finish = "stop";
144
+ const usage = { inputTokens: null, outputTokens: null };
145
+ const calls = new Map();
146
+ for await (const event of sseEvents(stream)) {
147
+ if (event.data === "[DONE]")
148
+ break;
149
+ const chunk = parse(event.data, connection.provider);
150
+ if (chunk?.error)
151
+ throw modelError("provider_error", `${connection.provider} reported: ${scrub(String(chunk.error.message ?? JSON.stringify(chunk.error)), connection.credential).slice(0, 300)}`, "Nothing more was generated.", { provider: connection.provider });
152
+ if (chunk?.usage) {
153
+ usage.inputTokens = chunk.usage.prompt_tokens ?? null;
154
+ usage.outputTokens = chunk.usage.completion_tokens ?? null;
155
+ if (typeof chunk.usage.cost === "number")
156
+ usage.cost = chunk.usage.cost;
157
+ }
158
+ const choice = chunk?.choices?.[0];
159
+ if (!choice)
160
+ continue;
161
+ const delta = choice.delta ?? {};
162
+ if (typeof delta.content === "string" && delta.content) {
163
+ text += delta.content;
164
+ request.onDelta?.(delta.content);
165
+ }
166
+ for (const call of delta.tool_calls ?? []) {
167
+ const at = calls.get(call.index ?? 0) ?? { id: "", name: "", args: "" };
168
+ if (call.id)
169
+ at.id = call.id;
170
+ if (call.function?.name)
171
+ at.name += call.function.name;
172
+ if (call.function?.arguments)
173
+ at.args += call.function.arguments;
174
+ calls.set(call.index ?? 0, at);
175
+ }
176
+ if (choice.finish_reason)
177
+ finish = choice.finish_reason === "tool_calls" ? "tool_calls" : choice.finish_reason === "length" ? "length" : choice.finish_reason === "content_filter" ? "refusal" : "stop";
178
+ }
179
+ const toolCalls = [...calls.entries()].sort(([a], [b]) => a - b).map(([, c]) => ({ id: c.id, name: capabilityName(c.name), input: parseInput(c.args, connection.provider, c.name) }));
180
+ return { text, toolCalls, finish: toolCalls.length ? "tool_calls" : finish, usage };
181
+ }
182
+ // ---- Anthropic Messages -------------------------------------------------------------------
183
+ async function anthropicStream(connection, request, signal) {
184
+ const system = request.messages.filter((m) => m.role === "system").map((m) => m.content).join("\n\n");
185
+ const messages = [];
186
+ for (const m of request.messages) {
187
+ if (m.role === "system")
188
+ continue;
189
+ if (m.role === "tool") {
190
+ const block = { type: "tool_result", tool_use_id: m.toolCallId, content: m.content };
191
+ const last = messages.at(-1);
192
+ // Consecutive tool results go in one user turn, as the API requires.
193
+ if (last?.role === "user" && Array.isArray(last.content) && last.content.every((b) => b.type === "tool_result"))
194
+ last.content.push(block);
195
+ else
196
+ messages.push({ role: "user", content: [block] });
197
+ continue;
198
+ }
199
+ if (m.role === "assistant" && m.toolCalls?.length) {
200
+ messages.push({ role: "assistant", content: [...(m.content ? [{ type: "text", text: m.content }] : []), ...m.toolCalls.map((c) => ({ type: "tool_use", id: c.id, name: toolName(c.name), input: c.input }))] });
201
+ continue;
202
+ }
203
+ messages.push({ role: m.role, content: m.content });
204
+ }
205
+ const base = connection.endpoint.replace(/\/+$/, "");
206
+ const url = base.endsWith("/v1") ? `${base}/messages` : `${base}/v1/messages`;
207
+ const body = {
208
+ model: connection.model,
209
+ max_tokens: request.maxTokens ?? DEFAULT_MAX_TOKENS,
210
+ stream: true,
211
+ messages,
212
+ ...(system ? { system } : {}),
213
+ ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),
214
+ ...(request.tools?.length ? { tools: request.tools.map((t) => ({ name: toolName(t.name), ...(t.description ? { description: t.description } : {}), input_schema: t.inputSchema })) } : {}),
215
+ };
216
+ const stream = await open(connection, url, { "anthropic-version": "2023-06-01", ...(connection.credential ? { "x-api-key": connection.credential } : {}) }, body, signal);
217
+ let text = "";
218
+ let finish = "stop";
219
+ const usage = { inputTokens: null, outputTokens: null };
220
+ const blocks = new Map();
221
+ for await (const event of sseEvents(stream)) {
222
+ const data = parse(event.data, connection.provider);
223
+ switch (data?.type) {
224
+ case "message_start":
225
+ usage.inputTokens = data.message?.usage?.input_tokens ?? null;
226
+ break;
227
+ case "content_block_start":
228
+ blocks.set(data.index, { type: data.content_block?.type, id: data.content_block?.id, name: data.content_block?.name, json: "" });
229
+ break;
230
+ case "content_block_delta": {
231
+ const d = data.delta ?? {};
232
+ if (d.type === "text_delta" && d.text) {
233
+ text += d.text;
234
+ request.onDelta?.(d.text);
235
+ }
236
+ else if (d.type === "input_json_delta") {
237
+ const block = blocks.get(data.index);
238
+ if (block)
239
+ block.json += d.partial_json ?? "";
240
+ }
241
+ break;
242
+ }
243
+ case "message_delta":
244
+ if (data.usage?.output_tokens !== undefined)
245
+ usage.outputTokens = data.usage.output_tokens;
246
+ if (data.delta?.stop_reason)
247
+ finish = data.delta.stop_reason === "tool_use" ? "tool_calls" : data.delta.stop_reason === "max_tokens" ? "length" : data.delta.stop_reason === "refusal" ? "refusal" : "stop";
248
+ break;
249
+ case "error":
250
+ throw modelError("provider_error", `${connection.provider} reported: ${scrub(String(data.error?.message ?? "an error"), connection.credential).slice(0, 300)}`, "Nothing more was generated.", { provider: connection.provider });
251
+ }
252
+ }
253
+ const toolCalls = [...blocks.entries()]
254
+ .sort(([a], [b]) => a - b)
255
+ .filter(([, b]) => b.type === "tool_use")
256
+ .map(([, b]) => ({ id: b.id ?? "", name: capabilityName(b.name ?? ""), input: parseInput(b.json, connection.provider, b.name ?? "") }));
257
+ return { text, toolCalls, finish: toolCalls.length ? "tool_calls" : finish, usage };
258
+ }
259
+ const PROTOCOL_STREAMS = {
260
+ openai: openaiStream,
261
+ "openai-compatible": openaiStream,
262
+ anthropic: anthropicStream,
263
+ };
264
+ export function supportsGeneration(protocol) {
265
+ return protocol in PROTOCOL_STREAMS;
266
+ }
267
+ /**
268
+ * Stream one generation over a resolved connection. Cancellation by the caller's signal returns
269
+ * what was received with finish "cancelled"; the timeout is a `timeout` model error.
270
+ */
271
+ export async function streamGeneration(protocol, connection, request) {
272
+ const run = PROTOCOL_STREAMS[protocol];
273
+ if (!run)
274
+ throw modelError("unknown_protocol", `FeltKit cannot generate with the "${protocol}" protocol.`, "Use an OpenAI, OpenAI-compatible or Anthropic provider.");
275
+ const timeoutMs = connection.timeoutMs ?? DEFAULT_GENERATION_TIMEOUT_MS;
276
+ const timeout = AbortSignal.timeout(timeoutMs);
277
+ const signal = request.signal ? AbortSignal.any([request.signal, timeout]) : timeout;
278
+ let text = "";
279
+ const tracked = { ...request, onDelta: (d) => ((text += d), request.onDelta?.(d)) };
280
+ try {
281
+ return await run(connection, tracked, signal);
282
+ }
283
+ catch (error) {
284
+ if (request.signal?.aborted)
285
+ return { text, toolCalls: [], finish: "cancelled", usage: { inputTokens: null, outputTokens: null } };
286
+ const partial = (e) => Object.assign(e, { partialText: text });
287
+ if (timeout.aborted)
288
+ throw partial(modelError("timeout", `${connection.provider} did not finish within ${timeoutMs} ms.`, "Raise agent.generationTimeoutMs, ask for less output, or check the provider.", { provider: connection.provider, timeoutMs }));
289
+ if (error?.details && error.code)
290
+ throw partial(error);
291
+ // The connection ended mid-stream (reset, closed, terminated): the provider stopped answering.
292
+ throw partial(modelError("unavailable", `The connection to ${connection.provider} ended before the generation finished (${scrub(String(error?.message ?? error), connection.credential).slice(0, 200)}).`, "Nothing more was generated. Try again; check the provider's status if it persists.", { provider: connection.provider }));
293
+ }
294
+ }
295
+ //# sourceMappingURL=generation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"generation.js","sourceRoot":"","sources":["../../src/runtime/generation.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,UAAU,EAA8C,MAAM,gBAAgB,CAAC;AAiDxF,4GAA4G;AAC5G,MAAM,UAAU,gBAAgB,CAAC,OAAoE;IACnG,OAAO,UAAU,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,EAAE,Q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AE,SAAS,EAAE,CAAC,CAAC,CAAC;QACzP,IAAK,KAA+B,EAAE,OAAO,IAAK,KAA2B,CAAC,IAAI;YAAE,MAAM,OAAO,CAAC,KAAc,CAAC,CAAC;QAClH,+FAA+F;QAC/F,MAAM,OAAO,CAAC,UAAU,CAAC,aAAa,EAAE,qBAAqB,UAAU,CAAC,QAAQ,0CAA0C,KAAK,CAAC,MAAM,CAAE,KAAe,EAAE,OAAO,IAAI,KAAK,CAAC,EAAE,UAAU,CAAC,UAAU,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,EAAE,oFAAoF,EAAE,EAAE,QAAQ,EAAE,UAAU,CAAC,QAAQ,EAAE,CAAC,CAAC,CAAC;IAClV,CAAC;AACH,CAAC"}
@@ -5,7 +5,7 @@ import { IntegrationHost } from "./integrations.js";
5
5
  import { type BackupHeader, type BackupSink } from "./backup.js";
6
6
  import { type FeltKitErrorJSON } from "../errors.js";
7
7
  import { ActivityLog, type ActivityVia } from "./activity.js";
8
- import { Authority, type Principal } from "./authority.js";
8
+ import { Authority, type CallerContext, type Principal } from "./authority.js";
9
9
  import { ChangeFeed } from "./changes.js";
10
10
  import type { AgentTrigger, Logger } from "./context.js";
11
11
  import { ModelHost } from "./decisions.js";
@@ -63,6 +63,14 @@ export interface CallOptions {
63
63
  definition: AgentDefinition;
64
64
  trigger: AgentTrigger;
65
65
  };
66
+ /** The caller's time zone and locale (validated), for `ctx.auth.context`. */
67
+ context?: CallerContext;
68
+ /** Actions: aborted when the caller cancels (closes the stream). */
69
+ signal?: AbortSignal;
70
+ /** Actions: the caller's stream, for `ctx.emit` and model deltas. */
71
+ emit?: (event: {
72
+ type: string;
73
+ } & Record<string, unknown>) => void;
66
74
  }
67
75
  export type CallResult = {
68
76
  ok: true;
@@ -125,7 +133,7 @@ export interface SchemaStatus {
125
133
  export type RuntimeState = "starting" | "ready" | "closing" | "closed" | "failed";
126
134
  export interface FunctionInfo {
127
135
  name: string;
128
- kind: "query" | "mutation";
136
+ kind: "query" | "mutation" | "action";
129
137
  access: string;
130
138
  description?: string;
131
139
  args: Record<string, unknown>;
@@ -27,6 +27,7 @@ import { validate } from "../schema.js";
27
27
  import { ActivityLog, errorSummary } from "./activity.js";
28
28
  import { Authority, authContext, fromAppPortPrincipal, normalizePrincipal } from "./authority.js";
29
29
  import { ChangeFeed } from "./changes.js";
30
+ import { generationDigest } from "./generation.js";
30
31
  import { ModelHost } from "./decisions.js";
31
32
  import { CollectionResolver, Reader, Writer, applicationView, ensureCollectionMarkers, feltdbRefusalJSON, readAll } from "./data.js";
32
33
  import { describeStorage } from "./environment.js";
@@ -1225,6 +1226,8 @@ export class FeltKitRuntime {
1225
1226
  });
1226
1227
  }
1227
1228
  const args = parsed.value;
1229
+ if (fn.kind === "action")
1230
+ return this.#runAction(name, fn, args, principal, options, requestId, authorityRecord, finish, failure);
1228
1231
  const handle = this.instance.handle("app");
1229
1232
  const release = this.#services.enter(requestId, principal);
1230
1233
  const servicesUsed = new Set();
@@ -1235,7 +1238,7 @@ export class FeltKitRuntime {
1235
1238
  const db = fn.kind === "mutation" ? new Writer(handle, this.#resolver) : new Reader(handle, this.#resolver);
1236
1239
  const used = new Set();
1237
1240
  const shared = {
1238
- auth: authContext(this.#authority, principal),
1241
+ auth: authContext(this.#authority, principal, options.context),
1239
1242
  tenancy: {
1240
1243
  members: async () => {
1241
1244
  if (!this.tenancy)
@@ -1410,6 +1413,127 @@ export class FeltKitRuntime {
1410
1413
  release();
1411
1414
  }
1412
1415
  }
1416
+ /**
1417
+ * Run an action: no transaction and no database handle. It reads and writes only through calls
1418
+ * (each authorized as the caller, each in its own transaction) and the agent's proposals, so
1419
+ * everything it changes passes the same authority as any other request.
1420
+ */
1421
+ async #runAction(name, fn, args, principal, options, requestId, authorityRecord, finish, failure) {
1422
+ const signal = options.signal ?? new AbortController().signal;
1423
+ const emit = (event) => {
1424
+ try {
1425
+ options.emit?.(event);
1426
+ }
1427
+ catch {
1428
+ /* a broken stream never fails the action; the caller sees the final result */
1429
+ }
1430
+ };
1431
+ const callAs = (kind) => async (ref, callArgs) => {
1432
+ const target = this.#project.functions.get(ref?.name);
1433
+ if (!target)
1434
+ throw new FeltKitError("FUNCTION_NOT_FOUND", `No function named "${ref?.name}".`);
1435
+ if (target.kind !== kind)
1436
+ throw new FeltKitError("INVALID_ARGUMENT", `${ref.name} is a ${target.kind}; use ctx.run${target.kind === "query" ? "Query" : target.kind === "mutation" ? "Mutation" : "…"}.`);
1437
+ // Cancellation stops the model (ctx.signal); it does not stop the action recording what happened.
1438
+ const result = await this.call(ref.name, callArgs ?? {}, { principal, via: options.via, ...(options.context ? { context: options.context } : {}) });
1439
+ if (!result.ok)
1440
+ throw new FeltKitError(result.error.code, result.error.message, { ...(result.error.details ? { details: result.error.details } : {}), ...(result.error.hint ? { hint: result.error.hint } : {}) });
1441
+ return result.value;
1442
+ };
1443
+ const signedIn = () => {
1444
+ if (!principal)
1445
+ throw new FeltKitError("UNAUTHORIZED", "Using the model or the agent from an action needs a signed-in caller.");
1446
+ return principal;
1447
+ };
1448
+ const agent = this.#agent;
1449
+ const ctx = {
1450
+ auth: authContext(this.#authority, principal, options.context),
1451
+ environment: { name: this.environment.name, production: this.environment.production, storage: describeStorage(this.environment.storage) },
1452
+ requestId,
1453
+ log: this.logger,
1454
+ signal,
1455
+ runQuery: callAs("query"),
1456
+ runMutation: callAs("mutation"),
1457
+ emit,
1458
+ model: {
1459
+ status: async () => {
1460
+ const s = await this.models.status();
1461
+ return { ready: s.ready, provider: s.provider, model: s.model, source: s.source, reference: s.reference ? { ref: s.reference.ref, revision: s.reference.revision } : null, problems: s.problems };
1462
+ },
1463
+ generate: async (request) => {
1464
+ const p = signedIn();
1465
+ const stream = request.stream !== false && Boolean(options.emit);
1466
+ const roles = {};
1467
+ for (const m of request.messages)
1468
+ roles[m.role] = (roles[m.role] ?? 0) + 1;
1469
+ // The record exists before the provider is contacted: every attempt has an outcome.
1470
+ const handle = await agent.beginGeneration(request.taskId, p, { digest: generationDigest(request), messages: request.messages.length, roles, tools: (request.tools ?? []).map((t) => t.name) });
1471
+ emit({ type: "generation.started", generationId: handle.generationId });
1472
+ let streamed = "";
1473
+ let outcome;
1474
+ try {
1475
+ outcome = await this.models.generate({
1476
+ messages: request.messages,
1477
+ ...(request.tools?.length ? { tools: request.tools } : {}),
1478
+ ...(request.maxTokens !== undefined ? { maxTokens: request.maxTokens } : {}),
1479
+ ...(request.temperature !== undefined ? { temperature: request.temperature } : {}),
1480
+ signal,
1481
+ onStart: (model) => handle.running(model),
1482
+ onDelta: (text) => {
1483
+ streamed += text;
1484
+ if (stream)
1485
+ emit({ type: "delta", text });
1486
+ },
1487
+ });
1488
+ }
1489
+ catch (error) {
1490
+ const memoryId = await handle.failed(error, error.partialText ?? streamed).catch(() => undefined);
1491
+ if (isFeltKitError(error))
1492
+ Object.assign(error, { details: { ...(error.details ?? {}), generationId: handle.generationId, ...(memoryId ? { memoryId } : {}) } });
1493
+ emit({ type: "generation", generationId: handle.generationId, state: "failed", ...(memoryId ? { memoryId } : {}) });
1494
+ throw error;
1495
+ }
1496
+ const { result, receipt } = outcome;
1497
+ const memoryId = result.finish === "cancelled" ? await handle.cancelled("cancelled by the caller", { text: result.text, toolCalls: result.toolCalls, usage: result.usage }) : await handle.completed(result);
1498
+ emit({ type: "generation", generationId: handle.generationId, memoryId, state: result.finish === "cancelled" ? "cancelled" : "completed", provider: receipt.provider, model: receipt.model, finish: receipt.finish, ...(receipt.resolution ? { reference: { ref: receipt.resolution.ref, revision: receipt.resolution.revision } } : {}) });
1499
+ return { ...result, receipt, memoryId, generationId: handle.generationId };
1500
+ },
1501
+ },
1502
+ agent: {
1503
+ tools: async () => {
1504
+ const p = signedIn();
1505
+ return (await agent.tools(p))
1506
+ .filter((t) => t.allowed && t.source === "application" && t.inputSchema)
1507
+ .map((t) => ({ name: t.name, ...(t.description ? { description: t.description } : {}), inputSchema: t.inputSchema, effect: t.effect, ...(t.approval ? { approval: t.approval } : {}) }));
1508
+ },
1509
+ openTask: (input) => agent.openTask({ principal: signedIn(), objective: input.objective, key: input.key }),
1510
+ actions: async (taskId) => (await agent.turnActions(taskId, signedIn())).map(({ at: _at, ...a }) => a),
1511
+ propose: async (taskId, proposal) => {
1512
+ const p = signedIn();
1513
+ await agent.propose(taskId, proposal, p);
1514
+ const proposed = await agent.proposalOutcome(taskId, proposal.idempotencyKey, p);
1515
+ emit({ type: "proposal", ...proposed });
1516
+ return proposed;
1517
+ },
1518
+ },
1519
+ };
1520
+ const started = performance.now();
1521
+ try {
1522
+ const reader = new Reader(this.instance.handle("app"), this.#resolver);
1523
+ await this.#authorizeResource(name, fn, args, principal, options, requestId, applicationView(reader), authorityRecord);
1524
+ const value = await fn.handler(ctx, args);
1525
+ if (fn.returns) {
1526
+ const output = validate(fn.returns, value);
1527
+ if (!output.ok)
1528
+ throw new FeltKitError("INTERNAL", `${name} returned a value that does not match its \`returns\` schema: ${output.issues.map((i) => `${i.path}: ${i.message}`).join("; ")}`);
1529
+ }
1530
+ finish({ outcome: "success", authority: authorityRecord, argKeys: Object.keys(args), detail: { action: true, ...(signal.aborted ? { cancelled: true } : {}), ms: Math.round(performance.now() - started) } });
1531
+ return { ok: true, value: value === undefined ? null : value, reads: [], requestId };
1532
+ }
1533
+ catch (error) {
1534
+ return failure(error, { authority: authorityRecord, argKeys: Object.keys(args) });
1535
+ }
1536
+ }
1413
1537
  async #authorizeResource(name, fn, args, principal, options, requestId, db, record) {
1414
1538
  const hook = this.app.options.authorize;
1415
1539
  if (!hook)