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

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 (93) hide show
  1. package/CHANGELOG.md +385 -0
  2. package/LICENSE +21 -0
  3. package/README.md +12 -0
  4. package/dist/ai-sdk.d.mts +3 -3
  5. package/dist/ai-sdk.mjs +9 -7
  6. package/dist/ai-sdk.mjs.map +1 -1
  7. package/dist/app.d.mts +2 -2
  8. package/dist/app.mjs +2 -2
  9. package/dist/bin.mjs +19 -15
  10. package/dist/bin.mjs.map +1 -1
  11. package/dist/cli.d.mts +9 -1
  12. package/dist/cli.mjs +1 -1
  13. package/dist/core.d.mts +3 -3
  14. package/dist/core.mjs +2 -2
  15. package/dist/eve.d.mts +92 -9
  16. package/dist/eve.mjs +606 -26
  17. package/dist/eve.mjs.map +1 -1
  18. package/dist/http.d.mts +1 -1
  19. package/dist/http.mjs +1 -1
  20. package/dist/{index-_qKFfWV4.d.mts → index-BIO_hbXJ.d.mts} +69 -26
  21. package/dist/{index-hdH_K5Zc.d.mts → index-C0tU5Y2n.d.mts} +4 -4
  22. package/dist/{index-Dl4NK9G0.d.mts → index-CwvjDizW.d.mts} +5 -3
  23. package/dist/{index-F4ba_olD.d.mts → index-F_eaksy8.d.mts} +58 -17
  24. package/dist/index.d.mts +4 -4
  25. package/dist/index.mjs +3 -3
  26. package/dist/mcp.d.mts +19 -4
  27. package/dist/mcp.mjs +2 -2
  28. package/dist/{mount-CEFAplR5.mjs → mount-pvIaehZC.mjs} +159 -107
  29. package/dist/mount-pvIaehZC.mjs.map +1 -0
  30. package/dist/react-query.d.mts +2 -2
  31. package/dist/react-query.mjs +1 -1
  32. package/dist/react-query.mjs.map +1 -1
  33. package/dist/runtime-support.d.mts +1 -1
  34. package/dist/runtime-support.mjs +3 -3
  35. package/dist/server.d.mts +1 -1
  36. package/dist/server.mjs +1 -1
  37. package/dist/{src-rkr5j_NH.mjs → src-Bk3lEhI7.mjs} +63 -25
  38. package/dist/src-Bk3lEhI7.mjs.map +1 -0
  39. package/dist/src-C2OEkZ3c.mjs +760 -0
  40. package/dist/src-C2OEkZ3c.mjs.map +1 -0
  41. package/dist/{src-BWxDO2Ua.mjs → src-DFrxQ_S6.mjs} +9 -7
  42. package/dist/src-DFrxQ_S6.mjs.map +1 -0
  43. package/dist/{src-D_0PIhqq.mjs → src-DklM1g7V.mjs} +69 -40
  44. package/dist/src-DklM1g7V.mjs.map +1 -0
  45. package/dist/{src-D-cm2gQ6.mjs → src-TCQGaWar.mjs} +119 -45
  46. package/dist/src-TCQGaWar.mjs.map +1 -0
  47. package/dist/{subscription-B-auXJbm.d.mts → subscription-fVgS4T8P.d.mts} +2 -2
  48. package/dist/swr.d.mts +2 -2
  49. package/dist/swr.mjs +1 -1
  50. package/dist/swr.mjs.map +1 -1
  51. package/docs/CONTEXT.md +44 -22
  52. package/docs/README.md +3 -0
  53. package/docs/internal/README.md +3 -0
  54. package/docs/internal/adr/0001-capability-is-the-semantic-boundary.md +1 -1
  55. package/docs/internal/adr/0003-capability-reference-customization.md +68 -0
  56. package/docs/internal/architecture.md +31 -17
  57. package/docs/internal/capability-first-model.md +126 -17
  58. package/docs/internal/eve-recovery-validation.md +87 -0
  59. package/docs/internal/feedback/v-ray/README.md +258 -0
  60. package/docs/internal/feedback/v-ray/inference.mjs +43 -0
  61. package/docs/internal/feedback/v-ray/reproduce.mjs +36 -0
  62. package/docs/internal/implementation-friction.md +445 -1
  63. package/docs/internal/releases.md +79 -0
  64. package/docs/site/capable-orpc-and-trpc.mdx +2 -2
  65. package/docs/site/concepts/apps.mdx +7 -1
  66. package/docs/site/concepts/architecture.mdx +9 -1
  67. package/docs/site/concepts/capabilities.mdx +41 -4
  68. package/docs/site/concepts/errors.mdx +26 -4
  69. package/docs/site/concepts/presentations.mdx +20 -0
  70. package/docs/site/hosting/standalone-server.mdx +2 -0
  71. package/docs/site/patterns/composition.mdx +152 -8
  72. package/docs/site/patterns/remote-apps.mdx +29 -3
  73. package/docs/site/patterns/subscriptions.mdx +79 -32
  74. package/docs/site/quickstart.mdx +3 -2
  75. package/docs/site/reference/packages-and-entry-points.mdx +52 -4
  76. package/docs/site/reference/the-cap-cli.mdx +2 -2
  77. package/docs/site/surfaces/cli.mdx +44 -0
  78. package/docs/site/surfaces/eve.mdx +67 -18
  79. package/docs/site/surfaces/mcp.mdx +84 -2
  80. package/docs/site/surfaces/typescript.mdx +3 -3
  81. package/package-docs.mjs +3 -0
  82. package/package.json +17 -12
  83. package/src/bin.ts +0 -0
  84. package/src/index.test.ts +2 -1
  85. package/src/index.ts +8 -1
  86. package/src/package.test.ts +15 -0
  87. package/dist/mount-CEFAplR5.mjs.map +0 -1
  88. package/dist/src-BWxDO2Ua.mjs.map +0 -1
  89. package/dist/src-D-cm2gQ6.mjs.map +0 -1
  90. package/dist/src-D_0PIhqq.mjs.map +0 -1
  91. package/dist/src-betOfnDL.mjs +0 -481
  92. package/dist/src-betOfnDL.mjs.map +0 -1
  93. package/dist/src-rkr5j_NH.mjs.map +0 -1
package/dist/eve.mjs CHANGED
@@ -1,5 +1,588 @@
1
- import { c as getAppRuntime } from "./src-betOfnDL.mjs";
1
+ import { r as defineApp, s as capability } from "./src-TCQGaWar.mjs";
2
+ import { d as getAppRuntime, h as flattenManifestCapabilities, i as getCapabilityDisplay, l as createApp } from "./src-C2OEkZ3c.mjs";
2
3
  import { defineDynamic, defineTool } from "eve/tools";
4
+ import { delivery, emptySessionView, failure, foldEvents, interaction, openInteractions, parts, reply, session, turn, turns } from "eve/events";
5
+ //#region packages/eve/src/agent-schemas.ts
6
+ var Invalid = class extends Error {
7
+ path;
8
+ constructor(path, message) {
9
+ super(message);
10
+ this.path = path;
11
+ }
12
+ };
13
+ function fail(path, message) {
14
+ throw new Invalid(path, message);
15
+ }
16
+ function field(parseAt, json) {
17
+ return {
18
+ parse: (value) => parseAt(value, []),
19
+ parseAt,
20
+ json,
21
+ inputOptional: false,
22
+ outputOptional: false
23
+ };
24
+ }
25
+ function string(options = {}) {
26
+ return field((value, path) => {
27
+ if (typeof value !== "string") fail(path, "Expected string");
28
+ if (options.minLength !== void 0 && value.length < options.minLength) fail(path, `Expected at least ${options.minLength} characters`);
29
+ if (options.maxLength !== void 0 && value.length > options.maxLength) fail(path, `Expected at most ${options.maxLength} characters`);
30
+ return value;
31
+ }, () => ({
32
+ type: "string",
33
+ ...options.minLength === void 0 ? {} : { minLength: options.minLength },
34
+ ...options.maxLength === void 0 ? {} : { maxLength: options.maxLength },
35
+ ...options.description === void 0 ? {} : { description: options.description }
36
+ }));
37
+ }
38
+ function integer(options = {}) {
39
+ const minimum = options.minimum ?? -Number.MAX_SAFE_INTEGER;
40
+ const maximum = options.maximum ?? Number.MAX_SAFE_INTEGER;
41
+ return field((value, path) => {
42
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) fail(path, "Expected integer");
43
+ if (value < minimum) fail(path, `Expected an integer >= ${minimum}`);
44
+ if (value > maximum) fail(path, `Expected an integer <= ${maximum}`);
45
+ return value;
46
+ }, () => ({
47
+ type: "integer",
48
+ minimum,
49
+ maximum,
50
+ ...options.description === void 0 ? {} : { description: options.description }
51
+ }));
52
+ }
53
+ function boolean(options = {}) {
54
+ return field((value, path) => {
55
+ if (typeof value !== "boolean") fail(path, "Expected boolean");
56
+ return value;
57
+ }, () => ({
58
+ type: "boolean",
59
+ ...options.description === void 0 ? {} : { description: options.description }
60
+ }));
61
+ }
62
+ function enumOf(...values) {
63
+ const allowed = new Set(values);
64
+ return field((value, path) => {
65
+ if (typeof value !== "string" || !allowed.has(value)) fail(path, `Expected one of: ${values.join(", ")}`);
66
+ return value;
67
+ }, () => ({
68
+ type: "string",
69
+ enum: [...values]
70
+ }));
71
+ }
72
+ function array(item) {
73
+ return field((value, path) => {
74
+ if (!Array.isArray(value)) fail(path, "Expected array");
75
+ return Array.from(value, (entry, index) => item.parseAt(entry, [...path, index]));
76
+ }, (direction) => ({
77
+ type: "array",
78
+ items: item.json(direction)
79
+ }));
80
+ }
81
+ function optional(item) {
82
+ return {
83
+ parse: (value) => value === void 0 ? void 0 : item.parse(value),
84
+ parseAt: (value, path) => value === void 0 ? void 0 : item.parseAt(value, path),
85
+ json: item.json,
86
+ inputOptional: true,
87
+ outputOptional: true
88
+ };
89
+ }
90
+ function withDefault(item, value) {
91
+ return {
92
+ parse: (input) => input === void 0 ? value : item.parse(input),
93
+ parseAt: (input, path) => input === void 0 ? value : item.parseAt(input, path),
94
+ json: (direction) => direction === "input" ? {
95
+ default: value,
96
+ ...item.json(direction)
97
+ } : item.json(direction),
98
+ inputOptional: true,
99
+ outputOptional: false
100
+ };
101
+ }
102
+ function jsonValueSchema() {
103
+ return { anyOf: [
104
+ { type: "string" },
105
+ { type: "number" },
106
+ { type: "boolean" },
107
+ { type: "null" },
108
+ {
109
+ type: "array",
110
+ items: {}
111
+ },
112
+ {
113
+ type: "object",
114
+ additionalProperties: {}
115
+ }
116
+ ] };
117
+ }
118
+ function json() {
119
+ return field((value, path) => parseJson(value, path, /* @__PURE__ */ new Set()), jsonValueSchema);
120
+ }
121
+ function parseJsonValue(value) {
122
+ return parseJson(value, [], /* @__PURE__ */ new Set());
123
+ }
124
+ function parseJson(value, path, seen) {
125
+ if (value === null) return null;
126
+ if (typeof value === "string" || typeof value === "boolean") return value;
127
+ if (typeof value === "number") {
128
+ if (!Number.isFinite(value)) fail(path, "Expected a finite number");
129
+ return value;
130
+ }
131
+ if (typeof value !== "object") fail(path, "Expected a JSON value");
132
+ if (seen.has(value)) fail(path, "Expected an acyclic JSON value");
133
+ seen.add(value);
134
+ try {
135
+ if (Array.isArray(value)) return Array.from(value, (entry, index) => parseJson(entry, [...path, index], seen));
136
+ const prototype = Object.getPrototypeOf(value);
137
+ if (prototype !== Object.prototype && prototype !== null) fail(path, "Expected a plain JSON object");
138
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [key, parseJson(entry, [...path, key], seen)]));
139
+ } finally {
140
+ seen.delete(value);
141
+ }
142
+ }
143
+ function object(shape) {
144
+ const json = (direction) => shapeJson(shape, direction);
145
+ const parseAt = (value, path) => parseShape(shape, value, path);
146
+ return {
147
+ ...defineSchema(parseAt, json),
148
+ parse: (value) => parseAt(value, []),
149
+ parseAt,
150
+ json,
151
+ inputOptional: false,
152
+ outputOptional: false
153
+ };
154
+ }
155
+ function parseShape(shape, value, path) {
156
+ if (typeof value !== "object" || value === null || Array.isArray(value)) fail(path, "Expected object");
157
+ const source = value;
158
+ const parsed = {};
159
+ for (const [key, item] of Object.entries(shape)) {
160
+ const fieldPath = [...path, key];
161
+ if (!Object.hasOwn(source, key)) {
162
+ if (!item.inputOptional) fail(fieldPath, "Required");
163
+ const output = item.parseAt(void 0, fieldPath);
164
+ if (output !== void 0) parsed[key] = output;
165
+ continue;
166
+ }
167
+ const output = item.parseAt(source[key], fieldPath);
168
+ if (output !== void 0) parsed[key] = output;
169
+ }
170
+ return parsed;
171
+ }
172
+ function shapeJson(shape, direction) {
173
+ const properties = {};
174
+ const required = [];
175
+ for (const [key, item] of Object.entries(shape)) {
176
+ properties[key] = item.json(direction);
177
+ if (!(direction === "input" ? item.inputOptional : item.outputOptional)) required.push(key);
178
+ }
179
+ return {
180
+ type: "object",
181
+ properties,
182
+ required,
183
+ ...direction === "output" ? { additionalProperties: false } : {}
184
+ };
185
+ }
186
+ const targetUrls = {
187
+ "draft-2020-12": "https://json-schema.org/draft/2020-12/schema",
188
+ "draft-07": "http://json-schema.org/draft-07/schema#"
189
+ };
190
+ function defineSchema(parseAt, json) {
191
+ return { "~standard": {
192
+ version: 1,
193
+ vendor: "capable-eve",
194
+ validate(value) {
195
+ try {
196
+ return { value: parseAt(value, []) };
197
+ } catch (error) {
198
+ if (!(error instanceof Invalid)) throw error;
199
+ return { issues: error.path.length === 0 ? [{ message: error.message }] : [{
200
+ message: error.message,
201
+ path: [...error.path]
202
+ }] };
203
+ }
204
+ },
205
+ jsonSchema: {
206
+ input: (options) => withTarget(json("input"), options.target),
207
+ output: (options) => withTarget(json("output"), options.target)
208
+ }
209
+ } };
210
+ }
211
+ function withTarget(schema, target) {
212
+ const url = targetUrls[target];
213
+ return url === void 0 ? schema : {
214
+ $schema: url,
215
+ ...schema
216
+ };
217
+ }
218
+ //#endregion
219
+ //#region packages/eve/src/agent-presentation.ts
220
+ /** Portable presentation shared by the CLI and other presentation-aware surfaces. */
221
+ function presentAgentResult(result) {
222
+ const parts = [{
223
+ running: "Running. Check the result again to follow progress.",
224
+ waiting: "Waiting for input.",
225
+ completed: "Completed.",
226
+ failed: "Agent execution failed.",
227
+ cancelled: "Cancelled."
228
+ }[result.status]];
229
+ if (result.text) parts.push(result.text);
230
+ if (result.data !== void 0) parts.push(JSON.stringify(result.data, null, 2));
231
+ if (result.textTruncated) parts.push("The answer was truncated.");
232
+ if (result.dataOmitted) parts.push("Structured output was too large to include.");
233
+ for (const request of result.requests) {
234
+ parts.push(request.prompt);
235
+ parts.push(`Request ID: ${request.requestId}`);
236
+ if (request.options?.length) parts.push(request.options.map((option) => `- ${option.label} (option ID: ${option.id})${option.description ? ` — ${option.description}` : ""}`).join("\n"));
237
+ if (request.allowFreeform === false || request.options?.length && request.allowFreeform !== true) parts.push("Reply with an option ID.");
238
+ }
239
+ if (result.requiresHostInput) parts.push("Approval or authorization must be completed through the Eve host.");
240
+ if (result.runId) parts.push(`Run ID: ${result.runId}`);
241
+ return parts.join("\n\n");
242
+ }
243
+ //#endregion
244
+ //#region packages/eve/src/agent.ts
245
+ const runId = string({
246
+ minLength: 1,
247
+ description: "Eve session ID returned by send."
248
+ });
249
+ const question = object({
250
+ requestId: string(),
251
+ prompt: string(),
252
+ display: optional(enumOf("confirmation", "select", "text")),
253
+ allowFreeform: optional(boolean()),
254
+ options: optional(array(object({
255
+ id: string(),
256
+ label: string(),
257
+ description: optional(string())
258
+ })))
259
+ });
260
+ const resultShape = {
261
+ status: enumOf("running", "waiting", "completed", "failed", "cancelled"),
262
+ cursor: integer({ minimum: 0 }),
263
+ eventCount: integer({ minimum: 0 }),
264
+ requests: array(question),
265
+ text: optional(string()),
266
+ data: optional(json()),
267
+ dataOmitted: optional(boolean()),
268
+ textTruncated: optional(boolean()),
269
+ requiresHostInput: optional(boolean()),
270
+ error: optional(string())
271
+ };
272
+ const resultSchema = object(resultShape);
273
+ const sendOutput = object({
274
+ ...resultShape,
275
+ runId: string()
276
+ });
277
+ /**
278
+ * Wrap Eve execution as a caller-scoped Capable App.
279
+ * Eve session IDs are run IDs. Every read reconstructs state from durable events.
280
+ */
281
+ function createEveAgentAdapter(options) {
282
+ if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(options.name)) throw new Error("Invalid Eve agent namespace");
283
+ const maxEvents = positive(options.maxEventsPerRead ?? 1e4, "maxEventsPerRead");
284
+ const timeoutMs = positive(options.readTimeoutMs ?? 1e3, "readTimeoutMs");
285
+ const lifetime = new AbortController();
286
+ async function authorize(operation, runId) {
287
+ lifetime.signal.throwIfAborted();
288
+ await options.authorize(operation, runId);
289
+ lifetime.signal.throwIfAborted();
290
+ }
291
+ function signalFor(signal) {
292
+ return AbortSignal.any([lifetime.signal, ...signal ? [signal] : []]);
293
+ }
294
+ async function readRun(runId, signal, since = 0, turnId) {
295
+ const requestSignal = signalFor(signal);
296
+ requestSignal.throwIfAborted();
297
+ const read = new AbortController();
298
+ const timer = setTimeout(() => read.abort(), timeoutMs);
299
+ const combined = AbortSignal.any([requestSignal, read.signal]);
300
+ const events = [];
301
+ try {
302
+ const session = options.client.sessions.attach(runId);
303
+ for await (const event of session.stream({
304
+ follow: false,
305
+ signal: combined,
306
+ reconnect: false
307
+ })) {
308
+ if (events.length >= maxEvents) throw new Error("Eve history exceeds maxEventsPerRead");
309
+ events.push(event);
310
+ }
311
+ combined.throwIfAborted();
312
+ } finally {
313
+ clearTimeout(timer);
314
+ read.abort();
315
+ }
316
+ const cursor = events.length ? events.at(-1).meta.position.line + 1 : 0;
317
+ const view = foldEvents(emptySessionView(), events);
318
+ const eventCount = events.filter((event) => event.meta.position.line >= since).length;
319
+ return {
320
+ view,
321
+ cursor,
322
+ result: summarize(view, cursor, eventCount, turnId)
323
+ };
324
+ }
325
+ const checked = {
326
+ send: capability({
327
+ id: `${options.name}.send`,
328
+ effect: "write",
329
+ description: "Send a message, optionally continuing an Eve session and waiting for its answer.",
330
+ meta: { cli: { positional: ["message"] } },
331
+ input: object({
332
+ message: string({
333
+ minLength: 1,
334
+ maxLength: 65536,
335
+ description: "Message to send, or a text answer to a pending question. With option-id, only the selected option is submitted."
336
+ }),
337
+ runId: optional(string({
338
+ minLength: 1,
339
+ description: "Continue this Eve session. Omit to begin a new conversation."
340
+ })),
341
+ requestId: optional(string({
342
+ minLength: 1,
343
+ description: "Pending question to answer. Required when several questions are waiting; use with run-id."
344
+ })),
345
+ optionId: optional(string({
346
+ minLength: 1,
347
+ description: "Answer option ID shown by result. Required for questions that do not accept freeform text; use with run-id."
348
+ })),
349
+ wait: optional(boolean({ description: "Wait for an answer, pending input, failure, or cancellation. Otherwise return the run ID immediately." })),
350
+ timeoutMs: optional(integer({
351
+ minimum: 1,
352
+ maximum: 3e5,
353
+ description: "Wait limit in milliseconds after acceptance (default: 30000; maximum: 300000). Only used with wait. Expiry leaves Eve running."
354
+ }))
355
+ }),
356
+ output: sendOutput,
357
+ toPresentation: presentAgentResult,
358
+ handler: async ({ input, signal }) => {
359
+ await authorize("send", input.runId);
360
+ if (!input.runId && (input.requestId || input.optionId)) throw new Error("Question answers require a runId");
361
+ const waiting = new AbortController();
362
+ const requestSignal = AbortSignal.any([signalFor(signal), waiting.signal]);
363
+ const sendOptions = {
364
+ signal: requestSignal,
365
+ reconnect: false
366
+ };
367
+ let delivery$1;
368
+ let answered;
369
+ let view = emptySessionView();
370
+ let cursor = 0;
371
+ if (input.runId) {
372
+ const run = await readRun(input.runId, signal);
373
+ ({view, cursor} = run);
374
+ const session = options.client.sessions.attach(input.runId, { streamIndex: cursor });
375
+ const open = openInteractions(view);
376
+ const pending = questionsOf(open);
377
+ if (input.requestId || pending.length) {
378
+ const selected = input.requestId ? pending.find((entry) => entry.requestId === input.requestId) : pending.length === 1 ? pending[0] : void 0;
379
+ if (!selected || run.result.status !== "waiting") throw new Error("Specify requestId for a current pending question");
380
+ if (input.optionId) {
381
+ if (!selected.options?.some((option) => option.id === input.optionId)) throw new Error("Unknown answer option");
382
+ } else if (selected.allowFreeform === false || selected.options?.length && selected.allowFreeform !== true) throw new Error("This question requires optionId");
383
+ answered = interaction(view, selected.requestId);
384
+ delivery$1 = await session.respond([{
385
+ interactionId: selected.requestId,
386
+ ...input.optionId ? { optionId: input.optionId } : { text: input.message }
387
+ }], sendOptions);
388
+ } else {
389
+ if (input.optionId) throw new Error("No pending question for optionId");
390
+ if (open.length) throw new Error("Pending approval or authorization requires host action");
391
+ delivery$1 = await session.send(input.message, sendOptions);
392
+ }
393
+ if (delivery$1.sessionId !== input.runId) throw new Error("Eve resumed a different session");
394
+ } else ({delivery: delivery$1} = await options.client.sessions.create({
395
+ message: input.message,
396
+ ...sendOptions
397
+ }));
398
+ const runId = delivery$1.sessionId;
399
+ const accepted = {
400
+ runId,
401
+ status: "running",
402
+ cursor: 0,
403
+ eventCount: 0,
404
+ requests: []
405
+ };
406
+ if (!input.wait) return accepted;
407
+ const timer = setTimeout(() => waiting.abort(), input.timeoutMs ?? 3e4);
408
+ try {
409
+ let line = [];
410
+ let count = 0;
411
+ let boundary = false;
412
+ const stream = options.client.sessions.attach(runId).stream({
413
+ startIndex: cursor,
414
+ signal: requestSignal,
415
+ reconnect: false
416
+ });
417
+ for await (const event of stream) {
418
+ requestSignal.throwIfAborted();
419
+ if (++count > maxEvents) throw new Error("Eve response exceeds maxEventsPerRead");
420
+ line.push(event);
421
+ if (event.meta.endOfLine === false) continue;
422
+ view = foldEvents(view, line);
423
+ line = [];
424
+ if (settled(view, delivery$1.deliveryId, answered)) {
425
+ boundary = delivery(view, delivery$1.deliveryId)?.turnId ?? answered?.turnId;
426
+ break;
427
+ }
428
+ }
429
+ requestSignal.throwIfAborted();
430
+ if (boundary === false) return accepted;
431
+ return {
432
+ runId,
433
+ ...(await readRun(runId, requestSignal, 0, boundary)).result
434
+ };
435
+ } catch (error) {
436
+ signalFor(signal).throwIfAborted();
437
+ if (waiting.signal.aborted) return accepted;
438
+ throw error;
439
+ } finally {
440
+ clearTimeout(timer);
441
+ waiting.abort();
442
+ }
443
+ }
444
+ }),
445
+ result: capability({
446
+ id: `${options.name}.result`,
447
+ effect: "read",
448
+ description: "Read bounded progress, pending questions, or the final output. Pass the last returned cursor.",
449
+ input: object({
450
+ runId,
451
+ cursor: withDefault(integer({
452
+ minimum: 0,
453
+ description: "Cursor from the previous result, used to count new events. Defaults to 0; the full current result is still returned."
454
+ }), 0)
455
+ }),
456
+ output: resultSchema,
457
+ toPresentation: presentAgentResult,
458
+ handler: async ({ input, signal }) => {
459
+ await authorize("result", input.runId);
460
+ const run = await readRun(input.runId, signal, input.cursor);
461
+ if (input.cursor > run.cursor) throw new Error("Eve cursor is ahead of this run");
462
+ return run.result;
463
+ }
464
+ }),
465
+ cancel: capability({
466
+ id: `${options.name}.cancel`,
467
+ effect: "write",
468
+ description: "Cancel the active Eve turn. Pending means Eve accepted the request but has not confirmed it yet.",
469
+ input: object({
470
+ runId,
471
+ turnId: optional(string({
472
+ minLength: 1,
473
+ description: "Specific Eve turn to cancel. Omit to cancel the session’s active turn."
474
+ }))
475
+ }),
476
+ output: object({ status: enumOf("accepted", "pending", "no_active_turn") }),
477
+ toPresentation: ({ status }) => status === "accepted" ? "Cancelled the active turn." : status === "pending" ? "Cancellation requested. Check the result to confirm execution has stopped." : "No active turn to cancel.",
478
+ handler: async ({ input, signal }) => {
479
+ await authorize("cancel", input.runId);
480
+ signalFor(signal).throwIfAborted();
481
+ const delivery = await options.client.sessions.attach(input.runId).cancel({
482
+ signal: signalFor(signal),
483
+ ...input.turnId ? { turnId: input.turnId } : {}
484
+ });
485
+ const confirm = new AbortController();
486
+ const timer = setTimeout(() => confirm.abort(), timeoutMs);
487
+ try {
488
+ const { outcome } = await delivery.result({ signal: AbortSignal.any([signalFor(signal), confirm.signal]) });
489
+ if (outcome === "applied") return { status: "accepted" };
490
+ if (outcome === "ignored") return { status: "no_active_turn" };
491
+ throw new Error("Eve cancellation failed");
492
+ } catch (error) {
493
+ signalFor(signal).throwIfAborted();
494
+ if (confirm.signal.aborted) return { status: "pending" };
495
+ throw error;
496
+ } finally {
497
+ clearTimeout(timer);
498
+ }
499
+ }
500
+ })
501
+ };
502
+ return {
503
+ app: createApp(defineApp({ capabilities: { [options.name]: checked } })),
504
+ dispose() {
505
+ lifetime.abort();
506
+ }
507
+ };
508
+ }
509
+ function positive(value, name) {
510
+ if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive safe integer`);
511
+ return value;
512
+ }
513
+ function questionsOf(open) {
514
+ const found = open.filter((entry) => entry.request.kind === "question");
515
+ if (found.length > 100) throw new Error("Eve question limit exceeded");
516
+ return found.map((entry) => {
517
+ const safe = question.parse({
518
+ ...entry.request,
519
+ requestId: entry.interactionId
520
+ });
521
+ if (JSON.stringify(safe).length > 65536) throw new Error("Eve question limit exceeded");
522
+ return safe;
523
+ });
524
+ }
525
+ function summarize(view, cursor, eventCount, turnId) {
526
+ const base = {
527
+ cursor,
528
+ eventCount,
529
+ requests: []
530
+ };
531
+ const latest = turnId ? turn(view, turnId) : turns(view).at(-1);
532
+ if (failure(view, latest?.turnId)) return {
533
+ ...base,
534
+ status: "failed",
535
+ error: "Eve agent execution failed"
536
+ };
537
+ const open = openInteractions(view).filter((entry) => !turnId || entry.turnId === turnId);
538
+ if (open.length) {
539
+ const requests = questionsOf(open);
540
+ return {
541
+ ...base,
542
+ status: "waiting",
543
+ requests,
544
+ requiresHostInput: requests.length < open.length
545
+ };
546
+ }
547
+ if (!latest || latest.status === "running") return {
548
+ ...base,
549
+ status: "running"
550
+ };
551
+ if (latest.outcome === "cancelled") return {
552
+ ...base,
553
+ status: "cancelled"
554
+ };
555
+ if (latest.outcome !== "completed") return {
556
+ ...base,
557
+ status: "failed",
558
+ error: "Eve agent execution failed"
559
+ };
560
+ const result = {
561
+ ...base,
562
+ status: "completed"
563
+ };
564
+ const text = reply(view, latest.turnId).flatMap((part) => part.kind === "text" && typeof part.value === "string" ? [part.value] : []).join("");
565
+ if (text) {
566
+ result.text = text.slice(0, 65536);
567
+ if (text.length > 65536) result.textTruncated = true;
568
+ }
569
+ const data = parts(view, {
570
+ turnId: latest.turnId,
571
+ kind: "result"
572
+ }).at(-1)?.value;
573
+ if (data !== void 0) if (JSON.stringify(data).length > 65536) result.dataOmitted = true;
574
+ else result.data = parseJsonValue(data);
575
+ return result;
576
+ }
577
+ /** True once the delivery settled and its turn settled or paused on a new interaction. */
578
+ function settled(view, deliveryId, answered) {
579
+ const received = delivery(view, deliveryId);
580
+ if (received?.status !== "settled") return session(view).status === "ended";
581
+ const turnId = received.turnId ?? answered?.turnId;
582
+ if (!turnId) return true;
583
+ return turn(view, turnId)?.status === "settled" || openInteractions(view).some((entry) => entry.turnId === turnId && entry.interactionId !== answered?.interactionId);
584
+ }
585
+ //#endregion
3
586
  //#region packages/eve/src/index.ts
4
587
  const emptyInputSchema = Object.freeze({
5
588
  type: "object",
@@ -9,53 +592,50 @@ const emptyInputSchema = Object.freeze({
9
592
  /**
10
593
  * Projects an executable Capable App into native, in-process Eve tools.
11
594
  *
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.
595
+ * Eve evaluates the resolver before every model call. The App manifest is
596
+ * memoized per session, and each call rebuilds the App from the execution
597
+ * session. Keep persistent data outside the process.
15
598
  */
16
599
  function createEveTools(app, options = {}) {
17
- const capabilitiesByApp = /* @__PURE__ */ new WeakMap();
18
- const capabilities = (resolvedApp) => {
19
- const existing = capabilitiesByApp.get(resolvedApp);
20
- if (existing) return existing;
21
- const resolved = getAppRuntime(resolvedApp).manifest().then((manifest) => flatten(manifest.capabilities));
22
- capabilitiesByApp.set(resolvedApp, resolved);
23
- return resolved;
24
- };
25
- return defineDynamic({ events: { "step.started": async (_event, context) => {
26
- const resolvedApp = typeof app === "function" ? await app(context) : app;
27
- const runtime = getAppRuntime(resolvedApp);
600
+ const resolveApp = (context) => typeof app === "function" ? app({ session: context.session }) : app;
601
+ return defineDynamic(async (context) => {
602
+ const capabilities = await context.memo(["capable.manifest", context.session.id], async () => {
603
+ return flattenManifestCapabilities((await getAppRuntime(await resolveApp(context)).manifest()).capabilities);
604
+ });
28
605
  const tools = {};
29
606
  const names = /* @__PURE__ */ new Set();
30
- for (const capability of await capabilities(resolvedApp)) {
607
+ for (const capability of capabilities) {
608
+ const display = getCapabilityDisplay(capability);
31
609
  const meta = capability.meta.eve;
32
610
  if (meta === false) continue;
611
+ if (capability.execution === "events") {
612
+ if (meta !== void 0) throw new Error(`Event Capability "${capability.id}" cannot be exposed as an Eve tool`);
613
+ continue;
614
+ }
33
615
  const name = meta?.name ?? capability.path.join("__");
34
616
  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
617
  if (names.has(name)) throw new Error(`Duplicate Eve tool name "${name}"`);
36
618
  names.add(name);
37
619
  const approval = options.approval?.(capability);
620
+ const id = capability.id;
38
621
  tools[name] = defineTool({
39
- description: capability.description ?? capability.title ?? `Run the Capable Capability at ${capability.path.join(".")}.`,
622
+ description: display.description ?? display.title ?? `Run the Capable Capability at ${capability.path.join(".")}.`,
40
623
  inputSchema: capability.input ?? emptyInputSchema,
41
624
  ...capability.output ? { outputSchema: capability.output } : {},
42
625
  ...approval ? { approval } : {},
43
- async execute(input, context) {
44
- return (await runtime.call({
45
- id: capability.id,
626
+ execute: async (input, toolContext) => {
627
+ return (await getAppRuntime(await resolveApp({ session: toolContext.session })).call({
628
+ id,
46
629
  input,
47
- signal: context.abortSignal
630
+ signal: toolContext.abortSignal
48
631
  })).output;
49
632
  }
50
633
  });
51
634
  }
52
635
  return tools;
53
- } } });
54
- }
55
- function flatten(nodes) {
56
- return nodes.flatMap((node) => node.type === "capability" ? [node] : flatten(node.children));
636
+ });
57
637
  }
58
638
  //#endregion
59
- export { createEveTools };
639
+ export { createEveAgentAdapter, createEveTools };
60
640
 
61
641
  //# sourceMappingURL=eve.mjs.map