@feltdb/feltkit 0.4.0 → 0.5.0
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.
- package/dist/agent-engine.d.ts +93 -0
- package/dist/agent-engine.js +40 -0
- package/dist/agent-engine.js.map +1 -0
- package/dist/app.d.ts +153 -4
- package/dist/app.js +134 -25
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +7 -0
- package/dist/appboundry/build.js +4 -1
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +4 -0
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.d.ts +21 -0
- package/dist/appboundry/host.js +25 -0
- package/dist/appboundry/host.js.map +1 -1
- package/dist/appboundry/runtime.js +1 -0
- package/dist/appboundry/runtime.js.map +1 -1
- package/dist/boards/index.d.ts +1258 -0
- package/dist/boards/index.js +1410 -0
- package/dist/boards/index.js.map +1 -0
- package/dist/boards/model.d.ts +177 -0
- package/dist/boards/model.js +177 -0
- package/dist/boards/model.js.map +1 -0
- package/dist/boards/react.d.ts +18 -0
- package/dist/boards/react.js +339 -0
- package/dist/boards/react.js.map +1 -0
- package/dist/cli/deploy-appboundry-self-hosted.js +2 -2
- package/dist/cli/deploy.js +19 -6
- package/dist/cli/deploy.js.map +1 -1
- package/dist/cli/main.js +70 -5
- package/dist/cli/main.js.map +1 -1
- package/dist/client/index.d.ts +265 -4
- package/dist/client/index.js +170 -3
- package/dist/client/index.js.map +1 -1
- package/dist/cron.d.ts +18 -0
- package/dist/cron.js +67 -0
- package/dist/cron.js.map +1 -0
- package/dist/dashboard/assets/index-iIj7SL77.js +15 -0
- package/dist/dashboard/index.html +1 -1
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +3 -0
- package/dist/docs.js.map +1 -1
- package/dist/eve/index.d.ts +77 -0
- package/dist/eve/index.js +128 -0
- package/dist/eve/index.js.map +1 -0
- package/dist/index.d.ts +7 -2
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/native/build.d.ts +112 -0
- package/dist/native/build.js +472 -0
- package/dist/native/build.js.map +1 -0
- package/dist/native/index.d.ts +67 -0
- package/dist/native/index.js +113 -0
- package/dist/native/index.js.map +1 -0
- package/dist/native/instance.d.ts +3 -0
- package/dist/native/instance.js +18 -0
- package/dist/native/instance.js.map +1 -0
- package/dist/react/agent-control.d.ts +2 -0
- package/dist/react/agent-control.js +1 -1
- package/dist/react/agent-control.js.map +1 -1
- package/dist/react/auth.d.ts +15 -1
- package/dist/react/auth.js +28 -5
- package/dist/react/auth.js.map +1 -1
- package/dist/react/hooks.d.ts +88 -0
- package/dist/react/hooks.js +188 -0
- package/dist/react/hooks.js.map +1 -0
- package/dist/react/index.d.ts +5 -88
- package/dist/react/index.js +3 -185
- package/dist/react/index.js.map +1 -1
- package/dist/runtime/agent-control.d.ts +10 -0
- package/dist/runtime/agent-control.js +9 -1
- package/dist/runtime/agent-control.js.map +1 -1
- package/dist/runtime/agent-run.d.ts +166 -0
- package/dist/runtime/agent-run.js +431 -0
- package/dist/runtime/agent-run.js.map +1 -0
- package/dist/runtime/agent.d.ts +158 -1
- package/dist/runtime/agent.js +329 -8
- package/dist/runtime/agent.js.map +1 -1
- package/dist/runtime/assemble.js +14 -1
- package/dist/runtime/assemble.js.map +1 -1
- package/dist/runtime/authority.d.ts +9 -0
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/context.d.ts +9 -0
- package/dist/runtime/required-capabilities.d.ts +73 -0
- package/dist/runtime/required-capabilities.js +69 -0
- package/dist/runtime/required-capabilities.js.map +1 -0
- package/dist/runtime/runtime.d.ts +70 -1
- package/dist/runtime/runtime.js +261 -9
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/sessions.d.ts +1 -0
- package/dist/runtime/sessions.js +1 -1
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/tenancy.d.ts +9 -1
- package/dist/runtime/tenancy.js +22 -0
- package/dist/runtime/tenancy.js.map +1 -1
- package/dist/runtime/transactions.d.ts +3 -1
- package/dist/runtime/transactions.js.map +1 -1
- package/dist/server/eve.d.ts +287 -0
- package/dist/server/eve.js +1071 -0
- package/dist/server/eve.js.map +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +58 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.d.ts +7 -7
- package/dist/server/project.js +20 -3
- package/dist/server/project.js.map +1 -1
- package/dist/server/tenancy.d.ts +2 -0
- package/dist/server/tenancy.js +31 -1
- package/dist/server/tenancy.js.map +1 -1
- package/dist/testing/index.d.ts +1 -4
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-CONTROL.md +36 -0
- package/docs/APPBOUNDRY.md +36 -0
- package/docs/AUTH.md +2 -0
- package/docs/EVE-COMPOSITION.md +75 -0
- package/docs/NATIVE-AGENTS.md +353 -0
- package/docs/NATIVE.md +137 -0
- package/docs/README.md +5 -2
- package/package.json +33 -7
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-agent/SKILL.md +1 -1
- package/skills/feltkit-build/SKILL.md +1 -1
- package/skills/feltkit-data/SKILL.md +1 -1
- package/skills/feltkit-operations/SKILL.md +1 -1
- package/skills/feltkit-services/SKILL.md +1 -1
- package/dist/dashboard/assets/index-BhxrvY37.js +0 -15
|
@@ -0,0 +1,1071 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* eve agents of the application (`feltkit({ eve })`): built and supervised by FeltKit, reached only through it.
|
|
3
|
+
*
|
|
4
|
+
* Process Each agent is its eve project's production server (`eve start`) on a loopback port: eve's
|
|
5
|
+
* supported self-hosted topology. Its sessions live in FeltDB through the FeltDB World
|
|
6
|
+
* (`EVE_FELTDB_PATH` = `<environment>/eve/<name>`); FeltKit refuses an agent that does not
|
|
7
|
+
* write there. Restarted with backoff when it exits; stopped with the application.
|
|
8
|
+
* Identity `/eve/<name>/…` is forwarded (prefix removed) only for a signed-in person, as a short-lived
|
|
9
|
+
* HS256 token eve verifies (`verifyJwtHmac`): the person, their workspace, their roles and a
|
|
10
|
+
* work grant to the agent's worker in that workspace. Nothing the browser sends is forwarded
|
|
11
|
+
* as identity. Sessions are recorded with the workspace they belong to; another workspace's
|
|
12
|
+
* session does not exist here.
|
|
13
|
+
* Authority In each workspace the agent is a worker (registered when a person activates it; a workspace
|
|
14
|
+
* member with `tenantRole`). It acts only through published capabilities, at FeltKit's bridge
|
|
15
|
+
* (`/_feltkit/eve/<name>/…`, loopback, a key only the agent's process holds), as that worker,
|
|
16
|
+
* under the person's work grant: AppPort's checks (roles, tenant, grant, `approval: "required"`).
|
|
17
|
+
* Approval eve holds the pause; AppPort holds the authority. A person's answer is read against the call
|
|
18
|
+
* eve recorded (`interaction.opened`): approving issues an AppPort approval of exactly that
|
|
19
|
+
* capability and input, and eve resumes with the approval's reference, which the call names.
|
|
20
|
+
*/
|
|
21
|
+
import { spawn } from "node:child_process";
|
|
22
|
+
import { createHmac, randomUUID } from "node:crypto";
|
|
23
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
24
|
+
import { request as httpRequest } from "node:http";
|
|
25
|
+
import { createServer as createNetServer } from "node:net";
|
|
26
|
+
import { createRequire } from "node:module";
|
|
27
|
+
import { join, resolve } from "node:path";
|
|
28
|
+
import { projectAgentsOf } from "../app.js";
|
|
29
|
+
import { FeltKitError } from "../errors.js";
|
|
30
|
+
import { queryPages } from "../runtime/paged-read.js";
|
|
31
|
+
import { readJSON, safeEqual, sendJSON } from "./http.js";
|
|
32
|
+
export const EVE_SESSIONS_COLLECTION = "_feltkit_eve_sessions";
|
|
33
|
+
const TOKEN_TTL_S = 300;
|
|
34
|
+
const HEALTH_TIMEOUT_MS = 30_000;
|
|
35
|
+
const MAX_BACKOFF_MS = 30_000;
|
|
36
|
+
const STREAM_READ_LIMIT = 4 * 1024 * 1024;
|
|
37
|
+
/** A tool name (eve: the tool file's name) for a capability: dots become underscores. */
|
|
38
|
+
export function eveToolName(capability) {
|
|
39
|
+
return capability.replace(/\./g, "_");
|
|
40
|
+
}
|
|
41
|
+
export function signEveToken(secret, claims, now = Date.now()) {
|
|
42
|
+
const b64 = (value) => Buffer.from(JSON.stringify(value)).toString("base64url");
|
|
43
|
+
const iat = Math.floor(now / 1000);
|
|
44
|
+
const body = `${b64({ alg: "HS256", typ: "JWT" })}.${b64({ iat, exp: iat + TOKEN_TTL_S, ...claims })}`;
|
|
45
|
+
return `${body}.${createHmac("sha256", secret).update(body).digest("base64url")}`;
|
|
46
|
+
}
|
|
47
|
+
async function freePort() {
|
|
48
|
+
return new Promise((resolvePort, reject) => {
|
|
49
|
+
const server = createNetServer();
|
|
50
|
+
server.unref();
|
|
51
|
+
server.once("error", reject);
|
|
52
|
+
server.listen(0, "127.0.0.1", () => {
|
|
53
|
+
const address = server.address();
|
|
54
|
+
const port = typeof address === "object" && address ? address.port : 0;
|
|
55
|
+
server.close(() => resolvePort(port));
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function eveBin(root) {
|
|
60
|
+
try {
|
|
61
|
+
const require = createRequire(join(root, "package.json"));
|
|
62
|
+
return join(require.resolve("eve/package.json"), "..", "bin", "eve.js");
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw new FeltKitError("FAILED_PRECONDITION", `The agent in ${root} has no agent runtime installed.`, { hint: 'Install it there: npm install eve@npm:@appport/eve @appport/eve-world-feltdb' });
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const isPerson = (p) => Boolean(p && p.type === "user" && !p.guest && !p.worker);
|
|
69
|
+
export class EveHost {
|
|
70
|
+
#runtime;
|
|
71
|
+
#projectDir;
|
|
72
|
+
#log;
|
|
73
|
+
#agents = new Map();
|
|
74
|
+
#observers = new Map();
|
|
75
|
+
#feltkitUrl = "";
|
|
76
|
+
#closing = false;
|
|
77
|
+
constructor(runtime, projectDir, log) {
|
|
78
|
+
this.#runtime = runtime;
|
|
79
|
+
this.#projectDir = projectDir;
|
|
80
|
+
this.#log = log;
|
|
81
|
+
for (const [name, declaration] of Object.entries(projectAgentsOf(runtime.app))) {
|
|
82
|
+
this.#agents.set(name, { name, declaration, root: resolve(projectDir, declaration.root ?? "."), port: 0, state: "stopped", child: null, restarts: 0, healthySince: null });
|
|
83
|
+
}
|
|
84
|
+
runtime.agent.useExternalReasoners((taskId) => this.#reasoner(taskId));
|
|
85
|
+
}
|
|
86
|
+
/** The session behind an agent task, as its reasoner: in-flight work from the facts it recorded; interrupt, resume, stop. */
|
|
87
|
+
async #reasoner(taskId) {
|
|
88
|
+
const [record] = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).find({ taskId }, { limit: 1 }));
|
|
89
|
+
if (!record || !this.#agents.has(record.agent))
|
|
90
|
+
return null;
|
|
91
|
+
const agent = this.#agentOf(record.agent);
|
|
92
|
+
const reader = { id: record.createdBy, type: "user", roles: [], ...(record.tenantId ? { tenant: { id: record.tenantId } } : {}) };
|
|
93
|
+
const command = async (p, path, body) => {
|
|
94
|
+
if (agent.state !== "ready")
|
|
95
|
+
throw new FeltKitError("UNAVAILABLE", `The agent is ${agent.state}.`);
|
|
96
|
+
if (path === "end" && (await this.#ended(agent, record.id, reader)))
|
|
97
|
+
return;
|
|
98
|
+
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" });
|
|
99
|
+
if (answer.status >= 300)
|
|
100
|
+
throw new FeltKitError("UNAVAILABLE", `The agent did not take ${path} (${answer.status}).`);
|
|
101
|
+
};
|
|
102
|
+
return {
|
|
103
|
+
inFlight: async () => sessionExecution(await this.#facts(agent, record.id, reader)),
|
|
104
|
+
ended: () => this.#ended(agent, record.id, reader),
|
|
105
|
+
interrupt: async (p) => {
|
|
106
|
+
this.#observe(taskId, record);
|
|
107
|
+
await command(p, "cancel", {});
|
|
108
|
+
},
|
|
109
|
+
resume: async (p) => {
|
|
110
|
+
this.#observe(taskId, record);
|
|
111
|
+
await command(p, "resume", {});
|
|
112
|
+
},
|
|
113
|
+
stop: async (p, reason) => {
|
|
114
|
+
await command(p, "end", reason ? { reason: reason.slice(0, 200) } : {});
|
|
115
|
+
// Accepted is not done: the task is recorded stopped only once the runtime says the session ended.
|
|
116
|
+
const deadline = Date.now() + 15_000;
|
|
117
|
+
while (Date.now() < deadline) {
|
|
118
|
+
if (await this.#ended(agent, record.id, reader)) {
|
|
119
|
+
await this.#patchSession(record.id, (r) => (r.stopped ? {} : { stopped: { by: p.id, at: Date.now(), ...(reason ? { reason: reason.slice(0, 200) } : {}) } }));
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
123
|
+
}
|
|
124
|
+
throw new FeltKitError("UNAVAILABLE", "The agent accepted the stop but has not ended the session yet.");
|
|
125
|
+
},
|
|
126
|
+
observe: () => this.#observe(taskId, record),
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Follow a held task's session stream (the runtime's own record) and report each change of what it is doing to the
|
|
131
|
+
* task's control, which publishes `appport.agent.changed`. One follower per task; it ends once the task runs and the
|
|
132
|
+
* session is not holding, or the session ends. A dropped stream is followed again from the start (the facts are
|
|
133
|
+
* replayed, and only a change from the last reported state is reported).
|
|
134
|
+
*/
|
|
135
|
+
#observe(taskId, record) {
|
|
136
|
+
if (this.#observers.has(taskId) || this.#closing)
|
|
137
|
+
return;
|
|
138
|
+
const stop = new AbortController();
|
|
139
|
+
this.#observers.set(taskId, stop);
|
|
140
|
+
const reader = { id: record.createdBy, type: "user", roles: [], ...(record.tenantId ? { tenant: { id: record.tenantId } } : {}) };
|
|
141
|
+
let reported = "";
|
|
142
|
+
const report = async (facts) => {
|
|
143
|
+
const now = sessionExecution(facts);
|
|
144
|
+
const ended = facts.some((f) => f.type === "session.ended");
|
|
145
|
+
const signature = JSON.stringify([now.generations, now.actions, now.held, ended]);
|
|
146
|
+
if (signature !== reported) {
|
|
147
|
+
reported = signature;
|
|
148
|
+
await this.#runtime.agent.control.inFlightChanged(taskId).catch(() => undefined);
|
|
149
|
+
}
|
|
150
|
+
const { mode } = await this.#runtime.agent.control.mode(taskId).catch(() => ({ mode: "running" }));
|
|
151
|
+
if (ended || (mode === "running" && !now.held && !now.generations.length && !now.actions.length))
|
|
152
|
+
stop.abort();
|
|
153
|
+
};
|
|
154
|
+
void (async () => {
|
|
155
|
+
let delay = 500;
|
|
156
|
+
while (!stop.signal.aborted && !this.#closing) {
|
|
157
|
+
const agent = this.#agents.get(record.agent);
|
|
158
|
+
try {
|
|
159
|
+
if (!agent || agent.state !== "ready")
|
|
160
|
+
throw new Error("not ready");
|
|
161
|
+
const response = await fetch(`http://127.0.0.1:${agent.port}/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 });
|
|
162
|
+
if (!response.ok || !response.body)
|
|
163
|
+
throw new Error(`stream ${response.status}`);
|
|
164
|
+
const facts = [];
|
|
165
|
+
let buffered = "";
|
|
166
|
+
const decoder = new TextDecoder();
|
|
167
|
+
for await (const chunk of response.body) {
|
|
168
|
+
buffered += decoder.decode(chunk, { stream: true });
|
|
169
|
+
const lines = buffered.split("\n");
|
|
170
|
+
buffered = lines.pop() ?? "";
|
|
171
|
+
const before = facts.length;
|
|
172
|
+
for (const line of lines)
|
|
173
|
+
facts.push(...factsOf(line));
|
|
174
|
+
if (facts.length > before)
|
|
175
|
+
await report(facts);
|
|
176
|
+
if (stop.signal.aborted)
|
|
177
|
+
break;
|
|
178
|
+
}
|
|
179
|
+
delay = 500;
|
|
180
|
+
}
|
|
181
|
+
catch {
|
|
182
|
+
if (stop.signal.aborted)
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
await new Promise((r) => setTimeout(r, delay));
|
|
186
|
+
delay = Math.min(delay * 2, 10_000);
|
|
187
|
+
}
|
|
188
|
+
this.#observers.delete(taskId);
|
|
189
|
+
})();
|
|
190
|
+
}
|
|
191
|
+
/** After the agent (re)starts: follow every session whose task a person holds, from the runtime's record. */
|
|
192
|
+
async #reconcile(name) {
|
|
193
|
+
for await (const page of queryPages(this.#runtime.instance.handle("app"), { collection: EVE_SESSIONS_COLLECTION, where: [{ field: "agent", eq: name }] }))
|
|
194
|
+
for (const row of page) {
|
|
195
|
+
const record = row;
|
|
196
|
+
if (!record.taskId)
|
|
197
|
+
continue;
|
|
198
|
+
const { mode } = await this.#runtime.agent.control.mode(record.taskId).catch(() => ({ mode: "running" }));
|
|
199
|
+
if (mode !== "running")
|
|
200
|
+
this.#observe(record.taskId, record);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
/** Whether the runtime has ended the session: it says so (`session.ended`), or its history is gone (410). */
|
|
204
|
+
async #ended(agent, sessionId, person) {
|
|
205
|
+
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" });
|
|
206
|
+
if (read.status === 410)
|
|
207
|
+
return true;
|
|
208
|
+
return read.status < 300 && read.body.toString("utf8").split("\n").some((line) => factsOf(line).some((f) => f.type === "session.ended"));
|
|
209
|
+
}
|
|
210
|
+
async #facts(agent, sessionId, person) {
|
|
211
|
+
if (agent.state !== "ready")
|
|
212
|
+
return [];
|
|
213
|
+
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" });
|
|
214
|
+
if (read.status >= 300)
|
|
215
|
+
return [];
|
|
216
|
+
return read.body.toString("utf8").split("\n").flatMap((line) => factsOf(line));
|
|
217
|
+
}
|
|
218
|
+
/** The workspace's worker for an agent, as a principal (null when the agent is not active there). */
|
|
219
|
+
#worker(name, tenantId) {
|
|
220
|
+
return this.#runtime.workerPrincipal(`worker:${this.workerName(name, tenantId)}`);
|
|
221
|
+
}
|
|
222
|
+
/** The agent task of a session the agent is running, by the agent's service key (the bridge). */
|
|
223
|
+
async #sessionTask(name, sessionId) {
|
|
224
|
+
const record = typeof sessionId === "string" ? (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).get(sessionId)) : null;
|
|
225
|
+
if (!record || record.agent !== name || !record.taskId)
|
|
226
|
+
throw new FeltKitError("NOT_FOUND", "No agent task for that session.");
|
|
227
|
+
const worker = await this.#worker(name, record.tenantId);
|
|
228
|
+
if (!worker)
|
|
229
|
+
throw new FeltKitError("FORBIDDEN", "The agent is no longer active in that workspace.");
|
|
230
|
+
return { taskId: record.taskId, worker };
|
|
231
|
+
}
|
|
232
|
+
static declared(runtime) {
|
|
233
|
+
return Object.keys(projectAgentsOf(runtime.app)).length > 0;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* The agent's view of its capabilities, generated into its project (`agent/lib/feltkit-capabilities.json`):
|
|
237
|
+
* for each capability the declaration covers, its tool name, description, JSON Schema input and whether it
|
|
238
|
+
* needs a person's approval. Tools are made from it (`feltkitCapability`), so the agent never restates them.
|
|
239
|
+
*/
|
|
240
|
+
static writeCapabilities(root, declaration, functions) {
|
|
241
|
+
const capabilities = {};
|
|
242
|
+
for (const fn of functions.values()) {
|
|
243
|
+
const capability = fn.capability?.name;
|
|
244
|
+
if (!capability || !declaration.capabilities.some((p) => (p.endsWith(".*") ? capability.startsWith(p.slice(0, -1)) : p === capability)))
|
|
245
|
+
continue;
|
|
246
|
+
capabilities[capability] = { capability, tool: eveToolName(capability), description: fn.capability?.description ?? fn.description ?? capability, inputSchema: fn.argsSchema.toJSONSchema(), approval: fn.approval === "required" ? "required" : "none" };
|
|
247
|
+
}
|
|
248
|
+
const file = join(root, "agent", "lib", "feltkit-capabilities.json");
|
|
249
|
+
mkdirSync(join(root, "agent", "lib"), { recursive: true });
|
|
250
|
+
const sorted = Object.fromEntries(Object.entries(capabilities).sort(([a], [b]) => a.localeCompare(b)));
|
|
251
|
+
const text = `${JSON.stringify(sorted, null, 2)}\n`;
|
|
252
|
+
if (!existsSync(file) || readFileSync(file, "utf8") !== text)
|
|
253
|
+
writeFileSync(file, text);
|
|
254
|
+
return file;
|
|
255
|
+
}
|
|
256
|
+
/** `eve build` for every agent: the production server `eve start` runs. */
|
|
257
|
+
/**
|
|
258
|
+
* Every session of a FeltKit agent is an agent task people steer (appport.agent-control/1), so the agent must honour
|
|
259
|
+
* control; and a session is evidence, so ending it must not delete its history. The compiled manifest says both.
|
|
260
|
+
* Refuses a build that does not, with the fix.
|
|
261
|
+
*/
|
|
262
|
+
static requireControl(name, root) {
|
|
263
|
+
const manifestPath = join(root, ".output", ".eve", "compile", "compiled-agent-manifest.json");
|
|
264
|
+
let control;
|
|
265
|
+
let retention;
|
|
266
|
+
try {
|
|
267
|
+
const config = JSON.parse(readFileSync(manifestPath, "utf8")).config;
|
|
268
|
+
control = config?.control;
|
|
269
|
+
retention = config?.experimental?.workflow?.retention;
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
throw new FeltKitError("FAILED_PRECONDITION", `The agent "${name}" built, but its manifest (${manifestPath}) could not be read to check that it honours agent control.`);
|
|
273
|
+
}
|
|
274
|
+
if (control !== true) {
|
|
275
|
+
throw new FeltKitError("FAILED_PRECONDITION", `The agent "${name}" does not honour agent control: people could not pause, resume, interrupt or stop it, or send it updates. In ${join(root, "agent", "agent.ts")}, add control: feltkitControl() (import { feltkitControl } from "@feltdb/feltkit/agent") to defineAgent, and upgrade the agent runtime if it has no control option.`, { hint: "AGENT_CONTROL" });
|
|
276
|
+
}
|
|
277
|
+
if (retention !== "default") {
|
|
278
|
+
throw new FeltKitError("FAILED_PRECONDITION", `The agent "${name}" would delete each session's history when it ends, so what it was asked, did and decided could not be reviewed afterwards. In ${join(root, "agent", "agent.ts")}, set experimental: { workflow: { retention: "default" } } in defineAgent: ending a session stops it; its history stays in this application's FeltDB.`, { hint: "AGENT_EVIDENCE" });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
static async build(projectDir, eve, functions, log) {
|
|
282
|
+
for (const [name, declaration] of Object.entries(eve)) {
|
|
283
|
+
const root = resolve(projectDir, declaration.root ?? ".");
|
|
284
|
+
EveHost.writeCapabilities(root, declaration, functions);
|
|
285
|
+
const code = await new Promise((done) => {
|
|
286
|
+
const child = spawn(process.execPath, [eveBin(root), "build"], { cwd: root, env: process.env, stdio: ["ignore", "pipe", "pipe"] });
|
|
287
|
+
let output = "";
|
|
288
|
+
child.stdout.on("data", (chunk) => (output += chunk));
|
|
289
|
+
child.stderr.on("data", (chunk) => (output += chunk));
|
|
290
|
+
child.on("exit", (status) => {
|
|
291
|
+
if (status !== 0)
|
|
292
|
+
log?.(output.slice(-4000));
|
|
293
|
+
done(status ?? 1);
|
|
294
|
+
});
|
|
295
|
+
});
|
|
296
|
+
if (code !== 0)
|
|
297
|
+
throw new FeltKitError("FAILED_PRECONDITION", `The agent "${name}" did not build (${root}).`);
|
|
298
|
+
EveHost.requireControl(name, root);
|
|
299
|
+
log?.(`agent "${name}" built`);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
#secret(name, purpose) {
|
|
303
|
+
return createHmac("sha256", this.#runtime.authSecret()).update(`feltkit/eve/${name}/${purpose}`).digest("base64url");
|
|
304
|
+
}
|
|
305
|
+
/** Start every agent's server. FeltKit must be listening (the agent calls back into it). */
|
|
306
|
+
async start(feltkitUrl, options = {}) {
|
|
307
|
+
this.#feltkitUrl = feltkitUrl;
|
|
308
|
+
if (options.build)
|
|
309
|
+
await EveHost.build(this.#projectDir, projectAgentsOf(this.#runtime.app), this.#runtime.project.functions, (line) => this.#log?.info(line));
|
|
310
|
+
await Promise.all([...this.#agents.values()].map((agent) => this.#launch(agent)));
|
|
311
|
+
}
|
|
312
|
+
#env(agent) {
|
|
313
|
+
const feltdbPath = join(this.#runtime.environment.runtimeDir, "eve", agent.name);
|
|
314
|
+
mkdirSync(feltdbPath, { recursive: true });
|
|
315
|
+
return {
|
|
316
|
+
...process.env,
|
|
317
|
+
EVE_FELTDB_PATH: feltdbPath,
|
|
318
|
+
FELTKIT_URL: this.#feltkitUrl,
|
|
319
|
+
FELTKIT_EVE_AGENT: agent.name,
|
|
320
|
+
FELTKIT_EVE_ISSUER: `feltkit:${this.#runtime.app.name}`,
|
|
321
|
+
FELTKIT_EVE_ASSERTION_KEY: this.#secret(agent.name, "assertion"),
|
|
322
|
+
FELTKIT_EVE_SERVICE_KEY: this.#secret(agent.name, "service"),
|
|
323
|
+
NODE_ENV: "production",
|
|
324
|
+
};
|
|
325
|
+
}
|
|
326
|
+
async #launch(agent) {
|
|
327
|
+
if (this.#closing)
|
|
328
|
+
return;
|
|
329
|
+
if (!existsSync(join(agent.root, ".output", "server", "index.mjs"))) {
|
|
330
|
+
agent.state = "failed";
|
|
331
|
+
agent.detail = `agent "${agent.name}" is not built (${agent.root}/.output): run feltkit build.`;
|
|
332
|
+
this.#log?.error(agent.detail);
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
agent.port = await freePort();
|
|
336
|
+
agent.state = agent.restarts ? "restarting" : "starting";
|
|
337
|
+
const child = spawn(process.execPath, [eveBin(agent.root), "start", "--host", "127.0.0.1", "--port", String(agent.port)], { cwd: agent.root, env: this.#env(agent), stdio: ["ignore", "pipe", "pipe"] });
|
|
338
|
+
agent.child = child;
|
|
339
|
+
const prefix = `[agent:${agent.name}] `;
|
|
340
|
+
child.stdout?.on("data", (chunk) => this.#log?.info(prefix + String(chunk).trimEnd()));
|
|
341
|
+
child.stderr?.on("data", (chunk) => this.#log?.warn(prefix + String(chunk).trimEnd()));
|
|
342
|
+
child.on("exit", (code, signal) => {
|
|
343
|
+
if (agent.child !== child)
|
|
344
|
+
return;
|
|
345
|
+
agent.child = null;
|
|
346
|
+
agent.healthySince = null;
|
|
347
|
+
if (this.#closing) {
|
|
348
|
+
agent.state = "stopped";
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
agent.restarts++;
|
|
352
|
+
const delay = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(agent.restarts - 1, 5));
|
|
353
|
+
agent.state = "restarting";
|
|
354
|
+
agent.detail = `exited (${signal ?? code}); restarting in ${delay} ms`;
|
|
355
|
+
this.#log?.warn(prefix + agent.detail);
|
|
356
|
+
setTimeout(() => void this.#launch(agent), delay).unref();
|
|
357
|
+
});
|
|
358
|
+
const deadline = Date.now() + HEALTH_TIMEOUT_MS;
|
|
359
|
+
while (Date.now() < deadline && agent.child === child) {
|
|
360
|
+
if (await this.#healthy(agent)) {
|
|
361
|
+
const statePath = join(this.#env(agent).EVE_FELTDB_PATH, "state");
|
|
362
|
+
if (!existsSync(statePath)) {
|
|
363
|
+
agent.state = "failed";
|
|
364
|
+
agent.detail = `agent "${agent.name}" does not keep its sessions in FeltDB: select the FeltDB World in agent/agent.ts (experimental.workflow.world: "@appport/eve-world-feltdb").`;
|
|
365
|
+
this.#log?.error(agent.detail);
|
|
366
|
+
child.kill("SIGTERM");
|
|
367
|
+
return;
|
|
368
|
+
}
|
|
369
|
+
agent.state = "ready";
|
|
370
|
+
agent.detail = undefined;
|
|
371
|
+
agent.healthySince = Date.now();
|
|
372
|
+
void this.#reconcile(agent.name).catch((error) => this.#log?.warn(`${prefix}could not follow held sessions: ${String(error)}`));
|
|
373
|
+
return;
|
|
374
|
+
}
|
|
375
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
376
|
+
}
|
|
377
|
+
if (agent.child === child) {
|
|
378
|
+
agent.detail = `did not answer /eve/v1/health within ${HEALTH_TIMEOUT_MS / 1000} s`;
|
|
379
|
+
child.kill("SIGKILL");
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
async #healthy(agent) {
|
|
383
|
+
try {
|
|
384
|
+
const response = await fetch(`http://127.0.0.1:${agent.port}/eve/v1/health`, { signal: AbortSignal.timeout(2000) });
|
|
385
|
+
return response.ok;
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return false;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
report() {
|
|
392
|
+
return Object.fromEntries([...this.#agents.values()].map((a) => [a.name, { state: a.state, ...(a.detail ? { detail: a.detail } : {}), restarts: a.restarts }]));
|
|
393
|
+
}
|
|
394
|
+
async close() {
|
|
395
|
+
this.#closing = true;
|
|
396
|
+
for (const stop of this.#observers.values())
|
|
397
|
+
stop.abort();
|
|
398
|
+
await Promise.all([...this.#agents.values()].map((agent) => new Promise((done) => {
|
|
399
|
+
const child = agent.child;
|
|
400
|
+
if (!child)
|
|
401
|
+
return done();
|
|
402
|
+
const timer = setTimeout(() => child.kill("SIGKILL"), 10_000);
|
|
403
|
+
child.once("exit", () => {
|
|
404
|
+
clearTimeout(timer);
|
|
405
|
+
done();
|
|
406
|
+
});
|
|
407
|
+
child.kill("SIGTERM");
|
|
408
|
+
})));
|
|
409
|
+
}
|
|
410
|
+
// ---- authority -----------------------------------------------------------------------------------------------
|
|
411
|
+
#agentOf(name) {
|
|
412
|
+
const agent = this.#agents.get(name);
|
|
413
|
+
if (!agent)
|
|
414
|
+
throw new FeltKitError("NOT_FOUND", `This application has no agent "${name}".`);
|
|
415
|
+
return agent;
|
|
416
|
+
}
|
|
417
|
+
/** The worker that is this agent in a workspace (or the application, without workspaces). */
|
|
418
|
+
workerName(agent, tenantId) {
|
|
419
|
+
return tenantId ? `eve-${agent}-${tenantId}`.replace(/[^A-Za-z0-9_.-]/g, "-").slice(0, 64) : `eve-${agent}`;
|
|
420
|
+
}
|
|
421
|
+
/** The published capabilities the declaration covers (patterns expanded), with the access each needs. */
|
|
422
|
+
capabilities(name) {
|
|
423
|
+
const patterns = this.#agentOf(name).declaration.capabilities;
|
|
424
|
+
const out = new Map();
|
|
425
|
+
for (const [fnName, fn] of this.#runtime.project.functions) {
|
|
426
|
+
const capability = fn.capability?.name;
|
|
427
|
+
if (!capability)
|
|
428
|
+
continue;
|
|
429
|
+
if (!patterns.some((p) => (p.endsWith(".*") ? capability.startsWith(p.slice(0, -1)) : p === capability)))
|
|
430
|
+
continue;
|
|
431
|
+
out.set(capability, { fn: fnName, access: fn.access, approval: fn.approval === "required" });
|
|
432
|
+
}
|
|
433
|
+
return out;
|
|
434
|
+
}
|
|
435
|
+
#requirePerson(principal) {
|
|
436
|
+
if (!isPerson(principal))
|
|
437
|
+
throw new FeltKitError("UNAUTHORIZED", "Sign in to work with the agent.");
|
|
438
|
+
if (this.#runtime.tenancy && !principal.tenant)
|
|
439
|
+
throw new FeltKitError("FAILED_PRECONDITION", "Choose a workspace first.", { hint: "NO_TENANT" });
|
|
440
|
+
return principal;
|
|
441
|
+
}
|
|
442
|
+
/** Activate the agent in the caller's workspace: its worker, and its membership there. Idempotent. */
|
|
443
|
+
async activate(name, principal) {
|
|
444
|
+
const agent = this.#agentOf(name);
|
|
445
|
+
const person = this.#requirePerson(principal);
|
|
446
|
+
const tenantId = person.tenant?.id ?? null;
|
|
447
|
+
const workerId = `worker:${this.workerName(name, tenantId)}`;
|
|
448
|
+
if (await this.#runtime.workerPrincipal(workerId))
|
|
449
|
+
return { worker: workerId, activated: false };
|
|
450
|
+
const grants = this.#runtime.grantsFor(person);
|
|
451
|
+
await grants.registerWorker({ name: this.workerName(name, tenantId), roles: [...agent.declaration.roles], displayName: agent.declaration.displayName ?? name });
|
|
452
|
+
if (tenantId && this.#runtime.tenancy) {
|
|
453
|
+
if (!person.tenant || !this.#runtime.holds(person, "tenant.members.manage"))
|
|
454
|
+
throw new FeltKitError("FORBIDDEN", `${person.id} may not add members to this workspace (needs tenant.members.manage).`);
|
|
455
|
+
await this.#runtime.tenancy.addPrincipal({ ...person.tenant, principalId: person.id }, { id: workerId, type: "agent", displayName: agent.declaration.displayName ?? name }, agent.declaration.tenantRole);
|
|
456
|
+
}
|
|
457
|
+
this.#runtime.recordAuth("agent.activated", person, { agent: name, worker: workerId, ...(tenantId ? { tenantId } : {}) }, "success", "runtime");
|
|
458
|
+
return { worker: workerId, activated: true };
|
|
459
|
+
}
|
|
460
|
+
/**
|
|
461
|
+
* A work grant from this person to the agent's worker in their workspace: what they may call of the declared. Working
|
|
462
|
+
* with an activated agent needs feltkit.agent.write; registering workers (activation) needs feltkit.workers.write.
|
|
463
|
+
*/
|
|
464
|
+
async #grantFor(name, person) {
|
|
465
|
+
if (!this.#runtime.holds(person, "feltkit.agent.write"))
|
|
466
|
+
throw new FeltKitError("FORBIDDEN", `${person.id} may not work with agents here (needs feltkit.agent.write).`, { hint: "AGENT_CONTROL" });
|
|
467
|
+
const tenantId = person.tenant?.id ?? null;
|
|
468
|
+
const workerId = `worker:${this.workerName(name, tenantId)}`;
|
|
469
|
+
if (!(await this.#runtime.workerPrincipal(workerId)))
|
|
470
|
+
throw new FeltKitError("FAILED_PRECONDITION", "The agent is not active in this workspace yet.", { hint: "EVE_NOT_ACTIVATED" });
|
|
471
|
+
const allowed = [...this.capabilities(name)].filter(([, c]) => this.#runtime.holds(person, c.access)).map(([capability]) => capability).sort();
|
|
472
|
+
if (allowed.length === 0)
|
|
473
|
+
throw new FeltKitError("FORBIDDEN", `${person.id} may call none of the agent's capabilities, so cannot work with it.`);
|
|
474
|
+
const now = Date.now();
|
|
475
|
+
const existing = (await this.#runtime.workers.grantsOf(workerId)).find((g) => g.state === "active" && g.actor.id === person.id && Date.parse(g.expiresAt) - now > 3_600_000 && g.capabilities.length === allowed.length && g.capabilities.every((c, i) => c === allowed[i]));
|
|
476
|
+
if (existing)
|
|
477
|
+
return existing.ref;
|
|
478
|
+
const grant = await this.#runtime.workers.issueGrant({ worker: workerId, actor: { id: person.id, type: person.type }, capabilities: allowed, ttlMs: this.#agentOf(name).declaration.grantTtlMs ?? 24 * 3_600_000, by: person });
|
|
479
|
+
this.#runtime.recordAuth("work-grant.issued", person, { grant: grant.ref, worker: grant.worker, actor: person.id, capabilities: grant.capabilities, agent: name }, "success", "runtime");
|
|
480
|
+
return grant.ref;
|
|
481
|
+
}
|
|
482
|
+
#token(name, person, extra) {
|
|
483
|
+
return signEveToken(this.#secret(name, "assertion"), {
|
|
484
|
+
iss: `feltkit:${this.#runtime.app.name}`,
|
|
485
|
+
aud: `eve:${name}`,
|
|
486
|
+
sub: person.id,
|
|
487
|
+
jti: randomUUID(),
|
|
488
|
+
kind: "person",
|
|
489
|
+
name: person.displayName ?? person.id,
|
|
490
|
+
roles: [...person.roles],
|
|
491
|
+
...(person.tenant ? { tenantId: person.tenant.id } : {}),
|
|
492
|
+
...extra,
|
|
493
|
+
});
|
|
494
|
+
}
|
|
495
|
+
async #session(name, sessionId, person) {
|
|
496
|
+
const record = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).get(sessionId));
|
|
497
|
+
const tenantId = person.tenant?.id ?? null;
|
|
498
|
+
const visible = record && record.agent === name && (tenantId ? record.tenantId === tenantId : record.createdBy === person.id);
|
|
499
|
+
if (!visible)
|
|
500
|
+
throw new FeltKitError("NOT_FOUND", "No such agent session here.");
|
|
501
|
+
return record;
|
|
502
|
+
}
|
|
503
|
+
/** The workspace's sessions with this agent, newest first. */
|
|
504
|
+
async sessions(name, principal, limit = 50) {
|
|
505
|
+
this.#agentOf(name);
|
|
506
|
+
const person = this.#requirePerson(principal);
|
|
507
|
+
const tenantId = person.tenant?.id ?? null;
|
|
508
|
+
const rows = (await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).find((tenantId ? { agent: name, tenantId } : { agent: name, createdBy: person.id }), { limit: 1000 }));
|
|
509
|
+
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 } : {}) }));
|
|
510
|
+
}
|
|
511
|
+
async status(name, principal) {
|
|
512
|
+
const agent = this.#agentOf(name);
|
|
513
|
+
const person = this.#requirePerson(principal);
|
|
514
|
+
const workerId = `worker:${this.workerName(name, person.tenant?.id ?? null)}`;
|
|
515
|
+
const worker = await this.#runtime.workerPrincipal(workerId);
|
|
516
|
+
return {
|
|
517
|
+
agent: name,
|
|
518
|
+
displayName: agent.declaration.displayName ?? name,
|
|
519
|
+
state: agent.state,
|
|
520
|
+
...(agent.detail ? { detail: agent.detail } : {}),
|
|
521
|
+
activated: Boolean(worker),
|
|
522
|
+
worker: workerId,
|
|
523
|
+
capabilities: [...this.capabilities(name)].map(([capability, c]) => ({ capability, approval: c.approval ? "required" : "none", allowed: this.#runtime.holds(person, c.access) })),
|
|
524
|
+
};
|
|
525
|
+
}
|
|
526
|
+
// ---- traffic ----------------------------------------------------------------------------------------------------
|
|
527
|
+
/**
|
|
528
|
+
* `/eve/<name>/…` (a person's traffic, forwarded) and `/_feltkit/eve/<name>/…` (the agent's bridge). Returns false
|
|
529
|
+
* for any other path.
|
|
530
|
+
*/
|
|
531
|
+
async handle(request, response, pathname, identify) {
|
|
532
|
+
const bridge = /^\/_feltkit\/eve\/([a-z][a-z0-9-]*)\/(invoke|control)$/.exec(pathname);
|
|
533
|
+
if (bridge) {
|
|
534
|
+
await (bridge[2] === "control" ? this.#control(bridge[1], request, response) : this.#bridge(bridge[1], request, response));
|
|
535
|
+
return true;
|
|
536
|
+
}
|
|
537
|
+
const evidence = /^\/api\/eve\/([a-z][a-z0-9-]*)\/sessions\/([A-Za-z0-9_.-]+)\/evidence$/.exec(pathname);
|
|
538
|
+
if (evidence && (request.method ?? "GET") === "GET") {
|
|
539
|
+
const { principal } = await identify();
|
|
540
|
+
return void sendJSON(response, 200, { ok: true, evidence: await this.evidence(evidence[1], evidence[2], principal) }), true;
|
|
541
|
+
}
|
|
542
|
+
const api = /^\/api\/eve\/([a-z][a-z0-9-]*)(?:\/(activate|sessions|answer))?$/.exec(pathname);
|
|
543
|
+
if (api) {
|
|
544
|
+
const name = api[1];
|
|
545
|
+
const { principal } = await identify();
|
|
546
|
+
const method = request.method ?? "GET";
|
|
547
|
+
if (!api[2] && method === "GET")
|
|
548
|
+
return void sendJSON(response, 200, { ok: true, ...(await this.status(name, principal)) }), true;
|
|
549
|
+
if (api[2] === "activate" && method === "POST")
|
|
550
|
+
return void sendJSON(response, 200, { ok: true, ...(await this.activate(name, principal)) }), true;
|
|
551
|
+
if (api[2] === "sessions" && method === "GET")
|
|
552
|
+
return void sendJSON(response, 200, { ok: true, sessions: await this.sessions(name, principal) }), true;
|
|
553
|
+
if (api[2] === "answer" && method === "POST") {
|
|
554
|
+
const body = await readJSON(request);
|
|
555
|
+
const result = await this.answer(name, principal, { sessionId: String(body.sessionId ?? ""), interactionId: String(body.interactionId ?? ""), decision: body.decision === "approve" ? "approve" : "deny" });
|
|
556
|
+
return void sendJSON(response, 200, { ok: true, ...result }), true;
|
|
557
|
+
}
|
|
558
|
+
throw new FeltKitError("NOT_FOUND", `No agent endpoint ${method} ${pathname}.`);
|
|
559
|
+
}
|
|
560
|
+
const forward = /^\/eve\/([a-z][a-z0-9-]*)(\/.*)$/.exec(pathname);
|
|
561
|
+
if (!forward)
|
|
562
|
+
return false;
|
|
563
|
+
const name = forward[1];
|
|
564
|
+
const rest = forward[2];
|
|
565
|
+
const agent = this.#agentOf(name);
|
|
566
|
+
if (agent.state !== "ready")
|
|
567
|
+
throw new FeltKitError("UNAVAILABLE", `The agent is ${agent.state}${agent.detail ? `: ${agent.detail}` : ""}.`);
|
|
568
|
+
if (rest === "/eve/v1/health")
|
|
569
|
+
return this.#proxy(agent, request, response, rest, null), true;
|
|
570
|
+
const person = this.#requirePerson((await identify()).principal);
|
|
571
|
+
const sessionPath = /^\/eve\/v1\/session(?:\/([A-Za-z0-9_.-]+)(\/[a-z]+)?)?$/.exec(rest);
|
|
572
|
+
if (!sessionPath)
|
|
573
|
+
throw new FeltKitError("NOT_FOUND", "Only the agent's session routes are served here.");
|
|
574
|
+
const method = request.method ?? "GET";
|
|
575
|
+
const sessionId = sessionPath[1];
|
|
576
|
+
if (sessionId)
|
|
577
|
+
await this.#session(name, sessionId, person);
|
|
578
|
+
else if (method !== "POST")
|
|
579
|
+
throw new FeltKitError("NOT_FOUND", "Create a session with POST.");
|
|
580
|
+
const needsGrant = method === "POST";
|
|
581
|
+
const claims = needsGrant ? { grant: await this.#grantFor(name, person) } : {};
|
|
582
|
+
if (sessionId && sessionPath[2] === undefined && method === "POST") {
|
|
583
|
+
const body = await readBodyBytes(request);
|
|
584
|
+
if (hasApproval(body))
|
|
585
|
+
throw new FeltKitError("FORBIDDEN", "Answer an approval through /api/eve/<agent>/answer, so the approval is recorded.");
|
|
586
|
+
return this.#proxy(agent, request, response, rest, this.#token(name, person, claims), body), true;
|
|
587
|
+
}
|
|
588
|
+
if (!sessionId) {
|
|
589
|
+
const body = await readBodyBytes(request);
|
|
590
|
+
const title = titleOf(body);
|
|
591
|
+
const answer = await this.#call(agent, "POST", rest, this.#token(name, person, claims), body, request.headers);
|
|
592
|
+
const created = JSON.parse(answer.body.toString("utf8") || "{}");
|
|
593
|
+
if (answer.status < 300 && typeof created.sessionId === "string") {
|
|
594
|
+
const worker = await this.#worker(name, person.tenant?.id ?? null);
|
|
595
|
+
const task = worker ? await this.#runtime.agent.openTask({ principal: worker, objective: title, key: `session:${created.sessionId}` }) : null;
|
|
596
|
+
const record = { id: created.sessionId, agent: name, tenantId: person.tenant?.id ?? null, createdBy: person.id, createdAt: Date.now(), title, ...(task ? { taskId: task.taskId } : {}) };
|
|
597
|
+
await this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION).insert(record, created.sessionId);
|
|
598
|
+
}
|
|
599
|
+
response.writeHead(answer.status, { "content-type": answer.headers["content-type"] ?? "application/json", "cache-control": "no-store" });
|
|
600
|
+
response.end(answer.body);
|
|
601
|
+
return true;
|
|
602
|
+
}
|
|
603
|
+
return this.#proxy(agent, request, response, rest, this.#token(name, person, claims)), true;
|
|
604
|
+
}
|
|
605
|
+
#authorizeBridge(name, request) {
|
|
606
|
+
this.#agentOf(name);
|
|
607
|
+
const remote = request.socket.remoteAddress ?? "";
|
|
608
|
+
if (!["127.0.0.1", "::1", "::ffff:127.0.0.1"].includes(remote))
|
|
609
|
+
throw new FeltKitError("FORBIDDEN", "The agent bridge answers only this machine.");
|
|
610
|
+
const key = String(request.headers.authorization ?? "").replace(/^Bearer\s+/i, "");
|
|
611
|
+
if (!key || !safeEqual(key, this.#secret(name, "service")))
|
|
612
|
+
throw new FeltKitError("UNAUTHORIZED", "The agent bridge needs the agent's key.");
|
|
613
|
+
}
|
|
614
|
+
/**
|
|
615
|
+
* The agent's side of appport.agent-control/1 for one of its sessions: `checkpoint` before new work (updates handed
|
|
616
|
+
* over, whether to proceed) and `acknowledge` of a delivered update, as the task's reasoner (the workspace's worker).
|
|
617
|
+
*/
|
|
618
|
+
async #control(name, request, response) {
|
|
619
|
+
this.#authorizeBridge(name, request);
|
|
620
|
+
const body = await readJSON(request);
|
|
621
|
+
const { taskId, worker } = await this.#sessionTask(name, body.sessionId);
|
|
622
|
+
if (body.op === "checkpoint") {
|
|
623
|
+
const checkpoint = await this.#runtime.agent.control.checkpoint(taskId, worker);
|
|
624
|
+
// The agent reached a boundary and holds there: the phase moved (pausing → paused, or stays interrupted).
|
|
625
|
+
if (!checkpoint.proceed)
|
|
626
|
+
await this.#runtime.agent.control.inFlightChanged(taskId);
|
|
627
|
+
const names = new Map((await this.#runtime.tenancy?.members(worker.tenant?.id ?? "").catch(() => []) ?? []).map((m) => [`user:${m.principalId}`, m.displayName ?? m.principalId]));
|
|
628
|
+
return sendJSON(response, 200, { ok: true, ...checkpoint, instructions: checkpoint.instructions.map((i) => ({ ...i, from: names.get(i.from) ?? i.from })) });
|
|
629
|
+
}
|
|
630
|
+
if (body.op === "acknowledge") {
|
|
631
|
+
const outcome = body.outcome === "conflict" ? "conflict" : "incorporated";
|
|
632
|
+
return sendJSON(response, 200, { ok: true, instruction: await this.#runtime.agent.control.acknowledge(taskId, String(body.instructionId ?? ""), { outcome, note: String(body.note ?? "") }, worker) });
|
|
633
|
+
}
|
|
634
|
+
throw new FeltKitError("INVALID_ARGUMENT", 'op is "checkpoint" or "acknowledge".');
|
|
635
|
+
}
|
|
636
|
+
async #bridge(name, request, response) {
|
|
637
|
+
this.#authorizeBridge(name, request);
|
|
638
|
+
const body = await readJSON(request);
|
|
639
|
+
const capability = String(body.capability ?? "");
|
|
640
|
+
const known = this.capabilities(name).get(capability);
|
|
641
|
+
if (!known)
|
|
642
|
+
throw new FeltKitError("NOT_FOUND", `${capability} is not one of this agent's capabilities.`);
|
|
643
|
+
const grantRef = typeof body.grant === "string" ? body.grant : "";
|
|
644
|
+
const grant = grantRef ? await this.#runtime.workers.grant(grantRef) : null;
|
|
645
|
+
const principalId = grant?.principalId;
|
|
646
|
+
if (!grant || !principalId || !principalId.startsWith(`worker:eve-${name}`))
|
|
647
|
+
throw new FeltKitError("FORBIDDEN", "The call names no work grant to this agent.");
|
|
648
|
+
const worker = await this.#runtime.workerPrincipal(principalId);
|
|
649
|
+
if (!worker)
|
|
650
|
+
throw new FeltKitError("FORBIDDEN", "The agent is no longer active in that workspace.");
|
|
651
|
+
const input = body.input && typeof body.input === "object" && !Array.isArray(body.input) ? body.input : {};
|
|
652
|
+
// A capability call is new work: refused while the session's task is paused or interrupted, or a person's update
|
|
653
|
+
// has not been handed to the agent yet (appport.agent-control/1 §4.2).
|
|
654
|
+
if (typeof body.sessionId === "string")
|
|
655
|
+
await this.#runtime.agent.control.gate((await this.#sessionTask(name, body.sessionId)).taskId, `the call to ${capability}`);
|
|
656
|
+
const claimed = { grantRef, ...(typeof body.approval === "string" && body.approval ? { approvalRef: body.approval } : {}) };
|
|
657
|
+
const result = await this.#runtime.call(known.fn, input, { principal: worker, via: "integration", invocation: { claimed } });
|
|
658
|
+
if (!result.ok)
|
|
659
|
+
return sendJSON(response, 200, { ok: false, error: result.error });
|
|
660
|
+
return sendJSON(response, 200, { ok: true, value: result.value });
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* Everything recorded about one session, for a person of its workspace who may read agent tasks: what they asked,
|
|
664
|
+
* what the agent was given and did (model steps, tool calls with their inputs, results and whether they changed
|
|
665
|
+
* anything), the approvals it asked for and who answered, the lifecycle (pauses, updates) and its state now. Facts
|
|
666
|
+
* come from the runtime; lifecycle, updates and answers from FeltKit's own records, which outlive the session.
|
|
667
|
+
*/
|
|
668
|
+
async evidence(name, sessionId, principal) {
|
|
669
|
+
const agent = this.#agentOf(name);
|
|
670
|
+
const person = this.#requirePerson(principal);
|
|
671
|
+
const record = await this.#session(name, sessionId, person);
|
|
672
|
+
const control = record.taskId ? await this.#runtime.agent.control.view(record.taskId, person) : null;
|
|
673
|
+
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;
|
|
674
|
+
const lines = read && read.status < 300 ? read.body.toString("utf8").split("\n") : [];
|
|
675
|
+
const facts = lines.flatMap((line) => timedFactsOf(line));
|
|
676
|
+
const ended = read?.status === 410 || facts.some((f) => f.type === "session.ended");
|
|
677
|
+
const history = (control?.instructions ?? []).map((i) => ({ ...i, ...updateOutcome(i.instructionId, facts) }));
|
|
678
|
+
const capabilities = this.capabilities(name);
|
|
679
|
+
const kindOf = (tool) => {
|
|
680
|
+
const capability = [...capabilities.keys()].find((c) => eveToolName(c) === tool);
|
|
681
|
+
const fn = capability ? this.#runtime.project.functions.get(capabilities.get(capability).fn) : undefined;
|
|
682
|
+
return { capability: capability ?? null, changes: fn ? fn.kind !== "query" : null };
|
|
683
|
+
};
|
|
684
|
+
return {
|
|
685
|
+
session: { id: record.id, title: record.title, createdBy: record.createdBy, createdAt: record.createdAt, taskId: record.taskId ?? null },
|
|
686
|
+
state: executionState(facts, control, ended).state,
|
|
687
|
+
ended,
|
|
688
|
+
runtimeHistory: read === null ? "unavailable" : read.status === 410 ? "gone" : read.status < 300 ? "available" : "unavailable",
|
|
689
|
+
control: control ? { phase: control.phase, mode: control.mode, reason: control.reason, revision: control.revision } : null,
|
|
690
|
+
controlHistory: record.taskId ? await this.#controlHistory(record.taskId) : [],
|
|
691
|
+
updates: history,
|
|
692
|
+
answers: record.answers ?? [],
|
|
693
|
+
stopped: record.stopped ?? null,
|
|
694
|
+
timeline: timeline(facts, kindOf),
|
|
695
|
+
};
|
|
696
|
+
}
|
|
697
|
+
async #controlHistory(taskId) {
|
|
698
|
+
return this.#runtime.agent.control.history(taskId);
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* A person's answer to an approval the agent is waiting on. The call is the one eve recorded for that
|
|
702
|
+
* interaction, never one the request describes. Approve: an AppPort approval of exactly that capability and
|
|
703
|
+
* input, by this person, for the workspace's worker; eve then resumes and the call names it. Deny: eve is told.
|
|
704
|
+
*/
|
|
705
|
+
async answer(name, principal, input) {
|
|
706
|
+
const agent = this.#agentOf(name);
|
|
707
|
+
const person = this.#requirePerson(principal);
|
|
708
|
+
await this.#session(name, input.sessionId, person);
|
|
709
|
+
const call = await this.#openCall(agent, input.sessionId, input.interactionId, person);
|
|
710
|
+
if (!call)
|
|
711
|
+
throw new FeltKitError("NOT_FOUND", "That approval is not waiting.");
|
|
712
|
+
let extra = { answers: input.interactionId };
|
|
713
|
+
let approval;
|
|
714
|
+
if (input.decision === "approve") {
|
|
715
|
+
// Approving runs the call, so it is refused while a person holds the task: approval never resumes work.
|
|
716
|
+
const session = await this.#session(name, input.sessionId, person);
|
|
717
|
+
if (session.taskId) {
|
|
718
|
+
const { mode, reason } = await this.#runtime.agent.control.mode(session.taskId);
|
|
719
|
+
if (mode !== "running")
|
|
720
|
+
throw new FeltKitError("CONFLICT", `The agent is ${mode}${reason ? ` (${reason})` : ""}: resume it before approving, so the approved call can run.`, { details: { reason: mode === "paused" ? "AGENT_PAUSED" : "AGENT_INTERRUPTED" } });
|
|
721
|
+
}
|
|
722
|
+
const capability = [...this.capabilities(name).keys()].find((c) => eveToolName(c) === call.name);
|
|
723
|
+
if (!capability)
|
|
724
|
+
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, ".")}).`);
|
|
725
|
+
const issued = await this.#runtime.grantsFor(person).approve({ capability, input: call.input, worker: `worker:${this.workerName(name, person.tenant?.id ?? null)}` });
|
|
726
|
+
approval = issued.ref;
|
|
727
|
+
extra = { ...extra, approvalRef: issued.ref };
|
|
728
|
+
}
|
|
729
|
+
const body = Buffer.from(JSON.stringify({ answers: [{ interactionId: input.interactionId, optionId: input.decision }] }));
|
|
730
|
+
const answer = await this.#call(agent, "POST", `/eve/v1/session/${encodeURIComponent(input.sessionId)}`, this.#token(name, person, extra), body, { "content-type": "application/json" });
|
|
731
|
+
if (answer.status >= 300)
|
|
732
|
+
throw new FeltKitError("CONFLICT", `The agent did not take the answer (${answer.status}).`);
|
|
733
|
+
// Evidence that outlives the session: who answered which request, and the approval of the exact call.
|
|
734
|
+
const capability = [...this.capabilities(name).keys()].find((c) => eveToolName(c) === call.name);
|
|
735
|
+
const entry = { interactionId: input.interactionId, decision: input.decision, by: person.id, at: Date.now(), ...(capability ? { capability } : {}), ...(approval ? { approval } : {}) };
|
|
736
|
+
await this.#patchSession(input.sessionId, (record) => ({ answers: [...(record.answers ?? []), entry].slice(-200) }));
|
|
737
|
+
return { ...(approval ? { approval } : {}), status: answer.status };
|
|
738
|
+
}
|
|
739
|
+
/** Change a session record from its current version, retrying a concurrent writer; the record is FeltKit's alone. */
|
|
740
|
+
async #patchSession(sessionId, change) {
|
|
741
|
+
const sessions = this.#runtime.instance.handle("app").collection(EVE_SESSIONS_COLLECTION);
|
|
742
|
+
for (let attempt = 0; attempt < 5; attempt++) {
|
|
743
|
+
const record = (await sessions.get(sessionId));
|
|
744
|
+
if (!record || record.__version === undefined)
|
|
745
|
+
return;
|
|
746
|
+
const written = await sessions.updateIfVersion(sessionId, record.__version, change(record)).catch(() => null);
|
|
747
|
+
if (written?.updated)
|
|
748
|
+
return;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
async #openCall(agent, sessionId, interactionId, person) {
|
|
752
|
+
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" });
|
|
753
|
+
if (read.status >= 300)
|
|
754
|
+
return null;
|
|
755
|
+
const calls = new Map();
|
|
756
|
+
let waiting = null;
|
|
757
|
+
for (const line of read.body.toString("utf8").split("\n")) {
|
|
758
|
+
for (const fact of factsOf(line)) {
|
|
759
|
+
const data = (fact.data ?? {});
|
|
760
|
+
if (fact.type === "call.requested") {
|
|
761
|
+
const capability = data.capability;
|
|
762
|
+
if (typeof data.callId === "string" && typeof capability?.name === "string")
|
|
763
|
+
calls.set(data.callId, { name: capability.name, input: data.input && typeof data.input === "object" ? data.input : {} });
|
|
764
|
+
}
|
|
765
|
+
if (data.interactionId !== interactionId)
|
|
766
|
+
continue;
|
|
767
|
+
if (fact.type === "interaction.opened")
|
|
768
|
+
waiting = typeof data.subject?.callId === "string" ? String(data.subject.callId) : null;
|
|
769
|
+
if (fact.type === "interaction.settled")
|
|
770
|
+
waiting = null;
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
const call = waiting ? (calls.get(waiting) ?? null) : null;
|
|
774
|
+
return call;
|
|
775
|
+
}
|
|
776
|
+
#call(agent, method, path, token, body, headers = {}) {
|
|
777
|
+
return new Promise((done, fail) => {
|
|
778
|
+
const outgoing = httpRequest({ host: "127.0.0.1", port: agent.port, method, path, headers: { ...(headers["content-type"] ? { "content-type": headers["content-type"] } : {}), ...(headers.accept ? { accept: headers.accept } : {}), authorization: `Bearer ${token}`, ...(body ? { "content-length": body.byteLength } : {}) } }, (incoming) => {
|
|
779
|
+
const chunks = [];
|
|
780
|
+
let size = 0;
|
|
781
|
+
incoming.on("data", (chunk) => {
|
|
782
|
+
size += chunk.byteLength;
|
|
783
|
+
if (size > STREAM_READ_LIMIT) {
|
|
784
|
+
incoming.destroy();
|
|
785
|
+
return fail(new FeltKitError("INTERNAL", "The agent's answer was too large to read."));
|
|
786
|
+
}
|
|
787
|
+
chunks.push(chunk);
|
|
788
|
+
});
|
|
789
|
+
incoming.on("end", () => done({ status: incoming.statusCode ?? 502, headers: incoming.headers, body: Buffer.concat(chunks) }));
|
|
790
|
+
incoming.on("error", fail);
|
|
791
|
+
});
|
|
792
|
+
outgoing.on("error", () => fail(new FeltKitError("UNAVAILABLE", "The agent is not answering.")));
|
|
793
|
+
outgoing.end(body);
|
|
794
|
+
});
|
|
795
|
+
}
|
|
796
|
+
#proxy(agent, request, response, path, token, body) {
|
|
797
|
+
const search = new URL(request.url ?? "/", "http://local").search;
|
|
798
|
+
const headers = {};
|
|
799
|
+
for (const name of ["content-type", "accept", "last-event-id"]) {
|
|
800
|
+
const value = request.headers[name];
|
|
801
|
+
if (typeof value === "string")
|
|
802
|
+
headers[name] = value;
|
|
803
|
+
}
|
|
804
|
+
if (token)
|
|
805
|
+
headers.authorization = `Bearer ${token}`;
|
|
806
|
+
if (body)
|
|
807
|
+
headers["content-length"] = body.byteLength;
|
|
808
|
+
const outgoing = httpRequest({ host: "127.0.0.1", port: agent.port, method: request.method, path: path + search, headers }, (incoming) => {
|
|
809
|
+
const out = { "cache-control": "no-store" };
|
|
810
|
+
for (const name of ["content-type", "x-eve-tail-index", "x-accel-buffering"]) {
|
|
811
|
+
const value = incoming.headers[name];
|
|
812
|
+
if (value !== undefined)
|
|
813
|
+
out[name] = value;
|
|
814
|
+
}
|
|
815
|
+
response.writeHead(incoming.statusCode ?? 502, out);
|
|
816
|
+
incoming.pipe(response);
|
|
817
|
+
});
|
|
818
|
+
outgoing.on("error", () => {
|
|
819
|
+
if (!response.headersSent)
|
|
820
|
+
sendJSON(response, 502, { ok: false, error: { code: "UNAVAILABLE", message: "The agent is not answering." } });
|
|
821
|
+
else
|
|
822
|
+
response.destroy();
|
|
823
|
+
});
|
|
824
|
+
response.on("close", () => outgoing.destroy());
|
|
825
|
+
if (body)
|
|
826
|
+
outgoing.end(body);
|
|
827
|
+
else if (request.method === "GET" || request.method === "HEAD")
|
|
828
|
+
outgoing.end();
|
|
829
|
+
else
|
|
830
|
+
request.pipe(outgoing);
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
async function readBodyBytes(request, limit = 1024 * 1024) {
|
|
834
|
+
const chunks = [];
|
|
835
|
+
let size = 0;
|
|
836
|
+
for await (const chunk of request) {
|
|
837
|
+
size += chunk.byteLength;
|
|
838
|
+
if (size > limit)
|
|
839
|
+
throw new FeltKitError("INVALID_ARGUMENT", "The message is too large.");
|
|
840
|
+
chunks.push(chunk);
|
|
841
|
+
}
|
|
842
|
+
return Buffer.concat(chunks);
|
|
843
|
+
}
|
|
844
|
+
function hasApproval(body) {
|
|
845
|
+
try {
|
|
846
|
+
const parsed = JSON.parse(body.toString("utf8") || "{}");
|
|
847
|
+
return Array.isArray(parsed.answers) && parsed.answers.length > 0;
|
|
848
|
+
}
|
|
849
|
+
catch {
|
|
850
|
+
return false;
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
function titleOf(body) {
|
|
854
|
+
try {
|
|
855
|
+
const parsed = JSON.parse(body.toString("utf8") || "{}");
|
|
856
|
+
const text = typeof parsed.message === "string" ? parsed.message : typeof parsed.message?.text === "string" ? String(parsed.message.text) : "";
|
|
857
|
+
return text.replace(/\s+/g, " ").trim().slice(0, 140) || "Session";
|
|
858
|
+
}
|
|
859
|
+
catch {
|
|
860
|
+
return "Session";
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
/** The facts of one line of an eve session stream (`{ at, facts: [{ type, data }] }`); progress and heartbeats have none. */
|
|
864
|
+
function factsOf(line) {
|
|
865
|
+
const text = line.trim();
|
|
866
|
+
if (!text.startsWith("{"))
|
|
867
|
+
return [];
|
|
868
|
+
try {
|
|
869
|
+
const parsed = JSON.parse(text);
|
|
870
|
+
return Array.isArray(parsed.facts) ? parsed.facts : [];
|
|
871
|
+
}
|
|
872
|
+
catch {
|
|
873
|
+
return [];
|
|
874
|
+
}
|
|
875
|
+
}
|
|
876
|
+
/**
|
|
877
|
+
* What a session is doing now, from the facts the agent runtime recorded: model calls started and not settled
|
|
878
|
+
* (generations), tool calls started and not settled (actions), and whether its turn is held by control.
|
|
879
|
+
*/
|
|
880
|
+
export function sessionExecution(facts) {
|
|
881
|
+
const generations = new Set();
|
|
882
|
+
const actions = new Set();
|
|
883
|
+
let held = false;
|
|
884
|
+
for (const fact of facts) {
|
|
885
|
+
const d = (fact.data ?? {});
|
|
886
|
+
if (fact.type === "model.started" && typeof d.runId === "string")
|
|
887
|
+
generations.add(d.runId);
|
|
888
|
+
else if (fact.type === "model.settled" && typeof d.runId === "string")
|
|
889
|
+
generations.delete(d.runId);
|
|
890
|
+
else if (fact.type === "call.started" && typeof d.callId === "string")
|
|
891
|
+
actions.add(d.callId);
|
|
892
|
+
else if (fact.type === "call.settled" && typeof d.callId === "string")
|
|
893
|
+
actions.delete(d.callId);
|
|
894
|
+
if (isControlHold(fact))
|
|
895
|
+
held = true;
|
|
896
|
+
else if (fact.type === "turn.started" || fact.type === "turn.settled" || fact.type === "model.started" || fact.type === "call.started" || fact.type === "session.ended")
|
|
897
|
+
held = false;
|
|
898
|
+
if (fact.type === "turn.settled" || fact.type === "session.ended") {
|
|
899
|
+
generations.clear();
|
|
900
|
+
actions.clear();
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
return { generations: [...generations], actions: [...actions], held };
|
|
904
|
+
}
|
|
905
|
+
/** A fact recording that the session's turn is held by agent control (`turn.held`; never an approval wait). */
|
|
906
|
+
export function isControlHold(fact) {
|
|
907
|
+
return fact.type === "turn.held";
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* The session's state from what the runtime recorded (its facts) and what the lifecycle recorded (the task's control
|
|
911
|
+
* phase and mode), never from a client: stopped and held states come from control and the runtime's `turn.held`;
|
|
912
|
+
* the work in progress from facts started and not settled.
|
|
913
|
+
*/
|
|
914
|
+
export function executionState(facts, control, ended) {
|
|
915
|
+
if (ended || control?.phase === "stopped")
|
|
916
|
+
return { state: "stopped" };
|
|
917
|
+
const now = sessionExecution(facts);
|
|
918
|
+
const busy = now.generations.length + now.actions.length > 0;
|
|
919
|
+
const types = facts.map((f) => f.type);
|
|
920
|
+
const openTurn = types.lastIndexOf("turn.started") > types.lastIndexOf("turn.settled");
|
|
921
|
+
const opened = new Set();
|
|
922
|
+
for (const f of facts) {
|
|
923
|
+
const d = (f.data ?? {});
|
|
924
|
+
if (f.type === "interaction.opened" && d.interactionId)
|
|
925
|
+
opened.add(d.interactionId);
|
|
926
|
+
if (f.type === "interaction.settled" && d.interactionId)
|
|
927
|
+
opened.delete(d.interactionId);
|
|
928
|
+
if (f.type === "turn.settled")
|
|
929
|
+
opened.clear();
|
|
930
|
+
}
|
|
931
|
+
if (control?.mode === "interrupted")
|
|
932
|
+
return { state: busy ? "interrupting" : "interrupted" };
|
|
933
|
+
if (control?.mode === "paused")
|
|
934
|
+
return { state: busy ? "pausing" : "paused" };
|
|
935
|
+
if (now.held)
|
|
936
|
+
return { state: "resuming" };
|
|
937
|
+
if (opened.size)
|
|
938
|
+
return { state: "approval" };
|
|
939
|
+
if (now.actions.length)
|
|
940
|
+
return { state: "tool" };
|
|
941
|
+
if (now.generations.length)
|
|
942
|
+
return { state: "model" };
|
|
943
|
+
if (openTurn)
|
|
944
|
+
return { state: "running" };
|
|
945
|
+
const admitted = facts.filter((f) => f.type === "delivery.admitted").length;
|
|
946
|
+
const consumed = facts.filter((f) => f.type === "delivery.consumed" || f.type === "delivery.settled").map((f) => f.data?.deliveryId);
|
|
947
|
+
const waiting = facts.filter((f) => f.type === "delivery.admitted").some((f) => !consumed.includes(f.data?.deliveryId));
|
|
948
|
+
if (admitted && waiting)
|
|
949
|
+
return { state: "submitted" };
|
|
950
|
+
const last = facts.filter((f) => f.type === "turn.settled").at(-1);
|
|
951
|
+
if (!last)
|
|
952
|
+
return { state: "idle" };
|
|
953
|
+
const outcome = last.data?.outcome;
|
|
954
|
+
return { state: outcome === "failed" ? "failed" : outcome === "completed" ? "completed" : "idle" };
|
|
955
|
+
}
|
|
956
|
+
/**
|
|
957
|
+
* Where an update stands, from both records: the lifecycle's (received, delivered, incorporated, …) and, once it was
|
|
958
|
+
* given to the agent, the runtime's: the turn it went into and how that turn ended. `completed` only when that turn
|
|
959
|
+
* completed; a turn that failed or was cancelled says so instead.
|
|
960
|
+
*/
|
|
961
|
+
export function updateOutcome(instructionId, facts) {
|
|
962
|
+
let turnId;
|
|
963
|
+
let current;
|
|
964
|
+
for (const f of facts) {
|
|
965
|
+
const d = (f.data ?? {});
|
|
966
|
+
if (f.type === "turn.started")
|
|
967
|
+
current = d.turnId ?? current;
|
|
968
|
+
if (f.type === "delivery.consumed" && d.deliveryId === `instruction:${instructionId}`)
|
|
969
|
+
turnId = d.turnId ?? current;
|
|
970
|
+
if (turnId && f.type === "turn.settled" && (d.turnId ?? current) === turnId)
|
|
971
|
+
return { turnId, turn: d.outcome ?? "settled" };
|
|
972
|
+
}
|
|
973
|
+
return turnId ? { turnId, turn: "running" } : {};
|
|
974
|
+
}
|
|
975
|
+
function timedFactsOf(line) {
|
|
976
|
+
const text = line.trim();
|
|
977
|
+
if (!text.startsWith("{"))
|
|
978
|
+
return [];
|
|
979
|
+
try {
|
|
980
|
+
const parsed = JSON.parse(text);
|
|
981
|
+
const at = typeof parsed.at === "string" ? parsed.at : typeof parsed.at === "number" ? new Date(parsed.at).toISOString() : undefined;
|
|
982
|
+
return Array.isArray(parsed.facts) ? parsed.facts.map((f) => ({ ...f, ...(at ? { at } : {}) })) : [];
|
|
983
|
+
}
|
|
984
|
+
catch {
|
|
985
|
+
return [];
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
/**
|
|
989
|
+
* The session's facts as evidence. A tool call that may change the application is "changed" only once the runtime
|
|
990
|
+
* recorded it completed, "attempted" if it started and settled otherwise, "not-run" if it settled without starting
|
|
991
|
+
* (its approval was denied or ended with the session), and "unknown" while no outcome is recorded; reads are
|
|
992
|
+
* "read"; a tool outside the application's capabilities is "outside" (its effect is not the application's to confirm).
|
|
993
|
+
*/
|
|
994
|
+
export function timeline(facts, kindOf) {
|
|
995
|
+
const out = [];
|
|
996
|
+
const calls = new Map();
|
|
997
|
+
const asks = new Map();
|
|
998
|
+
for (const f of facts) {
|
|
999
|
+
const d = (f.data ?? {});
|
|
1000
|
+
const at = f.at;
|
|
1001
|
+
switch (f.type) {
|
|
1002
|
+
case "delivery.consumed": {
|
|
1003
|
+
const text = (d.parts ?? []).filter((p) => p?.kind === "text").map((p) => p.text).join("\n");
|
|
1004
|
+
if (typeof d.deliveryId === "string" && d.deliveryId.startsWith("instruction:"))
|
|
1005
|
+
out.push({ kind: "update", at, instructionId: d.deliveryId.slice("instruction:".length), text });
|
|
1006
|
+
else if (text)
|
|
1007
|
+
out.push({ kind: "message", at, text });
|
|
1008
|
+
break;
|
|
1009
|
+
}
|
|
1010
|
+
case "model.started":
|
|
1011
|
+
out.push({ kind: "model", at, runId: String(d.runId) });
|
|
1012
|
+
break;
|
|
1013
|
+
case "model.settled": {
|
|
1014
|
+
const m = out.find((e) => e.kind === "model" && e.runId === d.runId);
|
|
1015
|
+
if (m)
|
|
1016
|
+
m.outcome = d.outcome;
|
|
1017
|
+
break;
|
|
1018
|
+
}
|
|
1019
|
+
case "call.requested": {
|
|
1020
|
+
const tool = String(d.capability?.name ?? "tool");
|
|
1021
|
+
const k = kindOf(tool);
|
|
1022
|
+
const entry = { kind: "tool", at, callId: String(d.callId), tool, capability: k.capability, input: d.input, effect: k.changes === null ? "outside" : k.changes ? "unknown" : "read" };
|
|
1023
|
+
calls.set(entry.callId, entry);
|
|
1024
|
+
out.push(entry);
|
|
1025
|
+
break;
|
|
1026
|
+
}
|
|
1027
|
+
case "call.started": {
|
|
1028
|
+
const c = calls.get(d.callId);
|
|
1029
|
+
if (c)
|
|
1030
|
+
c.started = true;
|
|
1031
|
+
if (c && d.clearedBy?.interactionId)
|
|
1032
|
+
c.approved = d.clearedBy.interactionId;
|
|
1033
|
+
break;
|
|
1034
|
+
}
|
|
1035
|
+
case "call.settled": {
|
|
1036
|
+
const c = calls.get(d.callId);
|
|
1037
|
+
if (!c)
|
|
1038
|
+
break;
|
|
1039
|
+
c.outcome = d.outcome;
|
|
1040
|
+
c.output = d.output ?? d.error;
|
|
1041
|
+
if (c.effect === "unknown")
|
|
1042
|
+
c.effect = !c.started ? "not-run" : d.outcome === "completed" ? "changed" : "attempted";
|
|
1043
|
+
break;
|
|
1044
|
+
}
|
|
1045
|
+
case "interaction.opened": {
|
|
1046
|
+
const entry = { kind: "approval", at, interactionId: String(d.interactionId), prompt: String(d.request?.prompt ?? "Approve?") };
|
|
1047
|
+
asks.set(entry.interactionId, entry);
|
|
1048
|
+
out.push(entry);
|
|
1049
|
+
break;
|
|
1050
|
+
}
|
|
1051
|
+
case "interaction.settled": {
|
|
1052
|
+
const a = asks.get(d.interactionId);
|
|
1053
|
+
if (a)
|
|
1054
|
+
a.outcome = d.response?.optionId === "approve" ? "approved" : d.response?.optionId === "deny" ? "denied" : d.outcome;
|
|
1055
|
+
break;
|
|
1056
|
+
}
|
|
1057
|
+
case "turn.held":
|
|
1058
|
+
out.push({ kind: "held", at, boundary: d.boundary, reason: d.reason });
|
|
1059
|
+
break;
|
|
1060
|
+
case "content.completed":
|
|
1061
|
+
if (d.phase === "reply" && d.value)
|
|
1062
|
+
out.push({ kind: "reply", at, text: String(d.value) });
|
|
1063
|
+
break;
|
|
1064
|
+
case "turn.settled":
|
|
1065
|
+
out.push({ kind: "turn", at, turnId: d.turnId, outcome: d.outcome });
|
|
1066
|
+
break;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
return out;
|
|
1070
|
+
}
|
|
1071
|
+
//# sourceMappingURL=eve.js.map
|