capable-kit 0.1.0-alpha.10 → 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 (67) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/LICENSE +21 -0
  3. package/README.md +6 -0
  4. package/dist/ai-sdk.d.mts +2 -2
  5. package/dist/ai-sdk.mjs +1 -1
  6. package/dist/app.d.mts +2 -2
  7. package/dist/app.mjs +1 -1
  8. package/dist/bin.mjs +19 -15
  9. package/dist/bin.mjs.map +1 -1
  10. package/dist/cli.d.mts +1 -1
  11. package/dist/cli.mjs +1 -1
  12. package/dist/core.d.mts +3 -3
  13. package/dist/core.mjs +2 -2
  14. package/dist/eve.d.mts +20 -14
  15. package/dist/eve.mjs +450 -211
  16. package/dist/eve.mjs.map +1 -1
  17. package/dist/http.d.mts +1 -1
  18. package/dist/http.mjs +1 -1
  19. package/dist/{index-WiBWfyTn.d.mts → index-BIO_hbXJ.d.mts} +8 -2
  20. package/dist/{index-D-NV4PiU.d.mts → index-C0tU5Y2n.d.mts} +4 -4
  21. package/dist/{index-CHuCLJIs.d.mts → index-CwvjDizW.d.mts} +5 -3
  22. package/dist/{index-1A44jLuE.d.mts → index-F_eaksy8.d.mts} +7 -4
  23. package/dist/index.d.mts +4 -4
  24. package/dist/index.mjs +2 -2
  25. package/dist/mcp.d.mts +14 -4
  26. package/dist/mcp.mjs +2 -2
  27. package/dist/{mount-BmLHp349.mjs → mount-pvIaehZC.mjs} +148 -104
  28. package/dist/mount-pvIaehZC.mjs.map +1 -0
  29. package/dist/react-query.d.mts +1 -1
  30. package/dist/react-query.mjs +1 -1
  31. package/dist/runtime-support.d.mts +1 -1
  32. package/dist/runtime-support.mjs +3 -3
  33. package/dist/server.d.mts +1 -1
  34. package/dist/server.mjs +1 -1
  35. package/dist/{src-_6OmFRYa.mjs → src-Bk3lEhI7.mjs} +38 -18
  36. package/dist/src-Bk3lEhI7.mjs.map +1 -0
  37. package/dist/{src-DePlcG_t.mjs → src-C2OEkZ3c.mjs} +38 -65
  38. package/dist/src-C2OEkZ3c.mjs.map +1 -0
  39. package/dist/{src-C5jGDnuu.mjs → src-DFrxQ_S6.mjs} +9 -7
  40. package/dist/src-DFrxQ_S6.mjs.map +1 -0
  41. package/dist/{src-3LE9S4QE.mjs → src-DklM1g7V.mjs} +5 -5
  42. package/dist/src-DklM1g7V.mjs.map +1 -0
  43. package/dist/{src-B2WeUwUT.mjs → src-TCQGaWar.mjs} +60 -18
  44. package/dist/src-TCQGaWar.mjs.map +1 -0
  45. package/dist/{subscription-DPdwovhw.d.mts → subscription-fVgS4T8P.d.mts} +2 -2
  46. package/dist/swr.d.mts +1 -1
  47. package/dist/swr.mjs +1 -1
  48. package/docs/CONTEXT.md +5 -2
  49. package/docs/internal/eve-recovery-validation.md +12 -11
  50. package/docs/internal/implementation-friction.md +59 -0
  51. package/docs/site/concepts/errors.mdx +15 -3
  52. package/docs/site/hosting/standalone-server.mdx +2 -0
  53. package/docs/site/patterns/remote-apps.mdx +23 -1
  54. package/docs/site/quickstart.mdx +2 -1
  55. package/docs/site/reference/packages-and-entry-points.mdx +2 -1
  56. package/docs/site/reference/the-cap-cli.mdx +2 -2
  57. package/docs/site/surfaces/eve.mdx +6 -4
  58. package/docs/site/surfaces/mcp.mdx +84 -2
  59. package/package.json +13 -7
  60. package/src/index.ts +2 -0
  61. package/src/package.test.ts +6 -0
  62. package/dist/mount-BmLHp349.mjs.map +0 -1
  63. package/dist/src-3LE9S4QE.mjs.map +0 -1
  64. package/dist/src-B2WeUwUT.mjs.map +0 -1
  65. package/dist/src-C5jGDnuu.mjs.map +0 -1
  66. package/dist/src-DePlcG_t.mjs.map +0 -1
  67. package/dist/src-_6OmFRYa.mjs.map +0 -1
package/dist/eve.mjs CHANGED
@@ -1,7 +1,221 @@
1
- import { r as defineApp, s as capability } from "./src-B2WeUwUT.mjs";
2
- import { d as getAppRuntime, h as flattenManifestCapabilities, i as getCapabilityDisplay, l as createApp } from "./src-DePlcG_t.mjs";
3
- import { defineDurableCallback, defineDynamic, defineTool } from "eve/tools";
4
- import { z } from "zod";
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";
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
5
219
  //#region packages/eve/src/agent-presentation.ts
6
220
  /** Portable presentation shared by the CLI and other presentation-aware surfaces. */
7
221
  function presentAgentResult(result) {
@@ -28,39 +242,37 @@ function presentAgentResult(result) {
28
242
  }
29
243
  //#endregion
30
244
  //#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()
245
+ const runId = string({
246
+ minLength: 1,
247
+ description: "Eve session ID returned by send."
46
248
  });
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()
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()
64
276
  });
65
277
  /**
66
278
  * Wrap Eve execution as a caller-scoped Capable App.
@@ -79,95 +291,36 @@ function createEveAgentAdapter(options) {
79
291
  function signalFor(signal) {
80
292
  return AbortSignal.any([lifetime.signal, ...signal ? [signal] : []]);
81
293
  }
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
- };
294
+ async function readRun(runId, signal, since = 0, turnId) {
99
295
  const requestSignal = signalFor(signal);
100
296
  requestSignal.throwIfAborted();
101
297
  const read = new AbortController();
102
298
  const timer = setTimeout(() => read.abort(), timeoutMs);
103
299
  const combined = AbortSignal.any([requestSignal, read.signal]);
300
+ const events = [];
104
301
  try {
105
302
  const session = options.client.sessions.attach(runId);
106
303
  for await (const event of session.stream({
107
- startIndex: 0,
108
304
  follow: false,
109
305
  signal: combined,
110
- streamReconnectPolicy: { reconnect: false }
306
+ reconnect: false
111
307
  })) {
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++;
308
+ if (events.length >= maxEvents) throw new Error("Eve history exceeds maxEventsPerRead");
309
+ events.push(event);
164
310
  }
165
311
  combined.throwIfAborted();
166
- return run;
167
312
  } finally {
168
313
  clearTimeout(timer);
169
314
  read.abort();
170
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
+ };
171
324
  }
172
325
  const checked = {
173
326
  send: capability({
@@ -175,15 +328,32 @@ function createEveAgentAdapter(options) {
175
328
  effect: "write",
176
329
  description: "Send a message, optionally continuing an Eve session and waiting for its answer.",
177
330
  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.")
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
+ }))
185
355
  }),
186
- output: resultSchema.extend({ runId: z.string() }),
356
+ output: sendOutput,
187
357
  toPresentation: presentAgentResult,
188
358
  handler: async ({ input, signal }) => {
189
359
  await authorize("send", input.runId);
@@ -192,33 +362,40 @@ function createEveAgentAdapter(options) {
192
362
  const requestSignal = AbortSignal.any([signalFor(signal), waiting.signal]);
193
363
  const sendOptions = {
194
364
  signal: requestSignal,
195
- streamReconnectPolicy: { reconnect: false }
365
+ reconnect: false
196
366
  };
197
- let response;
367
+ let delivery$1;
368
+ let answered;
369
+ let view = emptySessionView();
370
+ let cursor = 0;
198
371
  if (input.runId) {
199
372
  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");
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");
204
380
  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,
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,
209
386
  ...input.optionId ? { optionId: input.optionId } : { text: input.message }
210
387
  }], sendOptions);
211
388
  } else {
212
389
  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);
390
+ if (open.length) throw new Error("Pending approval or authorization requires host action");
391
+ delivery$1 = await session.send(input.message, sendOptions);
215
392
  }
216
- if (response.sessionId !== input.runId) throw new Error("Eve resumed a different session");
217
- } else ({response} = await options.client.sessions.create({
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({
218
395
  message: input.message,
219
396
  ...sendOptions
220
397
  }));
221
- const runId = response.sessionId;
398
+ const runId = delivery$1.sessionId;
222
399
  const accepted = {
223
400
  runId,
224
401
  status: "running",
@@ -229,28 +406,31 @@ function createEveAgentAdapter(options) {
229
406
  if (!input.wait) return accepted;
230
407
  const timer = setTimeout(() => waiting.abort(), input.timeoutMs ?? 3e4);
231
408
  try {
409
+ let line = [];
232
410
  let count = 0;
233
411
  let boundary = false;
234
- for await (const event of response) {
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) {
235
418
  requestSignal.throwIfAborted();
236
419
  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;
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;
244
426
  break;
245
427
  }
246
428
  }
247
429
  requestSignal.throwIfAborted();
248
- if (!boundary) return accepted;
249
- const run = await readRun(runId, requestSignal);
430
+ if (boundary === false) return accepted;
250
431
  return {
251
432
  runId,
252
- ...run.result,
253
- eventCount: run.result.cursor
433
+ ...(await readRun(runId, requestSignal, 0, boundary)).result
254
434
  };
255
435
  } catch (error) {
256
436
  signalFor(signal).throwIfAborted();
@@ -266,33 +446,56 @@ function createEveAgentAdapter(options) {
266
446
  id: `${options.name}.result`,
267
447
  effect: "read",
268
448
  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.") }),
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
+ }),
270
456
  output: resultSchema,
271
457
  toPresentation: presentAgentResult,
272
458
  handler: async ({ input, signal }) => {
273
459
  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
- };
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;
280
463
  }
281
464
  }),
282
465
  cancel: capability({
283
466
  id: `${options.name}.cancel`,
284
467
  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.",
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.",
289
478
  handler: async ({ input, signal }) => {
290
479
  await authorize("cancel", input.runId);
291
480
  signalFor(signal).throwIfAborted();
292
- return { status: (await options.client.sessions.attach(input.runId).cancel({
481
+ const delivery = await options.client.sessions.attach(input.runId).cancel({
293
482
  signal: signalFor(signal),
294
483
  ...input.turnId ? { turnId: input.turnId } : {}
295
- })).status };
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
+ }
296
499
  }
297
500
  })
298
501
  };
@@ -307,9 +510,77 @@ function positive(value, name) {
307
510
  if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive safe integer`);
308
511
  return value;
309
512
  }
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);
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);
313
584
  }
314
585
  //#endregion
315
586
  //#region packages/eve/src/index.ts
@@ -321,24 +592,19 @@ const emptyInputSchema = Object.freeze({
321
592
  /**
322
593
  * Projects an executable Capable App into native, in-process Eve tools.
323
594
  *
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.
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.
327
598
  */
328
599
  function createEveTools(app, options = {}) {
329
- const capabilitiesByApp = /* @__PURE__ */ new WeakMap();
330
- const capabilities = (resolvedApp) => {
331
- const existing = capabilitiesByApp.get(resolvedApp);
332
- if (existing) return existing;
333
- const resolved = getAppRuntime(resolvedApp).manifest().then((manifest) => flattenManifestCapabilities(manifest.capabilities));
334
- capabilitiesByApp.set(resolvedApp, resolved);
335
- return resolved;
336
- };
337
- return defineDynamic({ events: { "session.started": async (_event, resolveContext) => {
338
- const resolvedApp = typeof app === "function" ? await app(resolveContext) : app;
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
+ });
339
605
  const tools = {};
340
606
  const names = /* @__PURE__ */ new Set();
341
- for (const capability of await capabilities(resolvedApp)) {
607
+ for (const capability of capabilities) {
342
608
  const display = getCapabilityDisplay(capability);
343
609
  const meta = capability.meta.eve;
344
610
  if (meta === false) continue;
@@ -350,52 +616,25 @@ function createEveTools(app, options = {}) {
350
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`);
351
617
  if (names.has(name)) throw new Error(`Duplicate Eve tool name "${name}"`);
352
618
  names.add(name);
353
- const policy = options.approval?.(capability);
354
- const approval = policy && durableApproval(policy, capability.id);
355
- const definition = {
619
+ const approval = options.approval?.(capability);
620
+ const id = capability.id;
621
+ tools[name] = defineTool({
356
622
  description: display.description ?? display.title ?? `Run the Capable Capability at ${capability.path.join(".")}.`,
357
623
  inputSchema: capability.input ?? emptyInputSchema,
358
624
  ...capability.output ? { outputSchema: capability.output } : {},
359
- ...approval ? { approval } : {}
360
- };
361
- const id = capability.id;
362
- tools[name] = defineTool({
363
- ...definition,
364
- execute: defineDurableCallback({
365
- closure: { id },
366
- callback: async ({ id }, input, context) => {
367
- return (await getAppRuntime(typeof app === "function" ? await app({
368
- ...resolveContext,
369
- session: context.session
370
- }) : app).call({
371
- id,
372
- input,
373
- signal: context.abortSignal
374
- })).output;
375
- }
376
- })
625
+ ...approval ? { approval } : {},
626
+ execute: async (input, toolContext) => {
627
+ return (await getAppRuntime(await resolveApp({ session: toolContext.session })).call({
628
+ id,
629
+ input,
630
+ signal: toolContext.abortSignal
631
+ })).output;
632
+ }
377
633
  });
378
634
  }
379
635
  return tools;
380
- } } });
381
- }
382
- /** The resolver reconstructs policies; persist identity and reject rebinding to a different capability. */
383
- function durablePolicy(policy, id) {
384
- return defineDurableCallback({
385
- closure: { id },
386
- callback: (snapshot, ...args) => {
387
- if (snapshot.id !== id) throw new Error("Eve capability identity changed during recovery");
388
- return policy(...args);
389
- }
390
636
  });
391
637
  }
392
- function durableApproval(policy, id) {
393
- if (typeof policy === "function") return durablePolicy(policy, id);
394
- return {
395
- request: durablePolicy(policy.request, id),
396
- ...policy.response ? { response: durablePolicy(policy.response, id) } : {}
397
- };
398
- }
399
638
  //#endregion
400
639
  export { createEveAgentAdapter, createEveTools };
401
640