@feltdb/feltkit 0.5.3 → 0.5.5

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 (39) hide show
  1. package/dist/app.d.ts +22 -0
  2. package/dist/app.js +6 -2
  3. package/dist/app.js.map +1 -1
  4. package/dist/appboundry/build.d.ts +5 -1
  5. package/dist/appboundry/build.js +7 -3
  6. package/dist/appboundry/build.js.map +1 -1
  7. package/dist/appboundry/guest.js +32 -4
  8. package/dist/appboundry/guest.js.map +1 -1
  9. package/dist/appboundry/host.d.ts +20 -0
  10. package/dist/appboundry/host.js +25 -0
  11. package/dist/appboundry/host.js.map +1 -1
  12. package/dist/eve/index.d.ts +8 -0
  13. package/dist/eve/index.js +9 -0
  14. package/dist/eve/index.js.map +1 -1
  15. package/dist/runtime/context.d.ts +11 -2
  16. package/dist/runtime/generation.d.ts +28 -64
  17. package/dist/runtime/generation.js +30 -262
  18. package/dist/runtime/generation.js.map +1 -1
  19. package/dist/runtime/projects.d.ts +10 -1
  20. package/dist/runtime/projects.js +14 -3
  21. package/dist/runtime/projects.js.map +1 -1
  22. package/dist/runtime/runtime.d.ts +4 -0
  23. package/dist/runtime/runtime.js +4 -1
  24. package/dist/runtime/runtime.js.map +1 -1
  25. package/dist/server/eve.d.ts +31 -0
  26. package/dist/server/eve.js +117 -22
  27. package/dist/server/eve.js.map +1 -1
  28. package/dist/server/project.js +3 -0
  29. package/dist/server/project.js.map +1 -1
  30. package/docs/AGENT-CONTROL.md +5 -0
  31. package/docs/APPBOUNDRY.md +10 -3
  32. package/docs/GENERATION.md +7 -0
  33. package/docs/README.md +2 -2
  34. package/package.json +9 -9
  35. package/skills/.claude-plugin/marketplace.json +1 -1
  36. package/skills/.claude-plugin/plugin.json +1 -1
  37. package/skills/feltkit-agent/SKILL.md +1 -1
  38. package/skills/feltkit-data/SKILL.md +1 -1
  39. package/skills/feltkit-services/SKILL.md +1 -1
@@ -49,7 +49,29 @@ export interface EveSessionRecord {
49
49
  origin: AgentSessionOrigin;
50
50
  key?: string;
51
51
  };
52
+ /**
53
+ * The person this conversation belongs to. Set, only they read it (its history, evidence, listing), send to it, or
54
+ * end it; the workspace sees that it exists only through its effects (approvals its people answer, the agent task's
55
+ * lifecycle). Unset, every person of the workspace may, as before. See sessionReadable.
56
+ */
57
+ owner?: string;
52
58
  }
59
+ /**
60
+ * Whether a person may read and converse in a session: its owner only, when it has one; otherwise any person of its
61
+ * workspace (or, outside a workspace, its creator). Answering its approval requests is decided separately
62
+ * (sessionInWorkspace): an approver needs no access to the conversation.
63
+ */
64
+ export declare function sessionReadable(record: Pick<EveSessionRecord, "tenantId" | "createdBy" | "owner">, person: Pick<Principal, "id" | "tenant">): boolean;
65
+ /** Whether a session belongs to the person's workspace (or, outside a workspace, was created by them). */
66
+ export declare function sessionInWorkspace(record: Pick<EveSessionRecord, "tenantId" | "createdBy">, person: Pick<Principal, "id" | "tenant">): boolean;
67
+ /**
68
+ * The permission a person needs to approve one of an agent's calls: the agent's declared `approvers` permission, or by
69
+ * default the permission of the capability itself (only someone who could make the call may approve it).
70
+ */
71
+ export declare function answerPermission(declaration: Pick<EveAgentDeclaration, "approvers">, capabilityAccess: string): {
72
+ permission: string;
73
+ declared: boolean;
74
+ };
53
75
  /** A tool name (eve: the tool file's name) for a capability: dots become underscores. */
54
76
  export declare function eveToolName(capability: string): string;
55
77
  export declare function signEveToken(secret: string, claims: Record<string, unknown>, now?: number): string;
@@ -77,10 +99,19 @@ export declare class EveHost {
77
99
  message: string;
78
100
  origin: AgentSessionOrigin;
79
101
  key?: string;
102
+ owner?: string;
80
103
  }): Promise<{
81
104
  sessionId: string;
82
105
  created: boolean;
83
106
  }>;
107
+ /**
108
+ * Deliver a message into a delegated session (`ctx.agent.sendToSession`): new work for the agent, from the principal
109
+ * that started the session. The delegation is checked again first (active, its issuer still holding what it covers):
110
+ * a revoked delegation delivers nothing more. The agent runs a turn for it, as for a person's message.
111
+ */
112
+ sendDelegated(name: string, caller: Principal | null, sessionId: string, message: string): Promise<{
113
+ delivered: boolean;
114
+ }>;
84
115
  /** End a delegated session (`ctx.agent.endSession`): only the principal that started it, or a person of its workspace. */
85
116
  endDelegated(name: string, caller: Principal | null, sessionId: string, reason?: string): Promise<{
86
117
  ended: boolean;
@@ -35,6 +35,21 @@ const TOKEN_TTL_S = 300;
35
35
  const HEALTH_TIMEOUT_MS = 30_000;
36
36
  const MAX_BACKOFF_MS = 30_000;
37
37
  const STREAM_READ_LIMIT = 4 * 1024 * 1024;
38
+ /**
39
+ * Whether a person may read and converse in a session: its owner only, when it has one; otherwise any person of its
40
+ * workspace (or, outside a workspace, its creator). Answering its approval requests is decided separately
41
+ * (sessionInWorkspace): an approver needs no access to the conversation.
42
+ */
43
+ export function sessionReadable(record, person) {
44
+ if (record.owner)
45
+ return record.owner === person.id && sessionInWorkspace(record, person);
46
+ return sessionInWorkspace(record, person);
47
+ }
48
+ /** Whether a session belongs to the person's workspace (or, outside a workspace, was created by them). */
49
+ export function sessionInWorkspace(record, person) {
50
+ const tenantId = person.tenant?.id ?? null;
51
+ return tenantId ? record.tenantId === tenantId : record.createdBy === person.id;
52
+ }
38
53
  function originOrThrow(origin) {
39
54
  const o = origin;
40
55
  const short = (v, max) => typeof v === "string" && v.length > 0 && v.length <= max;
@@ -47,6 +62,14 @@ function originOrThrow(origin) {
47
62
  throw new FeltKitError("INVALID_ARGUMENT", "origin.detail is at most 20 short string entries.");
48
63
  return { application: o.application, kind: o.kind, ref: o.ref, ...(o.requestedBy ? { requestedBy: { id: o.requestedBy.id, ...(o.requestedBy.name ? { name: o.requestedBy.name } : {}) } } : {}), ...(Object.keys(detail).length ? { detail: { ...detail } } : {}) };
49
64
  }
65
+ /**
66
+ * The permission a person needs to approve one of an agent's calls: the agent's declared `approvers` permission, or by
67
+ * default the permission of the capability itself (only someone who could make the call may approve it).
68
+ */
69
+ export function answerPermission(declaration, capabilityAccess) {
70
+ const declared = typeof declaration.approvers === "string" && declaration.approvers.trim() !== "";
71
+ return { permission: declared ? declaration.approvers.trim() : capabilityAccess, declared };
72
+ }
50
73
  /** A tool name (eve: the tool file's name) for a capability: dots become underscores. */
51
74
  export function eveToolName(capability) {
52
75
  return capability.replace(/\./g, "_");
@@ -123,7 +146,7 @@ export class EveHost {
123
146
  this.#agents.set(name, { name, declaration, root: resolve(projectDir, declaration.root ?? "."), origin: remote, remote: Boolean(remote), port: 0, state: "stopped", child: null, restarts: 0, healthySince: null });
124
147
  }
125
148
  runtime.agent.useExternalReasoners((taskId) => this.#reasoner(taskId));
126
- runtime.useProjectAgentSessions({ start: (name, caller, input) => this.startDelegated(name, caller, input), end: (name, caller, sessionId, reason) => this.endDelegated(name, caller, sessionId, reason) });
149
+ runtime.useProjectAgentSessions({ start: (name, caller, input) => this.startDelegated(name, caller, input), send: (name, caller, sessionId, message) => this.sendDelegated(name, caller, sessionId, message), end: (name, caller, sessionId, reason) => this.endDelegated(name, caller, sessionId, reason) });
127
150
  }
128
151
  /**
129
152
  * Start a session under a standing delegation, from the application's own server code (`ctx.agent.startSession`):
@@ -145,10 +168,19 @@ export class EveHost {
145
168
  throw new FeltKitError("INVALID_ARGUMENT", "message is 1 to 20000 characters.");
146
169
  if (input.key !== undefined && (typeof input.key !== "string" || !input.key || input.key.length > 200))
147
170
  throw new FeltKitError("INVALID_ARGUMENT", "key is 1 to 200 characters.");
171
+ if (input.owner !== undefined && (typeof input.owner !== "string" || !input.owner || input.owner.length > 200))
172
+ throw new FeltKitError("INVALID_ARGUMENT", "owner is a person's id.");
148
173
  const tenantId = caller.tenant?.id ?? null;
174
+ if (input.owner !== undefined) {
175
+ // The conversation's owner must be a person of this workspace: never a worker, and never someone elsewhere.
176
+ const found = await this.#runtime.resolvePrincipal(input.owner);
177
+ const owner = found ? await this.#runtime.withTenant(found, tenantId ?? undefined) : null;
178
+ if (!isPerson(owner) || (tenantId !== null && owner.tenant?.id !== tenantId))
179
+ throw new FeltKitError("INVALID_ARGUMENT", "owner is not a person of this workspace.", { details: { reason: "OWNER_NOT_A_PERSON" } });
180
+ }
149
181
  const sessions = this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION);
150
182
  if (input.key) {
151
- const [existing] = (await sessions.find({ agent: name }, { limit: 1000 })).filter((r) => r.tenantId === tenantId && r.delegated?.key === input.key && r.delegated?.startedBy === caller.id);
183
+ const [existing] = (await sessions.find({ agent: name }, { limit: 1000 })).filter((r) => r.tenantId === tenantId && r.delegated?.key === input.key && r.delegated?.startedBy === caller.id && (r.owner ?? undefined) === (input.owner ?? undefined));
152
184
  if (existing)
153
185
  return { sessionId: existing.id, created: false };
154
186
  }
@@ -176,11 +208,51 @@ export class EveHost {
176
208
  const worker = await this.#worker(name, tenantId);
177
209
  const title = titleOf(body);
178
210
  const task = worker ? await this.#runtime.agent.openTask({ principal: worker, objective: title, key: `session:${created.sessionId}` }) : null;
179
- const record = { id: created.sessionId, agent: name, tenantId, createdBy: issuer.id, createdAt: Date.now(), title, ...(task ? { taskId: task.taskId } : {}), delegated: { grant: grant.ref, startedBy: caller.id, origin, ...(input.key ? { key: input.key } : {}) } };
211
+ const record = { id: created.sessionId, agent: name, tenantId, createdBy: issuer.id, createdAt: Date.now(), title, ...(task ? { taskId: task.taskId } : {}), ...(input.owner ? { owner: input.owner } : {}), delegated: { grant: grant.ref, startedBy: caller.id, origin, ...(input.key ? { key: input.key } : {}) } };
180
212
  await sessions.insert(record, created.sessionId);
181
213
  this.#runtime.recordAuth("agent.session.delegated", caller, { agent: name, session: created.sessionId, grant: grant.ref, delegatedBy: issuer.id, origin: `${origin.application}:${origin.kind}:${origin.ref}` }, "success", "runtime");
182
214
  return { sessionId: created.sessionId, created: true };
183
215
  }
216
+ /**
217
+ * Deliver a message into a delegated session (`ctx.agent.sendToSession`): new work for the agent, from the principal
218
+ * that started the session. The delegation is checked again first (active, its issuer still holding what it covers):
219
+ * a revoked delegation delivers nothing more. The agent runs a turn for it, as for a person's message.
220
+ */
221
+ async sendDelegated(name, caller, sessionId, message) {
222
+ const agent = this.#agentOf(name);
223
+ if (!caller || caller.guest)
224
+ throw new FeltKitError("UNAUTHORIZED", "Sending to an agent session needs a signed-in caller.");
225
+ if (!this.#runtime.holds(caller, "feltkit.agent.delegated"))
226
+ throw new FeltKitError("FORBIDDEN", `${caller.id} may not send to delegated agent sessions (needs feltkit.agent.delegated).`);
227
+ const text = typeof message === "string" ? message.trim() : "";
228
+ if (!text || text.length > 20_000)
229
+ throw new FeltKitError("INVALID_ARGUMENT", "message is 1 to 20000 characters.");
230
+ const record = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).get(sessionId));
231
+ if (!record || record.agent !== name || record.tenantId !== (caller.tenant?.id ?? null) || !record.delegated || record.delegated.startedBy !== caller.id)
232
+ throw new FeltKitError("NOT_FOUND", "No such delegated session here.");
233
+ if (record.stopped)
234
+ throw new FeltKitError("FAILED_PRECONDITION", "That session has ended.", { details: { reason: "SESSION_ENDED" } });
235
+ const workerId = `worker:${this.workerName(name, record.tenantId)}`;
236
+ const grant = (await this.#runtime.workers.grantsOf(workerId)).find((g) => g.ref === record.delegated.grant);
237
+ if (!grant || grant.state !== "active")
238
+ throw new FeltKitError("FORBIDDEN", `That session's delegation is ${grant?.state ?? "gone"}.`, { details: { reason: grant?.state === "expired" ? "DELEGATION_EXPIRED" : "DELEGATION_REVOKED" } });
239
+ const found = await this.#runtime.resolvePrincipal(grant.actor.id);
240
+ const issuer = found ? await this.#runtime.withTenant(found, record.tenantId ?? undefined) : null;
241
+ if (!isPerson(issuer) || (record.tenantId !== null && issuer.tenant?.id !== record.tenantId))
242
+ throw new FeltKitError("FORBIDDEN", "The person who issued that session's delegation is no longer a person of this workspace.", { details: { reason: "DELEGATOR_GONE" } });
243
+ const declared = this.capabilities(name);
244
+ const lapsed = grant.capabilities.filter((c) => !declared.has(c) || !this.#runtime.holds(issuer, declared.get(c).access));
245
+ if (lapsed.length)
246
+ throw new FeltKitError("FORBIDDEN", `The person who issued that session's delegation no longer holds what it covers: ${lapsed.join(", ")}.`, { details: { reason: "DELEGATION_EXCEEDS_DELEGATOR", capabilities: lapsed } });
247
+ if (agent.state !== "ready")
248
+ throw new FeltKitError("UNAVAILABLE", `The agent is ${agent.state}.`);
249
+ if (record.taskId)
250
+ await this.#runtime.agent.control.gate(record.taskId, "a message to the agent");
251
+ const answer = await this.#call(agent, "POST", `/eve/v1/session/${encodeURIComponent(sessionId)}`, this.#token(name, issuer, { grant: grant.ref, delegated: { startedBy: caller.id, origin: record.delegated.origin } }, sessionId), Buffer.from(JSON.stringify({ message: text })), { "content-type": "application/json" });
252
+ if (answer.status >= 300)
253
+ throw new FeltKitError("UNAVAILABLE", `The agent did not take the message (${answer.status}).`);
254
+ return { delivered: true };
255
+ }
184
256
  /** End a delegated session (`ctx.agent.endSession`): only the principal that started it, or a person of its workspace. */
185
257
  async endDelegated(name, caller, sessionId, reason) {
186
258
  this.#agentOf(name);
@@ -189,7 +261,7 @@ export class EveHost {
189
261
  if (!this.#runtime.holds(caller, "feltkit.agent.delegated"))
190
262
  throw new FeltKitError("FORBIDDEN", `${caller.id} may not end delegated agent sessions (needs feltkit.agent.delegated).`);
191
263
  const record = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).get(sessionId));
192
- if (!record || record.agent !== name || record.tenantId !== (caller.tenant?.id ?? null) || !record.delegated || (record.delegated.startedBy !== caller.id && !isPerson(caller)))
264
+ if (!record || record.agent !== name || record.tenantId !== (caller.tenant?.id ?? null) || !record.delegated || (record.delegated.startedBy !== caller.id && !isPerson(caller)) || (record.owner && record.delegated.startedBy !== caller.id && record.owner !== caller.id))
193
265
  throw new FeltKitError("NOT_FOUND", "No such delegated session here.");
194
266
  if (record.stopped)
195
267
  return { ended: false };
@@ -211,7 +283,7 @@ export class EveHost {
211
283
  throw new FeltKitError("UNAVAILABLE", `The agent is ${agent.state}.`);
212
284
  if (path === "end" && (await this.#ended(agent, record.id, reader)))
213
285
  return;
214
- const answer = await this.#call(agent, "POST", `/eve/v1/session/${encodeURIComponent(record.id)}/${path}`, this.#token(record.agent, isPerson(p) ? p : reader, {}), Buffer.from(JSON.stringify(body)), { "content-type": "application/json" });
286
+ const answer = await this.#call(agent, "POST", `/eve/v1/session/${encodeURIComponent(record.id)}/${path}`, this.#token(record.agent, isPerson(p) ? p : reader, {}, record.id), Buffer.from(JSON.stringify(body)), { "content-type": "application/json" });
215
287
  if (answer.status >= 300)
216
288
  throw new FeltKitError("UNAVAILABLE", `The agent did not take ${path} (${answer.status}).`);
217
289
  };
@@ -274,7 +346,7 @@ export class EveHost {
274
346
  try {
275
347
  if (!agent || agent.state !== "ready")
276
348
  throw new Error("not ready");
277
- const response = await fetch(`${this.#origin(agent)}eve/v1/session/${encodeURIComponent(record.id)}/stream?startIndex=0&follow=true`, { headers: { authorization: `Bearer ${this.#token(record.agent, reader, {})}`, accept: "application/x-ndjson" }, signal: stop.signal });
349
+ const response = await fetch(`${this.#origin(agent)}eve/v1/session/${encodeURIComponent(record.id)}/stream?startIndex=0&follow=true`, { headers: { authorization: `Bearer ${this.#token(record.agent, reader, {}, record.id)}`, accept: "application/x-ndjson" }, signal: stop.signal });
278
350
  if (!response.ok || !response.body)
279
351
  throw new Error(`stream ${response.status}`);
280
352
  const facts = [];
@@ -318,7 +390,7 @@ export class EveHost {
318
390
  }
319
391
  /** Whether the runtime has ended the session: it says so (`session.ended`), or its history is gone (410). */
320
392
  async #ended(agent, sessionId, person) {
321
- const read = await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(agent.name, person, {}), undefined, { accept: "application/x-ndjson" });
393
+ const read = await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(agent.name, person, {}, sessionId), undefined, { accept: "application/x-ndjson" });
322
394
  if (read.status === 410)
323
395
  return true;
324
396
  return read.status < 300 && read.body.toString("utf8").split("\n").some((line) => factsOf(line).some((f) => f.type === "session.ended"));
@@ -326,7 +398,7 @@ export class EveHost {
326
398
  async #facts(agent, sessionId, person) {
327
399
  if (agent.state !== "ready")
328
400
  return [];
329
- const read = await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(agent.name, person, {}), undefined, { accept: "application/x-ndjson" });
401
+ const read = await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(agent.name, person, {}, sessionId), undefined, { accept: "application/x-ndjson" });
330
402
  if (read.status >= 300)
331
403
  return [];
332
404
  return read.body.toString("utf8").split("\n").flatMap((line) => factsOf(line));
@@ -649,7 +721,7 @@ export class EveHost {
649
721
  this.#runtime.recordAuth("work-grant.issued", person, { grant: grant.ref, worker: grant.worker, actor: person.id, capabilities: grant.capabilities, agent: name }, "success", "runtime");
650
722
  return grant.ref;
651
723
  }
652
- #token(name, person, extra) {
724
+ #token(name, person, extra, session) {
653
725
  const remote = this.#agentOf(name).remote;
654
726
  const keys = remote ? this.#es256(name) : null;
655
727
  const sign = (claims) => (keys ? signEveTokenEs256(keys.privateKey, keys.kid, claims) : signEveToken(this.#secret(name, "assertion"), claims));
@@ -662,14 +734,20 @@ export class EveHost {
662
734
  name: person.displayName ?? person.id,
663
735
  roles: [...person.roles],
664
736
  ...(person.tenant ? { tenantId: person.tenant.id } : {}),
737
+ ...(session ? { session } : {}),
665
738
  ...extra,
666
739
  });
667
740
  }
668
741
  async #session(name, sessionId, person) {
669
742
  const record = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).get(sessionId));
670
- const tenantId = person.tenant?.id ?? null;
671
- const visible = record && record.agent === name && (tenantId ? record.tenantId === tenantId : record.createdBy === person.id);
672
- if (!visible)
743
+ if (!record || record.agent !== name || !sessionReadable(record, person))
744
+ throw new FeltKitError("NOT_FOUND", "No such agent session here.");
745
+ return record;
746
+ }
747
+ /** A session of the person's workspace, for answering its approval requests: no access to the conversation. */
748
+ async #sessionToAnswer(name, sessionId, person) {
749
+ const record = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).get(sessionId));
750
+ if (!record || record.agent !== name || !sessionInWorkspace(record, person))
673
751
  throw new FeltKitError("NOT_FOUND", "No such agent session here.");
674
752
  return record;
675
753
  }
@@ -679,7 +757,7 @@ export class EveHost {
679
757
  const person = this.#requirePerson(principal);
680
758
  const tenantId = person.tenant?.id ?? null;
681
759
  const rows = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).find((tenantId ? { agent: name, tenantId } : { agent: name, createdBy: person.id }), { limit: 1000 }));
682
- return rows.sort((a, b) => b.createdAt - a.createdAt).slice(0, Math.min(Math.max(limit, 1), 200)).map(({ id, agent, tenantId: t, createdBy, createdAt, title, taskId }) => ({ id, agent, tenantId: t, createdBy, createdAt, title, ...(taskId ? { taskId } : {}) }));
760
+ return rows.filter((r) => sessionReadable(r, person)).sort((a, b) => b.createdAt - a.createdAt).slice(0, Math.min(Math.max(limit, 1), 200)).map(({ id, agent, tenantId: t, createdBy, createdAt, title, taskId }) => ({ id, agent, tenantId: t, createdBy, createdAt, title, ...(taskId ? { taskId } : {}) }));
683
761
  }
684
762
  async status(name, principal) {
685
763
  const agent = this.#agentOf(name);
@@ -763,7 +841,7 @@ export class EveHost {
763
841
  const body = await readBodyBytes(request);
764
842
  if (hasApproval(body))
765
843
  throw new FeltKitError("FORBIDDEN", "Answer an approval through /api/eve/<agent>/answer, so the approval is recorded.");
766
- return this.#proxy(agent, request, response, rest, this.#token(name, person, claims), body), true;
844
+ return this.#proxy(agent, request, response, rest, this.#token(name, person, claims, sessionId), body), true;
767
845
  }
768
846
  if (!sessionId) {
769
847
  const body = await readBodyBytes(request);
@@ -773,14 +851,14 @@ export class EveHost {
773
851
  if (answer.status < 300 && typeof created.sessionId === "string") {
774
852
  const worker = await this.#worker(name, person.tenant?.id ?? null);
775
853
  const task = worker ? await this.#runtime.agent.openTask({ principal: worker, objective: title, key: `session:${created.sessionId}` }) : null;
776
- const record = { id: created.sessionId, agent: name, tenantId: person.tenant?.id ?? null, createdBy: person.id, createdAt: Date.now(), title, ...(task ? { taskId: task.taskId } : {}) };
854
+ const record = { id: created.sessionId, agent: name, tenantId: person.tenant?.id ?? null, createdBy: person.id, createdAt: Date.now(), title, ...(task ? { taskId: task.taskId } : {}), ...(agent.declaration.sessions === "owner" ? { owner: person.id } : {}) };
777
855
  await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).insert(record, created.sessionId);
778
856
  }
779
857
  response.writeHead(answer.status, { "content-type": answer.headers["content-type"] ?? "application/json", "cache-control": "no-store" });
780
858
  response.end(answer.body);
781
859
  return true;
782
860
  }
783
- return this.#proxy(agent, request, response, rest, this.#token(name, person, claims)), true;
861
+ return this.#proxy(agent, request, response, rest, this.#token(name, person, claims, sessionId)), true;
784
862
  }
785
863
  #authorizeBridge(name, request) {
786
864
  const agent = this.#agentOf(name);
@@ -850,7 +928,7 @@ export class EveHost {
850
928
  const person = this.#requirePerson(principal);
851
929
  const record = await this.#session(name, sessionId, person);
852
930
  const control = record.taskId ? await this.#runtime.agent.control.view(record.taskId, person) : null;
853
- const read = agent.state === "ready" ? await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(name, person, {}), undefined, { accept: "application/x-ndjson" }) : null;
931
+ const read = agent.state === "ready" ? await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(name, person, {}, sessionId), undefined, { accept: "application/x-ndjson" }) : null;
854
932
  const lines = read && read.status < 300 ? read.body.toString("utf8").split("\n") : [];
855
933
  const facts = lines.flatMap((line) => timedFactsOf(line));
856
934
  const ended = read?.status === 410 || facts.some((f) => f.type === "session.ended");
@@ -885,15 +963,19 @@ export class EveHost {
885
963
  async answer(name, principal, input) {
886
964
  const agent = this.#agentOf(name);
887
965
  const person = this.#requirePerson(principal);
888
- await this.#session(name, input.sessionId, person);
966
+ // Approvers answer a request without access to the conversation it came from (an owned session stays its owner's).
967
+ await this.#sessionToAnswer(name, input.sessionId, person);
889
968
  const call = await this.#openCall(agent, input.sessionId, input.interactionId, person);
890
969
  if (!call)
891
970
  throw new FeltKitError("NOT_FOUND", "That approval is not waiting.");
892
971
  let extra = { answers: input.interactionId };
893
972
  let approval;
973
+ if (input.decision === "deny" && agent.declaration.approvers && !this.#runtime.holds(person, agent.declaration.approvers)) {
974
+ throw new FeltKitError("FORBIDDEN", `${person.id} may not answer ${name}'s approval requests (requires ${agent.declaration.approvers}).`, { details: { reason: "APPROVER_NOT_PERMITTED", requires: agent.declaration.approvers } });
975
+ }
894
976
  if (input.decision === "approve") {
895
977
  // Approving runs the call, so it is refused while a person holds the task: approval never resumes work.
896
- const session = await this.#session(name, input.sessionId, person);
978
+ const session = await this.#sessionToAnswer(name, input.sessionId, person);
897
979
  if (session.taskId) {
898
980
  const { mode, reason } = await this.#runtime.agent.control.mode(session.taskId);
899
981
  if (mode !== "running")
@@ -902,12 +984,25 @@ export class EveHost {
902
984
  const capability = [...this.capabilities(name).keys()].find((c) => eveToolName(c) === call.name);
903
985
  if (!capability)
904
986
  throw new FeltKitError("FAILED_PRECONDITION", `The agent's tool ${call.name} is not one of its capabilities (name a capability's tool after it: ${call.name.replace(/_/g, ".")}).`);
905
- const issued = await this.#runtime.grantsFor(person).approve({ capability, input: call.input, worker: `worker:${this.workerName(name, person.tenant?.id ?? null)}` });
987
+ const worker = `worker:${this.workerName(name, person.tenant?.id ?? null)}`;
988
+ const rule = answerPermission(agent.declaration, this.capabilities(name).get(capability).access);
989
+ let issued;
990
+ if (rule.declared) {
991
+ // The agent names who may answer its approvals (EveAgentDeclaration.approvers): that permission, not the
992
+ // capability's own. The approval is of this one call by this agent's worker, which needs its grant regardless.
993
+ if (!this.#runtime.holds(person, rule.permission))
994
+ throw new FeltKitError("FORBIDDEN", `${person.id} may not answer ${name}'s approval requests (requires ${rule.permission}).`, { details: { reason: "APPROVER_NOT_PERMITTED", requires: rule.permission } });
995
+ issued = await this.#runtime.workers.issueApproval({ capability, input: call.input, worker, ttlMs: 24 * 3_600_000, by: person });
996
+ this.#runtime.recordAuth("approval.issued", person, { approval: issued.ref, capability, worker, basis: `agent ${name} approvers (${rule.permission})` }, "success", "runtime");
997
+ }
998
+ else {
999
+ issued = await this.#runtime.grantsFor(person).approve({ capability, input: call.input, worker });
1000
+ }
906
1001
  approval = issued.ref;
907
1002
  extra = { ...extra, approvalRef: issued.ref };
908
1003
  }
909
1004
  const body = Buffer.from(JSON.stringify({ answers: [{ interactionId: input.interactionId, optionId: input.decision }] }));
910
- const answer = await this.#call(agent, "POST", `/eve/v1/session/${encodeURIComponent(input.sessionId)}`, this.#token(name, person, extra), body, { "content-type": "application/json" });
1005
+ const answer = await this.#call(agent, "POST", `/eve/v1/session/${encodeURIComponent(input.sessionId)}`, this.#token(name, person, extra, input.sessionId), body, { "content-type": "application/json" });
911
1006
  if (answer.status >= 300)
912
1007
  throw new FeltKitError("CONFLICT", `The agent did not take the answer (${answer.status}).`);
913
1008
  // Evidence that outlives the session: who answered which request, and the approval of the exact call.
@@ -929,7 +1024,7 @@ export class EveHost {
929
1024
  }
930
1025
  }
931
1026
  async #openCall(agent, sessionId, interactionId, person) {
932
- const read = await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(agent.name, person, {}), undefined, { accept: "application/x-ndjson" });
1027
+ const read = await this.#call(agent, "GET", `/eve/v1/session/${encodeURIComponent(sessionId)}/stream?startIndex=0&follow=false`, this.#token(agent.name, person, {}, sessionId), undefined, { accept: "application/x-ndjson" });
933
1028
  if (read.status >= 300)
934
1029
  return null;
935
1030
  const calls = new Map();