capable-kit 0.0.1-alpha.8 → 0.1.0-alpha.9

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 (78) hide show
  1. package/CHANGELOG.md +108 -0
  2. package/README.md +6 -0
  3. package/dist/ai-sdk.d.mts +2 -2
  4. package/dist/ai-sdk.mjs +1 -1
  5. package/dist/app.d.mts +2 -2
  6. package/dist/app.mjs +2 -2
  7. package/dist/bin.mjs +4 -4
  8. package/dist/cli.d.mts +4 -1
  9. package/dist/cli.mjs +1 -1
  10. package/dist/core.d.mts +2 -2
  11. package/dist/core.mjs +1 -1
  12. package/dist/eve.d.mts +82 -5
  13. package/dist/eve.mjs +358 -19
  14. package/dist/eve.mjs.map +1 -1
  15. package/dist/http.d.mts +1 -1
  16. package/dist/http.mjs +1 -1
  17. package/dist/{index-F4ba_olD.d.mts → index-D63DSGZG.d.mts} +10 -5
  18. package/dist/{index-Dl4NK9G0.d.mts → index-D8DWjQ9f.d.mts} +3 -3
  19. package/dist/{index-hdH_K5Zc.d.mts → index-DgxvtAmv.d.mts} +4 -4
  20. package/dist/{index-_qKFfWV4.d.mts → index-ftQx6OMr.d.mts} +23 -13
  21. package/dist/index.d.mts +4 -4
  22. package/dist/index.mjs +3 -3
  23. package/dist/mcp.d.mts +2 -2
  24. package/dist/mcp.mjs +1 -1
  25. package/dist/{mount-CEFAplR5.mjs → mount-B9TrHWHh.mjs} +3 -3
  26. package/dist/{mount-CEFAplR5.mjs.map → mount-B9TrHWHh.mjs.map} +1 -1
  27. package/dist/react-query.d.mts +1 -1
  28. package/dist/react-query.mjs +1 -1
  29. package/dist/runtime-support.d.mts +1 -1
  30. package/dist/runtime-support.mjs +3 -3
  31. package/dist/server.d.mts +1 -1
  32. package/dist/server.mjs +1 -1
  33. package/dist/{src-betOfnDL.mjs → src-B592M-6b.mjs} +143 -44
  34. package/dist/src-B592M-6b.mjs.map +1 -0
  35. package/dist/{src-D-cm2gQ6.mjs → src-Bd1Vnze8.mjs} +16 -2
  36. package/dist/src-Bd1Vnze8.mjs.map +1 -0
  37. package/dist/{src-BWxDO2Ua.mjs → src-CKC1BdXO.mjs} +3 -3
  38. package/dist/{src-BWxDO2Ua.mjs.map → src-CKC1BdXO.mjs.map} +1 -1
  39. package/dist/{src-D_0PIhqq.mjs → src-CL9eA6_p.mjs} +42 -25
  40. package/dist/src-CL9eA6_p.mjs.map +1 -0
  41. package/dist/{src-rkr5j_NH.mjs → src-Hw9WBgEW.mjs} +3 -3
  42. package/dist/{src-rkr5j_NH.mjs.map → src-Hw9WBgEW.mjs.map} +1 -1
  43. package/dist/{subscription-B-auXJbm.d.mts → subscription-DbnHcm7C.d.mts} +2 -2
  44. package/dist/swr.d.mts +1 -1
  45. package/dist/swr.mjs +1 -1
  46. package/docs/CONTEXT.md +17 -10
  47. package/docs/README.md +3 -0
  48. package/docs/internal/README.md +3 -0
  49. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  50. package/docs/internal/architecture.md +11 -10
  51. package/docs/internal/capability-first-model.md +31 -8
  52. package/docs/internal/eve-recovery-validation.md +86 -0
  53. package/docs/internal/feedback/v-ray/README.md +258 -0
  54. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  55. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  56. package/docs/internal/implementation-friction.md +301 -1
  57. package/docs/internal/releases.md +79 -0
  58. package/docs/site/capable-orpc-and-trpc.mdx +2 -2
  59. package/docs/site/concepts/apps.mdx +6 -0
  60. package/docs/site/concepts/architecture.mdx +1 -1
  61. package/docs/site/concepts/capabilities.mdx +39 -2
  62. package/docs/site/concepts/errors.mdx +11 -1
  63. package/docs/site/concepts/presentations.mdx +16 -0
  64. package/docs/site/patterns/composition.mdx +50 -8
  65. package/docs/site/patterns/remote-apps.mdx +1 -1
  66. package/docs/site/quickstart.mdx +1 -1
  67. package/docs/site/reference/packages-and-entry-points.mdx +11 -3
  68. package/docs/site/surfaces/cli.mdx +33 -0
  69. package/docs/site/surfaces/eve.mdx +65 -18
  70. package/docs/site/surfaces/typescript.mdx +1 -1
  71. package/package-docs.mjs +3 -0
  72. package/package.json +10 -11
  73. package/src/bin.ts +0 -0
  74. package/src/index.test.ts +1 -1
  75. package/src/index.ts +1 -1
  76. package/dist/src-D-cm2gQ6.mjs.map +0 -1
  77. package/dist/src-D_0PIhqq.mjs.map +0 -1
  78. package/dist/src-betOfnDL.mjs.map +0 -1
package/dist/eve.mjs CHANGED
@@ -1,5 +1,317 @@
1
- import { c as getAppRuntime } from "./src-betOfnDL.mjs";
2
- import { defineDynamic, defineTool } from "eve/tools";
1
+ import { r as defineApp, s as capability } from "./src-Bd1Vnze8.mjs";
2
+ import { c as getAppRuntime, o as createApp } from "./src-B592M-6b.mjs";
3
+ import { defineDurableCallback, defineDynamic, defineTool } from "eve/tools";
4
+ import { z } from "zod";
5
+ //#region packages/eve/src/agent-presentation.ts
6
+ /** Portable presentation shared by the CLI and other presentation-aware surfaces. */
7
+ function presentAgentResult(result) {
8
+ const parts = [{
9
+ running: "Running. Check the result again to follow progress.",
10
+ waiting: "Waiting for input.",
11
+ completed: "Completed.",
12
+ failed: "Agent execution failed.",
13
+ cancelled: "Cancelled."
14
+ }[result.status]];
15
+ if (result.text) parts.push(result.text);
16
+ if (result.data !== void 0) parts.push(JSON.stringify(result.data, null, 2));
17
+ if (result.textTruncated) parts.push("The answer was truncated.");
18
+ if (result.dataOmitted) parts.push("Structured output was too large to include.");
19
+ for (const request of result.requests) {
20
+ parts.push(request.prompt);
21
+ parts.push(`Request ID: ${request.requestId}`);
22
+ if (request.options?.length) parts.push(request.options.map((option) => `- ${option.label} (option ID: ${option.id})${option.description ? ` — ${option.description}` : ""}`).join("\n"));
23
+ if (request.allowFreeform === false || request.options?.length && request.allowFreeform !== true) parts.push("Reply with an option ID.");
24
+ }
25
+ if (result.requiresHostInput) parts.push("Approval or authorization must be completed through the Eve host.");
26
+ if (result.runId) parts.push(`Run ID: ${result.runId}`);
27
+ return parts.join("\n\n");
28
+ }
29
+ //#endregion
30
+ //#region packages/eve/src/agent.ts
31
+ const runInput = z.object({ runId: z.string().min(1).describe("Eve session ID returned by send.") });
32
+ const question = z.object({
33
+ requestId: z.string(),
34
+ prompt: z.string(),
35
+ display: z.enum([
36
+ "confirmation",
37
+ "select",
38
+ "text"
39
+ ]).optional(),
40
+ allowFreeform: z.boolean().optional(),
41
+ options: z.array(z.object({
42
+ id: z.string(),
43
+ label: z.string(),
44
+ description: z.string().optional()
45
+ })).optional()
46
+ });
47
+ const resultSchema = z.object({
48
+ status: z.enum([
49
+ "running",
50
+ "waiting",
51
+ "completed",
52
+ "failed",
53
+ "cancelled"
54
+ ]),
55
+ cursor: z.number().int().nonnegative(),
56
+ eventCount: z.number().int().nonnegative(),
57
+ requests: z.array(question),
58
+ text: z.string().optional(),
59
+ data: z.json().optional(),
60
+ dataOmitted: z.boolean().optional(),
61
+ textTruncated: z.boolean().optional(),
62
+ requiresHostInput: z.boolean().optional(),
63
+ error: z.string().optional()
64
+ });
65
+ /**
66
+ * Wrap Eve execution as a caller-scoped Capable App.
67
+ * Eve session IDs are run IDs. Every read reconstructs state from durable events.
68
+ */
69
+ function createEveAgentAdapter(options) {
70
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(options.name)) throw new Error("Invalid Eve agent namespace");
71
+ const maxEvents = positive(options.maxEventsPerRead ?? 1e4, "maxEventsPerRead");
72
+ const timeoutMs = positive(options.readTimeoutMs ?? 1e3, "readTimeoutMs");
73
+ const lifetime = new AbortController();
74
+ async function authorize(operation, runId) {
75
+ lifetime.signal.throwIfAborted();
76
+ await options.authorize(operation, runId);
77
+ lifetime.signal.throwIfAborted();
78
+ }
79
+ function signalFor(signal) {
80
+ return AbortSignal.any([lifetime.signal, ...signal ? [signal] : []]);
81
+ }
82
+ async function readRun(runId, signal) {
83
+ const run = {
84
+ sessionId: runId,
85
+ result: {
86
+ status: "running",
87
+ cursor: 0,
88
+ eventCount: 0,
89
+ requests: []
90
+ },
91
+ cancelled: false,
92
+ hostInputs: /* @__PURE__ */ new Set(),
93
+ authorizations: /* @__PURE__ */ new Set(),
94
+ message: void 0,
95
+ data: void 0,
96
+ dataOmitted: false,
97
+ pending: /* @__PURE__ */ new Map()
98
+ };
99
+ const requestSignal = signalFor(signal);
100
+ requestSignal.throwIfAborted();
101
+ const read = new AbortController();
102
+ const timer = setTimeout(() => read.abort(), timeoutMs);
103
+ const combined = AbortSignal.any([requestSignal, read.signal]);
104
+ try {
105
+ const session = options.client.sessions.attach(runId);
106
+ for await (const event of session.stream({
107
+ startIndex: 0,
108
+ follow: false,
109
+ signal: combined,
110
+ streamReconnectPolicy: { reconnect: false }
111
+ })) {
112
+ if (run.result.cursor >= maxEvents) throw new Error("Eve history exceeds maxEventsPerRead");
113
+ if (event.type === "input.requested") for (const request of event.data.requests) if (request.kind === "question") {
114
+ const safe = question.parse(request);
115
+ if (JSON.stringify(safe).length > 65536 || !run.pending.has(safe.requestId) && run.pending.size >= 100) throw new Error("Eve question limit exceeded");
116
+ run.pending.set(safe.requestId, safe);
117
+ } else remember(run.hostInputs, request.requestId);
118
+ else if (event.type === "authorization.required") remember(run.authorizations, event.data.name);
119
+ else if (event.type === "authorization.completed") run.authorizations.delete(event.data.name);
120
+ else if (event.type === "input.resolved") {
121
+ for (const resolution of event.data.resolutions) {
122
+ run.pending.delete(resolution.requestId);
123
+ run.hostInputs.delete(resolution.requestId);
124
+ }
125
+ run.result.requests = [...run.pending.values()];
126
+ } else if (event.type === "turn.started" || event.type === "step.started") {
127
+ run.result = {
128
+ status: "running",
129
+ cursor: run.result.cursor,
130
+ eventCount: 0,
131
+ requests: []
132
+ };
133
+ if (event.type === "turn.started") {
134
+ run.cancelled = false;
135
+ run.message = void 0;
136
+ run.data = void 0;
137
+ run.dataOmitted = false;
138
+ }
139
+ } else if (event.type === "message.completed" && event.data.finishReason !== "tool-calls") {
140
+ run.message = event.data.message?.slice(0, 65536);
141
+ run.result.textTruncated = (event.data.message?.length ?? 0) > 65536;
142
+ } else if (event.type === "result.completed") {
143
+ run.dataOmitted = JSON.stringify(event.data.result).length > 65536;
144
+ run.data = run.dataOmitted ? void 0 : z.json().parse(event.data.result);
145
+ } else if (event.type === "turn.cancelled") run.cancelled = true;
146
+ else if (event.type === "session.failed" || event.type === "turn.failed") {
147
+ run.result.status = "failed";
148
+ run.result.error = "Eve agent execution failed";
149
+ } else if (event.type === "session.completed" || event.type === "session.waiting") {
150
+ run.result.status = run.cancelled ? "cancelled" : event.type === "session.waiting" && (run.pending.size > 0 || run.hostInputs.size > 0 || run.authorizations.size > 0 || run.message === void 0 && run.data === void 0 && !run.dataOmitted) ? "waiting" : "completed";
151
+ if (run.result.status === "completed" && run.message !== void 0) run.result.text = run.message;
152
+ if (run.result.status === "completed") {
153
+ run.result.requests = [];
154
+ delete run.result.requiresHostInput;
155
+ if (run.data !== void 0) run.result.data = run.data;
156
+ if (run.dataOmitted) run.result.dataOmitted = true;
157
+ }
158
+ if (run.result.status === "waiting") {
159
+ run.result.requests = [...run.pending.values()];
160
+ run.result.requiresHostInput = run.hostInputs.size > 0 || run.authorizations.size > 0 || run.pending.size === 0;
161
+ }
162
+ }
163
+ run.result.cursor++;
164
+ }
165
+ combined.throwIfAborted();
166
+ return run;
167
+ } finally {
168
+ clearTimeout(timer);
169
+ read.abort();
170
+ }
171
+ }
172
+ const checked = {
173
+ send: capability({
174
+ id: `${options.name}.send`,
175
+ effect: "write",
176
+ description: "Send a message, optionally continuing an Eve session and waiting for its answer.",
177
+ meta: { cli: { positional: ["message"] } },
178
+ input: z.object({
179
+ message: z.string().min(1).max(65536).describe("Message to send, or a text answer to a pending question. With option-id, only the selected option is submitted."),
180
+ runId: z.string().min(1).optional().describe("Continue this Eve session. Omit to begin a new conversation."),
181
+ requestId: z.string().min(1).optional().describe("Pending question to answer. Required when several questions are waiting; use with run-id."),
182
+ optionId: z.string().min(1).optional().describe("Answer option ID shown by result. Required for questions that do not accept freeform text; use with run-id."),
183
+ wait: z.boolean().optional().describe("Wait for an answer, pending input, failure, or cancellation. Otherwise return the run ID immediately."),
184
+ timeoutMs: z.number().int().min(1).max(3e5).optional().describe("Wait limit in milliseconds after acceptance (default: 30000; maximum: 300000). Only used with wait. Expiry leaves Eve running.")
185
+ }),
186
+ output: resultSchema.extend({ runId: z.string() }),
187
+ toPresentation: presentAgentResult,
188
+ handler: async ({ input, signal }) => {
189
+ await authorize("send", input.runId);
190
+ if (!input.runId && (input.requestId || input.optionId)) throw new Error("Question answers require a runId");
191
+ const waiting = new AbortController();
192
+ const requestSignal = AbortSignal.any([signalFor(signal), waiting.signal]);
193
+ const sendOptions = {
194
+ signal: requestSignal,
195
+ streamReconnectPolicy: { reconnect: false }
196
+ };
197
+ let response;
198
+ if (input.runId) {
199
+ const run = await readRun(input.runId, signal);
200
+ const session = options.client.sessions.attach(input.runId, { streamIndex: run.result.cursor });
201
+ if (input.requestId || run.pending.size) {
202
+ const pending = input.requestId ? run.pending.get(input.requestId) : run.pending.size === 1 ? [...run.pending.values()][0] : void 0;
203
+ if (!pending || run.result.status !== "waiting") throw new Error("Specify requestId for a current pending question");
204
+ if (input.optionId) {
205
+ if (!pending.options?.some((option) => option.id === input.optionId)) throw new Error("Unknown answer option");
206
+ } else if (pending.allowFreeform === false || pending.options?.length && pending.allowFreeform !== true) throw new Error("This question requires optionId");
207
+ response = await session.respond([{
208
+ requestId: pending.requestId,
209
+ ...input.optionId ? { optionId: input.optionId } : { text: input.message }
210
+ }], sendOptions);
211
+ } else {
212
+ if (input.optionId) throw new Error("No pending question for optionId");
213
+ if (run.hostInputs.size || run.authorizations.size) throw new Error("Pending approval or authorization requires host action");
214
+ response = await session.send(input.message, sendOptions);
215
+ }
216
+ if (response.sessionId !== input.runId) throw new Error("Eve resumed a different session");
217
+ } else ({response} = await options.client.sessions.create({
218
+ message: input.message,
219
+ ...sendOptions
220
+ }));
221
+ const runId = response.sessionId;
222
+ const accepted = {
223
+ runId,
224
+ status: "running",
225
+ cursor: 0,
226
+ eventCount: 0,
227
+ requests: []
228
+ };
229
+ if (!input.wait) return accepted;
230
+ const timer = setTimeout(() => waiting.abort(), input.timeoutMs ?? 3e4);
231
+ try {
232
+ let count = 0;
233
+ let boundary = false;
234
+ for await (const event of response) {
235
+ requestSignal.throwIfAborted();
236
+ if (++count > maxEvents) throw new Error("Eve response exceeds maxEventsPerRead");
237
+ if ([
238
+ "session.waiting",
239
+ "session.completed",
240
+ "session.failed",
241
+ "turn.failed"
242
+ ].includes(event.type)) {
243
+ boundary = true;
244
+ break;
245
+ }
246
+ }
247
+ requestSignal.throwIfAborted();
248
+ if (!boundary) return accepted;
249
+ const run = await readRun(runId, requestSignal);
250
+ return {
251
+ runId,
252
+ ...run.result,
253
+ eventCount: run.result.cursor
254
+ };
255
+ } catch (error) {
256
+ signalFor(signal).throwIfAborted();
257
+ if (waiting.signal.aborted) return accepted;
258
+ throw error;
259
+ } finally {
260
+ clearTimeout(timer);
261
+ waiting.abort();
262
+ }
263
+ }
264
+ }),
265
+ result: capability({
266
+ id: `${options.name}.result`,
267
+ effect: "read",
268
+ description: "Read bounded progress, pending questions, or the final output. Pass the last returned cursor.",
269
+ input: runInput.extend({ cursor: z.number().int().nonnegative().default(0).describe("Cursor from the previous result, used to count new events. Defaults to 0; the full current result is still returned.") }),
270
+ output: resultSchema,
271
+ toPresentation: presentAgentResult,
272
+ handler: async ({ input, signal }) => {
273
+ await authorize("result", input.runId);
274
+ const run = await readRun(input.runId, signal);
275
+ if (input.cursor > run.result.cursor) throw new Error("Eve cursor is ahead of this run");
276
+ return {
277
+ ...run.result,
278
+ eventCount: run.result.cursor - input.cursor
279
+ };
280
+ }
281
+ }),
282
+ cancel: capability({
283
+ id: `${options.name}.cancel`,
284
+ effect: "write",
285
+ description: "Request cooperative cancellation of the active Eve turn. Acceptance is not completion.",
286
+ input: runInput.extend({ turnId: z.string().min(1).optional().describe("Specific Eve turn to cancel. Omit to cancel the session’s active turn.") }),
287
+ output: z.object({ status: z.enum(["accepted", "no_active_turn"]) }),
288
+ toPresentation: ({ status }) => status === "accepted" ? "Cancellation requested. Check the result to confirm execution has stopped." : "No active turn to cancel.",
289
+ handler: async ({ input, signal }) => {
290
+ await authorize("cancel", input.runId);
291
+ signalFor(signal).throwIfAborted();
292
+ return { status: (await options.client.sessions.attach(input.runId).cancel({
293
+ signal: signalFor(signal),
294
+ ...input.turnId ? { turnId: input.turnId } : {}
295
+ })).status };
296
+ }
297
+ })
298
+ };
299
+ return {
300
+ app: createApp(defineApp({ capabilities: { [options.name]: checked } })),
301
+ dispose() {
302
+ lifetime.abort();
303
+ }
304
+ };
305
+ }
306
+ function positive(value, name) {
307
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive safe integer`);
308
+ return value;
309
+ }
310
+ function remember(values, value) {
311
+ if (value.length > 65536 || !values.has(value) && values.size >= 100) throw new Error("Eve pending input limit exceeded");
312
+ values.add(value);
313
+ }
314
+ //#endregion
3
315
  //#region packages/eve/src/index.ts
4
316
  const emptyInputSchema = Object.freeze({
5
317
  type: "object",
@@ -9,9 +321,9 @@ const emptyInputSchema = Object.freeze({
9
321
  /**
10
322
  * Projects an executable Capable App into native, in-process Eve tools.
11
323
  *
12
- * The returned dynamic definition resolves at `step.started`. Eve deliberately
13
- * keeps step-scoped executors live, so the Capable App and its context provider do
14
- * not have to cross a durable serialization boundary.
324
+ * Eve owns the live executor bindings and checkpoints each call and result.
325
+ * Session resolvers rebuild App bindings after a cold start. Define the App or
326
+ * provider in deployed module code and keep persistent data outside the process.
15
327
  */
16
328
  function createEveTools(app, options = {}) {
17
329
  const capabilitiesByApp = /* @__PURE__ */ new WeakMap();
@@ -22,9 +334,8 @@ function createEveTools(app, options = {}) {
22
334
  capabilitiesByApp.set(resolvedApp, resolved);
23
335
  return resolved;
24
336
  };
25
- return defineDynamic({ events: { "step.started": async (_event, context) => {
26
- const resolvedApp = typeof app === "function" ? await app(context) : app;
27
- const runtime = getAppRuntime(resolvedApp);
337
+ return defineDynamic({ events: { "session.started": async (_event, resolveContext) => {
338
+ const resolvedApp = typeof app === "function" ? await app(resolveContext) : app;
28
339
  const tools = {};
29
340
  const names = /* @__PURE__ */ new Set();
30
341
  for (const capability of await capabilities(resolvedApp)) {
@@ -34,28 +345,56 @@ function createEveTools(app, options = {}) {
34
345
  if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) throw new Error(`Eve tool name "${name}" is invalid; set meta.eve.name to 1-64 letters, numbers, underscores, or hyphens`);
35
346
  if (names.has(name)) throw new Error(`Duplicate Eve tool name "${name}"`);
36
347
  names.add(name);
37
- const approval = options.approval?.(capability);
38
- tools[name] = defineTool({
348
+ const policy = options.approval?.(capability);
349
+ const approval = policy && durableApproval(policy, capability.id);
350
+ const definition = {
39
351
  description: capability.description ?? capability.title ?? `Run the Capable Capability at ${capability.path.join(".")}.`,
40
352
  inputSchema: capability.input ?? emptyInputSchema,
41
353
  ...capability.output ? { outputSchema: capability.output } : {},
42
- ...approval ? { approval } : {},
43
- async execute(input, context) {
44
- return (await runtime.call({
45
- id: capability.id,
46
- input,
47
- signal: context.abortSignal
48
- })).output;
49
- }
354
+ ...approval ? { approval } : {}
355
+ };
356
+ const id = capability.id;
357
+ tools[name] = defineTool({
358
+ ...definition,
359
+ execute: defineDurableCallback({
360
+ closure: { id },
361
+ callback: async ({ id }, input, context) => {
362
+ return (await getAppRuntime(typeof app === "function" ? await app({
363
+ ...resolveContext,
364
+ session: context.session
365
+ }) : app).call({
366
+ id,
367
+ input,
368
+ signal: context.abortSignal
369
+ })).output;
370
+ }
371
+ })
50
372
  });
51
373
  }
52
374
  return tools;
53
375
  } } });
54
376
  }
377
+ /** The resolver reconstructs policies; persist identity and reject rebinding to a different capability. */
378
+ function durablePolicy(policy, id) {
379
+ return defineDurableCallback({
380
+ closure: { id },
381
+ callback: (snapshot, ...args) => {
382
+ if (snapshot.id !== id) throw new Error("Eve capability identity changed during recovery");
383
+ return policy(...args);
384
+ }
385
+ });
386
+ }
387
+ function durableApproval(policy, id) {
388
+ if (typeof policy === "function") return durablePolicy(policy, id);
389
+ return {
390
+ request: durablePolicy(policy.request, id),
391
+ ...policy.response ? { response: durablePolicy(policy.response, id) } : {}
392
+ };
393
+ }
55
394
  function flatten(nodes) {
56
395
  return nodes.flatMap((node) => node.type === "capability" ? [node] : flatten(node.children));
57
396
  }
58
397
  //#endregion
59
- export { createEveTools };
398
+ export { createEveAgentAdapter, createEveTools };
60
399
 
61
400
  //# sourceMappingURL=eve.mjs.map
package/dist/eve.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"eve.mjs","names":[],"sources":["../../eve/src/index.ts"],"sourcesContent":["import {\n getAppRuntime,\n type AnyApp,\n type ManifestNode,\n type ManifestCapability,\n} from \"@capable/app\";\nimport type { CapabilityMetaRegistry } from \"@capable/core\";\nimport {\n defineDynamic,\n defineTool,\n type DynamicResolveContext,\n type DynamicSentinel,\n type ToolDefinition,\n} from \"eve/tools\";\nimport type { Approval } from \"eve/tools/approval\";\n\nexport type EveCapabilityMeta =\n | false\n | {\n readonly name?: string;\n };\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly eve?: EveCapabilityMeta;\n }\n}\n\nexport type CreateEveToolsOptions = {\n readonly approval?: (\n capability: ManifestCapability,\n ) => Approval | undefined;\n};\n\nexport type EveAppProvider =\n | AnyApp\n | ((\n context: DynamicResolveContext,\n ) => AnyApp | Promise<AnyApp>);\n\nconst emptyInputSchema = Object.freeze({\n type: \"object\",\n properties: Object.freeze({}),\n additionalProperties: false,\n});\n\ntype EveTool = ToolDefinition<Record<string, unknown>, unknown>;\n\n/**\n * Projects an executable Capable App into native, in-process Eve tools.\n *\n * The returned dynamic definition resolves at `step.started`. Eve deliberately\n * keeps step-scoped executors live, so the Capable App and its context provider do\n * not have to cross a durable serialization boundary.\n */\nexport function createEveTools(\n app: EveAppProvider,\n options: CreateEveToolsOptions = {},\n): DynamicSentinel<Record<string, EveTool>> {\n const capabilitiesByApp = new WeakMap<\n AnyApp,\n Promise<readonly ManifestCapability[]>\n >();\n const capabilities = (resolvedApp: AnyApp) => {\n const existing = capabilitiesByApp.get(resolvedApp);\n if (existing) return existing;\n const resolved = getAppRuntime(resolvedApp).manifest().then((manifest) =>\n flatten(manifest.capabilities)\n );\n capabilitiesByApp.set(resolvedApp, resolved);\n return resolved;\n };\n\n return defineDynamic({\n events: {\n \"step.started\": async (_event, context) => {\n const resolvedApp = typeof app === \"function\"\n ? await app(context)\n : app;\n const runtime = getAppRuntime(resolvedApp);\n const tools: Record<string, EveTool> = {};\n const names = new Set<string>();\n\n for (const capability of await capabilities(resolvedApp)) {\n const meta = capability.meta.eve as EveCapabilityMeta | undefined;\n if (meta === false) continue;\n\n const name = meta?.name ?? capability.path.join(\"__\");\n if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) {\n throw new Error(\n `Eve tool name \"${name}\" is invalid; set meta.eve.name to 1-64 letters, numbers, underscores, or hyphens`,\n );\n }\n if (names.has(name)) {\n throw new Error(`Duplicate Eve tool name \"${name}\"`);\n }\n names.add(name);\n\n const approval = options.approval?.(capability);\n const tool: EveTool = {\n description:\n capability.description ??\n capability.title ??\n `Run the Capable Capability at ${capability.path.join(\".\")}.`,\n inputSchema: (capability.input ??\n emptyInputSchema) as EveTool[\"inputSchema\"],\n ...(capability.output\n ? {\n outputSchema:\n capability.output as NonNullable<EveTool[\"outputSchema\"]>,\n }\n : {}),\n ...(approval ? { approval } : {}),\n async execute(input, context) {\n const result = await runtime.call({\n id: capability.id,\n input,\n signal: context.abortSignal,\n });\n return result.output;\n },\n };\n tools[name] = defineTool(tool);\n }\n\n return tools;\n },\n },\n });\n}\n\nfunction flatten(\n nodes: readonly ManifestNode[],\n): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\" ? [node] : flatten(node.children)\n );\n}\n"],"mappings":";;;AAwCA,MAAM,mBAAmB,OAAO,OAAO;CACrC,MAAM;CACN,YAAY,OAAO,OAAO,CA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AQ,KAAK;MAChC,IAAI,WAAW;MACf;MACA,QAAQ,QAAQ;KAClB,CAAC,EAAA,CACa;IAChB;GAE0B,CAAC;EAC/B;EAEA,OAAO;CACT,EACF,EACF,CAAC;AACH;AAEA,SAAS,QACP,OAC+B;CAC/B,OAAO,MAAM,SAAS,SACpB,KAAK,SAAS,eAAe,CAAC,IAAI,IAAI,QAAQ,KAAK,QAAQ,CAC7D;AACF"}
1
+ {"version":3,"file":"eve.mjs","names":[],"sources":["../../eve/src/agent-presentation.ts","../../eve/src/agent.ts","../../eve/src/index.ts"],"sourcesContent":["import type { EveAgentResult } from \"./agent.ts\";\n\n/** Portable presentation shared by the CLI and other presentation-aware surfaces. */\nexport function presentAgentResult(result: EveAgentResult & { runId?: string }): string {\n const status = {\n running: \"Running. Check the result again to follow progress.\",\n waiting: \"Waiting for input.\",\n completed: \"Completed.\",\n failed: \"Agent execution failed.\",\n cancelled: \"Cancelled.\",\n }[result.status];\n const parts = [status];\n if (result.text) parts.push(result.text);\n if (result.data !== undefined) parts.push(JSON.stringify(result.data, null, 2));\n if (result.textTruncated) parts.push(\"The answer was truncated.\");\n if (result.dataOmitted) parts.push(\"Structured output was too large to include.\");\n for (const request of result.requests) {\n parts.push(request.prompt);\n parts.push(`Request ID: ${request.requestId}`);\n if (request.options?.length) {\n parts.push(request.options.map(option => `- ${option.label} (option ID: ${option.id})${option.description ? ` — ${option.description}` : \"\"}`).join(\"\\n\"));\n }\n if (request.allowFreeform === false || (request.options?.length && request.allowFreeform !== true)) {\n parts.push(\"Reply with an option ID.\");\n }\n }\n if (result.requiresHostInput) parts.push(\"Approval or authorization must be completed through the Eve host.\");\n if (result.runId) parts.push(`Run ID: ${result.runId}`);\n return parts.join(\"\\n\\n\");\n}\n","import { createApp, type App } from \"@capable/app\";\nimport { capability, defineApp, type CapabilityDefinition, type DefinedErrors, type Schema } from \"@capable/core\";\nimport type { Client } from \"eve/client\";\nimport { z } from \"zod\";\nimport { presentAgentResult } from \"./agent-presentation.ts\";\n\nconst runInput = z.object({ runId: z.string().min(1).describe(\"Eve session ID returned by send.\") });\nconst question = z.object({\n requestId: z.string(),\n prompt: z.string(),\n display: z.enum([\"confirmation\", \"select\", \"text\"]).optional(),\n allowFreeform: z.boolean().optional(),\n options: z.array(z.object({ id: z.string(), label: z.string(), description: z.string().optional() })).optional(),\n});\nconst resultSchema = z.object({\n status: z.enum([\"running\", \"waiting\", \"completed\", \"failed\", \"cancelled\"]),\n cursor: z.number().int().nonnegative(),\n eventCount: z.number().int().nonnegative(),\n requests: z.array(question),\n text: z.string().optional(),\n data: z.json().optional(),\n dataOmitted: z.boolean().optional(),\n textTruncated: z.boolean().optional(),\n requiresHostInput: z.boolean().optional(),\n error: z.string().optional(),\n});\nexport interface EveAgentQuestion {\n requestId: string;\n prompt: string;\n display?: \"confirmation\" | \"select\" | \"text\" | undefined;\n allowFreeform?: boolean | undefined;\n options?: { id: string; label: string; description?: string | undefined }[] | undefined;\n}\nexport type EveAgentData = string | number | boolean | null | EveAgentData[] | { [key: string]: EveAgentData };\nexport interface EveAgentResult {\n status: \"running\" | \"waiting\" | \"completed\" | \"failed\" | \"cancelled\";\n cursor: number;\n eventCount: number;\n requests: EveAgentQuestion[];\n text?: string | undefined;\n data?: EveAgentData | undefined;\n dataOmitted?: boolean | undefined;\n textTruncated?: boolean | undefined;\n requiresHostInput?: boolean | undefined;\n error?: string | undefined;\n}\n\ntype AgentCapability<TInput extends Record<string, unknown>, TOutput, TParsed extends Record<string, unknown> = TInput> =\n CapabilityDefinition<undefined, Schema<TInput, TParsed>, TOutput, DefinedErrors<{}>, {}, false>;\ntype AgentCapabilities = {\n send: AgentCapability<{\n message: string; runId?: string | undefined; requestId?: string | undefined;\n optionId?: string | undefined; wait?: boolean | undefined; timeoutMs?: number | undefined;\n }, EveAgentResult & { runId: string }>;\n result: AgentCapability<{ runId: string; cursor?: number | undefined }, EveAgentResult, { runId: string; cursor: number }>;\n cancel: AgentCapability<{ runId: string; turnId?: string | undefined }, { status: \"accepted\" | \"no_active_turn\" }>;\n};\nexport interface EveAgentAdapter<TName extends string> {\n readonly app: App<{ [K in TName]: AgentCapabilities }>;\n /** Abort local requests without cancelling remote execution. */\n dispose(): void;\n}\nexport type EveAgentOperation = \"send\" | \"result\" | \"cancel\";\n\nexport interface EveAgentAdapterOptions<TName extends string> {\n /** Namespace and capability ID prefix; unique within the composed App. */\n readonly name: TName;\n /** Host-configured client for ONE authenticated caller. Never share an adapter across callers. */\n readonly client: Pick<Client, \"sessions\">;\n /** Recheck host-owned authorization on every invocation, including reconstructed reads. Throw to deny. */\n readonly authorize: (operation: EveAgentOperation, runId?: string) => void | Promise<void>;\n readonly maxEventsPerRead?: number;\n readonly readTimeoutMs?: number;\n}\n\ntype Run = {\n sessionId: string;\n result: EveAgentResult;\n cancelled: boolean;\n hostInputs: Set<string>;\n authorizations: Set<string>;\n message: string | undefined;\n data: EveAgentData | undefined;\n dataOmitted: boolean;\n pending: Map<string, z.infer<typeof question>>;\n};\n\n/**\n * Wrap Eve execution as a caller-scoped Capable App.\n * Eve session IDs are run IDs. Every read reconstructs state from durable events.\n */\nexport function createEveAgentAdapter<const TName extends string>(options: EveAgentAdapterOptions<TName>): EveAgentAdapter<TName> {\n if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(options.name)) throw new Error(\"Invalid Eve agent namespace\");\n const maxEvents = positive(options.maxEventsPerRead ?? 10_000, \"maxEventsPerRead\");\n const timeoutMs = positive(options.readTimeoutMs ?? 1_000, \"readTimeoutMs\");\n const lifetime = new AbortController();\n\n async function authorize(operation: EveAgentOperation, runId?: string) {\n lifetime.signal.throwIfAborted();\n await options.authorize(operation, runId);\n lifetime.signal.throwIfAborted();\n }\n function signalFor(signal?: AbortSignal) {\n return AbortSignal.any([lifetime.signal, ...(signal ? [signal] : [])]);\n }\n async function readRun(runId: string, signal?: AbortSignal): Promise<Run> {\n const run: Run = {\n sessionId: runId,\n result: { status: \"running\", cursor: 0, eventCount: 0, requests: [] },\n cancelled: false, hostInputs: new Set(), authorizations: new Set(),\n message: undefined, data: undefined, dataOmitted: false, pending: new Map(),\n };\n const requestSignal = signalFor(signal);\n requestSignal.throwIfAborted();\n const read = new AbortController();\n const timer = setTimeout(() => read.abort(), timeoutMs);\n const combined = AbortSignal.any([requestSignal, read.signal]);\n try {\n const session = options.client.sessions.attach(runId);\n for await (const event of session.stream({ startIndex: 0, follow: false, signal: combined, streamReconnectPolicy: { reconnect: false } })) {\n if (run.result.cursor >= maxEvents) throw new Error(\"Eve history exceeds maxEventsPerRead\");\n if (event.type === \"input.requested\") {\n for (const request of event.data.requests) {\n if (request.kind === \"question\") {\n // Deliberate allowlist: no action input, tool names, IDs, or credentials.\n const safe = question.parse(request);\n if (JSON.stringify(safe).length > 65_536 || (!run.pending.has(safe.requestId) && run.pending.size >= 100)) throw new Error(\"Eve question limit exceeded\");\n run.pending.set(safe.requestId, safe);\n } else {\n remember(run.hostInputs, request.requestId);\n }\n }\n } else if (event.type === \"authorization.required\") {\n remember(run.authorizations, event.data.name);\n } else if (event.type === \"authorization.completed\") {\n run.authorizations.delete(event.data.name);\n } else if (event.type === \"input.resolved\") {\n for (const resolution of event.data.resolutions) {\n run.pending.delete(resolution.requestId);\n run.hostInputs.delete(resolution.requestId);\n }\n run.result.requests = [...run.pending.values()];\n } else if (event.type === \"turn.started\" || event.type === \"step.started\") {\n run.result = { status: \"running\", cursor: run.result.cursor, eventCount: 0, requests: [] };\n if (event.type === \"turn.started\") {\n run.cancelled = false;\n run.message = undefined;\n run.data = undefined;\n run.dataOmitted = false;\n }\n } else if (event.type === \"message.completed\" && event.data.finishReason !== \"tool-calls\") {\n run.message = event.data.message?.slice(0, 65_536);\n run.result.textTruncated = (event.data.message?.length ?? 0) > 65_536;\n } else if (event.type === \"result.completed\") {\n run.dataOmitted = JSON.stringify(event.data.result).length > 65_536;\n run.data = run.dataOmitted ? undefined : z.json().parse(event.data.result);\n } else if (event.type === \"turn.cancelled\") {\n run.cancelled = true;\n } else if (event.type === \"session.failed\" || event.type === \"turn.failed\") {\n run.result.status = \"failed\";\n // Raw failure details can include private tool arguments or credentials.\n run.result.error = \"Eve agent execution failed\";\n } else if (event.type === \"session.completed\" || event.type === \"session.waiting\") {\n run.result.status = run.cancelled ? \"cancelled\"\n : event.type === \"session.waiting\" && (run.pending.size > 0 || (run.hostInputs.size > 0 || run.authorizations.size > 0) || (run.message === undefined && run.data === undefined && !run.dataOmitted)) ? \"waiting\" : \"completed\";\n if (run.result.status === \"completed\" && run.message !== undefined) run.result.text = run.message;\n if (run.result.status === \"completed\") {\n run.result.requests = [];\n delete run.result.requiresHostInput;\n if (run.data !== undefined) run.result.data = run.data;\n if (run.dataOmitted) run.result.dataOmitted = true;\n }\n if (run.result.status === \"waiting\") {\n run.result.requests = [...run.pending.values()];\n run.result.requiresHostInput = (run.hostInputs.size > 0 || run.authorizations.size > 0) || run.pending.size === 0;\n }\n }\n\n run.result.cursor++;\n }\n // Eve can swallow stream aborts. Never validate an answer against partial history.\n combined.throwIfAborted();\n return run;\n } finally {\n clearTimeout(timer);\n read.abort();\n }\n }\n\n const capabilities = {\n send: capability({\n id: `${options.name}.send`, effect: \"write\",\n description: \"Send a message, optionally continuing an Eve session and waiting for its answer.\",\n meta: { cli: { positional: [\"message\"] } },\n input: z.object({\n message: z.string().min(1).max(65_536).describe(\"Message to send, or a text answer to a pending question. With option-id, only the selected option is submitted.\"),\n runId: z.string().min(1).optional().describe(\"Continue this Eve session. Omit to begin a new conversation.\"),\n requestId: z.string().min(1).optional().describe(\"Pending question to answer. Required when several questions are waiting; use with run-id.\"),\n optionId: z.string().min(1).optional().describe(\"Answer option ID shown by result. Required for questions that do not accept freeform text; use with run-id.\"),\n wait: z.boolean().optional().describe(\"Wait for an answer, pending input, failure, or cancellation. Otherwise return the run ID immediately.\"),\n timeoutMs: z.number().int().min(1).max(300_000).optional().describe(\"Wait limit in milliseconds after acceptance (default: 30000; maximum: 300000). Only used with wait. Expiry leaves Eve running.\"),\n }),\n output: resultSchema.extend({ runId: z.string() }),\n toPresentation: presentAgentResult,\n handler: async ({ input, signal }) => {\n await authorize(\"send\", input.runId);\n if (!input.runId && (input.requestId || input.optionId)) throw new Error(\"Question answers require a runId\");\n const waiting = new AbortController();\n const requestSignal = AbortSignal.any([signalFor(signal), waiting.signal]);\n const sendOptions = { signal: requestSignal, streamReconnectPolicy: { reconnect: false as const } };\n let response;\n if (input.runId) {\n const run = await readRun(input.runId, signal);\n const session = options.client.sessions.attach(input.runId, { streamIndex: run.result.cursor });\n if (input.requestId || run.pending.size) {\n const pending = input.requestId ? run.pending.get(input.requestId)\n : run.pending.size === 1 ? [...run.pending.values()][0] : undefined;\n if (!pending || run.result.status !== \"waiting\") throw new Error(\"Specify requestId for a current pending question\");\n if (input.optionId) {\n if (!pending.options?.some(option => option.id === input.optionId)) throw new Error(\"Unknown answer option\");\n } else if (pending.allowFreeform === false || (pending.options?.length && pending.allowFreeform !== true)) {\n throw new Error(\"This question requires optionId\");\n }\n response = await session.respond([{\n requestId: pending.requestId,\n ...(input.optionId ? { optionId: input.optionId } : { text: input.message }),\n }], sendOptions);\n } else {\n if (input.optionId) throw new Error(\"No pending question for optionId\");\n if (run.hostInputs.size || run.authorizations.size) throw new Error(\"Pending approval or authorization requires host action\");\n response = await session.send(input.message, sendOptions);\n }\n if (response.sessionId !== input.runId) throw new Error(\"Eve resumed a different session\");\n } else {\n ({ response } = await options.client.sessions.create({ message: input.message, ...sendOptions }));\n }\n const runId = response.sessionId;\n const accepted = { runId, status: \"running\" as const, cursor: 0, eventCount: 0, requests: [] };\n if (!input.wait) return accepted;\n // Eve correlates this stream with the accepted delivery, skipping old turn boundaries.\n // The timer starts after acceptance; aborting this local stream never cancels Eve.\n const timer = setTimeout(() => waiting.abort(), input.timeoutMs ?? 30_000);\n try {\n let count = 0;\n let boundary = false;\n for await (const event of response) {\n requestSignal.throwIfAborted();\n if (++count > maxEvents) throw new Error(\"Eve response exceeds maxEventsPerRead\");\n if ([\"session.waiting\", \"session.completed\", \"session.failed\", \"turn.failed\"].includes(event.type)) {\n boundary = true;\n break;\n }\n }\n requestSignal.throwIfAborted();\n if (!boundary) return accepted;\n const run = await readRun(runId, requestSignal);\n return { runId, ...run.result, eventCount: run.result.cursor };\n } catch (error) {\n signalFor(signal).throwIfAborted();\n if (waiting.signal.aborted) return accepted;\n throw error;\n } finally {\n clearTimeout(timer);\n waiting.abort();\n }\n },\n }),\n result: capability({\n id: `${options.name}.result`, effect: \"read\",\n description: \"Read bounded progress, pending questions, or the final output. Pass the last returned cursor.\",\n input: runInput.extend({ cursor: z.number().int().nonnegative().default(0).describe(\"Cursor from the previous result, used to count new events. Defaults to 0; the full current result is still returned.\") }),\n output: resultSchema,\n toPresentation: presentAgentResult,\n handler: async ({ input, signal }) => {\n await authorize(\"result\", input.runId);\n const run = await readRun(input.runId, signal);\n if (input.cursor > run.result.cursor) throw new Error(\"Eve cursor is ahead of this run\");\n return { ...run.result, eventCount: run.result.cursor - input.cursor };\n },\n }),\n cancel: capability({\n id: `${options.name}.cancel`, effect: \"write\",\n description: \"Request cooperative cancellation of the active Eve turn. Acceptance is not completion.\",\n input: runInput.extend({ turnId: z.string().min(1).optional().describe(\"Specific Eve turn to cancel. Omit to cancel the session’s active turn.\") }),\n output: z.object({ status: z.enum([\"accepted\", \"no_active_turn\"]) }),\n toPresentation: ({ status }) => status === \"accepted\"\n ? \"Cancellation requested. Check the result to confirm execution has stopped.\"\n : \"No active turn to cancel.\",\n handler: async ({ input, signal }) => {\n await authorize(\"cancel\", input.runId);\n signalFor(signal).throwIfAborted();\n // Cancellation can run alongside a bounded result read.\n const result = await options.client.sessions.attach(input.runId).cancel({\n signal: signalFor(signal),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n });\n return { status: result.status };\n },\n }),\n };\n // Widen the key during construction: TypeScript cannot reduce context inference\n // for a generic mapped namespace, although all three capabilities are context-free.\n const checked: AgentCapabilities = capabilities;\n const app = createApp(defineApp({ capabilities: { [options.name]: checked } })) as App<{ [K in TName]: AgentCapabilities }>;\n return {\n app,\n dispose() {\n lifetime.abort();\n },\n };\n}\n\nfunction positive(value: number, name: string) {\n if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive safe integer`);\n return value;\n}\n\nfunction remember(values: Set<string>, value: string) {\n if (value.length > 65_536 || (!values.has(value) && values.size >= 100)) {\n throw new Error(\"Eve pending input limit exceeded\");\n }\n values.add(value);\n}\n","import {\n getAppRuntime,\n type AnyApp,\n type ManifestNode,\n type ManifestCapability,\n} from \"@capable/app\";\nimport type { CapabilityMetaRegistry } from \"@capable/core\";\nimport {\n defineDynamic,\n defineTool,\n defineDurableCallback,\n type DynamicResolveContext,\n type DynamicSentinel,\n type ToolDefinition,\n type ToolContext,\n} from \"eve/tools\";\nimport type { Approval } from \"eve/tools/approval\";\n\nexport type EveCapabilityMeta =\n | false\n | {\n readonly name?: string;\n };\n\ndeclare module \"@capable/core\" {\n interface CapabilityMetaRegistry {\n readonly eve?: EveCapabilityMeta;\n }\n}\n\nexport type CreateEveToolsOptions = {\n readonly approval?: (\n capability: ManifestCapability,\n ) => Approval | undefined;\n};\n\nexport type EveAppProvider =\n | AnyApp\n | ((\n context: DynamicResolveContext,\n ) => AnyApp | Promise<AnyApp>);\n\nconst emptyInputSchema = Object.freeze({\n type: \"object\",\n properties: Object.freeze({}),\n additionalProperties: false,\n});\n\ntype EveTool = ToolDefinition<Record<string, unknown>, unknown>;\n\n/**\n * Projects an executable Capable App into native, in-process Eve tools.\n *\n * Eve owns the live executor bindings and checkpoints each call and result.\n * Session resolvers rebuild App bindings after a cold start. Define the App or\n * provider in deployed module code and keep persistent data outside the process.\n */\nexport function createEveTools(\n app: EveAppProvider,\n options: CreateEveToolsOptions = {},\n): DynamicSentinel<Record<string, EveTool>> {\n const capabilitiesByApp = new WeakMap<\n AnyApp,\n Promise<readonly ManifestCapability[]>\n >();\n const capabilities = (resolvedApp: AnyApp) => {\n const existing = capabilitiesByApp.get(resolvedApp);\n if (existing) return existing;\n const resolved = getAppRuntime(resolvedApp).manifest().then((manifest) =>\n flatten(manifest.capabilities)\n );\n capabilitiesByApp.set(resolvedApp, resolved);\n return resolved;\n };\n\n return defineDynamic({\n events: {\n \"session.started\": async (_event, resolveContext) => {\n const resolvedApp = typeof app === \"function\"\n ? await app(resolveContext)\n : app;\n const tools: Record<string, EveTool> = {};\n const names = new Set<string>();\n\n for (const capability of await capabilities(resolvedApp)) {\n const meta = capability.meta.eve as EveCapabilityMeta | undefined;\n if (meta === false) continue;\n\n const name = meta?.name ?? capability.path.join(\"__\");\n if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) {\n throw new Error(\n `Eve tool name \"${name}\" is invalid; set meta.eve.name to 1-64 letters, numbers, underscores, or hyphens`,\n );\n }\n if (names.has(name)) {\n throw new Error(`Duplicate Eve tool name \"${name}\"`);\n }\n names.add(name);\n\n const policy = options.approval?.(capability);\n const approval = policy && durableApproval(policy, capability.id);\n const definition: Omit<EveTool, \"execute\"> = {\n description:\n capability.description ??\n capability.title ??\n `Run the Capable Capability at ${capability.path.join(\".\")}.`,\n inputSchema: (capability.input ??\n emptyInputSchema) as EveTool[\"inputSchema\"],\n ...(capability.output\n ? {\n outputSchema:\n capability.output as NonNullable<EveTool[\"outputSchema\"]>,\n }\n : {}),\n ...(approval ? { approval } : {}),\n };\n const id = capability.id;\n tools[name] = defineTool({\n ...definition,\n execute: defineDurableCallback({\n closure: { id },\n callback: async ({ id }, input: Record<string, unknown>, context: ToolContext) => {\n // A rejected approval can change the latest resolver's caller.\n // Rebuild per-caller Apps from the actual execution identity.\n const executionApp = typeof app === \"function\"\n ? await app({ ...resolveContext, session: context.session })\n : app;\n const result = await getAppRuntime(executionApp).call({\n id, input, signal: context.abortSignal,\n });\n return result.output;\n },\n }),\n });\n }\n\n return tools;\n },\n },\n });\n}\n\n/** The resolver reconstructs policies; persist identity and reject rebinding to a different capability. */\nfunction durablePolicy<T extends (...args: never[]) => unknown>(policy: T, id: string): T {\n return defineDurableCallback({\n closure: { id },\n callback: (snapshot, ...args: Parameters<T>) => {\n if (snapshot.id !== id) throw new Error(\"Eve capability identity changed during recovery\");\n return policy(...args);\n },\n }) as T;\n}\n\nfunction durableApproval(policy: Approval, id: string): Approval {\n if (typeof policy === \"function\") return durablePolicy(policy, id);\n return {\n request: durablePolicy(policy.request, id),\n ...(policy.response ? { response: durablePolicy(policy.response, id) } : {}),\n };\n}\n\nfunction flatten(\n nodes: readonly ManifestNode[],\n): readonly ManifestCapability[] {\n return nodes.flatMap((node) =>\n node.type === \"capability\" ? [node] : flatten(node.children)\n );\n}\n\nexport {\n createEveAgentAdapter,\n type EveAgentAdapter,\n type EveAgentAdapterOptions,\n type EveAgentOperation,\n type EveAgentData,\n type EveAgentQuestion,\n type EveAgentResult,\n} from \"./agent.ts\";\n"],"mappings":";;;;;;AAGA,SAAgB,mBAAmB,QAAqD;CAQtF,MAAM,QAAQ,CAPC;EACb,SAAS;EACT,SAAS;EACT,WAAW;EACX,QAAQ;EACR,WAAW;CACb,EAAE,OAAO,OACY;CACrB,IAAI,OAAO,MAAM,MAAM,KAAK,OAAO,IAAI;CACvC,IAAI,OAAO,SAAS,KAAA,GAAW,MAAM,KAAK,KAAK,UAAU,OAAO,MAAM,MAAM,CAAC,CAAC;CAC9E,IAAI,OAAO,eAAe,MAAM,KAAK,2BAA2B;CAChE,IAAI,OAAO,aAAa,MAAM,KAAK,6CAA6C;CAChF,KAAK,MAAM,WAAW,OAAO,UAAU;EACrC,MAAM,KAAK,QAAQ,MAAM;EACzB,MAAM,KAAK,eAAe,QAAQ,WAAW;EAC7C,IAAI,QAAQ,SAAS,QACnB,MAAM,KAAK,QAAQ,QAAQ,KAAI,WAAU,KAAK,OAAO,MAAM,eAAe,OAAO,GAAG,GAAG,OAAO,cAAc,MAAM,OAAO,gBAAgB,IAAI,CAAC,CAAC,KAAK,IAAI,CAAC;EAE3J,IAAI,QAAQ,kBAAkB,SAAU,QAAQ,SAAS,UAAU,QAAQ,kBAAkB,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AHc,cAHA,OAAO,QAAQ,aAChC,MAAM,IAAI;OAAE,GAAG;OAAgB,SAAS,QAAQ;MAAQ,CAAC,IACzD,GAC2C,CAAC,CAAC,KAAK;OACpD;OAAI;OAAO,QAAQ,QAAQ;MAC7B,CAAC,EAAA,CACa;KAChB;IACF,CAAC;GACH,CAAC;EACH;EAEA,OAAO;CACT,EACF,EACF,CAAC;AACH;;AAGA,SAAS,cAAuD,QAAW,IAAe;CACxF,OAAO,sBAAsB;EAC3B,SAAS,EAAE,GAAG;EACd,WAAW,UAAU,GAAG,SAAwB;GAC9C,IAAI,SAAS,OAAO,IAAI,MAAM,IAAI,MAAM,iDAAiD;GACzF,OAAO,OAAO,GAAG,IAAI;EACvB;CACF,CAAC;AACH;AAEA,SAAS,gBAAgB,QAAkB,IAAsB;CAC/D,IAAI,OAAO,WAAW,YAAY,OAAO,cAAc,QAAQ,EAAE;CACjE,OAAO;EACL,SAAS,cAAc,OAAO,SAAS,EAAE;EACzC,GAAI,OAAO,WAAW,EAAE,UAAU,cAAc,OAAO,UAAU,EAAE,EAAE,IAAI,CAAC;CAC5E;AACF;AAEA,SAAS,QACP,OAC+B;CAC/B,OAAO,MAAM,SAAS,SACpB,KAAK,SAAS,eAAe,CAAC,IAAI,IAAI,QAAQ,KAAK,QAAQ,CAC7D;AACF"}
package/dist/http.d.mts CHANGED
@@ -1,2 +1,2 @@
1
- import { a as HttpGroupMeta, c as FetchHandler, d as createProtocolHandler, f as JsonValue, i as HttpCapabilityMeta, l as TransportHeaders, m as defineProtocolCodec, n as CompiledHttpRoute, o as HttpMethod, p as ProtocolCodec, r as ContextProvider, s as createHttpHandler, t as CapabilitySelection, u as createHttpTransport } from "./index-Dl4NK9G0.mjs";
1
+ import { a as HttpGroupMeta, c as FetchHandler, d as createProtocolHandler, f as JsonValue, i as HttpCapabilityMeta, l as TransportHeaders, m as defineProtocolCodec, n as CompiledHttpRoute, o as HttpMethod, p as ProtocolCodec, r as ContextProvider, s as createHttpHandler, t as CapabilitySelection, u as createHttpTransport } from "./index-D8DWjQ9f.mjs";
2
2
  export { type CapabilitySelection, type CompiledHttpRoute, type ContextProvider, type FetchHandler, type HttpCapabilityMeta, type HttpGroupMeta, type HttpMethod, type JsonValue, type ProtocolCodec, type TransportHeaders, createHttpHandler, createHttpTransport, createProtocolHandler, defineProtocolCodec };
package/dist/http.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { i as defineProtocolCodec, n as createHttpTransport, r as createProtocolHandler, t as createHttpHandler } from "./src-rkr5j_NH.mjs";
1
+ import { i as defineProtocolCodec, n as createHttpTransport, r as createProtocolHandler, t as createHttpHandler } from "./src-Hw9WBgEW.mjs";
2
2
  export { createHttpHandler, createHttpTransport, createProtocolHandler, defineProtocolCodec };
@@ -1,4 +1,4 @@
1
- import { A as CapabilityTree, D as AppDefinition, E as AppContext, f as CapabilityOutput, g as SubscribableCapability, i as CapabilityDefinition, it as AnyObjectSchema, k as CapabilityGroupDefinition, ot as InferSchemaInput, q as MaybePromise, t as AnyCapability, z as PresentationPart } from "./index-_qKFfWV4.mjs";
1
+ import { A as CapabilityTree, D as AppDefinition, E as AppContext, f as CapabilityOutput, g as SubscribableCapability, i as CapabilityDefinition, it as AnyObjectSchema, k as CapabilityGroupDefinition, ot as InferSchemaInput, q as MaybePromise, t as AnyCapability, z as PresentationPart } from "./index-ftQx6OMr.mjs";
2
2
  //#region packages/app/src/manifest.d.ts
3
3
  type JsonSchema = Readonly<Record<string, unknown>>;
4
4
  type ManifestError = {
@@ -112,8 +112,13 @@ declare class TransportError extends Error {
112
112
  //#endregion
113
113
  //#region packages/app/src/composition.d.ts
114
114
  type UnionToIntersection<TValue> = (TValue extends unknown ? (value: TValue) => void : never) extends ((value: infer TIntersection) => void) ? TIntersection : never;
115
- type MergedCapabilities<TApplications extends readonly AnyApp[]> = UnionToIntersection<AppCapabilities<TApplications[number]>> & CapabilityTree;
116
- declare function mergeApps<const TApplications extends readonly [AnyApp, ...AnyApp[]]>(...applications: TApplications): App<MergedCapabilities<TApplications>>;
115
+ type AppComposition = AnyApp | {
116
+ readonly [key: string]: AppComposition;
117
+ };
118
+ type ComposedNode<TNode> = TNode extends AnyApp ? AppCapabilities<TNode> : TNode extends Readonly<Record<string, unknown>> ? { readonly [TKey in keyof TNode]: ComposedNode<TNode[TKey]>; } : never;
119
+ type ComposedCapabilities<TNodes extends readonly AppComposition[]> = UnionToIntersection<ComposedNode<TNodes[number]>> extends (infer TCapabilities extends CapabilityTree) ? TCapabilities : never;
120
+ /** Compose root Apps and tree-shaped App placements into one executable App. */
121
+ declare function composeApps<const TNodes extends readonly [AppComposition, ...AppComposition[]]>(...nodes: TNodes): App<ComposedCapabilities<TNodes>>;
117
122
  type SelectionNode<TTree> = TTree extends AnyCapability ? true : TTree extends CapabilityGroupDefinition<infer TCapabilities, any, any> ? true | SelectionNode<TCapabilities> : TTree extends CapabilityTree ? true | { readonly [TKey in keyof TTree]?: SelectionNode<TTree[TKey]>; } : never;
118
123
  type ApplicationSelection<TCapabilities extends CapabilityTree = CapabilityTree> = {
119
124
  readonly include?: Exclude<SelectionNode<TCapabilities>, true>;
@@ -121,5 +126,5 @@ type ApplicationSelection<TCapabilities extends CapabilityTree = CapabilityTree>
121
126
  };
122
127
  declare function selectApp<const TCapabilities extends CapabilityTree>(application: App<TCapabilities>, selection: ApplicationSelection<TCapabilities>): App<TCapabilities>;
123
128
  //#endregion
124
- export { JsonSchema as C, ManifestNode as D, ManifestGroup as E, createAppManifest as O, ApplicationManifest as S, ManifestError as T, createApp as _, APP_RUNTIME_SYMBOL as a, isApp as b, AppCapabilities as c, AppContextProvider as d, ApplicationTransport as f, TransportError as g, CapabilityResult as h, APP_CAPABILITIES_SYMBOL as i, AppCapabilityCall as l, CapabilityCall as m, mergeApps as n, AnyApp as o, CallableTree as p, selectApp as r, App as s, ApplicationSelection as t, AppCapabilityIsSubscribable as u, createRemoteApp as v, ManifestCapability as w, subscribe as x, getAppRuntime as y };
125
- //# sourceMappingURL=index-F4ba_olD.d.mts.map
129
+ export { JsonSchema as C, ManifestNode as D, ManifestGroup as E, createAppManifest as O, ApplicationManifest as S, ManifestError as T, createApp as _, APP_RUNTIME_SYMBOL as a, isApp as b, AppCapabilities as c, AppContextProvider as d, ApplicationTransport as f, TransportError as g, CapabilityResult as h, APP_CAPABILITIES_SYMBOL as i, AppCapabilityCall as l, CapabilityCall as m, composeApps as n, AnyApp as o, CallableTree as p, selectApp as r, App as s, ApplicationSelection as t, AppCapabilityIsSubscribable as u, createRemoteApp as v, ManifestCapability as w, subscribe as x, getAppRuntime as y };
130
+ //# sourceMappingURL=index-D63DSGZG.d.mts.map
@@ -1,5 +1,5 @@
1
- import { A as CapabilityTree, D as AppDefinition, M as LocatedCapability } from "./index-_qKFfWV4.mjs";
2
- import { f as ApplicationTransport, o as AnyApp, t as ApplicationSelection } from "./index-F4ba_olD.mjs";
1
+ import { A as CapabilityTree, D as AppDefinition, M as LocatedCapability } from "./index-ftQx6OMr.mjs";
2
+ import { f as ApplicationTransport, o as AnyApp, t as ApplicationSelection } from "./index-D63DSGZG.mjs";
3
3
  //#region packages/fetch/src/codec.d.ts
4
4
  type JsonValue = null | boolean | number | string | readonly JsonValue[] | {
5
5
  readonly [key: string]: JsonValue;
@@ -70,4 +70,4 @@ declare function createHttpHandler<const TCapabilities extends CapabilityTree, T
70
70
  };
71
71
  //#endregion
72
72
  export { HttpGroupMeta as a, FetchHandler as c, createProtocolHandler as d, JsonValue as f, HttpCapabilityMeta as i, TransportHeaders as l, defineProtocolCodec as m, CompiledHttpRoute as n, HttpMethod as o, ProtocolCodec as p, ContextProvider as r, createHttpHandler as s, CapabilitySelection as t, createHttpTransport as u };
73
- //# sourceMappingURL=index-Dl4NK9G0.d.mts.map
73
+ //# sourceMappingURL=index-D8DWjQ9f.d.mts.map
@@ -1,6 +1,6 @@
1
- import { D as AppDefinition, q as MaybePromise } from "./index-_qKFfWV4.mjs";
2
- import { t as ApplicationSelection } from "./index-F4ba_olD.mjs";
3
- import { p as ProtocolCodec, r as ContextProvider, t as CapabilitySelection } from "./index-Dl4NK9G0.mjs";
1
+ import { D as AppDefinition, q as MaybePromise } from "./index-ftQx6OMr.mjs";
2
+ import { t as ApplicationSelection } from "./index-D63DSGZG.mjs";
3
+ import { p as ProtocolCodec, r as ContextProvider, t as CapabilitySelection } from "./index-D8DWjQ9f.mjs";
4
4
  //#region packages/server/src/index.d.ts
5
5
  type ServerMount<TContext> = {
6
6
  readonly kind: "capable.server.mount";
@@ -40,4 +40,4 @@ type CreateServerArgs<TContext> = [TContext] extends [undefined] ? [options?: Cr
40
40
  declare function createServer<TContext>(app: AppDefinition<any, TContext>, ...[providedOptions]: CreateServerArgs<TContext>): CapableServer;
41
41
  //#endregion
42
42
  export { createServer as a, ServerMount as i, CompiledServerMount as n, http as o, ServerMiddleware as r, protocol as s, CapableServer as t };
43
- //# sourceMappingURL=index-hdH_K5Zc.d.mts.map
43
+ //# sourceMappingURL=index-DgxvtAmv.d.mts.map